Files
clean-architecture-frontend…/tests/unit/second-api-feature-registries.test.ts
T
DongHyeonka 7450e1f2b3 test(features): 기능 추가 테스트에 무효화 topic을 넣고 폴더 밖 수정 표를 고친다 (1101/16-01)
문제
- starter-experience.md "Adding a feature"의 폴더 밖 수정 표가 실제와 다르다.
  라우트마다 필요한 수동 a11y 기록이 없고, 어느 검사가 실패하는지도 적지
  않는다.
- 이 주장을 지키는 second-api-feature-registries 테스트는 무효화 topic이
  없는 기능만 넣는다. 그래서 topic 추가가 기준선 재승인을 요구하던 결함을
  보지 못했다.
- http-operation-v2-v3-parity 테스트는 스키마 ID "NoRequest"를 "입력 없음"
  표시로 고정해 쓴다. 스키마 ID는 전역이라 두 번째 기능은 다른 이름(예:
  OrderNoRequest)을 써야 한다. 그러면 이 테스트가 그 기능의 path·request
  스키마를 둘 다 입력으로 세어 실패한다(16-02 작업자 발견).

고른 방법
- 표를 지금 코드 기준으로 다시 썼다. 열은 파일 / 언제 / 없으면 무엇이
  실패하나. 리뷰 실험 E의 ①~⑨ 중 이번 라운드 앞 커밋이 없앤 것은 뺐다:
  governance allowlist(0929/07-03), 기준선 재승인(앞 커밋, 결정 1), README·
  체크리스트 route ID 목록(14-05), 인증 프로필 이름(16-03, EXTERNAL_BEARER
  재사용), MSW 카탈로그와 무관한 테스트 3개(16-02). runtime-adapters.ts는
  product-composition.ts로 바뀌었다(09-02).
- 남은 것: context 선언, 라우트별 a11y 기록, 경로 파라미터가
  :resourceId가 아니거나 빈 배열 응답으로 그려지지 않는 페이지의 e2e a11y
  spec, 제품 capability·인증 프로필·설정 키(제품 소유 파일 2개), 선택인
  FEATURE_OVERRIDES, 계약 패키지를 npm 의존성으로 들일 때의 의존성 검토
  증거. 계약 출처(EXTERNAL_PACKAGE)는 기능 계약의 contractPackages에
  선언하므로 폴더 밖 수정이 아니다.
- 표 아래에 레지스트리 추가는 기준선을 바꾸지 않는다는 것, 전역 ID에 기능
  접두어를 붙인다는 것, 기능의 MSW 시나리오는 createHttpScenarioHandler로
  만든다는 것을 적었다.
- second-api 기능에 무효화 topic·namespace·edge·topicVersion을 더하고,
  무효화 그래프 변경 3건이 additive인지 단언한다. 라우트는 0929/07-03이
  이미 넣었으므로(SECOND_ITEM_LIST) 더하지 않았다.
- second-api의 통과 codec은 검증을 생략하므로 1101/07-03의
  unvalidatedPayload로 만든다.
- parity 테스트는 V2 행에서 입력이 있는 쪽을 읽는다. path 스키마는
  pathParameterNames가 있을 때, request 스키마는 requestSource가 "none"이
  아닐 때 입력이다. 둘 다 없으면 행의 requestSchema(그 기능의 빈 입력
  스키마)를 기대한다.

버린 대안
- 표만 고치기(리뷰 대안 a): 테스트가 계속 좁은 모양만 증명한다.
- 참조 기능의 NoRequest를 ReferenceNoRequest로 바꾸기: FE-REG-API 행의
  requestSchema·pathSchema가 바뀌어 기준선 재승인이 필요하고 범위 밖이다.
- parity 테스트에서 이름 끝이 NoRequest인 스키마를 빈 입력으로 보기: 이름
  관례에 기대는 규칙이라 다른 이름을 쓰면 다시 깨진다.
- second-api 기능에 V3 기여를 넣어 parity를 그 사본에서 돌리기:
  1101/07-02(3c31576)가 같은 이유로 버렸다(사본에서는 check:registries만
  돈다).

위험·한계
- e2e a11y spec 행은 코드(:resourceId만 치환, 모든 API에 [] 응답)를 읽고
  적었다. 다른 파라미터를 가진 라우트로 test:a11y를 실제로 돌려 보지는
  않았다.
