A DataSource over a REST API, proved by the conformance suite

Your team has a REST API with a few query parameters and JSON replies, and no SQL. This recipe puts a DataSource over one, and proves it with the conformance suite: one call that runs the library's expectations and names what is wrong.

The adapter here was written by an agent that was given the adapters guide, what that page says to read, and the suite, and nothing else. It passed on its first run of the suite: 59 checks passed, none failed, and 8 were skipped because this API cannot group or explain. How that went, and a second run with less to read, is in the conformance evidence.

The API

A made-up stock list, of the kind a team already has. It knows nothing of Surfaces UI. Its comment is its documentation:

stockApi.ts:

ts
/**
 * A small made-up REST API, of the kind a team already has: a stock list
 * with one resource, a few query parameters and JSON replies. It knows
 * nothing of Surfaces UI. The recipe's adapter is written over it.
 *
 *   GET /v1/resources
 *     -> { "resources": [{ "name": "conformance_items", "title": "Stock items" }] }
 *
 *   GET /v1/resources/{name}/schema
 *     -> { "name": ..., "fields": [{ "name": "id", "type": "integer", "nullable": false }, ...] }
 *     A field's type is "integer", "number", "string" or "date" (a date is "YYYY-MM-DD" text).
 *
 *   GET /v1/resources/{name}/items
 *     -> { "items": [{ ... }], "total": 12 }
 *     `total` is the number of items that match the filters, before `limit` and `offset`.
 *     Query parameters, all optional:
 *       where   Repeatable; every one must hold. Each is a JSON object, URL-encoded:
 *                 { "field": "quantity", "op": "gte", "value": 5 }
 *               op is one of
 *                 eq, ne, lt, lte, gt, gte   compare with `value` (a string, a number, or a date as text)
 *                 in                         `value` is a list; the field equals any of them
 *                 contains, prefix, suffix   `value` is text, matched as it is, ignoring case
 *                 null, notnull              take no value
 *               There is no "between" and no "not in". A null field matches only `null`.
 *       sort    Comma-separated, in order of importance: field:asc|desc:nulls_first|nulls_last
 *                 sort=quantity:desc:nulls_last,id:asc:nulls_last
 *       fields  Comma-separated field names to return, in that order. Default: all.
 *       limit   The most items to return. Default: all.
 *       offset  Items to skip first. Default 0.
 *
 *   Errors are a 4xx status with { "error": { "code": "unknown_field", "detail": "..." } }.
 *   Codes: unknown_resource, unknown_field, bad_request, not_found.
 *
 * The API cannot group or aggregate, and has no plan to explain.
 */
export interface StockItem {
  [field: string]: string | number | null;
}

interface Field {
  name: string;
  type: "integer" | "number" | "string" | "date";
  nullable: boolean;
}

const FIELDS: Field[] = [
  { name: "id", type: "integer", nullable: false },
  { name: "name", type: "string", nullable: false },
  { name: "category", type: "string", nullable: true },
  { name: "quantity", type: "integer", nullable: true },
  { name: "price", type: "number", nullable: false },
  { name: "added", type: "date", nullable: false },
];

const RESOURCE = "conformance_items";

class ApiError extends Error {
  constructor(
    readonly status: number,
    readonly code: string,
    detail: string,
  ) {
    super(detail);
  }
}

const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });

type Where = { field: string; op: string; value?: unknown };

function field(name: string): Field {
  const found = FIELDS.find((f) => f.name === name);
  if (!found) throw new ApiError(400, "unknown_field", `There is no field "${name}".`);
  return found;
}

function compare(a: string | number, b: unknown): number {
  if (typeof a === "number") {
    if (typeof b !== "number") throw new ApiError(400, "bad_request", "A number field is compared with a number.");
    return a - b;
  }
  if (typeof b !== "string") throw new ApiError(400, "bad_request", "A text or date field is compared with text.");
  return a < b ? -1 : a > b ? 1 : 0;
}

function holds(item: StockItem, where: Where): boolean {
  const value = item[field(where.field).name] ?? null;
  if (where.op === "null") return value === null;
  if (where.op === "notnull") return value !== null;
  if (value === null) return false;
  const text = () => {
    if (typeof where.value !== "string") throw new ApiError(400, "bad_request", `"${where.op}" takes text.`);
    return [String(value).toLowerCase(), where.value.toLowerCase()] as const;
  };
  switch (where.op) {
    case "eq":
      return compare(value, where.value) === 0;
    case "ne":
      return compare(value, where.value) !== 0;
    case "lt":
      return compare(value, where.value) < 0;
    case "lte":
      return compare(value, where.value) <= 0;
    case "gt":
      return compare(value, where.value) > 0;
    case "gte":
      return compare(value, where.value) >= 0;
    case "in":
      if (!Array.isArray(where.value)) throw new ApiError(400, "bad_request", '"in" takes a list.');
      return where.value.some((v) => compare(value, v) === 0);
    case "contains":
      return text()[0].includes(text()[1]);
    case "prefix":
      return text()[0].startsWith(text()[1]);
    case "suffix":
      return text()[0].endsWith(text()[1]);
    default:
      throw new ApiError(400, "bad_request", `There is no op "${where.op}".`);
  }
}

