import type { ComposedContractContributions } from "../../../src/contracts/external-contract-runtime.ts"; import { successEnvelope } from "../../mocks/handlers/http-scenarios.ts"; /** * 1103/11-01, 16-03. What `tests/e2e/accessibility.spec.ts` answers a * protected page's API request with. Feature data is not that spec's subject, * so a list read gets an empty list, framed the way the operation's own * descriptor declares: inside the paired backend's Envelope for * `responseEnvelope: "ENVELOPE_V1"`, bare otherwise. A global bare `[]` put * every Envelope feature on the mismatch error screen and still passed. * * The request is matched to an installed GET by method and `pathTemplate`, so * a new feature needs no edit here. A read with a path parameter whose payload * is not a list (a detail page) cannot be answered with an empty list: the * spec renders it in its failure state and says so. Any other request fails * the spec instead of drawing an error screen that passes. */ export type InstalledApiAnswer = | Readonly<{ kind: "empty-list"; operationId: string; body: unknown }> | Readonly<{ kind: "single-resource"; operationId: string; body: unknown }> | Readonly<{ kind: "unanswerable"; request: string; reason?: string }>; const EMPTY_LIST: readonly never[] = Object.freeze([]); function templatePattern(pathTemplate: string): RegExp { const pattern = pathTemplate .split(/\{[^}]+\}/u) .map((part) => part.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")) .join("[^/]+"); return new RegExp(`^${pattern}$`, "u"); } export function answerInstalledApiRequest( contracts: ComposedContractContributions, method: string, pathname: string, ): InstalledApiAnswer { const request = `${method} ${pathname}`; for (const { contract } of contracts.httpByOperationId.values()) { if (contract.method !== method || contract.method !== "GET") continue; if (!templatePattern(contract.pathTemplate).test(pathname)) continue; const body = contract.responseEnvelope === "ENVELOPE_V1" ? successEnvelope([]) : EMPTY_LIST; if (contract.outputValidator.safeParse(EMPTY_LIST).success) { return Object.freeze({ kind: "empty-list", operationId: contract.operationId, body }); } if (contract.pathTemplate.includes("{")) { return Object.freeze({ kind: "single-resource", operationId: contract.operationId, body, }); } return Object.freeze({ kind: "unanswerable", request, reason: `${contract.operationId} reads no single resource and rejects an empty list`, }); } return Object.freeze({ kind: "unanswerable", request }); }