From d3ddc8957fba1204f41987957cd4fec01acd108f Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 01:32:41 +0900 Subject: [PATCH] =?UTF-8?q?feat(contracts):=20zod=20=EA=B2=80=EC=A6=9D?= =?UTF-8?q?=EA=B8=B0=20=EC=96=B4=EB=8C=91=ED=84=B0=EB=A5=BC=20=EA=B3=B5?= =?UTF-8?q?=EC=9C=A0=ED=95=98=EA=B3=A0=20=EA=B2=80=EC=A6=9D=20=EC=83=9D?= =?UTF-8?q?=EB=9E=B5=EC=9D=84=20=EC=9D=B4=EB=A6=84=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EB=93=9C=EB=9F=AC=EB=82=B8=EB=8B=A4=20(1101/07-03)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 - zod 스키마를 RuntimeValidator로 바꾸는 zodValidator가 참조 기능의 reference-schemas.ts 안에만 있다. 기능끼리 import가 금지라 새 기능은 복사하고, 복사본은 이미 갈라졌다(tests/helpers 복사본은 성공 값을 structuredClone하지 않는다). 참조 기능을 지우면 어댑터도 사라진다. - RuntimeValidator는 schemaId와 safeParse만 요구한다. 아무것도 검증하지 않는 검증기도 조립을 통과하고, 검증을 생략했다는 사실이 타입·이름·조립 결과 어디에도 남지 않는다. 고른 방법 (C: 공유 어댑터 + 생략 표시) - zodValidator를 src/contracts/zod-validator.ts로 옮긴다. 참조 기능과 tests/helpers/external-contract-fixture.ts가 이것을 import한다. 동작은 참조 기능 쪽 원본 그대로다(성공 값 structuredClone, 경로 배열, code 문자열). tests/helpers도 이제 성공 값을 복사한다. - unvalidatedPayload(schemaId, reason)를 external-contract-runtime.ts에 둔다. 만든 검증기에는 validation: "NONE"과 unvalidatedReason이 붙는다. zod가 필요 없어서 검증기 프로토콜 옆에 뒀다. - composeContractContributions가 이 표시가 붙은 검증기를 unvalidatedPayloads(featureId, contractId, validator, schemaId, reason)로 내놓는다. HTTP의 input·output·problem과 이벤트의 envelope·payload를 모두 본다. 표시가 "NONE"이 아니거나 이유가 비어 있으면 조립을 거부한다. - 플랫폼 개요 화면(스타터 화면)의 계약 절에 "런타임 검증을 생략한 계약" 표를 둔다. 목록이 비면 그리지 않는다. 버린 대안 - (B) 공유 어댑터만: 검증 생략이 여전히 보이지 않는다. - (D) 브랜드 타입으로 zodValidator가 만든 검증기만 받기: 외부 패키지의 자체 검증기까지 막아 §4 설계와 충돌한다. 위험·한계 - 표시 없이 손으로 쓴 통과 검증기(리뷰 실험 L5)는 여전히 조립을 통과하고 목록에도 없다. 이 변경은 생략을 막지 않는다. 이름 있는 길을 만들어 그 길로 생략한 것만 드러낸다. - 공개 계약 추가: RuntimeValidator에 선택 필드 2개, ComposedContractContributions에 필드 1개, 새 export zodValidator· unvalidatedPayload·UnvalidatedPayloadEntry. 기존 호출자는 바뀌지 않는다. ComposedContractContributions를 손으로 만드는 코드는 새 필드를 채워야 한다(repo 안에는 없다). - 초기 JS gzip 204,586 → 204,745 B(+159). 예산 204,800까지 55 B 남는다. 플랫폼 개요 청크 4,625 → 4,750 B. - 참조 기능은 모든 검증기가 검증하므로 화면 모양은 그대로다. 시각 회귀는 돌리지 않았다. - tests/unit/second-api-feature-registries.test.ts의 V2 codec 통과 검증기는 그대로 둔다(16-01이 그 파일을 넓힌다). 검증 - RED(수정 전): zod-validator.test.ts "Cannot find module '../../src/contracts/zod-validator.ts'", external-contract-runtime.test.ts와 starter-platform-overview-page.test.tsx "unvalidatedPayload is not a function". 3파일 모두 실패. - GREEN: 같은 3파일 33건 통과. - 회귀: tests/unit·contract·component·runtime-schema·features·platform 268파일 3,189건, tests/integration 12파일 158건(pnpm을 띄우는 security-followup-archive 제외), tests/architecture 7파일 33건 통과. tsc app·node·test·recipes·web-worker·service-worker 오류 0. 바꾼 파일 eslint 0. check-registries PASS(compatibility=none), verify-documentation PASS_SCOPED, check-adapter-inventory PASS. 아키텍처 그래프 검사(pnpm 대신 exec stub) 383 모듈 PASS. - 참조 기능 삭제 모의: scripts/test-sample-removal.ts의 삭제 목록(기능 폴더, tests/features, reference-context, SAMPLE_EXTRAS)을 복사본에 적용. src/contracts/zod-validator.ts가 남고, tsc app·test 오류 0, 어댑터·조립· 플랫폼 개요·HTTP 시나리오 테스트 4파일 35건 통과. Refs: docs/reviews/2026-11-01-maturity-review/07-contracts.md 07-03, 5.3 --- src/contracts/external-contract-runtime.ts | 124 +++++++++++++++--- src/contracts/zod-validator.ts | 47 +++++++ ...reference-feature-contract-contribution.ts | 2 +- .../contracts/reference-schemas.ts | 40 +----- .../examples/platform-overview-page.tsx | 29 ++++ .../starter-platform-overview-page.test.tsx | 49 +++++++ tests/helpers/external-contract-fixture.ts | 32 +---- tests/unit/external-contract-runtime.test.ts | 73 ++++++++++- tests/unit/zod-validator.test.ts | 68 ++++++++++ 9 files changed, 372 insertions(+), 92 deletions(-) create mode 100644 src/contracts/zod-validator.ts create mode 100644 tests/unit/zod-validator.test.ts diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 96131dd9..0da310d6 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -58,9 +58,42 @@ export type RuntimeValidationResult = export interface RuntimeValidator { readonly schemaId: string; + /** + * 1101/07-03. Absent on a validator that checks its input. `"NONE"` marks + * one made by `unvalidatedPayload`, which accepts any value as `T`; + * composition lists it in `unvalidatedPayloads`. A hand-written validator + * that checks nothing and omits the marker is not detected. + */ + readonly validation?: "NONE"; + /** Why validation is skipped. Required with `validation: "NONE"`. */ + readonly unvalidatedReason?: string; safeParse(value: unknown): RuntimeValidationResult; } +/** + * 1101/07-03. The named way to skip runtime validation, for a payload whose + * shape the feature decides to trust (for example generated client types). + * The value reaches the mapper as `T` unchecked: a server that sends another + * shape produces no `SCHEMA_MISMATCH`. The skip and its reason stay visible in + * `ComposedContractContributions.unvalidatedPayloads`. + */ +export function unvalidatedPayload( + schemaId: string, + reason: string, +): RuntimeValidator { + return Object.freeze({ + schemaId, + validation: "NONE" as const, + unvalidatedReason: reason, + safeParse(value: unknown) { + return Object.freeze({ + success: true as const, + data: structuredClone(value) as T, + }); + }, + }); +} + /** * A validator invocation never escapes as a native throw. `THROWN` is the * `CONTRACT_RUNTIME_FAILURE` signal; `false` success is the ordinary @@ -306,18 +339,58 @@ function assertPackageIdentity( } } -function assertValidator( - validator: RuntimeValidator, - label: string, -): void { - if ( - !validator || - typeof validator.safeParse !== "function" || - typeof validator.schemaId !== "string" || - validator.schemaId.length === 0 - ) { - fail(`${label}: runtime validator with non-empty schemaId is required`); +/** 1101/07-03. A validator slot whose validation is skipped by name. */ +export type UnvalidatedPayloadEntry = Readonly<{ + featureId: string; + /** The HTTP operationId, or the event type of an event contract. */ + contractId: string; + validator: "input" | "output" | "problem" | "envelope" | "payload"; + schemaId: string; + reason: string; +}>; + +/** Checks each validator and returns the ones that skip validation by name. */ +function assertValidators( + featureId: string, + contractId: string, + validators: Partial< + Record> + >, +): UnvalidatedPayloadEntry[] { + const unvalidated: UnvalidatedPayloadEntry[] = []; + for (const [role, validator] of Object.entries(validators) as [ + UnvalidatedPayloadEntry["validator"], + RuntimeValidator, + ][]) { + const label = `${featureId}/${contractId}.${role}`; + if ( + !validator || + typeof validator.safeParse !== "function" || + typeof validator.schemaId !== "string" || + validator.schemaId.length === 0 + ) { + fail(`${label}: runtime validator with non-empty schemaId is required`); + } + if (validator.validation === undefined) continue; + const reason = validator.unvalidatedReason; + if ( + validator.validation !== "NONE" || + typeof reason !== "string" || + reason.trim().length === 0 + ) { + fail(`${label}: an unvalidated payload needs validation "NONE" and a reason`); + } + unvalidated.push( + Object.freeze({ + featureId, + contractId, + validator: role, + schemaId: validator.schemaId, + reason, + }), + ); } + return unvalidated; } function assertStatuses( @@ -405,7 +478,7 @@ function assertHttpContract( installed: InstalledHttpContract, featureId: string, authProfiles: InstalledRestAuthProfiles, -): void { +): UnvalidatedPayloadEntry[] { const contract = installed?.contract; if (!contract || typeof contract !== "object") { fail(`${featureId}: http contract descriptor missing`); @@ -434,9 +507,11 @@ function assertHttpContract( ) { fail(`${label}: pathTemplate`); } - assertValidator(contract.inputValidator, `${label}.input`); - assertValidator(contract.outputValidator, `${label}.output`); - assertValidator(contract.problemValidator, `${label}.problem`); + const unvalidated = assertValidators(featureId, String(contract.operationId), { + input: contract.inputValidator, + output: contract.outputValidator, + problem: contract.problemValidator, + }); if (typeof contract.projectRequest !== "function") { fail(`${label}: descriptor request projection is required`); } @@ -514,12 +589,13 @@ function assertHttpContract( ) { fail(`${label}: retry budget contradicts NEVER retry semantics`); } + return unvalidated; } function assertEventContract( event: InstalledEventContract, featureId: string, -): void { +): UnvalidatedPayloadEntry[] { const label = `${featureId}/${String(event?.eventType)}`; if ( typeof event?.eventType !== "string" || @@ -529,8 +605,10 @@ function assertEventContract( ) { fail(`${label}: eventType`); } - assertValidator(event.envelopeValidator, `${label}.envelope`); - assertValidator(event.payloadValidator, `${label}.payload`); + return assertValidators(featureId, event.eventType, { + envelope: event.envelopeValidator, + payload: event.payloadValidator, + }); } export type ComposedContractContributions = Readonly<{ @@ -549,6 +627,8 @@ export type ComposedContractContributions = Readonly<{ InstalledEventContract >; externalPackages: readonly InstalledContractPackageIdentity[]; + /** 1101/07-03. Every validator made by `unvalidatedPayload`, in install order. */ + unvalidatedPayloads: readonly UnvalidatedPayloadEntry[]; }>; const EXECUTION_POLICY_KEYS = [ @@ -698,6 +778,7 @@ export function composeContractContributions( const packagesById = new Map(); const contributionIds = new Set(); const installedContributions: InstalledContractContribution[] = []; + const unvalidatedPayloads: UnvalidatedPayloadEntry[] = []; let fixtureInstalled = false; for (const raw of rows) { @@ -833,7 +914,9 @@ export function composeContractContributions( installed as InstalledHttpContract, featureId, ); - assertHttpContract(snapshot, featureId, authProfiles); + unvalidatedPayloads.push( + ...assertHttpContract(snapshot, featureId, authProfiles), + ); const operationId = snapshot.contract.operationId; const previous = httpByOperationId.get(operationId); if (previous) fail(`duplicate operation: ${operationId}`); @@ -847,7 +930,7 @@ export function composeContractContributions( event as InstalledEventContract, featureId, ); - assertEventContract(snapshot, featureId); + unvalidatedPayloads.push(...assertEventContract(snapshot, featureId)); if (eventByType.has(snapshot.eventType)) { fail(`duplicate event type: ${snapshot.eventType}`); } @@ -877,5 +960,6 @@ export function composeContractContributions( httpByOperationId: createReadOnlyRegistry(httpByOperationId), eventByType: createReadOnlyRegistry(eventByType), externalPackages: Object.freeze(externalPackages), + unvalidatedPayloads: Object.freeze(unvalidatedPayloads), }); } diff --git a/src/contracts/zod-validator.ts b/src/contracts/zod-validator.ts new file mode 100644 index 00000000..47b5b026 --- /dev/null +++ b/src/contracts/zod-validator.ts @@ -0,0 +1,47 @@ +import type { RuntimeValidator } from "./external-contract-runtime.ts"; +import type { ZodType } from "./zod.ts"; + +/** + * 1101/07-03. The one adapter from a zod schema to the `RuntimeValidator` + * protocol (`external-contract-runtime.ts`). Features import it from here + * rather than keeping a copy, so its rules cannot drift between features: + * - a success value is a `structuredClone` copy, so the caller's object never + * reaches the executor; + * - an issue path stays an array of numbers and strings (symbol keys become + * strings); an issue code is zod's code as a string. + * A package that ships its own validators keeps implementing the protocol + * directly. To skip validation on purpose, use `unvalidatedPayload`, which + * composition lists. + */ +export function zodValidator( + schemaId: string, + schema: ZodType, +): RuntimeValidator { + return Object.freeze({ + schemaId, + safeParse(value: unknown) { + const result = schema.safeParse(value); + if (result.success) { + return Object.freeze({ + success: true as const, + data: structuredClone(result.data), + }); + } + return Object.freeze({ + success: false as const, + issues: Object.freeze( + result.error.issues.map((issue) => + Object.freeze({ + path: Object.freeze( + issue.path.map((segment): string | number => + typeof segment === "number" ? segment : String(segment), + ), + ), + code: String(issue.code), + }), + ), + ), + }); + }, + }); +} diff --git a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts index fb5daae5..b01ee5ba 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts +++ b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts @@ -5,6 +5,7 @@ import type { InstalledContractContribution, InstalledHttpContract, } from "../../../contracts/external-contract-runtime.ts"; +import { zodValidator } from "../../../contracts/zod-validator.ts"; import { REFERENCE_FEATURE_ID } from "./reference-feature-contract.ts"; import { createReferenceResourceCommandSchema, @@ -13,7 +14,6 @@ import { referenceResourceListQuerySchema, referenceResourceParamsSchema, type ReferenceProblem, - zodValidator, } from "./reference-schemas.ts"; export type { ReferenceProblem } from "./reference-schemas.ts"; diff --git a/src/features/reference-feature/contracts/reference-schemas.ts b/src/features/reference-feature/contracts/reference-schemas.ts index 276cee25..619cd866 100644 --- a/src/features/reference-feature/contracts/reference-schemas.ts +++ b/src/features/reference-feature/contracts/reference-schemas.ts @@ -1,6 +1,6 @@ import { z } from "../../../contracts/zod.ts"; -import type { RuntimeValidator } from "../../../contracts/external-contract-runtime.ts"; import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts"; +import { zodValidator } from "../../../contracts/zod-validator.ts"; export const referenceResourceListQuerySchema = z .object({ @@ -80,44 +80,6 @@ const requestSchemas = { CreateReferenceResourceCommand: createReferenceResourceCommandSchema, } satisfies Record; -/** - * D-15. The one zod wrapper: every reference schema is exposed through the - * canonical `RuntimeValidator`, and the registry codecs below are adapters - * over it. - */ -export function zodValidator( - schemaId: string, - schema: z.ZodType, -): RuntimeValidator { - return Object.freeze({ - schemaId, - safeParse(value: unknown) { - const result = schema.safeParse(value); - if (result.success) { - return Object.freeze({ - success: true as const, - data: structuredClone(result.data), - }); - } - return Object.freeze({ - success: false as const, - issues: Object.freeze( - result.error.issues.map((issue) => - Object.freeze({ - path: Object.freeze( - issue.path.map((segment): string | number => - typeof segment === "number" ? segment : String(segment), - ), - ), - code: String(issue.code), - }), - ), - ), - }); - }, - }); -} - const codec = (schemaId: string, schema: z.ZodType) => runtimeSchemaCodecFromValidator(zodValidator(schemaId, schema)); diff --git a/src/presentation/examples/platform-overview-page.tsx b/src/presentation/examples/platform-overview-page.tsx index 4768fba7..9435c29e 100644 --- a/src/presentation/examples/platform-overview-page.tsx +++ b/src/presentation/examples/platform-overview-page.tsx @@ -3,6 +3,7 @@ import { type ComponentType, useEffect, useState } from "react"; import { HTTP_EXECUTION_CEILINGS, type ComposedContractContributions, + type UnvalidatedPayloadEntry, } from "../../contracts/external-contract-runtime.ts"; import { SERVER_STATE_PROFILES } from "../../contracts/server-state.ts"; import { EXPECTED_CONTRACT_SET_PACKAGES } from "../../features/installed-contract-contributions.ts"; @@ -155,6 +156,26 @@ const OPERATION_COLUMNS: readonly DataTableColumn[] = }, ]); +const UNVALIDATED_COLUMNS: readonly DataTableColumn[] = + Object.freeze([ + { + id: "contractId", + header: "계약", + cell: (row) => {row.contractId}, + }, + { + id: "validator", + header: "검증기", + cell: (row) => ( + <> + {row.validator} + {row.schemaId} + + ), + }, + { id: "reason", header: "생략 이유", cell: (row) => row.reason }, + ]); + type ProfileRow = (typeof SERVER_STATE_PROFILES)[keyof typeof SERVER_STATE_PROFILES]; const PROFILE_COLUMNS: readonly DataTableColumn[] = Object.freeze([ @@ -448,6 +469,14 @@ export function PlatformOverviewPage({ /> } /> + {/* 1101/07-03. Drawn only when a contract skips validation by name. */} + `${row.contractId}.${row.validator}`} + empty={null} + />
{ } }); + // 1101/07-03. A skipped validation is shown, not just composed. + it("lists the operations that skip runtime validation, with the reason", () => { + const [listRow, ...rest] = TEST_CONTRACT_CONTRIBUTION.http; + const contracts = composeContractContributions([ + Object.freeze({ + ...TEST_CONTRACT_CONTRIBUTION, + http: Object.freeze([ + { + ...listRow!, + contract: { + ...listRow!.contract, + outputValidator: unvalidatedPayload( + "TestEntityListPayload", + "typed by the package", + ), + }, + }, + ...rest, + ]), + }), + ]); + render( + + + + + , + ); + + const table = tableByCaption("런타임 검증을 생략한 계약"); + const [row, ...others] = within(table).getAllByRole("row").slice(1); + expect(others).toHaveLength(0); + expect(within(row!).getByText("TEST_LIST_ENTITIES")).toBeVisible(); + expect(within(row!).getByText("typed by the package")).toBeVisible(); + }); + + it("shows no skipped-validation list when every operation validates", () => { + renderPage(); + + expect( + screen.queryByRole("table", { name: "런타임 검증을 생략한 계약" }), + ).toBeNull(); + }); + it("renders every fixed server-state profile with its own budget", () => { renderPage(); diff --git a/tests/helpers/external-contract-fixture.ts b/tests/helpers/external-contract-fixture.ts index 4960a2cc..a65e5f74 100644 --- a/tests/helpers/external-contract-fixture.ts +++ b/tests/helpers/external-contract-fixture.ts @@ -5,38 +5,8 @@ import type { InstalledContractContribution, InstalledEventContract, InstalledHttpContract, - RuntimeValidator, } from "../../src/contracts/external-contract-runtime.ts"; - -function zodValidator( - schemaId: string, - schema: z.ZodType, -): RuntimeValidator { - return Object.freeze({ - schemaId, - safeParse(value: unknown) { - const result = schema.safeParse(value); - if (result.success) { - return Object.freeze({ success: true as const, data: result.data }); - } - return Object.freeze({ - success: false as const, - issues: Object.freeze( - result.error.issues.map((issue) => - Object.freeze({ - path: Object.freeze( - issue.path.map((segment) => - typeof segment === "number" ? segment : String(segment), - ), - ), - code: String(issue.code), - }), - ), - ), - }); - }, - }); -} +import { zodValidator } from "../../src/contracts/zod-validator.ts"; const entitySchema = z .object({ diff --git a/tests/unit/external-contract-runtime.test.ts b/tests/unit/external-contract-runtime.test.ts index cf0495a1..52020384 100644 --- a/tests/unit/external-contract-runtime.test.ts +++ b/tests/unit/external-contract-runtime.test.ts @@ -4,10 +4,14 @@ import { ContractContributionError, composeContractContributions, invokeValidator, + unvalidatedPayload, type InstalledContractContribution, type RuntimeValidator, } from "../../src/contracts/external-contract-runtime.ts"; -import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts"; +import { + TEST_CONTRACT_CONTRIBUTION, + TEST_EVENT_CONTRACT, +} from "../helpers/external-contract-fixture.ts"; function contribution( contributionId: string, @@ -159,6 +163,73 @@ describe("template fixture provenance (07-04, §4.8)", () => { }); }); +// 1101/07-03. Skipping runtime validation stays possible, but only a skip +// made through `unvalidatedPayload` is named, so composition can list it. +describe("validation skipped by name (1101/07-03)", () => { + const [listRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [ + InstalledContractContribution["http"][number], + ]; + const skipped = unvalidatedPayload("TestEntityListPayload", "typed by the package"); + + function withOutput(validator: RuntimeValidator) { + return contribution("skip-test", [ + { ...listRow, contract: { ...listRow.contract, outputValidator: validator } }, + ]); + } + + it("lists nothing when every validator checks its input", () => { + expect( + composeContractContributions([TEST_CONTRACT_CONTRIBUTION]).unvalidatedPayloads, + ).toEqual([]); + }); + + it("lists an operation whose output skips validation, with its reason", () => { + expect( + composeContractContributions([withOutput(skipped)]).unvalidatedPayloads, + ).toEqual([ + { + featureId: "test-feature", + contractId: "TEST_LIST_ENTITIES", + validator: "output", + schemaId: "TestEntityListPayload", + reason: "typed by the package", + }, + ]); + }); + + it("lists an event whose payload skips validation", () => { + const composed = composeContractContributions([ + Object.freeze({ + ...contribution("skip-event", []), + events: Object.freeze([ + { ...TEST_EVENT_CONTRACT, payloadValidator: unvalidatedPayload("TestEntity", "trusted feed") }, + ]), + }), + ]); + + expect(composed.unvalidatedPayloads).toEqual([ + expect.objectContaining({ + contractId: "test.entity.changed", + validator: "payload", + reason: "trusted feed", + }), + ]); + }); + + it.each([ + ["no reason", { ...skipped, unvalidatedReason: " " }], + ["an unknown marker", { ...skipped, validation: "PARTIAL" }], + ])("rejects a skip marker with %s", (_label, validator) => { + expect( + captureContributionError(() => + composeContractContributions([withOutput(validator as RuntimeValidator)]), + ).reason, + ).toBe( + 'test-feature/TEST_LIST_ENTITIES.output: an unvalidated payload needs validation "NONE" and a reason', + ); + }); +}); + describe("validator invocation (07-06)", () => { const returning = (result: unknown): RuntimeValidator => ({ schemaId: "Malformed", diff --git a/tests/unit/zod-validator.test.ts b/tests/unit/zod-validator.test.ts new file mode 100644 index 00000000..d9d3868a --- /dev/null +++ b/tests/unit/zod-validator.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from "vitest"; + +import { + invokeValidator, + unvalidatedPayload, +} from "../../src/contracts/external-contract-runtime.ts"; +import { z } from "../../src/contracts/zod.ts"; +import { zodValidator } from "../../src/contracts/zod-validator.ts"; + +/** + * 1101/07-03. The one zod adapter lives in src/contracts, so every feature + * imports it instead of copying it, and it outlives the sample feature. + */ +describe("zodValidator", () => { + const validator = zodValidator( + "Entity", + z.object({ id: z.string().min(1), tags: z.array(z.string()) }).strip(), + ); + + it("returns a copy of the parsed value, not the caller's object", () => { + const source = { id: "a", tags: ["x"] }; + const result = validator.safeParse(source); + + expect(result).toEqual({ success: true, data: source }); + if (!result.success) throw new Error("expected success"); + expect(result.data.tags).not.toBe(source.tags); + expect(Object.isFrozen(result)).toBe(true); + }); + + it("reports issues with array paths and string codes", () => { + expect(validator.safeParse({ id: "", tags: [1] })).toEqual({ + success: false, + issues: [ + { path: ["id"], code: "too_small" }, + { path: ["tags", 0], code: "invalid_type" }, + ], + }); + }); + + it("checks its input, so it carries no skip marker", () => { + expect(validator.schemaId).toBe("Entity"); + expect(validator.validation).toBeUndefined(); + }); +}); + +describe("unvalidatedPayload", () => { + const skipped = unvalidatedPayload<{ id: string }>( + "EntityPayload", + "generated client types are trusted", + ); + + it("names the skip on the validator itself", () => { + expect(skipped).toMatchObject({ + schemaId: "EntityPayload", + validation: "NONE", + unvalidatedReason: "generated client types are trusted", + }); + }); + + it("accepts any value as a copy", () => { + const source = { anything: [1] }; + const invocation = invokeValidator(skipped, source); + + expect(invocation).toEqual({ outcome: "VALID", value: source }); + if (invocation.outcome !== "VALID") throw new Error("expected VALID"); + expect(invocation.value).not.toBe(source); + }); +});