function sorted(items: StockItem[], sort: string | null): StockItem[] {
  if (!sort) return items;
  const keys = sort.split(",").map((part) => {
    const [name = "", direction = "asc", nulls = "nulls_last"] = part.split(":");
    if (!["asc", "desc"].includes(direction) || !["nulls_first", "nulls_last"].includes(nulls)) throw new ApiError(400, "bad_request", `Cannot sort by "${part}".`);
    return { name: field(name).name, desc: direction === "desc", first: nulls === "nulls_first" };
  });
  return [...items].sort((a, b) => {
    for (const key of keys) {
      const x = a[key.name] ?? null;
      const y = b[key.name] ?? null;
      if (x === null || y === null) {
        if (x === null && y === null) continue;
        return (x === null) === key.first ? -1 : 1;
      }
      const result = compare(x, y);
      if (result !== 0) return key.desc ? -result : result;
    }
    return 0;
  });
}

const whole = (text: string | null, name: string): number | undefined => {
  if (text === null) return undefined;
  if (!/^\d+$/.test(text)) throw new ApiError(400, "bad_request", `${name} must be a whole number.`);
  return Number(text);
};

/**
 * The API as a function from a `Request` to a `Response`, holding `items`.
 * In the recipe's test it stands in for the network: pass
 * `(input, init) => api(new Request(input, init))` as the adapter's `fetch`.
 */
export function stockApi(items: readonly StockItem[]): (request: Request) => Promise<Response> {
  return async (request) => {
    // What `fetch` itself does with a request that was stopped.
    if (request.signal.aborted) throw new DOMException("This operation was aborted", "AbortError");
    try {
      if (request.method !== "GET") throw new ApiError(405, "bad_request", "Use GET.");
      const url = new URL(request.url);
      const parts = url.pathname.split("/").filter(Boolean);
      if (parts[0] !== "v1" || parts[1] !== "resources") throw new ApiError(404, "not_found", "No such path.");
      if (parts.length === 2) return json(200, { resources: [{ name: RESOURCE, title: "Stock items" }] });
      if (parts[2] !== RESOURCE) throw new ApiError(404, "unknown_resource", `There is no resource "${parts[2]}".`);
      if (parts[3] === "schema" && parts.length === 4) return json(200, { name: RESOURCE, fields: FIELDS });
      if (parts[3] !== "items" || parts.length !== 4) throw new ApiError(404, "not_found", "No such path.");

      const wheres = url.searchParams.getAll("where").map((text) => {
        try {
          const where = JSON.parse(text) as Where;
          if (typeof where?.field !== "string" || typeof where.op !== "string") throw new Error("shape");
          return where;
        } catch {
          throw new ApiError(400, "bad_request", "where must be a JSON object with field and op.");
        }
      });
      const matching = sorted(items.filter((item) => wheres.every((where) => holds(item, where))), url.searchParams.get("sort"));
      const names = url.searchParams.get("fields")?.split(",").map((name) => field(name).name);
      const offset = whole(url.searchParams.get("offset"), "offset") ?? 0;
      const limit = whole(url.searchParams.get("limit"), "limit");
      const page = matching.slice(offset, limit === undefined ? undefined : offset + limit);
      return json(200, { items: names ? page.map((item) => Object.fromEntries(names.map((name) => [name, item[name] ?? null]))) : page, total: matching.length });
    } catch (error) {
      if (error instanceof ApiError) return json(error.status, { error: { code: error.code, detail: error.message } });
      return json(500, { error: { code: "internal", detail: "Something went wrong." } });
    }
  };
}

The adapter

Writing it is mostly a mapping. Each part of a ViewQuery becomes one of the API's own parameters, and the API does the work:

ViewQueryThe API
filtersone where each; BETWEEN is gte and lte, and NOT_IN is notnull and one ne for each value, since the API has neither
sortssort=field:asc:nulls_last,...
columnsfields
pagelimit and offset
countthe reply's total, asked for with limit=0
a COUNT with no groupingtotal again
group_by, other aggregates, buckets, samples, cursors, explain, time travelrefused, with an error that says the API cannot

Three things are not mapping:

  • The base query. The API runs no SQL, so the adapter answers SELECT * FROM <resource> and refuses anything else. That is also what makes it read-only.
  • The reply is JSON and components read Arrow. The adapter asks the API for its schema, builds an Arrow table with a type for each field (so a result with no rows still has its columns), and frames it with encodeTable as a header, batches and a footer.
  • What the API cannot do is refused, never finished in the browser. There is no line here that filters, sorts or trims rows.

restDataSource.ts:

