import { describe, expect, it } from "vitest"; import type { RuntimeValidator } from "../../src/contracts/external-contract-runtime.ts"; import type { SchemaDefinition } from "../../src/contracts/schema-registry.ts"; import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts"; import { COMPOSED_CONTRACT_CONTRIBUTIONS, SCHEMA_REGISTRY, } from "../../src/features/loaded-feature-runtimes.ts"; /** * 1103/07-03. FE-REG-SCHEMA rows state each HTTP schema's direction and * unknown-field policy, and `docs/contracts/compatibility.md` builds the * "adding a response field is additive" rule on `STRIP_UNKNOWN`. Nothing at * run time reads those two fields, so they are checked here against the * validators the installed HTTP descriptors run. * * The probe is an object with one key no schema declares, and the same object * as the only item of an array, so it reaches the first object level of an * object or list payload. A validator that rejects it with * `unrecognized_keys` rejects unknown fields; one that reaches the object * without that issue tolerates them. A nested object below that level is not * probed. * * 1106/07-02. Both fields are optional in the row type, and a row that left * them out used to be skipped here. 1105/07-02 grades a response row whose * policy turns `REJECT_UNKNOWN` as breaking, but a row with no policy does not * change when its DTO turns `.strict()`, so nothing saw it. A schema an HTTP * operation uses now fails here without them; the policy only where the probe * reaches an object (`policyProblems`). Route-only rows (`NotFoundSplat`) are * not in `slots` and still need neither. */ const PROBE_KEY = "__unknownFieldProbe"; type ProbedPolicy = "REJECT_UNKNOWN" | "STRIP_UNKNOWN" | "UNREACHED"; function probeUnknownFieldPolicy(validator: RuntimeValidator): ProbedPolicy { const probe = { [PROBE_KEY]: true }; for (const [value, objectPath] of [ [probe, []], [[probe], [0]], ] as const) { const result = validator.safeParse(value); if (result.success) return "STRIP_UNKNOWN"; const atObject = (path: readonly (string | number)[]) => JSON.stringify(path) === JSON.stringify(objectPath); if ( result.issues.some( (issue) => issue.code === "unrecognized_keys" && atObject(issue.path), ) ) { return "REJECT_UNKNOWN"; } // Every issue sits at or above the probed object (wrong type, wrong // shape): the validator never looked inside it, so try the next probe. const unreached = result.issues.every( (issue) => issue.path.length <= objectPath.length && issue.path.every((segment, index) => segment === objectPath[index]), ); if (!unreached) return "STRIP_UNKNOWN"; } return "UNREACHED"; } const slots = COMPOSED_CONTRACT_CONTRIBUTIONS.contributions.flatMap( ({ http }) => http.flatMap(({ contract }) => [ { operationId: contract.operationId, direction: "REQUEST" as const, validator: contract.inputValidator, }, { operationId: contract.operationId, direction: "RESPONSE" as const, validator: contract.outputValidator, }, // 1103/16-04. The failure body is read as a response too. { operationId: contract.operationId, direction: "RESPONSE" as const, validator: contract.problemValidator, }, ]), ); type Slot = Readonly<{ operationId: string; direction: "REQUEST" | "RESPONSE"; validator: RuntimeValidator; }>; type Rows = Readonly>; function directionProblems(used: readonly Slot[], rows: Rows): string[] { return used.flatMap(({ operationId, direction, validator }) => { const declared = rows[validator.schemaId]?.direction; return declared === direction ? [] : [ `${operationId} ${validator.schemaId}: row ${declared ?? "states no direction"}, used as ${direction}`, ]; }); } /** * 1106/07-02 (diff review DR-04). A validator the probe cannot reach, one * that refuses both probes at the root (`z.undefined()` for a * `responseBody: "NONE"` output, a string or null payload), has no object * level to judge, and no row value equals `UNREACHED`. Its policy is not * compared; `directionProblems` still requires its `direction`. */ function policyProblems(used: readonly Slot[], rows: Rows): string[] { return used.flatMap(({ operationId, validator }) => { const probed = probeUnknownFieldPolicy(validator); if (probed === "UNREACHED") return []; const declared = rows[validator.schemaId]?.unknownFieldPolicy; return probed === declared ? [] : [ `${operationId} ${validator.schemaId}: row ${declared ?? "states no unknownFieldPolicy"}, validator ${probed}`, ]; }); } type Boundary = SchemaDefinition["boundary"]; /** * 1103/16-04. Where each installed schema is used: an HTTP input, output or * failure body, or a route's params or search. The row's `boundary` is * derived from that set; a schema used in two places that no one boundary * names (an output that is also an input) has no right answer and is listed. */ function usesBySchema(): ReadonlyMap> { const uses = new Map>(); const add = (schemaId: string | null, use: string) => { if (schemaId === null) return; const set = uses.get(schemaId) ?? new Set(); set.add(use); uses.set(schemaId, set); }; for (const { http } of COMPOSED_CONTRACT_CONTRIBUTIONS.contributions) { for (const { contract } of http) { add(contract.inputValidator.schemaId, "http-input"); add(contract.outputValidator.schemaId, "http-output"); add(contract.problemValidator.schemaId, "http-problem"); } } for (const route of Object.values(ROUTE_REGISTRY)) { add(route.paramsSchema, "route-params"); add(route.searchSchema, "route-search"); } return uses; } function boundaryFor(uses: ReadonlySet): Boundary | undefined { const key = [...uses].sort().join("+"); const boundaries: Readonly> = { "http-input": "api-request", "http-output": "api-response", "http-problem": "api-problem", "route-params": "route-params", "http-input+route-params": "route-params", "route-search": "route-search", "http-input+route-search": "route-search-api-request", }; return boundaries[key]; } // With no installed feature (after the sample is removed) there is nothing to // probe, and both cases pass empty. describe("FE-REG-SCHEMA policy of the installed HTTP schemas (1103/07-03)", () => { it("declares the direction each schema is used in", () => { expect(directionProblems(slots, SCHEMA_REGISTRY)).toEqual([]); }); it("gives every schema an operation or route uses a row at the boundary it is used", () => { const wrong = [...usesBySchema()].flatMap(([schemaId, uses]) => { const row = SCHEMA_REGISTRY[schemaId]; const expected = boundaryFor(uses); if (row === undefined) return [`${schemaId}: no FE-REG-SCHEMA row`]; if (expected === undefined) { return [`${schemaId}: used as ${[...uses].sort().join(" and ")}, which no boundary names`]; } return row.boundary === expected ? [] : [`${schemaId}: row ${row.boundary}, used as ${expected}`]; }); expect(wrong).toEqual([]); }); it("declares the unknown-field policy its validator applies", () => { expect(policyProblems(slots, SCHEMA_REGISTRY)).toEqual([]); }); }); // 1106/07-02 (diff review DR-04). No row value passed for such a schema: the // policy check asked for a field and then compared it with `UNREACHED`. describe("FE-REG-SCHEMA policy of a schema the probe cannot reach (1106/07-02)", () => { const noContent: RuntimeValidator = { schemaId: "NoContent", safeParse: (value) => value === undefined ? { success: true, data: value } : { success: false, issues: [{ path: [], code: "invalid_type" }] }, }; const used: readonly Slot[] = [ { operationId: "DELETE_THING", direction: "RESPONSE", validator: noContent }, ]; const rows = ( fields: Pick, ): Rows => ({ NoContent: { schemaId: "NoContent", boundary: "api-response", owner: "test", runtime: "zod", ...fields, }, }); it("is a schema the probe cannot reach", () => { expect(probeUnknownFieldPolicy(noContent)).toBe("UNREACHED"); }); it("still needs its direction", () => { expect(directionProblems(used, rows({}))).toEqual([ "DELETE_THING NoContent: row states no direction, used as RESPONSE", ]); expect(directionProblems(used, rows({ direction: "RESPONSE" }))).toEqual([]); }); it("is not held to an unknown-field policy", () => { expect(policyProblems(used, rows({ direction: "RESPONSE" }))).toEqual([]); expect( policyProblems( used, rows({ direction: "RESPONSE", unknownFieldPolicy: "STRIP_UNKNOWN" }), ), ).toEqual([]); }); });