chore(review): 1103 계약·레지스트리 조치 브랜치를 합친다
Refs: docs/reviews/2026-11-03-maturity-review/README.md 07-01~07-04 13-04 14-06
This commit is contained in:
@@ -58,14 +58,14 @@
|
||||
},
|
||||
{
|
||||
"name": "zod-is-reached-through-contracts-zod",
|
||||
"comment": "F-7 (13-08). src/contracts/zod.ts sets zod jitless before any schema is built, so the production CSP never sees zod's Function probe. Schema code imports z from there.",
|
||||
"comment": "F-7 (13-08). src/contracts/zod.ts sets zod jitless before any schema is built, so the production CSP never sees zod's Function probe. Schema code imports z from there. A subpath (zod/v4, zod/mini) is the same zod and counts too (0929/P-07-06).",
|
||||
"severity": "error",
|
||||
"from": {
|
||||
"path": "^src",
|
||||
"pathNot": "^src/contracts/zod\\.ts$"
|
||||
},
|
||||
"to": {
|
||||
"path": "^zod$"
|
||||
"path": "^zod(/|$)"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"snapshotDigest": "16f727424579279e0ef810620f672a8a9d74de6b71e3e9ce37ab07a82f645588",
|
||||
"snapshotDigest": "8f5ae6dde9c6a293144e5bccad1765367f06ac3a6b58a6229c69426703158c9c",
|
||||
"owner": "DongHyeonka",
|
||||
"reason": "2026-11-03 사용자 승인('둘 다 지워'): V2 API 행 제거. FE-REG-API 행은 V3 descriptor에서 뽑은 projection(operationId·featureId·method·path·authProfileId·retrySemantics·requestBody·responseBody·responseEnvelope·request/response/problemSchema)이다. V3 descriptor가 쓰지 않는 참조 기능 NoRequest 스키마 행 제거",
|
||||
"approvedAt": "2026-11-03T12:22:21.004Z"
|
||||
"reason": "1103/13-04 FE-REG-ENV runtime rows state required and defaultValue as runtimeConfigV2ArtifactSchema reads them (TELEMETRY_ENABLED, AUTH_MODE, RELEASE_MANIFEST_URL, CAPABILITY_OVERRIDES, FEATURE_OVERRIDES); defaultValue may be an object",
|
||||
"approvedAt": "2026-11-04T11:26:00.863Z"
|
||||
}
|
||||
|
||||
@@ -341,7 +341,17 @@
|
||||
"responseEnvelope",
|
||||
"requestSchema",
|
||||
"responseSchema",
|
||||
"problemSchema"
|
||||
"problemSchema",
|
||||
"acceptedStatuses",
|
||||
"emptyBodyStatuses",
|
||||
"unvalidated",
|
||||
"requestByteLimit",
|
||||
"responseByteLimit",
|
||||
"totalDeadlineMs",
|
||||
"retryBudget",
|
||||
"traffic",
|
||||
"commandEffect",
|
||||
"commandRecovery"
|
||||
],
|
||||
"fieldTypes": {
|
||||
"operationId": "string",
|
||||
@@ -355,7 +365,17 @@
|
||||
"responseEnvelope": "string",
|
||||
"requestSchema": "string",
|
||||
"responseSchema": "string",
|
||||
"problemSchema": "string"
|
||||
"problemSchema": "string",
|
||||
"acceptedStatuses": "array",
|
||||
"emptyBodyStatuses": "array",
|
||||
"unvalidated": "array",
|
||||
"requestByteLimit": "integer",
|
||||
"responseByteLimit": "integer",
|
||||
"totalDeadlineMs": "integer",
|
||||
"retryBudget": "integer",
|
||||
"traffic": "object|null",
|
||||
"commandEffect": "object|null",
|
||||
"commandRecovery": "object|null"
|
||||
},
|
||||
"uniqueFields": [
|
||||
"operationId"
|
||||
@@ -412,51 +432,110 @@
|
||||
"responseBody",
|
||||
"responseEnvelope",
|
||||
"requestSchema",
|
||||
"responseSchema"
|
||||
"responseSchema",
|
||||
"problemSchema",
|
||||
"unvalidated"
|
||||
]
|
||||
},
|
||||
"rows": {
|
||||
"CREATE_REFERENCE_RESOURCE": {
|
||||
"acceptedStatuses": [
|
||||
200,
|
||||
201
|
||||
],
|
||||
"authProfileId": "EXTERNAL_BEARER",
|
||||
"commandEffect": {
|
||||
"classifiesStatus": true
|
||||
},
|
||||
"commandRecovery": {
|
||||
"mode": "IDEMPOTENCY_REPLAY",
|
||||
"operationIdentityField": "idempotencyKey"
|
||||
},
|
||||
"emptyBodyStatuses": [],
|
||||
"featureId": "reference-feature",
|
||||
"method": "POST",
|
||||
"operationId": "CREATE_REFERENCE_RESOURCE",
|
||||
"path": "/api/reference-resources",
|
||||
"problemSchema": "ReferenceProblem",
|
||||
"requestBody": "JSON",
|
||||
"requestByteLimit": 32768,
|
||||
"requestSchema": "CreateReferenceResourceCommand",
|
||||
"responseBody": "REQUIRED_JSON",
|
||||
"responseByteLimit": 32768,
|
||||
"responseEnvelope": "NONE",
|
||||
"responseSchema": "ReferenceResourcePayload",
|
||||
"retrySemantics": "KEYED"
|
||||
"retryBudget": 0,
|
||||
"retrySemantics": "KEYED",
|
||||
"totalDeadlineMs": 10000,
|
||||
"traffic": {
|
||||
"maxConcurrentRequests": 1,
|
||||
"maxPhysicalRequests": 1,
|
||||
"maxQueuedRequests": 0,
|
||||
"maxRetries": 0
|
||||
},
|
||||
"unvalidated": []
|
||||
},
|
||||
"GET_REFERENCE_RESOURCE": {
|
||||
"acceptedStatuses": [
|
||||
200
|
||||
],
|
||||
"authProfileId": "EXTERNAL_BEARER",
|
||||
"commandEffect": null,
|
||||
"commandRecovery": null,
|
||||
"emptyBodyStatuses": [],
|
||||
"featureId": "reference-feature",
|
||||
"method": "GET",
|
||||
"operationId": "GET_REFERENCE_RESOURCE",
|
||||
"path": "/api/reference-resources/{resourceId}",
|
||||
"problemSchema": "ReferenceProblem",
|
||||
"requestBody": "NONE",
|
||||
"requestByteLimit": 0,
|
||||
"requestSchema": "ReferenceResourceParams",
|
||||
"responseBody": "REQUIRED_JSON",
|
||||
"responseByteLimit": 32768,
|
||||
"responseEnvelope": "NONE",
|
||||
"responseSchema": "ReferenceResourcePayload",
|
||||
"retrySemantics": "SAFE"
|
||||
"retryBudget": 2,
|
||||
"retrySemantics": "SAFE",
|
||||
"totalDeadlineMs": 10000,
|
||||
"traffic": {
|
||||
"maxConcurrentRequests": 1,
|
||||
"maxPhysicalRequests": 3,
|
||||
"maxQueuedRequests": 0,
|
||||
"maxRetries": 2
|
||||
},
|
||||
"unvalidated": []
|
||||
},
|
||||
"LIST_REFERENCE_RESOURCES": {
|
||||
"acceptedStatuses": [
|
||||
200
|
||||
],
|
||||
"authProfileId": "EXTERNAL_BEARER",
|
||||
"commandEffect": null,
|
||||
"commandRecovery": null,
|
||||
"emptyBodyStatuses": [],
|
||||
"featureId": "reference-feature",
|
||||
"method": "GET",
|
||||
"operationId": "LIST_REFERENCE_RESOURCES",
|
||||
"path": "/api/reference-resources",
|
||||
"problemSchema": "ReferenceProblem",
|
||||
"requestBody": "NONE",
|
||||
"requestByteLimit": 0,
|
||||
"requestSchema": "ReferenceResourceListQuery",
|
||||
"responseBody": "REQUIRED_JSON",
|
||||
"responseByteLimit": 262144,
|
||||
"responseEnvelope": "NONE",
|
||||
"responseSchema": "ReferenceResourceListPayload",
|
||||
"retrySemantics": "SAFE"
|
||||
"retryBudget": 2,
|
||||
"retrySemantics": "SAFE",
|
||||
"totalDeadlineMs": 10000,
|
||||
"traffic": {
|
||||
"maxConcurrentRequests": 1,
|
||||
"maxPhysicalRequests": 3,
|
||||
"maxQueuedRequests": 0,
|
||||
"maxRetries": 2
|
||||
},
|
||||
"unvalidated": []
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -565,7 +644,7 @@
|
||||
"registryId": "FE-REG-ENV",
|
||||
"owner": "feature-frontend-env-runtime-config-contract",
|
||||
"source": "src/contracts/env.ts",
|
||||
"rowCount": 16,
|
||||
"rowCount": 18,
|
||||
"contract": {
|
||||
"requiredFields": [
|
||||
"phase",
|
||||
@@ -577,7 +656,7 @@
|
||||
"phase": "string",
|
||||
"classification": "string",
|
||||
"required": "boolean",
|
||||
"defaultValue": "string|integer|boolean|null"
|
||||
"defaultValue": "string|integer|boolean|object|null"
|
||||
},
|
||||
"uniqueFields": [],
|
||||
"allowedValues": {
|
||||
@@ -615,13 +694,24 @@
|
||||
},
|
||||
"AUTH_MODE": {
|
||||
"classification": "public",
|
||||
"defaultValue": "external",
|
||||
"defaultValue": null,
|
||||
"phase": "runtime",
|
||||
"required": true
|
||||
},
|
||||
"BUILD_ID": {
|
||||
"classification": "public-metadata",
|
||||
"defaultValue": null,
|
||||
"phase": "runtime",
|
||||
"required": false
|
||||
},
|
||||
"CAPABILITY_OVERRIDES": {
|
||||
"classification": "public",
|
||||
"defaultValue": null,
|
||||
"defaultValue": {
|
||||
"OFFLINE_COMMANDS": "DEFAULT",
|
||||
"REALTIME": "DEFAULT",
|
||||
"SERVICE_WORKER": "DEFAULT",
|
||||
"WEB_WORKER": "DEFAULT"
|
||||
},
|
||||
"phase": "runtime",
|
||||
"required": false
|
||||
},
|
||||
@@ -633,7 +723,7 @@
|
||||
},
|
||||
"FEATURE_OVERRIDES": {
|
||||
"classification": "public",
|
||||
"defaultValue": null,
|
||||
"defaultValue": {},
|
||||
"phase": "runtime",
|
||||
"required": false
|
||||
},
|
||||
@@ -643,11 +733,17 @@
|
||||
"phase": "runtime",
|
||||
"required": false
|
||||
},
|
||||
"RELEASE_ID": {
|
||||
"classification": "public-metadata",
|
||||
"defaultValue": null,
|
||||
"phase": "runtime",
|
||||
"required": false
|
||||
},
|
||||
"RELEASE_MANIFEST_URL": {
|
||||
"classification": "public",
|
||||
"defaultValue": "/release-manifest.json",
|
||||
"phase": "runtime",
|
||||
"required": true
|
||||
"required": false
|
||||
},
|
||||
"REQUEST_TIMEOUT_MS": {
|
||||
"classification": "public",
|
||||
@@ -657,7 +753,7 @@
|
||||
},
|
||||
"TELEMETRY_ENABLED": {
|
||||
"classification": "public",
|
||||
"defaultValue": false,
|
||||
"defaultValue": null,
|
||||
"phase": "runtime",
|
||||
"required": true
|
||||
},
|
||||
|
||||
@@ -149,7 +149,17 @@
|
||||
"responseEnvelope",
|
||||
"requestSchema",
|
||||
"responseSchema",
|
||||
"problemSchema"
|
||||
"problemSchema",
|
||||
"acceptedStatuses",
|
||||
"emptyBodyStatuses",
|
||||
"unvalidated",
|
||||
"requestByteLimit",
|
||||
"responseByteLimit",
|
||||
"totalDeadlineMs",
|
||||
"retryBudget",
|
||||
"traffic",
|
||||
"commandEffect",
|
||||
"commandRecovery"
|
||||
],
|
||||
"fieldTypes": {
|
||||
"operationId": "string",
|
||||
@@ -163,7 +173,17 @@
|
||||
"responseEnvelope": "string",
|
||||
"requestSchema": "string",
|
||||
"responseSchema": "string",
|
||||
"problemSchema": "string"
|
||||
"problemSchema": "string",
|
||||
"acceptedStatuses": "array",
|
||||
"emptyBodyStatuses": "array",
|
||||
"unvalidated": "array",
|
||||
"requestByteLimit": "integer",
|
||||
"responseByteLimit": "integer",
|
||||
"totalDeadlineMs": "integer",
|
||||
"retryBudget": "integer",
|
||||
"traffic": "object|null",
|
||||
"commandEffect": "object|null",
|
||||
"commandRecovery": "object|null"
|
||||
},
|
||||
"uniqueFields": [
|
||||
"operationId"
|
||||
@@ -224,7 +244,9 @@
|
||||
"responseBody",
|
||||
"responseEnvelope",
|
||||
"requestSchema",
|
||||
"responseSchema"
|
||||
"responseSchema",
|
||||
"problemSchema",
|
||||
"unvalidated"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -269,7 +291,7 @@
|
||||
"phase": "string",
|
||||
"classification": "string",
|
||||
"required": "boolean",
|
||||
"defaultValue": "string|integer|boolean|null"
|
||||
"defaultValue": "string|integer|boolean|object|null"
|
||||
},
|
||||
"allowedValues": {
|
||||
"phase": ["build", "runtime"],
|
||||
|
||||
@@ -42,7 +42,7 @@ Each row is one `forbidden` rule in `.dependency-cruiser.json`, by its `name`.
|
||||
| `presentation-does-not-know-adapters` | `src/presentation`, except `adapters/query` | adapters, bootstrap, TanStack |
|
||||
| `page-templates-own-layout-only` | `src/presentation/templates` | application, adapters, bootstrap, the presentation query adapter, TanStack. Templates take data and actions as props |
|
||||
| `icon-vendor-is-facade-only` | all of `src`, except the lucide vendor facade | `lucide-react` |
|
||||
| `zod-is-reached-through-contracts-zod` | all of `src`, except `src/contracts/zod.ts` | `zod` |
|
||||
| `zod-is-reached-through-contracts-zod` | all of `src`, except `src/contracts/zod.ts` | `zod` and its subpaths (`zod/v4`) |
|
||||
| `design-system-is-reached-through-its-index` | code outside the design system and its named facades | design-system files other than its `index.ts` |
|
||||
| `adapters-do-not-know-presentation` | `src/adapters` | presentation, bootstrap |
|
||||
| `feature-domain-is-framework-neutral` | `src/features/<id>/domain` | application, presentation, adapters, bootstrap, any feature's application, adapters and presentation, React, TanStack |
|
||||
|
||||
@@ -497,7 +497,10 @@ projectRequest: (input) => Object.freeze({
|
||||
② **기준**
|
||||
|
||||
- 라우트, operation, 스키마, 무효화 topic·namespace·edge를 **더하기만** 하면 기준선은 바뀌지 않는다.
|
||||
- 행을 **빼거나 바꾸면** breaking 변경이다. 둘 중 하나를 한다.
|
||||
- 행을 **빼거나** breaking 칸을 **바꾸면** breaking 변경이다. breaking 칸은 `config/contracts/registry-governance.json`의 `breakingFields`다. 배열 칸에서 값을 빼는 것도 breaking이다.
|
||||
- FE-REG-API 예: 생성 API의 `acceptedStatuses`를 `[200, 201]`에서 `[201]`로 줄이거나, `problemSchema`를 바꾸거나, 검증기를 `unvalidatedPayload`로 바꾸면(`unvalidated` 칸) breaking이다.
|
||||
- status를 더하는 것, 바이트 상한·마감·`retryBudget`·`traffic`·`commandEffect`·`commandRecovery`를 바꾸는 것은 behavior-change다. 통과하지만 스냅샷 diff(`artifacts/quality/registries.json`의 `compatibility.changes`)에 남는다. PR에서 본다.
|
||||
- breaking 변경이면 둘 중 하나를 한다.
|
||||
- `REGISTRY_BASELINE_OWNER`, `REGISTRY_BASELINE_REASON`을 주고 `corepack pnpm update:registry-baseline`을 돌린다.
|
||||
- 또는 `config/contracts/registry-change-evidence.json`에 항목을 더한다. 칸 설명은 `docs/operations/ci-quality-gates.md`에 있다.
|
||||
- a11y 기록은 생성 명령이 pending으로 만든다. 서명은 릴리스 전에 사람이 한다([03 문서](03-outside-feature-folder.md)).
|
||||
@@ -510,6 +513,7 @@ projectRequest: (input) => Object.freeze({
|
||||
- 메시지: `breaking change missing evidence: <changeId>`
|
||||
- 지금 diff와 맞지 않는 증거 행이 남으면 `stale breaking evidence <changeId>: ...`로 실패한다.
|
||||
- **못 잡음**: 사람이 서명하지 않은 a11y 기록은 merge 게이트를 통과한다. 릴리스 게이트 FE-GATE-028이 막는다.
|
||||
- **못 잡음**: descriptor의 함수는 행에 없다. `classifyProblem`·`classifyStatus`가 무엇을 `NOT_APPLIED`로 보는지, `projectRequest`가 무엇을 보내는지는 PR에서 본다.
|
||||
|
||||
④ **쓸 스킬**: `documentation-and-adrs`, `deprecation-and-migration`
|
||||
|
||||
|
||||
@@ -102,6 +102,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
|
||||
|
||||
**틀리면**
|
||||
|
||||
- 읽기(GET·HEAD)에 `KEYED`나 `NEVER`를 적으면 계약 조립이 `<method> is a read; its retrySemantics is SAFE or IDEMPOTENT, not <값>`으로 거부한다.
|
||||
- `NEVER`에 `retryBudget`을 0보다 크게 주면 계약 조립이 `retry budget contradicts NEVER retry semantics`로 거부한다.
|
||||
- `KEYED`에 `commandRecovery`가 없으면 `KEYED commands require a recovery descriptor`로 거부한다.
|
||||
- 서버 보장과 다른 의미를 고른 것은 검사가 잡지 못한다.
|
||||
|
||||
@@ -109,6 +109,8 @@ release admission refused for staging:
|
||||
- 실시간 갱신: 짝 백엔드의 실시간 출구(STOMP·NDJSON)와 프론트 realtime 어댑터(SSE·`realtime.v1` WebSocket)는 그대로 연결되지 않는다. 지금 되는 경로는 bounded polling이다. 대응표: [realtime 설계 0.1절](../architecture/realtime-events-web-push-and-bounded-polling.md#01-짝-백엔드-템플릿과의-대응-110304-02).
|
||||
- `src/contracts/product-contracts.ts`: 제품 인증 프로필이나 제품 런타임 설정 키가 필요할 때.
|
||||
- 템플릿 파일 `src/contracts/rest-profiles.ts`는 고치지 않는다.
|
||||
- 설정 키 이름에 `TOKEN`·`COOKIE`·`SECRET`·`PASSWORD` 같은 조각(`src/contracts/env.ts`의 `FORBIDDEN_CONFIG_NAME_FRAGMENTS`, 대소문자 무관)을 넣지 않는다. 부팅이 `CONFIG_SECRET_NAME_REJECTED`로 멈춘다. `test:unit`의 `env-registry-coverage`가 먼저 `Forbidden client configuration key: <키>`로 실패한다.
|
||||
- FE-REG-ENV 행의 `required`·`defaultValue`는 zod 필드가 키가 없을 때 하는 것과 같게 적는다. 기본값이 없으면 `defaultValue: null`이다. 같은 테스트가 대조한다.
|
||||
- `config/runtime/<profile>.json`: 환경별로 기능을 끄고 싶을 때(`FEATURE_OVERRIDES`).
|
||||
- `src/features/product-capabilities.ts`의 선택 런타임(`PRODUCT_RUNTIME_CAPABILITY_SELECTION`): Service Worker를 켤 때. 아래 "SW 켜기"를 본다.
|
||||
- `package.json`, lockfile, `config/security/dependency-change-evidence.json`: 계약 패키지를 더할 때(B절).
|
||||
|
||||
@@ -98,6 +98,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
|
||||
| `<id>/<operationId>: unknown authProfileId <profile>` | V3 `frontend.authProfileId`가 없는 프로필 | V3 `frontend.authProfileId` |
|
||||
| `<id>/<operationId>: retry budget contradicts NEVER retry semantics` | `NEVER`인데 `retryBudget`가 0이 아니다 | V3 `frontend.retryBudget` |
|
||||
| `<id>/<operationId>: KEYED commands require a recovery descriptor` | `KEYED`인데 `commandRecovery`가 없다 | V3 `commandRecovery` |
|
||||
| `<id>/<operationId>: <GET·HEAD> is a read; its retrySemantics is SAFE or IDEMPOTENT, not <값>` | 읽기에 `KEYED`나 `NEVER`를 적었다 | V3 `retrySemantics`. 재시도를 막으려면 `frontend.retryBudget: 0` |
|
||||
| `<id>/<operationId>: command operations require a command effect descriptor` | 쓰기에 `commandEffect`가 없다 | V3 `commandEffect` |
|
||||
| `<id>/<operationId>: read operations carry no command descriptors` | GET에 `commandEffect`·`commandRecovery`를 적었다 | 둘 다 `null` |
|
||||
| `<id>: package version must be exact SemVer` | 버전 범위(`^1.2.0`)나 형식 오류 | `<BASE>_CONTRACT_PACKAGE.version` |
|
||||
@@ -145,6 +146,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
|
||||
| `FE-REG-ROUTE.<ROUTE_ID>.<field> has unknown value <value>` | `access`·`errorSurface`가 정해진 값이 아니다 | 계약 `routes` |
|
||||
| `FE-REG-ROUTE.<ROUTE_ID>.paramsSchema references unknown FE-REG-SCHEMA.schemaId=<id>` | 라우트 스키마 ID를 기능이 등록하지 않았다 (`searchSchema`도 같은 꼴) | 계약 스키마 메타 |
|
||||
| `FE-REG-API.<operationId> has no executable consumer for operationId=<operationId>` | 계약의 operation을 기능 `adapters/`·`application/`에서 쓰지 않는다 | 쓰지 않으면 descriptor를 지운다 |
|
||||
| `missing registry source <path>: <message> (reason: <reason>)` | 레지스트리 source를 읽다가 오류가 났다. 계약 조립 실패면 `<reason>`이 위 `reason` 표의 값이다. 읽지 못한 레지스트리는 `removed` 증거를 요구하지 않는다 | `<reason>`이 가리키는 곳 |
|
||||
| `breaking change missing evidence: <changeId>` | 행을 빼거나 바꿨는데 승인이 없다 | `update:registry-baseline` 또는 `config/contracts/registry-change-evidence.json` |
|
||||
| `stale breaking evidence <changeId>: no breaking change in the current diff has this changeId. ...` | 지금 diff와 맞지 않는 증거 행 | 그 행을 지운다 |
|
||||
| `registry baseline approval digest mismatch: approved=<digest> actual=<digest>` | 기준선 파일을 손으로 고쳤다 | `update:registry-baseline`으로 다시 찍는다 |
|
||||
|
||||
@@ -931,6 +931,15 @@ async function runGraphFixtureChecks(): Promise<GraphFixtureResult> {
|
||||
target === "zod",
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "zod subpath import outside src/contracts/zod.ts is rejected",
|
||||
passed: blockingViolations(importBoundaryGraph).some(
|
||||
({ rule, source, target }) =>
|
||||
rule === "zod-is-reached-through-contracts-zod" &&
|
||||
source === "src/presentation/pages/subpath-zod.ts" &&
|
||||
target === "zod/v4",
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "zod through src/contracts/zod.ts is accepted",
|
||||
passed: !blockingViolations(importBoundaryGraph).some(({ source }) =>
|
||||
|
||||
@@ -116,6 +116,13 @@ const owners = new Map<string, string>();
|
||||
const snapshots: RegistrySnapshot[] = [];
|
||||
const rowsByRegistry = new Map<string, RegistryRows>();
|
||||
const sourcesByRegistry = new Map<string, string>();
|
||||
/**
|
||||
* 1103/14-06. Registries whose source did not load. Their failure is already
|
||||
* reported with its cause, so the checks that read their rows (references,
|
||||
* the baseline comparison) skip them instead of reporting the same failure
|
||||
* again as a deleted registry.
|
||||
*/
|
||||
const unloadedRegistries = new Set<string>();
|
||||
const registryExtensions = [".ts", ".tsx", ".mts", ".cts"];
|
||||
|
||||
async function resolveRegistrySource(
|
||||
@@ -144,6 +151,33 @@ async function resolveRegistrySource(
|
||||
return candidates[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1103/14-06. A contract composition failure (`ContractContributionError`)
|
||||
* says only "not composable"; its cause is the `reason` property.
|
||||
*/
|
||||
function loadErrorText(error: Error): string {
|
||||
const message = error.message.split("\n")[0] ?? "";
|
||||
const reason: unknown = (error as Error & { reason?: unknown }).reason;
|
||||
return typeof reason === "string" && reason.length > 0
|
||||
? `${message} (reason: ${reason})`
|
||||
: message;
|
||||
}
|
||||
|
||||
function withoutRegistries(
|
||||
snapshot: Readonly<Record<string, unknown>>,
|
||||
registryIds: ReadonlySet<string>,
|
||||
): Readonly<Record<string, unknown>> {
|
||||
if (registryIds.size === 0 || !Array.isArray(snapshot.registries)) {
|
||||
return snapshot;
|
||||
}
|
||||
return {
|
||||
...snapshot,
|
||||
registries: (snapshot.registries as Array<{ registryId?: unknown }>).filter(
|
||||
(registry) => !registryIds.has(String(registry.registryId)),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
type FieldLookup = Readonly<{
|
||||
found: boolean;
|
||||
value: unknown;
|
||||
@@ -371,8 +405,12 @@ for (const specification of governance.registries) {
|
||||
} catch (error) {
|
||||
// A source that exists but fails to load names its error, so a broken
|
||||
// import in a feature contract is not reported as a missing file.
|
||||
const reason = sourcePath && error instanceof Error ? `: ${error.message.split("\n")[0]}` : "";
|
||||
if (!rows) failures.push(`missing registry source ${specification.path}${reason}`);
|
||||
const reason = sourcePath && error instanceof Error ? `: ${loadErrorText(error)}` : "";
|
||||
if (!rows) {
|
||||
failures.push(`missing registry source ${specification.path}${reason}`);
|
||||
unloadedRegistries.add(specification.registryId);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const registryRows = projectRegistryRows(specification, rows);
|
||||
@@ -534,6 +572,7 @@ for (const specification of governance.registries) {
|
||||
for (const reference of specification.references ?? []) {
|
||||
const targetRows = rowsByRegistry.get(reference.registryId);
|
||||
if (!targetRows) {
|
||||
if (unloadedRegistries.has(reference.registryId)) continue;
|
||||
failures.push(
|
||||
`${specification.registryId} references unknown registry ${reference.registryId}`,
|
||||
);
|
||||
@@ -672,7 +711,10 @@ if (baselinePath && approvalPath && evidencePath) {
|
||||
`registry baseline approval digest mismatch: approved=${approvalResult.approvedDigest} actual=${approvalResult.actualDigest}`,
|
||||
);
|
||||
}
|
||||
const registryDiff = diffRegistrySnapshots(baseline, currentSnapshot);
|
||||
const registryDiff = diffRegistrySnapshots(
|
||||
withoutRegistries(baseline, unloadedRegistries),
|
||||
currentSnapshot,
|
||||
);
|
||||
compatibility = registryDiff;
|
||||
const evidence = JSON.parse(
|
||||
await readFile(evidencePath, "utf8"),
|
||||
|
||||
@@ -1,16 +1,40 @@
|
||||
import type {
|
||||
CommandEffectDescriptor,
|
||||
CommandRecoveryDescriptor,
|
||||
HttpMethod,
|
||||
InstalledContractContribution,
|
||||
InstalledHttpContract,
|
||||
ResponseEnvelope,
|
||||
RetrySemantics,
|
||||
RuntimeValidator,
|
||||
} from "./external-contract-runtime.ts";
|
||||
import type { TrafficBudget } from "../platform/traffic/traffic-budget.ts";
|
||||
|
||||
/**
|
||||
* 1103/07-01. The data of a command effect descriptor. Its classifiers are
|
||||
* behaviour and stay out of the row; what the row keeps is whether the
|
||||
* descriptor answers 401, 403 and 429 itself, and the problem codes it names
|
||||
* as refused before any write when it names them.
|
||||
*/
|
||||
export type ApiCommandEffectRow = Readonly<{
|
||||
classifiesStatus: boolean;
|
||||
refusedBeforeWrite?: readonly string[];
|
||||
}>;
|
||||
|
||||
/** A validator slot whose validation is skipped (`unvalidatedPayload`). */
|
||||
export type ApiUnvalidatedSlot = "input" | "output" | "problem";
|
||||
|
||||
/**
|
||||
* FE-REG-API. The governed row of one installed HTTP operation, projected
|
||||
* from its V3 descriptor (`InstalledHttpContract`). A feature writes the
|
||||
* operation once, in its contract contribution; `check:registries` compares
|
||||
* these rows with the approved baseline.
|
||||
*
|
||||
* 1103/07-01. The row carries every wire-facing value of the descriptor:
|
||||
* what is sent and accepted, the bounds, and the retry and command data. The
|
||||
* governance grades a change (`config/contracts/registry-governance.json`).
|
||||
* Only functions stay out (`projectRequest`, the validators' parsing, the
|
||||
* command effect classifiers), with the policy and diagnostics names.
|
||||
*/
|
||||
export type ApiOperationRow = Readonly<{
|
||||
operationId: string;
|
||||
@@ -25,6 +49,17 @@ export type ApiOperationRow = Readonly<{
|
||||
requestSchema: string;
|
||||
responseSchema: string;
|
||||
problemSchema: string;
|
||||
acceptedStatuses: readonly number[];
|
||||
emptyBodyStatuses: readonly number[];
|
||||
/** Validator slots that skip validation by name; `[]` when all validate. */
|
||||
unvalidated: readonly ApiUnvalidatedSlot[];
|
||||
requestByteLimit: number;
|
||||
responseByteLimit: number;
|
||||
totalDeadlineMs: number;
|
||||
retryBudget: 0 | 1 | 2;
|
||||
traffic: TrafficBudget | null;
|
||||
commandEffect: ApiCommandEffectRow | null;
|
||||
commandRecovery: CommandRecoveryDescriptor | null;
|
||||
}>;
|
||||
|
||||
/**
|
||||
@@ -50,8 +85,60 @@ export function projectApiOperationRows(
|
||||
requestSchema: contract.inputValidator.schemaId,
|
||||
responseSchema: contract.outputValidator.schemaId,
|
||||
problemSchema: contract.problemValidator.schemaId,
|
||||
acceptedStatuses: Object.freeze([...contract.acceptedStatuses]),
|
||||
emptyBodyStatuses: Object.freeze([...contract.emptyBodyStatuses]),
|
||||
unvalidated: unvalidatedSlots({
|
||||
input: contract.inputValidator,
|
||||
output: contract.outputValidator,
|
||||
problem: contract.problemValidator,
|
||||
}),
|
||||
requestByteLimit: frontend.requestByteLimit,
|
||||
responseByteLimit: frontend.responseByteLimit,
|
||||
totalDeadlineMs: frontend.totalDeadlineMs,
|
||||
retryBudget: frontend.retryBudget,
|
||||
traffic:
|
||||
frontend.traffic === undefined
|
||||
? null
|
||||
: Object.freeze({
|
||||
maxPhysicalRequests: frontend.traffic.maxPhysicalRequests,
|
||||
maxRetries: frontend.traffic.maxRetries,
|
||||
maxConcurrentRequests: frontend.traffic.maxConcurrentRequests,
|
||||
maxQueuedRequests: frontend.traffic.maxQueuedRequests,
|
||||
}),
|
||||
commandEffect: commandEffectRow(contract.commandEffect),
|
||||
commandRecovery:
|
||||
contract.commandRecovery === null
|
||||
? null
|
||||
: Object.freeze({ ...contract.commandRecovery }),
|
||||
});
|
||||
}
|
||||
}
|
||||
return Object.freeze(rows);
|
||||
}
|
||||
|
||||
/** The same marker rule as `listUnvalidatedPayloads`: any marker counts. */
|
||||
function unvalidatedSlots(
|
||||
validators: Readonly<Record<ApiUnvalidatedSlot, RuntimeValidator<unknown>>>,
|
||||
): readonly ApiUnvalidatedSlot[] {
|
||||
return Object.freeze(
|
||||
(Object.keys(validators) as ApiUnvalidatedSlot[]).filter(
|
||||
(slot) => validators[slot].validation !== undefined,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function commandEffectRow(
|
||||
effect: CommandEffectDescriptor<unknown> | null,
|
||||
): ApiCommandEffectRow | null {
|
||||
if (effect === null) return null;
|
||||
// Read structurally: a descriptor that does not name refused codes has no
|
||||
// such list, and the row then has no such field.
|
||||
const refused: unknown = (effect as Readonly<{ refusedBeforeWrite?: unknown }>)
|
||||
.refusedBeforeWrite;
|
||||
return Object.freeze({
|
||||
classifiesStatus: typeof effect.classifyStatus === "function",
|
||||
...(Array.isArray(refused)
|
||||
? { refusedBeforeWrite: Object.freeze(refused.map(String)) }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
+16
-5
@@ -41,6 +41,12 @@ export type EnvironmentDefinition = Readonly<{
|
||||
defaultValue: unknown;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* FE-REG-ENV. A runtime row states its key as `runtimeConfigV2ArtifactSchema`
|
||||
* (`release-artifacts.ts`) reads it: `required` when config.json must carry
|
||||
* the key, and `defaultValue` the value the schema gives an absent key, or
|
||||
* `null` when it gives none (1103/13-04, tests/unit/env-registry-coverage).
|
||||
*/
|
||||
export const ENV_REGISTRY = Object.freeze(withProductRows({
|
||||
// F-6. Required: a staging or production build fails without it
|
||||
// (scripts/generate-runtime-config.ts). Local and development builds fall
|
||||
@@ -53,20 +59,25 @@ export const ENV_REGISTRY = Object.freeze(withProductRows({
|
||||
API_BASE_URL: runtime("public-sensitive", true, null),
|
||||
REQUEST_TIMEOUT_MS: runtime("public", false, 10_000),
|
||||
MAX_RETRY_ATTEMPTS: runtime("public", false, 2),
|
||||
TELEMETRY_ENABLED: runtime("public", true, false),
|
||||
TELEMETRY_ENABLED: runtime("public", true, null),
|
||||
TELEMETRY_ENDPOINT: runtime("public-sensitive", false, null),
|
||||
AUTH_MODE: runtime("public", true, "external"),
|
||||
AUTH_MODE: runtime("public", true, null),
|
||||
CONFIG_SCHEMA_VERSION: runtime("public", true, null),
|
||||
RELEASE_MANIFEST_URL: runtime("public", true, "/release-manifest.json"),
|
||||
RELEASE_MANIFEST_URL: runtime("public", false, "/release-manifest.json"),
|
||||
// F-6. The release identity the build writes into config.json. It must match
|
||||
// the deployed HTML and release manifest, or boot stops with
|
||||
// CONFIG_BUILD_MISMATCH (scripts/check-release-admission.ts).
|
||||
RELEASE_ID: runtime("public-metadata", false, null),
|
||||
BUILD_ID: runtime("public-metadata", false, null),
|
||||
// §3.5: overrides may only disable an installed capability, never enable one.
|
||||
CAPABILITY_OVERRIDES: runtime("public", false, null),
|
||||
CAPABILITY_OVERRIDES: runtime("public", false, Object.freeze({
|
||||
REALTIME: "DEFAULT",
|
||||
WEB_WORKER: "DEFAULT",
|
||||
SERVICE_WORKER: "DEFAULT",
|
||||
OFFLINE_COMMANDS: "DEFAULT",
|
||||
})),
|
||||
// §3.5: likewise for features — subtractive, keyed by installed feature id.
|
||||
FEATURE_OVERRIDES: runtime("public", false, null),
|
||||
FEATURE_OVERRIDES: runtime("public", false, Object.freeze({})),
|
||||
// §3.5: build-time narrowing of the product manifest, applied by
|
||||
// scripts/generate-product-feature-index.ts (09-02). A feature left out here
|
||||
// is not imported by any registry and never reaches the bundle.
|
||||
|
||||
@@ -118,10 +118,27 @@ export type FailureEffectCertainty =
|
||||
| "APPLIED_CONFIRMED"
|
||||
| "MAYBE_APPLIED";
|
||||
|
||||
/**
|
||||
* 1101/07-05. The failure that crosses an application input boundary: a
|
||||
* gateway result, a query or mutation error. Its `kind` is the closed set
|
||||
* above. `AppError` (`src/platform/errors/app-error.ts`) is the other
|
||||
* vocabulary: an open `owner.reason` kind a feature uses inside its own
|
||||
* domain, mapped from an `AppFailure` where the feature needs it. Neither
|
||||
* changes how a request is retried; the HTTP executor follows the
|
||||
* operation's `retrySemantics` and `retryBudget`.
|
||||
*/
|
||||
export type AppFailure = Readonly<{
|
||||
kind: FailureKind;
|
||||
code: string;
|
||||
httpStatus?: number;
|
||||
/**
|
||||
* Whether sending the same operation again is safe as far as this failure
|
||||
* tells: the registry default, forced `false` once a write may have
|
||||
* applied. Nothing in src reads it today. What the screen offers is
|
||||
* `action`: `"retry"` shows a retry button even when this is `false`
|
||||
* (`CONFLICT`, `QUERY_CACHE_FAILURE`): the user, not the runtime, sends
|
||||
* again.
|
||||
*/
|
||||
retryable: boolean;
|
||||
operationId: string;
|
||||
attemptCount: number;
|
||||
|
||||
@@ -127,6 +127,15 @@ export function mappingViolation(code: string): MappingResult<never> {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 1101/07-07. How the package says a write whose result is unknown can be
|
||||
* settled: resend with the same idempotency key, or read the operation back
|
||||
* through `inspectOperationId`. Composition requires one on a KEYED command,
|
||||
* and FE-REG-API records it. The HTTP executor does not read it: a write
|
||||
* that ends `MAYBE_APPLIED` comes back to the feature, and the feature's
|
||||
* gateway decides whether to resend or inspect (closed-deep-design.md
|
||||
* §4.4 under docs/architecture).
|
||||
*/
|
||||
export type CommandRecoveryDescriptor = Readonly<{
|
||||
mode: "IDEMPOTENCY_REPLAY" | "INSPECT_OPERATION";
|
||||
operationIdentityField: string;
|
||||
@@ -510,6 +519,17 @@ function assertHttpContract(
|
||||
if (contract.requestBody !== "NONE") {
|
||||
fail(`${label}: read operations carry no request body`);
|
||||
}
|
||||
// 1103/07-01 (c). The executor runs a read as a read whatever it is
|
||||
// declared; KEYED or NEVER here only looks like a decision the executor
|
||||
// never makes. A realtime snapshot binding reads the same pair.
|
||||
if (
|
||||
contract.retrySemantics !== "SAFE" &&
|
||||
contract.retrySemantics !== "IDEMPOTENT"
|
||||
) {
|
||||
fail(
|
||||
`${label}: ${contract.method} is a read; its retrySemantics is SAFE or IDEMPOTENT, not ${contract.retrySemantics}`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (!contract.commandEffect) {
|
||||
fail(`${label}: command operations require a command effect descriptor`);
|
||||
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
// 0929/P-07-06: a zod subpath is the same zod, so it is reached through
|
||||
// src/contracts/zod.ts too.
|
||||
import { z } from "zod/v4";
|
||||
|
||||
export const subpathSchema = z.string();
|
||||
@@ -1,13 +1,22 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
canonicalizeRegistryValue,
|
||||
diffRegistrySnapshots,
|
||||
} from "../../scripts/lib/registry-compatibility.ts";
|
||||
import { projectApiOperationRows } from "../../src/contracts/api-operations.ts";
|
||||
import { composeContractContributions } from "../../src/contracts/external-contract-runtime.ts";
|
||||
import { unvalidatedPayload } from "../../src/contracts/unvalidated-payload.ts";
|
||||
import {
|
||||
API_OPERATIONS,
|
||||
COMPOSED_CONTRACT_CONTRIBUTIONS,
|
||||
} from "../../src/features/loaded-feature-runtimes.ts";
|
||||
import {
|
||||
TEST_CLASSIFIED_CREATE_HTTP_CONTRACT,
|
||||
TEST_CONTRACT_CONTRIBUTION,
|
||||
TEST_CREATE_HTTP_CONTRACT,
|
||||
TEST_LIST_HTTP_CONTRACT,
|
||||
} from "../helpers/external-contract-fixture.ts";
|
||||
|
||||
@@ -40,11 +49,80 @@ describe("FE-REG-API rows projected from HTTP descriptors", () => {
|
||||
requestSchema: "TestEntityListQuery",
|
||||
responseSchema: "TestEntityListPayload",
|
||||
problemSchema: "TestProblem",
|
||||
acceptedStatuses: [200],
|
||||
emptyBodyStatuses: [],
|
||||
unvalidated: [],
|
||||
requestByteLimit: 0,
|
||||
responseByteLimit: 32_768,
|
||||
totalDeadlineMs: 10_000,
|
||||
retryBudget: 2,
|
||||
traffic: null,
|
||||
commandEffect: null,
|
||||
commandRecovery: null,
|
||||
});
|
||||
expect(rows.TEST_CREATE_ENTITY).toMatchObject({
|
||||
method: "POST",
|
||||
retrySemantics: "KEYED",
|
||||
requestBody: "JSON",
|
||||
acceptedStatuses: [201],
|
||||
retryBudget: 0,
|
||||
commandEffect: { classifiesStatus: false },
|
||||
commandRecovery: {
|
||||
mode: "IDEMPOTENCY_REPLAY",
|
||||
operationIdentityField: "idempotencyKey",
|
||||
},
|
||||
});
|
||||
expect(rows.TEST_CREATE_ENTITY?.commandEffect).not.toHaveProperty(
|
||||
"refusedBeforeWrite",
|
||||
);
|
||||
});
|
||||
|
||||
it("carries the command effect data and the validator slots that skip validation", () => {
|
||||
const traffic = Object.freeze({
|
||||
maxPhysicalRequests: 2,
|
||||
maxRetries: 1,
|
||||
maxConcurrentRequests: 1,
|
||||
maxQueuedRequests: 0,
|
||||
});
|
||||
const rows = projectApiOperationRows(
|
||||
composeContractContributions([
|
||||
{
|
||||
...TEST_CONTRACT_CONTRIBUTION,
|
||||
http: [
|
||||
{
|
||||
...TEST_LIST_HTTP_CONTRACT,
|
||||
contract: {
|
||||
...TEST_LIST_HTTP_CONTRACT.contract,
|
||||
outputValidator: unvalidatedPayload(
|
||||
"TestEntityListPayload",
|
||||
"typed by the package",
|
||||
),
|
||||
},
|
||||
frontend: { ...TEST_LIST_HTTP_CONTRACT.frontend, traffic },
|
||||
},
|
||||
{
|
||||
...TEST_CLASSIFIED_CREATE_HTTP_CONTRACT,
|
||||
contract: {
|
||||
...TEST_CLASSIFIED_CREATE_HTTP_CONTRACT.contract,
|
||||
// A descriptor that names the codes refused before any write.
|
||||
commandEffect: {
|
||||
...TEST_CLASSIFIED_CREATE_HTTP_CONTRACT.contract.commandEffect,
|
||||
refusedBeforeWrite: ["VALIDATION_FAILED", "CONFLICT"],
|
||||
},
|
||||
},
|
||||
},
|
||||
] as never,
|
||||
},
|
||||
]).contributions,
|
||||
);
|
||||
|
||||
expect(rows.TEST_LIST_ENTITIES).toMatchObject({
|
||||
unvalidated: ["output"],
|
||||
traffic,
|
||||
});
|
||||
expect(rows.TEST_CREATE_ENTITY?.commandEffect).toEqual({
|
||||
classifiesStatus: true,
|
||||
refusedBeforeWrite: ["VALIDATION_FAILED", "CONFLICT"],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -78,3 +156,148 @@ describe("FE-REG-API rows projected from HTTP descriptors", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 1103/07-01. The wire values of a descriptor are graded by the governance
|
||||
* the repository ships, not only recorded: narrowing what the frontend
|
||||
* accepts, or changing how it validates, needs baseline evidence.
|
||||
*/
|
||||
describe("FE-REG-API compatibility of descriptor wire values", () => {
|
||||
async function snapshotOf(
|
||||
rows: Readonly<Record<string, unknown>>,
|
||||
): Promise<Readonly<Record<string, unknown>>> {
|
||||
const governance = JSON.parse(
|
||||
await readFile("config/contracts/registry-governance.json", "utf8"),
|
||||
) as {
|
||||
registries: Array<{
|
||||
registryId: string;
|
||||
breakingFields: string[];
|
||||
fieldTypes: Record<string, string>;
|
||||
}>;
|
||||
};
|
||||
const api = governance.registries.find(
|
||||
(registry) => registry.registryId === "FE-REG-API",
|
||||
)!;
|
||||
return {
|
||||
registries: [
|
||||
{
|
||||
registryId: "FE-REG-API",
|
||||
contract: {
|
||||
breakingFields: api.breakingFields,
|
||||
fieldTypes: api.fieldTypes,
|
||||
},
|
||||
rows: canonicalizeRegistryValue(rows),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
const rowsWith = (
|
||||
contract: Partial<typeof TEST_CREATE_HTTP_CONTRACT.contract> = {},
|
||||
frontend: Partial<typeof TEST_CREATE_HTTP_CONTRACT.frontend> = {},
|
||||
) =>
|
||||
projectApiOperationRows(
|
||||
composeContractContributions([
|
||||
{
|
||||
...TEST_CONTRACT_CONTRIBUTION,
|
||||
http: [
|
||||
{
|
||||
contract: {
|
||||
...TEST_CREATE_HTTP_CONTRACT.contract,
|
||||
acceptedStatuses: [200, 201],
|
||||
emptyBodyStatuses: [201],
|
||||
...contract,
|
||||
},
|
||||
frontend: { ...TEST_CREATE_HTTP_CONTRACT.frontend, ...frontend },
|
||||
},
|
||||
] as never,
|
||||
},
|
||||
]).contributions,
|
||||
);
|
||||
async function changesFor(after: Readonly<Record<string, unknown>>) {
|
||||
const diff = diffRegistrySnapshots(
|
||||
await snapshotOf(rowsWith()),
|
||||
await snapshotOf(after),
|
||||
);
|
||||
return diff.changes.map(({ changeId, impact }) => `${changeId} ${impact}`);
|
||||
}
|
||||
|
||||
it.each([
|
||||
[
|
||||
"a narrowed status list",
|
||||
{ acceptedStatuses: [201] },
|
||||
{},
|
||||
[
|
||||
"FE-REG-API:TEST_CREATE_ENTITY:acceptedStatuses:allowed-value-removed breaking",
|
||||
],
|
||||
],
|
||||
[
|
||||
"a narrowed empty-body list",
|
||||
{ emptyBodyStatuses: [] },
|
||||
{},
|
||||
[
|
||||
"FE-REG-API:TEST_CREATE_ENTITY:emptyBodyStatuses:allowed-value-removed breaking",
|
||||
],
|
||||
],
|
||||
[
|
||||
"another problem schema",
|
||||
{
|
||||
problemValidator: {
|
||||
...TEST_CREATE_HTTP_CONTRACT.contract.problemValidator,
|
||||
schemaId: "OtherProblem",
|
||||
},
|
||||
},
|
||||
{},
|
||||
["FE-REG-API:TEST_CREATE_ENTITY:problemSchema:field-changed breaking"],
|
||||
],
|
||||
[
|
||||
"an output whose validation is skipped",
|
||||
{ outputValidator: unvalidatedPayload("TestEntityPayload", "trusted") },
|
||||
{},
|
||||
["FE-REG-API:TEST_CREATE_ENTITY:unvalidated:field-changed breaking"],
|
||||
],
|
||||
[
|
||||
"a widened status list",
|
||||
{ acceptedStatuses: [200, 201, 202] },
|
||||
{},
|
||||
[
|
||||
"FE-REG-API:TEST_CREATE_ENTITY:acceptedStatuses:field-changed behavior-change",
|
||||
],
|
||||
],
|
||||
[
|
||||
"a larger response limit and a longer deadline",
|
||||
{},
|
||||
{ responseByteLimit: 8_388_608, totalDeadlineMs: 60_000 },
|
||||
[
|
||||
"FE-REG-API:TEST_CREATE_ENTITY:responseByteLimit:field-changed behavior-change",
|
||||
"FE-REG-API:TEST_CREATE_ENTITY:totalDeadlineMs:field-changed behavior-change",
|
||||
],
|
||||
],
|
||||
[
|
||||
"a traffic policy",
|
||||
{},
|
||||
{
|
||||
traffic: {
|
||||
maxPhysicalRequests: 1,
|
||||
maxRetries: 0,
|
||||
maxConcurrentRequests: 1,
|
||||
maxQueuedRequests: 0,
|
||||
},
|
||||
},
|
||||
["FE-REG-API:TEST_CREATE_ENTITY:traffic:field-changed behavior-change"],
|
||||
],
|
||||
[
|
||||
"a status classifier",
|
||||
{
|
||||
commandEffect: TEST_CLASSIFIED_CREATE_HTTP_CONTRACT.contract.commandEffect,
|
||||
},
|
||||
{},
|
||||
[
|
||||
"FE-REG-API:TEST_CREATE_ENTITY:commandEffect:field-changed behavior-change",
|
||||
],
|
||||
],
|
||||
] as const)("grades %s", async (_name, contract, frontend, expected) => {
|
||||
expect(await changesFor(rowsWith(contract as never, frontend as never))).toEqual(
|
||||
expected,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,19 +1,84 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ENV_REGISTRY } from "../../src/contracts/env.ts";
|
||||
import {
|
||||
assertSafeConfigNames,
|
||||
ENV_REGISTRY,
|
||||
type EnvironmentDefinition,
|
||||
} from "../../src/contracts/env.ts";
|
||||
import { runtimeConfigV2ArtifactSchema } from "../../src/contracts/release-artifacts.ts";
|
||||
|
||||
const rows: Readonly<Record<string, EnvironmentDefinition>> = ENV_REGISTRY;
|
||||
const shape = runtimeConfigV2ArtifactSchema.shape as Readonly<
|
||||
Record<string, { safeParse(value: unknown): { success: boolean; data?: unknown } }>
|
||||
>;
|
||||
|
||||
/**
|
||||
* What the schema field says when the key is left out of config.json: a field
|
||||
* that fails on `undefined` is required and has no default; one that passes
|
||||
* has the parsed value as its default (`null` when it stays absent).
|
||||
*/
|
||||
function schemaDeclaration(key: string) {
|
||||
const result = shape[key]!.safeParse(undefined);
|
||||
return result.success
|
||||
? { required: false, defaultValue: result.data ?? null }
|
||||
: { required: true, defaultValue: null };
|
||||
}
|
||||
|
||||
// 09-02. A key the deployed config.json may carry needs an FE-REG-ENV row, so
|
||||
// check:registries sees it. A product key added to
|
||||
// PRODUCT_RUNTIME_CONFIG_FIELDS without a PRODUCT_ENV_REGISTRY row fails here.
|
||||
describe("FE-REG-ENV coverage", () => {
|
||||
it("has a runtime row for every V2 runtime config key", () => {
|
||||
const missing = Object.keys(runtimeConfigV2ArtifactSchema.shape).filter(
|
||||
(key) =>
|
||||
!Object.hasOwn(ENV_REGISTRY, key) ||
|
||||
ENV_REGISTRY[key as keyof typeof ENV_REGISTRY].phase !== "runtime",
|
||||
const missing = Object.keys(shape).filter(
|
||||
(key) => !Object.hasOwn(rows, key) || rows[key]!.phase !== "runtime",
|
||||
);
|
||||
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
|
||||
// 1103/13-04, 0929/P-07-05. The other direction: a runtime row names a key
|
||||
// the schema reads, and states its required flag and default as the schema
|
||||
// field does, so the governed snapshot does not describe another document.
|
||||
it("has no runtime row the V2 schema does not read", () => {
|
||||
const extra = Object.keys(rows).filter(
|
||||
(key) => rows[key]!.phase === "runtime" && !Object.hasOwn(shape, key),
|
||||
);
|
||||
|
||||
expect(extra).toEqual([]);
|
||||
});
|
||||
|
||||
it("states each runtime row's required flag and default as its schema field does", () => {
|
||||
const differences = Object.keys(shape).flatMap((key) => {
|
||||
const row = rows[key];
|
||||
if (!row) return [];
|
||||
const declared = { required: row.required, defaultValue: row.defaultValue };
|
||||
const expected = schemaDeclaration(key);
|
||||
return isDeepStrictEqual(declared, expected)
|
||||
? []
|
||||
: [`${key}: row ${JSON.stringify(declared)}, schema ${JSON.stringify(expected)}`];
|
||||
});
|
||||
|
||||
expect(differences).toEqual([]);
|
||||
});
|
||||
|
||||
// 1103/07-04. The boot refuses a config.json key with a credential-like
|
||||
// name (`assertSafeConfigNames`). Checking every key the schema reads, with
|
||||
// the nested keys of its defaults, fails here instead of at the first boot,
|
||||
// and the error names the key.
|
||||
it("names no runtime config key the boot would refuse", () => {
|
||||
const keys = new Set([
|
||||
...Object.keys(shape),
|
||||
...Object.keys(rows).filter((key) => rows[key]!.phase === "runtime"),
|
||||
]);
|
||||
const document = Object.fromEntries(
|
||||
[...keys].map((key) => [
|
||||
key,
|
||||
Object.hasOwn(shape, key) ? schemaDeclaration(key).defaultValue : null,
|
||||
]),
|
||||
);
|
||||
|
||||
expect(() => assertSafeConfigNames(document)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -124,6 +124,39 @@ describe("write operation rules", () => {
|
||||
).toBe("test-feature/TEST_LIST_ENTITIES: read operations carry no command descriptors");
|
||||
});
|
||||
|
||||
// 1103/07-01 (c). The KEYED recovery check sits in the write branch, so a
|
||||
// GET written as KEYED or NEVER used to compose and run as a read with no
|
||||
// retry. A read is SAFE or IDEMPOTENT (docs/manual/02-decision-tables.md 3절).
|
||||
it.each([
|
||||
["GET", "KEYED"],
|
||||
["GET", "NEVER"],
|
||||
["HEAD", "KEYED"],
|
||||
["HEAD", "NEVER"],
|
||||
] as const)("rejects a %s declared %s", (method, retrySemantics) => {
|
||||
expect(
|
||||
reasonFor({
|
||||
...listRow,
|
||||
contract: { ...listRow.contract, method, retrySemantics },
|
||||
frontend: { ...listRow.frontend, retryBudget: 0 },
|
||||
}),
|
||||
).toBe(
|
||||
`test-feature/TEST_LIST_ENTITIES: ${method} is a read; its retrySemantics is SAFE or IDEMPOTENT, not ${retrySemantics}`,
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["SAFE", "IDEMPOTENT"] as const)("composes a GET declared %s", (retrySemantics) => {
|
||||
expect(
|
||||
composeContractContributions([
|
||||
contribution("read-rule", [
|
||||
{
|
||||
...listRow,
|
||||
contract: { ...listRow.contract, retrySemantics },
|
||||
} as InstalledContractContribution["http"][number],
|
||||
]),
|
||||
]).httpByOperationId.size,
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it("requires a recovery descriptor on a KEYED command", () => {
|
||||
expect(
|
||||
reasonFor({
|
||||
|
||||
@@ -115,6 +115,16 @@ const snapshotOperation: ApiOperationRow = Object.freeze({
|
||||
requestSchema: "NoRequest",
|
||||
responseSchema: "ReferenceRealtimeCheckpoint",
|
||||
problemSchema: "ReferenceRealtimeProblem",
|
||||
acceptedStatuses: [200],
|
||||
emptyBodyStatuses: [],
|
||||
unvalidated: [],
|
||||
requestByteLimit: 0,
|
||||
responseByteLimit: 32_768,
|
||||
totalDeadlineMs: 10_000,
|
||||
retryBudget: 2,
|
||||
traffic: null,
|
||||
commandEffect: null,
|
||||
commandRecovery: null,
|
||||
});
|
||||
|
||||
export const TEST_API_OPERATIONS = Object.freeze({
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { projectApiOperationRows } from "../../../src/contracts/api-operations.ts";
|
||||
import {
|
||||
composeContractContributions,
|
||||
type HttpMethod,
|
||||
type RetrySemantics,
|
||||
} from "../../../src/contracts/external-contract-runtime.ts";
|
||||
import {
|
||||
createRealtimePolicyRegistry,
|
||||
defineEventTypeId,
|
||||
@@ -20,6 +26,7 @@ import {
|
||||
TEST_SCHEMA_CODECS,
|
||||
createTestRealtimeRegistry,
|
||||
} from "./fixture.ts";
|
||||
import { TEST_CONTRACT_CONTRIBUTION } from "../../helpers/external-contract-fixture.ts";
|
||||
|
||||
describe("realtime policy registry", () => {
|
||||
it("deep-snapshots registrations and resolves only stream-owned event types", () => {
|
||||
@@ -209,6 +216,105 @@ describe("realtime policy registry", () => {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 1103/04-03, 07-02, 10-04. Recovery sends the snapshot operation on every
|
||||
* reconnect, so it must be a read that may be sent again: GET with SAFE or
|
||||
* IDEMPOTENT. A HEAD carries no checkpoint body. The row is the FE-REG-API
|
||||
* projection of a composed descriptor, so a renamed projected field breaks
|
||||
* this table too.
|
||||
*/
|
||||
describe("realtime snapshot operation binding", () => {
|
||||
const projected = projectApiOperationRows(
|
||||
composeContractContributions([TEST_CONTRACT_CONTRIBUTION]).contributions,
|
||||
);
|
||||
const methods: readonly HttpMethod[] = [
|
||||
"GET",
|
||||
"HEAD",
|
||||
"POST",
|
||||
"PUT",
|
||||
"PATCH",
|
||||
"DELETE",
|
||||
];
|
||||
const retries: readonly RetrySemantics[] = [
|
||||
"SAFE",
|
||||
"IDEMPOTENT",
|
||||
"KEYED",
|
||||
"NEVER",
|
||||
];
|
||||
const register = (
|
||||
recovery: "CURSOR" | "SNAPSHOT_ONLY",
|
||||
apiOperations: Readonly<Record<string, unknown>>,
|
||||
) => {
|
||||
const baseline = createTestRealtimeRegistry();
|
||||
const stream = baseline.listStreams()[0]!;
|
||||
return createRealtimePolicyRegistry({
|
||||
streams: [
|
||||
{
|
||||
...stream,
|
||||
recovery:
|
||||
recovery === "CURSOR"
|
||||
? stream.recovery
|
||||
: {
|
||||
mode: "SNAPSHOT_ONLY",
|
||||
snapshotOperationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
|
||||
checkpointCodecId: "ReferenceRealtimeCheckpoint",
|
||||
barrier: "CONNECT_BUFFER",
|
||||
},
|
||||
},
|
||||
],
|
||||
eventTypes: [baseline.listEventTypes()[0]!],
|
||||
bindings: {
|
||||
...bindings(),
|
||||
apiOperations: apiOperations as ReturnType<
|
||||
typeof bindings
|
||||
>["apiOperations"],
|
||||
},
|
||||
});
|
||||
};
|
||||
const snapshotRow = (method: HttpMethod, retrySemantics: RetrySemantics) => ({
|
||||
GET_REFERENCE_REALTIME_SNAPSHOT: {
|
||||
...projected.TEST_LIST_ENTITIES!,
|
||||
operationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
|
||||
method,
|
||||
retrySemantics,
|
||||
},
|
||||
});
|
||||
const cases = methods.flatMap((method) =>
|
||||
retries.map((retrySemantics) => ({
|
||||
method,
|
||||
retrySemantics,
|
||||
accepted:
|
||||
method === "GET" &&
|
||||
(retrySemantics === "SAFE" || retrySemantics === "IDEMPOTENT"),
|
||||
})),
|
||||
);
|
||||
|
||||
it.each(cases)(
|
||||
"$method $retrySemantics as the snapshot operation: accepted=$accepted",
|
||||
({ method, retrySemantics, accepted }) => {
|
||||
for (const recovery of ["CURSOR", "SNAPSHOT_ONLY"] as const) {
|
||||
const install = () =>
|
||||
register(recovery, snapshotRow(method, retrySemantics));
|
||||
if (accepted) {
|
||||
expect(install().findStream(STREAM_ID)?.recovery.mode).toBe(recovery);
|
||||
} else {
|
||||
expect(install, recovery).toThrow(
|
||||
recovery === "CURSOR"
|
||||
? "Realtime cursor recovery profile is invalid."
|
||||
: "Realtime snapshot recovery profile is invalid.",
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("refuses a snapshot operation id with no FE-REG-API row", () => {
|
||||
expect(() => register("CURSOR", {})).toThrow(
|
||||
"Realtime cursor recovery profile is invalid.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
function bindings() {
|
||||
return {
|
||||
schemaCodecs: TEST_SCHEMA_CODECS,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
diffRegistrySnapshots,
|
||||
registrySnapshotDigest,
|
||||
validateBreakingEvidence,
|
||||
verifyRegistryBaselineApproval,
|
||||
} from "../../scripts/lib/registry-compatibility.ts";
|
||||
@@ -536,4 +537,115 @@ describe("registry governance manifest", () => {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// 1103/14-06. A contract contribution that fails to compose throws while
|
||||
// the registry source loads. The gate names the cause the error carries in
|
||||
// `reason` and does not also report the unloaded registries as deleted
|
||||
// (`removed` evidence) or as unknown reference targets.
|
||||
it("names a load error's reason and reports no cascade for the registries it did not load", async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "registry-source-reason-"));
|
||||
const run = (extra: readonly string[]) =>
|
||||
spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
path.resolve("scripts/check-registries.ts"),
|
||||
"--governance",
|
||||
"governance.json",
|
||||
"--artifact",
|
||||
"out.json",
|
||||
...extra,
|
||||
],
|
||||
{ cwd: directory, encoding: "utf8" },
|
||||
);
|
||||
try {
|
||||
await mkdir(path.join(directory, "src"), { recursive: true });
|
||||
await writeFile(
|
||||
path.join(directory, "src/composed.ts"),
|
||||
'export const ROWS = { A: { id: "A" } };\n',
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "src/routes.ts"),
|
||||
'export const ROUTES = { R: { id: "R", target: "A" } };\n',
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "governance.json"),
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
sourceDirectories: [],
|
||||
registries: [
|
||||
{
|
||||
registryId: "FIXTURE-COMPOSED",
|
||||
path: "src/composed.ts",
|
||||
exportName: "ROWS",
|
||||
owner: "fixture",
|
||||
keyField: "id",
|
||||
requiredFields: ["id"],
|
||||
fieldTypes: { id: "string" },
|
||||
},
|
||||
{
|
||||
registryId: "FIXTURE-ROUTES",
|
||||
path: "src/routes.ts",
|
||||
exportName: "ROUTES",
|
||||
owner: "fixture",
|
||||
keyField: "id",
|
||||
requiredFields: ["id", "target"],
|
||||
fieldTypes: { id: "string", target: "string" },
|
||||
references: [
|
||||
{
|
||||
field: "target",
|
||||
registryId: "FIXTURE-COMPOSED",
|
||||
targetField: "id",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const healthy = run(["--no-baseline"]);
|
||||
expect(healthy.status, healthy.stderr).toBe(0);
|
||||
const report = JSON.parse(
|
||||
await readFile(path.join(directory, "out.json"), "utf8"),
|
||||
) as { registries: unknown[] };
|
||||
const baseline = { schemaVersion: 2, registries: report.registries };
|
||||
await writeFile(path.join(directory, "baseline.json"), JSON.stringify(baseline));
|
||||
await writeFile(
|
||||
path.join(directory, "approval.json"),
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
snapshotDigest: registrySnapshotDigest(baseline),
|
||||
owner: "fixture",
|
||||
reason: "fixture",
|
||||
approvedAt: "2026-11-04T00:00:00.000Z",
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "evidence.json"),
|
||||
JSON.stringify({ schemaVersion: 1, changes: [] }),
|
||||
);
|
||||
const withBaseline = [
|
||||
"--baseline",
|
||||
"baseline.json",
|
||||
"--approval",
|
||||
"approval.json",
|
||||
"--compatibility-evidence",
|
||||
"evidence.json",
|
||||
];
|
||||
expect(run(withBaseline).status).toBe(0);
|
||||
|
||||
await writeFile(
|
||||
path.join(directory, "src/composed.ts"),
|
||||
'throw Object.assign(new Error("Installed contract contribution is not composable"), { reason: "notice-feature/NOTICE_LIST_ITEMS: unknown authProfileId NOTICE_NOPE" });\n',
|
||||
);
|
||||
const broken = run(withBaseline);
|
||||
const output = `${broken.stdout}${broken.stderr}`;
|
||||
|
||||
expect(broken.status).toBe(1);
|
||||
expect(output.trim().split("\n")).toEqual([
|
||||
"Registry governance failed:",
|
||||
"missing registry source src/composed.ts: Installed contract contribution is not composable (reason: notice-feature/NOTICE_LIST_ITEMS: unknown authProfileId NOTICE_NOPE)",
|
||||
]);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -63,26 +63,79 @@ describe("one installed REST auth profile registry", () => {
|
||||
* installed HTTP contract has to refuse it too.
|
||||
*/
|
||||
describe("cookie profiles on writes", () => {
|
||||
const cookie = (authProfileId: string, csrf: readonly ("x-csrf-token" | "x-xsrf-token")[]) => ({
|
||||
const cookie = (
|
||||
authProfileId: string,
|
||||
headers: readonly ("x-csrf-token" | "x-xsrf-token" | "x-tenant-context")[],
|
||||
) => ({
|
||||
authProfileId,
|
||||
transport: "SAME_ORIGIN_COOKIE" as const,
|
||||
credentials: "include" as const,
|
||||
allowedCredentialHeaders: [...csrf],
|
||||
requiredCredentialHeaders: [...csrf],
|
||||
allowedCredentialHeaders: [...headers],
|
||||
requiredCredentialHeaders: [...headers],
|
||||
});
|
||||
const registry = installRestAuthProfileRegistry({
|
||||
...REST_AUTH_PROFILES,
|
||||
COOKIE_READ: cookie("COOKIE_READ", []),
|
||||
COOKIE_WRITE: cookie("COOKIE_WRITE", ["x-xsrf-token"]),
|
||||
COOKIE_CSRF: cookie("COOKIE_CSRF", ["x-csrf-token"]),
|
||||
COOKIE_TENANT: cookie("COOKIE_TENANT", ["x-tenant-context"]),
|
||||
});
|
||||
const withProfile = (index: number, authProfileId: string) => {
|
||||
const withProfile = (
|
||||
index: number,
|
||||
authProfileId: string,
|
||||
method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE",
|
||||
) => {
|
||||
const row = TEST_CONTRACT_CONTRIBUTION.http[index]!;
|
||||
return {
|
||||
...TEST_CONTRACT_CONTRIBUTION,
|
||||
http: [{ ...row, frontend: { ...row.frontend, authProfileId } }],
|
||||
http: [
|
||||
{
|
||||
contract: method ? { ...row.contract, method } : row.contract,
|
||||
frontend: { ...row.frontend, authProfileId },
|
||||
},
|
||||
],
|
||||
};
|
||||
};
|
||||
// TEST_CONTRACT_CONTRIBUTION.http: [list (GET), detail (GET), create (POST)]
|
||||
const compose = (
|
||||
index: number,
|
||||
authProfileId: string,
|
||||
method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE",
|
||||
) =>
|
||||
composeContractContributions(
|
||||
[withProfile(index, authProfileId, method)],
|
||||
registry,
|
||||
).httpByOperationId.size;
|
||||
|
||||
// 1103/07-02, 10-03. Every write method, not POST alone, and only the two
|
||||
// CSRF header names count: another required header is not a CSRF proof.
|
||||
it.each(["POST", "PUT", "PATCH", "DELETE"] as const)(
|
||||
"refuses a %s whose cookie profile requires no CSRF header",
|
||||
(method) => {
|
||||
for (const authProfileId of ["COOKIE_READ", "COOKIE_TENANT"]) {
|
||||
expect(() => compose(2, authProfileId, method)).toThrow(
|
||||
expect.objectContaining({
|
||||
reason: `test-feature/TEST_CREATE_ENTITY: ${method} with cookie profile ${authProfileId} must require x-csrf-token or x-xsrf-token`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["POST", "PUT", "PATCH", "DELETE"] as const)(
|
||||
"accepts a %s that requires x-csrf-token or x-xsrf-token",
|
||||
(method) => {
|
||||
expect(compose(2, "COOKIE_CSRF", method)).toBe(1);
|
||||
expect(compose(2, "COOKIE_WRITE", method)).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["GET", "HEAD"] as const)(
|
||||
"accepts a cookie %s without a CSRF header",
|
||||
(method) => {
|
||||
expect(compose(0, "COOKIE_READ", method)).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("refuses a write whose cookie profile requires no CSRF header", () => {
|
||||
expect(() =>
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { RuntimeValidator } from "../../src/contracts/external-contract-runtime.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.
|
||||
*/
|
||||
const PROBE_KEY = "__unknownFieldProbe";
|
||||
|
||||
type ProbedPolicy = "REJECT_UNKNOWN" | "STRIP_UNKNOWN" | "UNREACHED";
|
||||
|
||||
function probeUnknownFieldPolicy(validator: RuntimeValidator<unknown>): 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,
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
// 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", () => {
|
||||
const wrong = slots.flatMap(({ operationId, direction, validator }) => {
|
||||
const declared = SCHEMA_REGISTRY[validator.schemaId]?.direction;
|
||||
return declared === undefined || declared === direction
|
||||
? []
|
||||
: [`${operationId} ${validator.schemaId}: row ${declared}, used as ${direction}`];
|
||||
});
|
||||
|
||||
expect(wrong).toEqual([]);
|
||||
});
|
||||
|
||||
it("declares the unknown-field policy its validator applies", () => {
|
||||
const wrong = slots.flatMap(({ operationId, validator }) => {
|
||||
const declared = SCHEMA_REGISTRY[validator.schemaId]?.unknownFieldPolicy;
|
||||
if (declared === undefined) return [];
|
||||
const probed = probeUnknownFieldPolicy(validator);
|
||||
return probed === declared
|
||||
? []
|
||||
: [`${operationId} ${validator.schemaId}: row ${declared}, validator ${probed}`];
|
||||
});
|
||||
|
||||
expect(wrong).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user