ts
import { create } from "@bufbuild/protobuf";
import { type DataSource, QueryError, encodeTable } from "@surfaces-ui/data";
import {
  type Aggregate,
  AggregateFunction,
  CancelRequestSchema,
  CancelResponseSchema,
  CountRequestSchema,
  CountResponseSchema,
  DescribeTableRequestSchema,
  DescribeTableResponseSchema,
  ExecuteRequestSchema,
  ExecuteResponseSchema,
  type Filter,
  FilterOperator,
  ListCatalogsResponseSchema,
  ListSchemasRequestSchema,
  ListSchemasResponseSchema,
  ListSnapshotsResponseSchema,
  ListSourcesResponseSchema,
  ListTablesRequestSchema,
  ListTablesResponseSchema,
  NoticeSeverity,
  NullOrder,
  RewriteMode,
  SortDirection,
  TableKind,
  TestSourceResponseSchema,
  type Value,
  type ViewQuery,
} from "@surfaces-ui/proto";
import { type DataType, DateDay, Float64, Int32, Table, Utf8, vectorFromArray } from "apache-arrow";

export interface RestDataSourceOptions {
  /** Where the stock API lives, e.g. "https://stock.example.com". */
  baseUrl: string;
  /** Defaults to the global `fetch`. */
  fetch?: typeof fetch;
  /** The id of the one source this API is. Defaults to "stock". */
  sourceId?: string;
}

type FieldType = "integer" | "number" | "string" | "date";
interface ApiField {
  name: string;
  type: FieldType;
  nullable: boolean;
}
type ApiValue = string | number | null;
interface Where {
  field: string;
  op: string;
  value?: ApiValue | ApiValue[];
}
interface Items {
  items: Record<string, ApiValue>[];
  total: number;
}

// The API has no catalogs or schemas; these two names stand for "the API" and its version.
const CATALOG = "api";
const SCHEMA = "v1";

// The API takes no SQL. The one statement that can be answered is "every item of a resource".
const SELECT_ALL = /^\s*select\s+\*\s+from\s+(?:"?[A-Za-z_][\w$]*"?\.){0,2}"?([A-Za-z_][\w$]*)"?\s*;?\s*$/i;

const ARROW: Record<FieldType, () => DataType> = {
  integer: () => new Int32(),
  number: () => new Float64(),
  string: () => new Utf8(),
  date: () => new DateDay(),
};

const CODES: Record<string, string> = { unknown_field: "UNKNOWN_COLUMN" };

/** The resource a base query reads, or a refusal that says why it cannot be answered. */
function resourceOf(query: ViewQuery | undefined): string {
  const sql = query?.baseSql ?? "";
  const name = SELECT_ALL.exec(sql)?.[1];
  if (name) return name;
  if (/;\s*\S/.test(sql)) throw new QueryError("Only one statement can be run, and the stock API runs none but SELECT * FROM <resource>.", { code: "MULTIPLE_STATEMENTS" });
  if (!/^\s*(select|with)\b/i.test(sql)) throw new QueryError("The stock API is read-only: it only answers SELECT * FROM <resource>.", { code: "NOT_READ_ONLY" });
  throw new QueryError('The stock API runs no SQL. The only query it can answer is "SELECT * FROM <resource>"; filters, sorts, columns and the page go in the view query.', { code: "ENGINE" });
}

/** One filter value as the API takes it for a field of this type. */
function apiValue(value: Value | undefined, field: ApiField | undefined, column: string): string | number {
  const kind = value?.kind;
  if (!kind || kind.case === undefined) throw new QueryError(`The filter on ${column} is missing a value.`, { code: "ENGINE" });
  if (kind.case === "boolValue") throw new QueryError(`The stock API has no true or false values to compare ${column} with.`, { code: "ENGINE" });
  const raw: string | number = typeof kind.value === "bigint" ? Number(kind.value) : (kind.value as string | number);
  if (!field) return kind.case === "decimalValue" ? Number(raw) : raw;
  if (field.type === "integer" || field.type === "number") {
    const number = typeof raw === "number" ? raw : raw.trim() === "" ? Number.NaN : Number(raw);
    if (!Number.isFinite(number)) throw new QueryError(`${column} is a number, and "${raw}" is not one.`, { code: "ENGINE" });
    return number;
  }
  if (field.type === "date") {
    const text = String(raw);
    const day = /^(\d{4}-\d{2}-\d{2})(?:[T ]00:00(?::00(?:\.0+)?)?(?:Z|[+-]00:?00)?)?$/.exec(text)?.[1];
    if (!day) throw new QueryError(`${column} is a date with no time of day (YYYY-MM-DD), and the stock API cannot compare it with "${text}".`, { code: "ENGINE" });
    return day;
  }
  return String(raw);
}

