Files
clean-architecture-frontend…/tests/unit/second-api-feature-registries.test.ts
T
DongHyeonka e8d7fb427f fix(registry): 기능 라우트를 추가해도 governance를 고치지 않게 한다 (0929/07-03)
문제
FE-REG-ROUTE governance가 paramsSchema·searchSchema·loadingSurface를 참조
기능 값까지 적은 닫힌 목록으로 둔다. 기능이 자기 search 스키마나 자기
로딩 화면 이름을 가진 라우트를 더하면 check:registries가 "has unknown
value"로 실패하고, 템플릿 소유 파일인 registry-governance.json을 고쳐야
한다. 목록은 contract 일부라 고치면 breaking 증거나 재승인도 필요하다.
두 다운스트림 모두 여기서 충돌했다. 스키마 id는 이미 references가
FE-REG-SCHEMA와 대조하므로 목록은 같은 사실의 세 번째 사본이고,
loadingSurface는 data-surface 속성 말고 읽는 코드가 없다. 문서는
"governance file do not change"라고 적지만 그 약속을 고정하는 테스트는
라우트 없는 기능만 넣었다.

고른 방법 (2026-11-03 결정, 리뷰 (B))
- paramsSchema·searchSchema를 FE-REG-ROUTE allowedValues에서 뺐다.
  references 검사는 그대로라 등록되지 않은 스키마 id는 계속 실패한다.
- loadingSurface는 목록 대신 이름 형식만 본다. governance에 선언형 키
  fieldPatterns(필드 → 고정된 정규식)를 더하고 check-registries가 문자열
  값을 대조한다. FE-REG-ROUTE는 kebab-case
  ^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$를 쓴다. fieldPatterns는 선언한
  레지스트리에서만 contract 스냅샷에 들어가므로 다른 레지스트리의
  contract는 바뀌지 않고, 정규식을 바꾸면 contract 변경(breaking)으로
  잡힌다.
- second-api-feature-registries 테스트의 두 번째 기능에 자기 search 스키마
  (SecondItemListQuery)와 전용 loading surface(second-item-list)를 가진
  라우트를 넣었다. 저장소 사본에 기능 디렉터리와 context만 더하고
  check-registries가 PASS인지 본다. 지시의 two-feature-install-typecheck는
  app 타입 검사만 돌려 governance를 보지 않으므로, check-registries를 돌리는
  이 테스트를 확장했다.
- 라우트 fixture(check:routes:fixture)의 governance도 같은 모양으로 바꾸고,
  형식에 맞지 않는 이름("Unknown loading")이 거절되는 단위 테스트를 더했다.
- starter-experience.md가 이 테스트를 가리키고, 라우트의 스키마·로딩 화면이
  governance 수정 없이 들어가는 이유를 적는다.
- 두 contract 변경(allowedValues 축소, fieldPatterns 추가)은 breaking이다.
  이 커밋에서는 증거 2건으로 게이트를 통과시키고, 기준선 재승인은 이번
  작업 묶음 끝에서 한 번에 한다.

이유: 기능 하나를 추가할 때 템플릿 파일을 고치게 만드는 지점이다. 두
다운스트림 모두에서 충돌했다.

버린 대안
- 문서만 "allowlist를 고치고 증거를 쓴다"로 정정: 기능마다 비용이
  반복된다.
- 기능 계약이 자기 allowlist 값을 기여하는 확장 메커니즘: 등록 규약이
  하나 더 생긴다.

위험·한계
- loadingSurface 오타는 이제 형식만 맞으면 통과한다. 이 값은 로딩
  요소의 data-surface 속성일 뿐이라 동작이 바뀌지 않는다. loadingSurface가
  로딩 컴포넌트 선택 같은 실행 의미를 갖게 되면 닫힌 목록을 다시 둔다.
- errorSurface·access는 라우터가 의미로 읽으므로 닫힌 목록을 유지한다.
  기능이 새 errorSurface를 쓰려면 지금처럼 governance를 고친다.
- 다운스트림은 다음 동기화에서 자기가 이 목록에 더한 값을 지운다.
  CHANGELOG [계약] 행이 필요하다.

검증
- RED(수정 전): 확장한 second-api-feature-registries 테스트가
  "FE-REG-ROUTE.SECOND_ITEM_LIST.searchSchema has unknown value
  SecondItemListQuery", "...loadingSurface has unknown value
  second-item-list"로 실패. 새 형식 테스트는 수정 전 checker로
  "expected [] to deeply equal [ Array(1) ]"로 실패.
- GREEN: 두 테스트 통과. 증거 없이 check-registries는 "breaking change
  missing evidence" 2건(allowedValues contract-field-changed,
  fieldPatterns contract-field-added)으로 실패, 증거를 넣은 뒤
  "11 registries PASS".
