export type ApiOperation = Readonly<{ method: string; path: string; operationId: string; auth: "none" | "external-session"; timeoutMs: number | null; idempotency: "safe" | "keyed" | "none"; retry: "runtime" | "never"; requestSource: "search" | "body" | "none"; requestSchema: string; responseSchema: string; owner: string; contractVersion?: 2; protocol?: "REST"; semantics?: "QUERY" | "COMMAND"; replayPolicy?: "SAFE" | "IDEMPOTENT" | "KEYED_COMMAND" | "NON_REPLAYABLE"; idempotencyKeyPolicy?: "NONE" | "REQUIRED"; mapperId?: string; successStatuses?: readonly number[]; responseMediaTypes?: readonly string[]; maxResponseBytes?: number; providerId?: string; authProfileId?: string; csrfProfileId?: string; pathSchema?: string; pathParameterNames?: readonly string[]; maxEncodedSearchBytes?: number; }>; /** * 07-02. A V2 row is the declaration `check:registries` (FE-REG-API) governs; * it is not what executes. The executed copy of the same HTTP API is the V3 * descriptor (`InstalledHttpContract`) in the feature's contract contribution. * A feature writes both, and `tests/unit/http-operation-v2-v3-parity.test.ts` * checks they name the same operations, method, path, statuses, limits, auth * profile, replay and write semantics, request body and schema ids. The * deadline is not compared: V2 `timeoutMs` is `null` while V3 always has one. */ export type RestOperationV2 = ApiOperation & Readonly<{ contractVersion: 2; protocol: "REST"; semantics: "QUERY" | "COMMAND"; replayPolicy: | "SAFE" | "IDEMPOTENT" | "KEYED_COMMAND" | "NON_REPLAYABLE"; idempotencyKeyPolicy: "NONE" | "REQUIRED"; mapperId: string; successStatuses: readonly number[]; responseMediaTypes: readonly string[]; maxResponseBytes: number; providerId: string; authProfileId: string; csrfProfileId: string; pathSchema: string; pathParameterNames: readonly string[]; maxEncodedSearchBytes: number; }>; const MAX_RESPONSE_BYTES = 8 * 1024 * 1024; const OPERATION_ID = /^[A-Z][A-Z0-9_]{2,79}$/; const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/; export function defineRestOperation( operation: RestOperationV2, ): RestOperationV2 { validateRestOperation(operation); return Object.freeze({ ...operation, successStatuses: Object.freeze([...operation.successStatuses]), responseMediaTypes: Object.freeze([...operation.responseMediaTypes]), pathParameterNames: Object.freeze([...operation.pathParameterNames]), }); } export function composeApiOperations( contributions: readonly Readonly>[], ): Readonly> { const result: Record = Object.create(null); for (const contribution of contributions) { for (const [registryId, operation] of Object.entries(contribution)) { if (registryId !== operation.operationId) { throw new TypeError("API operation registry key does not match operationId."); } if (Object.hasOwn(result, registryId)) { throw new TypeError(`Duplicate API operation: ${registryId}`); } if (operation.contractVersion === 2) { validateRestOperation(operation as RestOperationV2); } result[registryId] = operation; } } return Object.freeze(result); } export function validateApiRuntimeBindings( operations: Readonly>, schemaMetadata: Readonly>>, schemaCodecs: Readonly>>, mappers: Readonly< Record< string, Readonly<{ mapperId: string; inputSchemaId: string; maxOutputItems: number }> > >, ): true { for (const operation of Object.values(operations)) { if (operation.contractVersion !== 2) continue; for (const schemaId of [ operation.pathSchema, operation.requestSchema, operation.responseSchema, ]) { if ( !schemaId || schemaMetadata[schemaId]?.schemaId !== schemaId || schemaCodecs[schemaId]?.schemaId !== schemaId ) { throw new TypeError( `Unresolved API schema binding: ${operation.operationId}`, ); } } const mapper = mappers[operation.mapperId ?? ""]; if ( !mapper || mapper.mapperId !== operation.mapperId || mapper.inputSchemaId !== operation.responseSchema || mapper.maxOutputItems < 1 ) { throw new TypeError( `Unresolved API mapper binding: ${operation.operationId}`, ); } } return true; } function validateRestOperation(operation: RestOperationV2): void { if ( operation.protocol !== "REST" || !OPERATION_ID.test(operation.operationId) || !operation.owner || !operation.mapperId || !operation.providerId || !operation.authProfileId || !operation.csrfProfileId || !operation.pathSchema || !operation.path.startsWith("/") || operation.path.startsWith("//") || operation.path.includes("?") || operation.path.includes("#") || !Number.isSafeInteger(operation.maxResponseBytes) || operation.maxResponseBytes < 1 || operation.maxResponseBytes > MAX_RESPONSE_BYTES || !Number.isSafeInteger(operation.maxEncodedSearchBytes) || operation.maxEncodedSearchBytes < 0 || operation.maxEncodedSearchBytes > 32_768 || operation.successStatuses.length === 0 || operation.successStatuses.some( (status) => !Number.isInteger(status) || status < 200 || status > 299, ) || new Set(operation.successStatuses).size !== operation.successStatuses.length || operation.responseMediaTypes.length === 0 || operation.responseMediaTypes.some( (value) => !MEDIA_TYPE.test(value) || value !== value.toLowerCase(), ) ) { throw new TypeError(`Invalid REST operation contract: ${operation.operationId}`); } const placeholders = [ ...operation.path.matchAll( /:([A-Za-z][A-Za-z0-9_]*)|\{([A-Za-z][A-Za-z0-9_]*)\}/g, ), ] .map((match) => match[1] ?? match[2] ?? "") .sort(); const codecKeys = [...operation.pathParameterNames].sort(); if ( new Set(codecKeys).size !== codecKeys.length || placeholders.length !== codecKeys.length || placeholders.some((name, index) => name !== codecKeys[index]) ) { throw new TypeError( `REST path codec does not match its template: ${operation.operationId}`, ); } const isQuery = operation.semantics === "QUERY"; // R-7.4. CSRF need is decided from the method (rest-profiles), so a COMMAND // must use an unsafe method. Same binding as browser-rpc and the V3 runtime. if ( !["QUERY", "COMMAND"].includes(operation.semantics) || !["SAFE", "IDEMPOTENT", "KEYED_COMMAND", "NON_REPLAYABLE"].includes( operation.replayPolicy, ) || (!isQuery && !["POST", "PUT", "PATCH", "DELETE"].includes(operation.method)) || (isQuery && !["GET", "HEAD"].includes(operation.method)) || (isQuery && !["SAFE", "IDEMPOTENT"].includes(operation.replayPolicy)) || (operation.replayPolicy === "KEYED_COMMAND" && (operation.idempotencyKeyPolicy !== "REQUIRED" || operation.idempotency !== "keyed")) || (operation.replayPolicy === "NON_REPLAYABLE" && (operation.retry !== "never" || operation.idempotency !== "none")) ) { throw new TypeError(`Incoherent REST replay contract: ${operation.operationId}`); } } export const API_OPERATIONS: Readonly> = Object.freeze({}); export function getApiOperation( operationId: string, operations: Readonly> = API_OPERATIONS, ): ApiOperation { const selected = Object.hasOwn(operations, operationId) ? operations[operationId] : undefined; if (!selected) { throw new Error(`Unregistered API operation: ${operationId}`); } return selected; }