/** A filter as the API's `where` objects. Every one must hold, so BETWEEN and NOT IN are made of several. */
function wheresOf(filter: Filter, fields: ApiField[]): Where[] {
  const column = filter.column;
  const field = fields.find((f) => f.name === column);
  const need = (count: number) => {
    if (filter.values.length !== count) throw new QueryError(`The filter on ${column} takes ${count === 1 ? "one value" : `${count} values`}, and got ${filter.values.length}.`, { code: "ENGINE" });
  };
  const one = (op: string): Where[] => {
    need(1);
    return [{ field: column, op, value: apiValue(filter.values[0], field, column) }];
  };
  const text = (op: string): Where[] => {
    need(1);
    const kind = filter.values[0]?.kind;
    if (kind?.case !== "stringValue") throw new QueryError(`The stock API matches text only: the filter on ${column} needs a text value.`, { code: "ENGINE" });
    return [{ field: column, op, value: kind.value }];
  };
  switch (filter.operator) {
    case FilterOperator.EQ:
      return one("eq");
    case FilterOperator.NEQ:
      return one("ne");
    case FilterOperator.LT:
      return one("lt");
    case FilterOperator.LTE:
      return one("lte");
    case FilterOperator.GT:
      return one("gt");
    case FilterOperator.GTE:
      return one("gte");
    case FilterOperator.IN:
      return [{ field: column, op: "in", value: filter.values.map((v) => apiValue(v, field, column)) }];
    case FilterOperator.NOT_IN:
      // No "not in" in the API: "differs from each" is the same thing. A null is in neither, as in SQL.
      return [{ field: column, op: "notnull" }, ...filter.values.map((v) => ({ field: column, op: "ne", value: apiValue(v, field, column) }))];
    case FilterOperator.BETWEEN:
      // No "between" in the API: from the first value to the second, both included.
      need(2);
      return [
        { field: column, op: "gte", value: apiValue(filter.values[0], field, column) },
        { field: column, op: "lte", value: apiValue(filter.values[1], field, column) },
      ];
    case FilterOperator.CONTAINS:
      return text("contains");
    case FilterOperator.STARTS_WITH:
      return text("prefix");
    case FilterOperator.ENDS_WITH:
      return text("suffix");
    case FilterOperator.IS_NULL:
      return [{ field: column, op: "null" }];
    case FilterOperator.IS_NOT_NULL:
      return [{ field: column, op: "notnull" }];
    default:
      throw new QueryError(`The filter on ${column} has no operator the stock API knows.`, { code: "ENGINE" });
  }
}

/** Refuses what the API has no way to do, in words. */
function refuseUnsupported(query: ViewQuery | undefined): void {
  const no = (what: string): never => {
    throw new QueryError(`The stock API cannot ${what}.`, { code: "ENGINE" });
  };
  if (!query) return;
  if (query.parameters.length > 0) no("take query parameters: it runs no SQL");
  if (query.groupBy.length > 0) no("group rows");
  if (query.buckets.length > 0) no("bucket rows by time or by width");
  if (query.derived.length > 0) no("work out derived measures");
  if (query.sample && query.sample.rows > 0) no("take a random sample");
  if (query.page?.cursor) no("page by cursor: it pages by limit and offset");
  for (const item of query.aggregates) {
    if (item.function !== AggregateFunction.COUNT) no("aggregate: the only summary it gives is a count of the items that match");
  }
}

/**
 * A DataSource over the stock list's REST API.
 *
 * Each part of a `ViewQuery` becomes a query parameter of
 * `GET /v1/resources/{name}/items`: filters are `where`, sorts are `sort`,
 * columns are `fields` and the page is `limit` and `offset`. The API does the
 * work and answers with only that window; nothing is filtered, sorted or
 * trimmed here. What the API cannot do (SQL other than
 * `SELECT * FROM <resource>`, grouping, aggregates other than a count,
 * buckets, samples, cursors, plans, time travel) is refused with an error
 * that says so.
 */