- 회귀: registry-compatibility·registry-governance·second-api-feature-
  registries·release-artifacts·two-feature-install-typecheck 57/57.
  compatibility fixtures 11 PASS. check:routes:fixture는 기대대로
  "duplicates routeId=DUPLICATE"로 실패. verify-documentation-readiness
  PASS_SCOPED. tsc node·test rc=0, 바꾼 파일 eslint rc=0.
- 미실행: check:architecture, test:sample-removal(pnpm 필요).

Refs: docs/reviews/2026-09-29-maturity-review/07-contracts.md
2026-11-03 00:55:33 +09:00

233 lines
8.7 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts";
/**
* F-3 (09-07). Adding a feature that owns an API operation must not require
* edits outside its own directory: governance, composers and the registry
* baseline stay as they are. This writes one such feature (plus the bounded
* context it declares, so the check survives the sample's removal) into a copy
* of the repository and runs the production generator and `check-registries`.
* 0929/07-03. The feature also owns a route with its own search schema and its
* own loading surface name, the values FE-REG-ROUTE once kept in a central
* allowlist.
*/
const FEATURE_ID = "second-api-feature";
const CONTEXT_ID = "second-api-context";
const FEATURE_CONTRACT = `import { defineRestOperation } from "../../../contracts/api-operations.ts";
import type { InstalledBoundaryMapper } from "../../../contracts/boundary-mapper.ts";
import { mappingFailure, mappingSuccess } from "../../../contracts/boundary-mapper.ts";
import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts";
const OWNER = "feature-frontend-second-api-feature";
const schema = (schemaId: string, boundary: string, direction: string) =>
Object.freeze({ schemaId, boundary, owner: OWNER, runtime: "zod", schemaVersion: 1, direction });
const codec = (schemaId: string) =>
runtimeSchemaCodecFromValidator({
schemaId,
safeParse: (value: unknown) => Object.freeze({ success: true as const, data: value }),
});
const ROUTES = Object.freeze({
SECOND_ITEM_LIST: Object.freeze({
routeId: "SECOND_ITEM_LIST",
path: "/second-api/items",
paramsSchema: null,
searchSchema: "SecondItemListQuery",
access: "public",
loadingSurface: "second-item-list",
errorSurface: "feature-boundary",
chunkId: "route-second-item-list",
title: "Second items",
navigationLabel: null,
navigationOrder: null,
}),
});
// 15-01. Declaration half: what the shell reads at boot.
export const SECOND_API_CONTRACT = Object.freeze({
featureId: "${FEATURE_ID}",
routes: ROUTES,
routeRuntimeContracts: Object.freeze({
SECOND_ITEM_LIST: Object.freeze({
routeId: "SECOND_ITEM_LIST",
moduleId: "second-item-list-page",
paramsCodec: "none",
searchCodec: "SecondItemListQuery",
}),
}),
invalidation: { topics: Object.freeze([]), namespaces: Object.freeze([]), edges: Object.freeze([]) },
topicVersions: Object.freeze([]),
contractPackages: Object.freeze([]),
} as const);
// Runtime half: the V2 API contract, loaded with feature-runtime.ts.
export const SECOND_API_V2_CONTRACT = Object.freeze({
apiOperations: Object.freeze({
GET_SECOND_ITEM: defineRestOperation({
method: "GET",
path: "/api/second-items/{itemId}",
operationId: "GET_SECOND_ITEM",
auth: "none",
timeoutMs: null,
idempotency: "safe",
retry: "runtime",
requestSource: "none",
requestSchema: "SecondItemRequest",
responseSchema: "SecondItemPayload",
owner: OWNER,
contractVersion: 2,
protocol: "REST",
semantics: "QUERY",
replayPolicy: "SAFE",
idempotencyKeyPolicy: "NONE",
mapperId: "SecondItemMapper",
successStatuses: [200],
responseMediaTypes: ["application/json"],
maxResponseBytes: 16_384,
providerId: "PRIMARY_API",
authProfileId: "ANONYMOUS",
csrfProfileId: "NO_CSRF_BEARER",
pathSchema: "SecondItemParams",
pathParameterNames: ["itemId"],
maxEncodedSearchBytes: 0,
}),
}),
schemas: Object.freeze({
SecondItemListQuery: schema("SecondItemListQuery", "route-search", "REQUEST"),
SecondItemParams: schema("SecondItemParams", "api-request", "REQUEST"),
SecondItemRequest: schema("SecondItemRequest", "api-request", "REQUEST"),
SecondItemPayload: schema("SecondItemPayload", "api-response", "RESPONSE"),
}),
runtimeSchemas: Object.freeze({
SecondItemListQuery: codec("SecondItemListQuery"),
SecondItemParams: codec("SecondItemParams"),
SecondItemRequest: codec("SecondItemRequest"),
SecondItemPayload: codec("SecondItemPayload"),
}),
mappers: Object.freeze({
SecondItemMapper: Object.freeze({
mapperId: "SecondItemMapper",
mapperVersion: 1,
inputSchemaId: "SecondItemPayload",
outputContractId: "SecondItem",
owner: OWNER,
maxOutputItems: 1,
map: (value: unknown) =>
value && typeof value === "object" ? mappingSuccess(value) : mappingFailure("MAPPING_INVARIANT_REJECTED"),
} satisfies InstalledBoundaryMapper),
}),
} as const);
`;
const FEATURE_MODULE = `import { defineFeatureModule } from "../feature-module.ts";
import { SECOND_API_CONTRACT } from "./contracts/second-api-contract.ts";
export const FEATURE_MODULE_ID = "${FEATURE_ID}";
export const FEATURE_CONTEXT_ID = "${CONTEXT_ID}";
export const FEATURE_MODULE = defineFeatureModule({
id: FEATURE_MODULE_ID,
contracts: SECOND_API_CONTRACT,
routes: SECOND_API_CONTRACT.routes,
messages: {},
loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME,
} as const);
`;
const FEATURE_RUNTIME = `import { defineFeatureRuntime } from "../feature-module.ts";
import { SECOND_API_V2_CONTRACT } from "./contracts/second-api-contract.ts";
export const FEATURE_RUNTIME = defineFeatureRuntime({
featureId: "${FEATURE_ID}",
apiContract: SECOND_API_V2_CONTRACT,
adapters: [],
contractContributions: [],
} as const);
`;
const FEATURE_GATEWAY = `// The executable consumer of GET_SECOND_ITEM.
export const SECOND_ITEM_OPERATION = "GET_SECOND_ITEM";
`;
const CONTEXT_ROUTES = `import type { RouteObject } from "react-router-dom";
export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze([]);
`;
const CONTEXT_MODULE = `export const CONTEXT_MODULE_ID = "${CONTEXT_ID}";
export const CONTEXT_APP_ID = "template-app";
export const CONTEXT_ROUTE_PATH = "second-api/*";
export const CONTEXT_MAX_FEATURES = 1;
`;
const roots: string[] = [];
afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
describe("adding a feature with an API operation and a route (F-3, 09-07, 0929/07-03)", () => {
it("passes check-registries without edits outside the feature and its context", async () => {
const root = await mkdtemp(path.join(tmpdir(), "second-api-feature-"));
roots.push(root);
// scripts/check-diagnostics.ts is a FE-REG-TELEMETRY consumer path.
for (const entry of [
"src",
"config/contracts",
"schemas/artifacts",
"scripts/check-diagnostics.ts",
]) {
await cp(path.resolve(entry), path.join(root, entry), { recursive: true });
}
await linkFixtureNodeModules(root);
const files: Readonly<Record<string, string>> = {
[`src/contexts/${CONTEXT_ID}/context-module.ts`]: CONTEXT_MODULE,
[`src/features/${FEATURE_ID}/feature-module.ts`]: FEATURE_MODULE,
[`src/features/${FEATURE_ID}/feature-runtime.ts`]: FEATURE_RUNTIME,
[`src/features/${FEATURE_ID}/context-routes.ts`]: CONTEXT_ROUTES,
[`src/features/${FEATURE_ID}/contracts/second-api-contract.ts`]: FEATURE_CONTRACT,
[`src/features/${FEATURE_ID}/adapters/second-api-gateway.ts`]: FEATURE_GATEWAY,
};
for (const [file, content] of Object.entries(files)) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), content);
}
const generated = spawnSync(
process.execPath,
[path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`],
{ encoding: "utf8" },
);
expect(generated.stderr).toBe("");
expect(generated.status).toBe(0);
const checked = spawnSync(
process.execPath,
[path.resolve("scripts/check-registries.ts")],
{ cwd: root, encoding: "utf8" },
);
expect(checked.stderr).toBe("");
expect(checked.stdout).toMatch(/11 registries PASS/u);
expect(checked.status).toBe(0);
const report = JSON.parse(
await readFile(path.join(root, "artifacts/quality/registries.json"), "utf8"),
) as { registries: { registryId: string; rows: Record<string, unknown> }[] };
const api = report.registries.find(({ registryId }) => registryId === "FE-REG-API");
expect(Object.keys(api?.rows ?? {})).toContain("GET_SECOND_ITEM");
const routes = report.registries.find(({ registryId }) => registryId === "FE-REG-ROUTE");
expect(routes?.rows.SECOND_ITEM_LIST).toMatchObject({
searchSchema: "SecondItemListQuery",
loadingSurface: "second-item-list",
});
}, 60_000);
});