- 의존성 행은 직접 production 의존성을 더하면 generate:supply-chain이
  "high-risk dependency missing review"로 실패한다는 코드를 읽고 적었다.
  실행하지 않았다.
- 초기 JS 예산은 표에 넣지 않았다. 기능 하나가 초기 JS를 늘리지만 예산은
  기능이 고칠 파일이 아니다. 이번에 측정하지 않았다.
- 표의 완전성은 테스트가 지키지 않는다. 생성 명령(U7)의 게이트 실행이
  이 표를 실행으로 확인할 자리다.

검증
- RED: 넓힌 second-api 테스트를 결정 1 전 분류기(HEAD~1의
  registry-compatibility.ts)로 돌리면 실패한다. check-registries stderr
  "breaking change missing evidence:
  FE-REG-QUERY-INVALIDATION:invalidation-graph:{edges,namespaces,topics}:field-changed".
  parity 테스트는 참조 기능의 NoRequest를 ReferenceNoRequest로 바꾼
  변이(커밋 안 함)에서 "LIST_REFERENCE_RESOURCES: V2 declares both a path
  and a request schema" 실패.
- GREEN: second-api 1/1, 같은 변이에서 parity 2/2, 변이 없이 2/2 통과.
  V3 inputValidator schemaId를 바꾼 변이는 여전히 inputSchema 차이로
  실패한다.
- 회귀: tests/unit 178파일 중 177 통과. 실패 1건 feature-shape-growth(초기
  JS 증가 1 KiB 초과)는 기준 커밋에서도 실패한다. tsc app·test rc=0, 바꾼
  테스트 eslint rc=0, verify-documentation-readiness PASS_SCOPED,
  check-registries PASS(compatibility=none).
- 미실행: check:architecture(pnpm 필요), test:a11y, test:sample-removal.

Refs: docs/reviews/2026-11-01-maturity-review/16-structure-patterns.md 16-01, 8.1, 8.2
2026-11-03 01:50:12 +09:00

266 lines
10 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.
* 1101/16-01. And an invalidation topic, namespace and edge: every feature
* with server state has them, and adding them is additive.
*/
const FEATURE_ID = "second-api-feature";
const CONTEXT_ID = "second-api-context";
const TOPIC_ID = "qinv.01kb3m8q2v6t4r9s1n5p7c0w";
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 { unvalidatedPayload } from "../../../contracts/external-contract-runtime.ts";
import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts";
import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.ts";
import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts";
const OWNER = "feature-frontend-second-api-feature";
const SECOND_ITEM_TOPIC = defineQueryInvalidationTopic("${TOPIC_ID}");
const SECOND_ITEM_NAMESPACE = defineQueryNamespaceIdentity("second-item", 1);
const schema = (schemaId: string, boundary: string, direction: string) =>
Object.freeze({ schemaId, boundary, owner: OWNER, runtime: "zod", schemaVersion: 1, direction });
const codec = (schemaId: string) =>
runtimeSchemaCodecFromValidator(
unvalidatedPayload(schemaId, "registry fixture: only check-registries reads it"),
);
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: Object.freeze({
topics: Object.freeze([SECOND_ITEM_TOPIC]),
namespaces: Object.freeze([SECOND_ITEM_NAMESPACE]),
edges: Object.freeze([
Object.freeze({ topicId: SECOND_ITEM_TOPIC, namespace: SECOND_ITEM_NAMESPACE }),
]),
}),
topicVersions: Object.freeze([
Object.freeze({ topicId: SECOND_ITEM_TOPIC, topicVersion: 1 }),
]),
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, a route and an invalidation topic (F-3, 09-07, 0929/07-03, 1101/16-01)", () => {
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> }[];
compatibility: { changes: { registryId: string; field: string; impact: string }[] };
};
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",
});
const graph = report.registries.find(
({ registryId }) => registryId === "FE-REG-QUERY-INVALIDATION",
);
expect(graph?.rows["invalidation-graph"]).toMatchObject({
topics: expect.arrayContaining([TOPIC_ID]),
});
expect(
report.compatibility.changes
.filter(({ registryId }) => registryId === "FE-REG-QUERY-INVALIDATION")
.map(({ field, impact }) => [field, impact]),
).toEqual([
["edges", "additive"],
["namespaces", "additive"],
["topics", "additive"],
]);
}, 60_000);
});