export function restDataSource(options: RestDataSourceOptions): DataSource {
  const base = options.baseUrl.replace(/\/+$/, "");
  const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
  const sourceId = options.sourceId ?? "stock";
  const running = new Map<string, AbortController>();

  const get = async <T>(path: string, params?: URLSearchParams, signal?: AbortSignal): Promise<T> => {
    const search = params?.toString();
    let reply: Response;
    try {
      reply = await doFetch(`${base}${path}${search ? `?${search}` : ""}`, { method: "GET", headers: { accept: "application/json" }, signal });
    } catch (error) {
      if (signal?.aborted) throw new QueryError("The query was cancelled.", { code: "CANCELLED" });
      throw new Error(`Could not reach the stock API: ${error instanceof Error ? error.message : String(error)}`);
    }
    const text = await reply.text();
    let body: unknown;
    try {
      body = JSON.parse(text);
    } catch {
      body = undefined;
    }
    if (!reply.ok) {
      const error = (body as { error?: { code?: unknown; detail?: unknown } } | undefined)?.error;
      if (typeof error?.detail === "string" && error.detail !== "") {
        const code = typeof error.code === "string" ? error.code : "";
        throw new QueryError(error.detail, { code: CODES[code] ?? "ENGINE", engineCode: code });
      }
      throw new Error(`The stock API answered ${reply.status}${reply.statusText ? ` ${reply.statusText}` : ""}.`);
    }
    if (body === undefined) throw new Error("The stock API answered with something that is not JSON.");
    return body as T;
  };

  const checkSource = (id: string | undefined) => {
    if ((id ?? "") !== sourceId) throw new QueryError(`There is no source "${id ?? ""}" here. The only one is "${sourceId}".`, { code: "ENGINE" });
  };

  const resourcePath = (name: string) => `/v1/resources/${encodeURIComponent(name)}`;
  const fieldsOf = async (resource: string, signal?: AbortSignal) => (await get<{ fields: ApiField[] }>(`${resourcePath(resource)}/schema`, undefined, signal)).fields;

  /** The `where` parameters of a view query. */
  const paramsOf = (query: ViewQuery | undefined, fields: ApiField[], extra: Where[] = []): URLSearchParams => {
    const params = new URLSearchParams();
    for (const where of [...(query?.filters ?? []).flatMap((f) => wheresOf(f, fields)), ...extra]) params.append("where", JSON.stringify(where));
    return params;
  };

  /** The `where`, `sort` and `fields` parameters of a view query over items. */
  const itemParams = (query: ViewQuery | undefined, fields: ApiField[]): URLSearchParams => {
    const params = paramsOf(query, fields);
    const sorts = query?.sorts ?? [];
    if (sorts.length > 0) {
      params.set(
        "sort",
        sorts.map((s) => `${s.column}:${s.direction === SortDirection.DESC ? "desc" : "asc"}:${s.nulls === NullOrder.FIRST ? "nulls_first" : "nulls_last"}`).join(","),
      );
    }
    if (query && query.columns.length > 0) params.set("fields", query.columns.join(","));
    return params;
  };

  /** How many items match the filters, from the API's own `total`, asking for no items. */
  const total = async (resource: string, query: ViewQuery | undefined, fields: ApiField[], extra: Where[], signal?: AbortSignal): Promise<number> => {
    const params = paramsOf(query, fields, extra);
    params.set("limit", "0");
    return (await get<Items>(`${resourcePath(resource)}/items`, params, signal)).total;
  };

  /** A count aggregate, as the extra condition it puts on the items counted. */
  const countWhere = (item: Aggregate): Where[] => (item.column === "" ? [] : [{ field: item.column, op: "notnull" }]);

  /** Checks that the sorts, columns and page of a summary name only its own outputs. A summary is one row. */
  const checkSummary = (query: ViewQuery): string[] => {
    const aliases = query.aggregates.map((a) => a.alias);
    if (aliases.some((a) => a === "")) throw new QueryError("Every aggregate needs an alias.", { code: "ENGINE" });
    for (const name of [...query.sorts.map((s) => s.column), ...query.columns]) {
      if (!aliases.includes(name)) throw new QueryError(`There is no column "${name}" in the summary.`, { code: "UNKNOWN_COLUMN" });
    }
    if ((query.page?.offset ?? 0n) > 0n) throw new QueryError("The stock API cannot page a summary: it is one row.", { code: "ENGINE" });
    return query.columns.length > 0 ? query.columns : aliases;
  };

  return {
    async *execute(init, callOptions) {
      const started = Date.now();
      const request = create(ExecuteRequestSchema, init);
      checkSource(request.sourceId);
      if (request.timeTravel) throw new QueryError("The stock API has no time travel.", { code: "ENGINE" });
      const query = request.query;
      const resource = resourceOf(query);
      refuseUnsupported(query);

      // One signal for the caller's abort and for cancel(queryId).
      const controller = new AbortController();
      const outer = callOptions?.signal;
      const stop = () => controller.abort();
      if (outer?.aborted) controller.abort();
      else outer?.addEventListener("abort", stop, { once: true });
      if (request.queryId) running.set(request.queryId, controller);
      const signal = controller.signal;
      const cancelled = () => new QueryError("The query was cancelled.", { code: "CANCELLED" });

      try {
        if (signal.aborted) throw cancelled();
        const fields = await fieldsOf(resource, signal);
        let table: Table;
        let more = false;
        const notices: { severity: NoticeSeverity; code: string; message: string }[] = [];
        let nativeTypes: string[];

        if (query && query.aggregates.length > 0) {
          // Counts only: each is the API's `total` for the filters, read without any items.
          const names = checkSummary(query);
          const counts = new Map<string, number>();
          for (const item of query.aggregates) counts.set(item.alias, await total(resource, query, fields, countWhere(item), signal));
          table = new Table(Object.fromEntries(names.map((name) => [name, vectorFromArray([counts.get(name) ?? null], new Float64())])));
          nativeTypes = names.map(() => "number");
        } else {
          const params = itemParams(query, fields);
          const sorts = query?.sorts ?? [];
          const columns = query?.columns ?? [];
          const limit = query?.page?.limit ?? 0;
          const offset = query?.page?.offset ?? 0n;
          if (limit > 0) params.set("limit", String(limit));
          if (offset > 0n) params.set("offset", String(offset));
          const reply = await get<Items>(`${resourcePath(resource)}/items`, params, signal);

          // The reply as an Arrow table, in the order asked for, typed by the API's schema.
          const names = columns.length > 0 ? columns : fields.map((f) => f.name);
          const typed = names.map((name) => {
            const field = fields.find((f) => f.name === name);
            if (!field) throw new QueryError(`There is no field "${name}".`, { code: "UNKNOWN_COLUMN" });
            return field;
          });
          table = new Table(
            Object.fromEntries(
              typed.map((field) => {
                const cells = reply.items.map((item) => {
                  const cell = item[field.name] ?? null;
                  return field.type === "date" && typeof cell === "string" ? Date.parse(`${cell}T00:00:00Z`) : cell;
                });
                return [field.name, vectorFromArray(cells, ARROW[field.type]())];
              }),
            ),
          );
          nativeTypes = typed.map((f) => f.type);
          more = Number(offset) + reply.items.length < reply.total;
          if (limit > 0 && sorts.length === 0) notices.push({ severity: NoticeSeverity.INFO, code: "UNSTABLE_PAGE_ORDER", message: "Paging without a sort: the stock API gives no fixed order." });
        }

        const encoded = encodeTable(table, request.batchRows);
        yield create(ExecuteResponseSchema, {
          part: {
            case: "header",
            value: {
              arrowSchema: encoded.schema,
              executedSql: query?.baseSql ?? "",
              rewriteMode: RewriteMode.NONE,
              queryId: request.queryId,
              notices,
              columns: table.schema.fields.map((f, i) => ({ name: f.name, nativeType: nativeTypes[i] ?? "", sortable: true, filterable: true })),
            },
          },
        });
        for (const batch of encoded.batches) {
          if (signal.aborted) throw cancelled();
          yield create(ExecuteResponseSchema, { part: { case: "batch", value: { arrowBatch: batch.bytes, rowCount: BigInt(batch.rows) } } });
        }
        if (signal.aborted) throw cancelled();
        yield create(ExecuteResponseSchema, {
          part: { case: "footer", value: { totalRowsReturned: BigInt(table.numRows), nextCursor: "", truncated: more, elapsedMs: BigInt(Date.now() - started) } },
        });
      } finally {
        outer?.removeEventListener("abort", stop);
        if (request.queryId && running.get(request.queryId) === controller) running.delete(request.queryId);
      }
    },

    async count(init, callOptions) {
      const request = create(CountRequestSchema, init);
      checkSource(request.sourceId);
      if (request.timeTravel) throw new QueryError("The stock API has no time travel.", { code: "ENGINE" });
      const signal = callOptions?.signal;
      if (signal?.aborted) throw new QueryError("The query was cancelled.", { code: "CANCELLED" });
      const query = request.query;
      const resource = resourceOf(query);
      refuseUnsupported(query);
      const fields = await fieldsOf(resource, signal);
      if (query && query.aggregates.length > 0) {
        // A summary with no grouping is one row. The filters are still sent, so a bad one is refused.
        checkSummary(query);
        await total(resource, query, fields, [], signal);
        return create(CountResponseSchema, { rowCount: 1n, estimated: false });
      }
      // The sorts and columns go too, so the API refuses a name it does not know, as execute would.
      const params = itemParams(query, fields);
      params.set("limit", "0");
      const reply = await get<Items>(`${resourcePath(resource)}/items`, params, signal);
      return create(CountResponseSchema, { rowCount: BigInt(reply.total), estimated: false });
    },

    async explain() {
      throw new Error("The stock API has no plan to explain: it runs no SQL.");
    },

    async cancel(init) {
      const controller = running.get(create(CancelRequestSchema, init).queryId);
      if (!controller) return create(CancelResponseSchema, { cancelled: false });
      controller.abort();
      return create(CancelResponseSchema, { cancelled: true });
    },

    async listSources() {
      return create(ListSourcesResponseSchema, {
        sources: [{ id: sourceId, displayName: "Stock API", readOnly: true, capabilities: { cancel: true, explain: false, exactCount: true } }],
      });
    },

    async testSource(init, callOptions) {
      const started = Date.now();
      if (init.target?.case !== "id") throw new Error("Only the stock API itself can be tested here.");
      checkSource(init.target.value);
      try {
        const { resources } = await get<{ resources: { name: string }[] }>("/v1/resources", undefined, callOptions?.signal);
        return create(TestSourceResponseSchema, { ok: true, message: "Connected", elapsedMs: BigInt(Date.now() - started), checks: resources.map((r) => ({ name: r.name, ok: true, message: "Listed" })) });
      } catch (error) {
        return create(TestSourceResponseSchema, { ok: false, message: error instanceof Error ? error.message : String(error), elapsedMs: BigInt(Date.now() - started) });
      }
    },

    async listCatalogs(init) {
      checkSource(init.sourceId);
      return create(ListCatalogsResponseSchema, { catalogs: [{ name: CATALOG, comment: "The stock API" }] });
    },

    async listSchemas(init) {
      const request = create(ListSchemasRequestSchema, init);
      checkSource(request.sourceId);
      return create(ListSchemasResponseSchema, { schemas: [{ catalog: CATALOG, name: SCHEMA }] });
    },

    async listTables(init, callOptions) {
      const request = create(ListTablesRequestSchema, init);
      checkSource(request.sourceId);
      const { resources } = await get<{ resources: { name: string; title?: string }[] }>("/v1/resources", undefined, callOptions?.signal);
      // The API lists every resource at once and has no search, so the names (not rows) are matched and paged here.
      const search = request.search.toLowerCase();
      const found = resources.filter((r) => r.name.toLowerCase().includes(search));
      const from = Number.parseInt(request.pageToken || "0", 10) || 0;
      const to = request.pageSize > 0 ? from + request.pageSize : found.length;
      return create(ListTablesResponseSchema, {
        tables: found.slice(from, to).map((r) => ({ ref: { catalog: CATALOG, schema: SCHEMA, table: r.name }, kind: TableKind.TABLE, comment: r.title ?? "" })),
        nextPageToken: to < found.length ? String(to) : "",
      });
    },

    async describeTable(init, callOptions) {
      const request = create(DescribeTableRequestSchema, init);
      checkSource(request.sourceId);
      const name = request.ref?.table ?? "";
      if (name === "") throw new Error("Name the table to describe.");
      const fields = await fieldsOf(name, callOptions?.signal);
      const rows = await total(name, undefined, fields, [], callOptions?.signal);
      return create(DescribeTableResponseSchema, {
        table: {
          summary: { ref: { catalog: CATALOG, schema: SCHEMA, table: name }, kind: TableKind.TABLE },
          rowCount: BigInt(rows),
          columns: fields.map((f, i) => ({ name: f.name, nativeType: f.type, arrowType: String(ARROW[f.type]()), nullable: f.nullable, ordinal: i + 1 })),
        },
      });
    },

    // No time travel, so no snapshots.
    async listSnapshots(init) {
      checkSource(init.sourceId);
      return create(ListSnapshotsResponseSchema, {});
    },
  };
}

Prove it

The API holds the standard fixture, conformanceRows. What the API cannot do is listed under unsupported: each is still tried, and passes as a skip only because the adapter refuses it in words.

conformance.test.ts:

ts
import fs from "node:fs";
import { checkDataSource, conformanceRows, dataSourceChecks, vitestConformance } from "@surfaces-ui/data/conformance";
import { beforeAll, describe, it } from "vitest";
import { restDataSource } from "./restDataSource.js";
import { stockApi } from "./stockApi.js";

// The API stands in for the network, holding the standard fixture rows.
const api = stockApi(conformanceRows);
const source = restDataSource({ baseUrl: "https://stock.example.test", fetch: (input, init) => api(new Request(input, init)) });

// One test per check: a rule the adapter breaks shows up by name, with what was sent and what came back.
vitestConformance({ beforeAll, describe, it }, "restDataSource keeps every rule of a DataSource", dataSourceChecks, async () => {
  const report = await checkDataSource(source, {
    sourceId: "stock",
    subject: "rest-datasource recipe (restDataSource)",
    // The stock API cannot group or aggregate. The adapter refuses each in words.
    unsupported: ["group", "count.grouped"],
  });
  if (process.env.SURFACES_CONFORMANCE_OUT) fs.appendFileSync(process.env.SURFACES_CONFORMANCE_OUT, `${JSON.stringify(report)}\n`);
  return report;
});

Run it and each check is a test:

text
 ✓ filter.between: BETWEEN keeps rows from the first value to the second, both included
 ✓ bind.probes: A value that looks like SQL is compared as text
 ✓ page.walk: Pages cover every row once
 ↓ group.count: Grouping gives one row per value, null included, with COUNT of rows and of non-null values

A runner shows a skipped test without its reason. To read the reasons, print the report: console.log(formatReport(report)) in a script, or write it to a file as the test above does when SURFACES_CONFORMANCE_OUT names one.

The suite asks for sums beside its counts, so it never reaches the one summary this API can give. The recipe's own test covers that, and that the requests sent are the ones the table above says:

restDataSource.test.ts:

ts
import { collect, queryErrorInfo, toRows } from "@surfaces-ui/data";
import { conformanceRows } from "@surfaces-ui/data/conformance";
import { AggregateFunction, FilterOperator, SortDirection } from "@surfaces-ui/proto";
import { describe, expect, it } from "vitest";
import { restDataSource } from "./restDataSource.js";
import { stockApi } from "./stockApi.js";

/** The API standing in for the network, keeping every address it was asked for. */
function setup() {
  const api = stockApi(conformanceRows);
  const asked: URL[] = [];
  const source = restDataSource({
    baseUrl: "https://stock.example.test",
    fetch: (input, init) => {
      asked.push(new URL(String(input)));
      return api(new Request(input, init));
    },
  });
  const wheres = () => asked.at(-1)!.searchParams.getAll("where").map((text) => JSON.parse(text) as unknown);
  return { source, asked, wheres };
}
const base = { baseSql: "SELECT * FROM conformance_items" };
const int = (value: number) => ({ kind: { case: "intValue" as const, value: BigInt(value) } });

describe("a DataSource over a REST API", () => {
  it("turns a ViewQuery into the API's own parameters, and the API does the work", async () => {
    const { source, asked } = setup();
    const result = await collect(
      source.execute({
        sourceId: "stock",
        query: { ...base, filters: [{ column: "category", operator: FilterOperator.EQ, values: [{ kind: { case: "stringValue", value: "tool" } }] }], sorts: [{ column: "price", direction: SortDirection.DESC }], columns: ["id", "price"], page: { limit: 2, offset: 1n } },
      }),
    );
    expect(toRows(result.table)).toEqual([{ id: 4, price: 19.5 }, { id: 5, price: 14.5 }]);
    const params = asked.at(-1)!.searchParams;
    expect(asked.at(-1)!.pathname).toBe("/v1/resources/conformance_items/items");
    expect(Object.fromEntries(params)).toEqual({ where: '{"field":"category","op":"eq","value":"tool"}', sort: "price:desc:nulls_last", fields: "id,price", limit: "2", offset: "1" });
    expect(result.footer.truncated).toBe(true);
  });

  it("makes the operators the API lacks out of the ones it has", async () => {
    const { source, wheres } = setup();
    const between = await collect(source.execute({ sourceId: "stock", query: { ...base, filters: [{ column: "quantity", operator: FilterOperator.BETWEEN, values: [int(3), int(8)] }] } }));
    expect(wheres()).toEqual([{ field: "quantity", op: "gte", value: 3 }, { field: "quantity", op: "lte", value: 8 }]);
    expect(toRows(between.table).map((r) => r.id)).toEqual([4, 5, 6, 9, 12]);
    await collect(source.execute({ sourceId: "stock", query: { ...base, filters: [{ column: "quantity", operator: FilterOperator.NOT_IN, values: [int(3), int(8)] }] } }));
    expect(wheres()).toEqual([{ field: "quantity", op: "notnull" }, { field: "quantity", op: "ne", value: 3 }, { field: "quantity", op: "ne", value: 8 }]);
  });

  it("answers a count from the API's total, asking for no items", async () => {
    // The one summary this API can give. The conformance suite asks for sums beside its counts, so it does not reach this.
    const { source, asked } = setup();
    const query = { ...base, filters: [{ column: "category", operator: FilterOperator.EQ, values: [{ kind: { case: "stringValue" as const, value: "tool" } }] }], aggregates: [{ function: AggregateFunction.COUNT, column: "", alias: "items" }, { function: AggregateFunction.COUNT, column: "quantity", alias: "counted" }] };
    const result = await collect(source.execute({ sourceId: "stock", query }));
    expect(toRows(result.table)).toEqual([{ items: 4, counted: 3 }]);
    expect(asked.filter((url) => url.pathname.endsWith("/items")).every((url) => url.searchParams.get("limit") === "0")).toBe(true);
    expect((await source.count({ sourceId: "stock", query })).rowCount).toBe(1n);
  });

  it("refuses what the API cannot do, in words", async () => {
    const { source, asked } = setup();
    const grouped = await collect(source.execute({ sourceId: "stock", query: { ...base, groupBy: ["category"], aggregates: [{ function: AggregateFunction.SUM, column: "quantity", alias: "total" }] } })).catch((e: unknown) => e);
    expect(queryErrorInfo(grouped)).toMatchObject({ message: "The stock API cannot group rows.", code: "ENGINE" });
    const sql = await collect(source.execute({ sourceId: "stock", query: { baseSql: "SELECT name FROM conformance_items WHERE quantity > 3" } })).catch((e: unknown) => e);
    expect(queryErrorInfo(sql).message).toMatch(/runs no SQL/);
    expect(asked).toEqual([]);
    const unknown = await collect(source.execute({ sourceId: "stock", query: { ...base, sorts: [{ column: "colour" }] } })).catch((e: unknown) => e);
    expect(queryErrorInfo(unknown)).toMatchObject({ message: 'There is no field "colour".', code: "UNKNOWN_COLUMN", engineCode: "unknown_field" });
  });
});

It has not been run against a real HTTP server: the API here is a function standing in for the network.

Source and test: apps/recipes/src/rest-datasource