Files
clean-architecture-frontend…/tests/unit/second-api-feature-registries.test.ts
T
donghyeon.kang 79dc945a67 refactor(layout): 루트 경로 목록을 등록부 하나에서 고르고 schemas/를 옮긴다
루트 항목 하나를 옮기려면 코드 7곳의 루트 경로 목록을 같이 고쳐야
했다(복사 대상, 비밀값 검사 범위, 공급망 시험의 필수 입력, 이력 문서
검사, 규모 입력, vite 입력, TS 전용 규칙). 서로 다른 부분집합이고 한
곳에서 선언하지 않았다. 목록이 갈라져 공급망 생성이 깨진 적도 있다
(removal-fixture.ts 주석). 루트에는 JSON Schema 5개만 담은 `schemas/`가
`config/` 옆에 따로 있었다. `artifacts/`(출력 폴더)에는 사람이 쓴 수동
a11y 기록이, `config/hosting/`(호스트 계약)에는 시험 fixture가 섞였다.

고른 방법(design-docs repo-structure/04-frontend-layout.md 9.2절 3단계,
11절 R1·R2, 소유자 승인 2026-11-07):
- `config/repository-layout.json`이 루트 항목마다 종류·역할·읽는 곳과
  들어가는 목록(`sets`, 항목 안 경로는 `setPaths`)을 적는다.
  `scripts/lib/repository-layout.ts`가 읽고 검증한다. 6곳은 이름 붙은
  집합을 고른다. JSON인 비밀값 검사 정책은 집합의 사본을 두고 시험이
  같은지 본다(정책 파일은 릴리스 후보에 실려 형식을 바꾸지 않았다).
  공급망 시험의 필수 입력 목록은 그 시험으로 대신한다.
- `tests/unit/repository-layout.test.ts`: 등록부에 없는 루트 항목이
  추적되면 실패(R1). 7곳이 등록부 모듈을 쓰고 루트 이름 둘 이상의
  문자열 배열을 갖지 않는지(R2).
- `schemas/artifacts/` → `config/schemas/artifacts/`, recipe 카탈로그
  스키마 → `config/schemas/recipes/`. 정책 입력 순서(ASCII)에 맞춰
  `config/schemas/`가 `config/security/` 앞에 온다.
- 수동 a11y 기록 3개 → `docs/accessibility/route-reviews/`. `artifacts/`는
  `.gitkeep`만 추적한다. 기록은 단위 시험이 읽어서 drill 사본에도
  복사한다(`fixture-copy` 집합의 `docs/accessibility/route-reviews`).
- `config/hosting/response-headers.fixture.json` →
  `tests/fixtures/hosting/response-headers.json`.

버린 것: 비밀값 검사 정책이 집합 이름을 참조하게 바꾸는 방법. 정책
파일은 릴리스 후보와 로컬 증거 평가가 읽는 형식이라 바꾸면 릴리스
증거 계약이 바뀐다. 루트 항목이 지워졌는데 등록부에 남는 경우는
시험하지 않았다. drill 사본은 일부만 복사해 그 방향을 볼 수 없다.
그런 항목은 그 집합을 쓰는 곳(복사, 비밀값 검사)에서 실패한다.

위험: 하네스 작업(fe-c)이 더할 `AGENTS.md`·`.claude/`를 미리 등록했다
(optional). 등록부가 이력 문서(`SPEC.md`)와 `CLAUDE.md` 이름을 적어서
이력 문서 검사에서 등록부 파일은 뺐다. 다운스트림은 자기 루트 항목을
등록부에 더해야 한다(CHANGELOG). CI 계약 기준선을 다시 받았다(a11y
기록 산출물 id·경로).

검증(desktop): 아래 4단계 커밋까지 쌓은 트리에서 test:unit,
check:types, check:ci, lint, verify:documentation을 돌렸다(그 커밋에
적음). 이 커밋 단독으로 test:unit·check:ci·check:types를 돌렸다.

Refs: design-docs repo-structure/04-frontend-layout.md 2.4·9.2·11절, README.md 3.4절
2026-11-08 17:41:07 +09:00

296 lines
11 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 {
PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,
PLACEHOLDER_CONTRACT_PACKAGE_REVISION,
PLACEHOLDER_CONTRACT_PACKAGE_VERSION,
} from "../../../contracts/deployment-admission.ts";
import type {
InstalledContractContribution,
InstalledHttpContract,
} from "../../../contracts/external-contract-runtime.ts";
import { unvalidatedPayload } from "../../../contracts/unvalidated-payload.ts";
import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts";
import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.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 unchecked = (schemaId: string) =>
unvalidatedPayload(schemaId, "registry fixture: only check-registries reads it");
const SECOND_CONTRACT_PACKAGE = Object.freeze({
packageId: "@org-contracts/second-api",
version: PLACEHOLDER_CONTRACT_PACKAGE_VERSION,
digest: PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,
runtimeProtocolVersion: 1 as const,
sourceRevision: PLACEHOLDER_CONTRACT_PACKAGE_REVISION,
});
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([SECOND_CONTRACT_PACKAGE]),
} as const);
// Runtime half, loaded with feature-runtime.ts.
export const SECOND_API_SCHEMAS = Object.freeze({
SecondItemListQuery: schema("SecondItemListQuery", "route-search", "REQUEST"),
SecondItemParams: schema("SecondItemParams", "api-request", "REQUEST"),
SecondItemPayload: schema("SecondItemPayload", "api-response", "RESPONSE"),
// 1103/16-04. FE-REG-API's problemSchema references a row too.
SecondItemProblem: schema("SecondItemProblem", "api-problem", "RESPONSE"),
} as const);
export const SECOND_API_CONTRIBUTION: InstalledContractContribution = Object.freeze({
contributionId: "second-api-feature-http-v1",
featureId: "${FEATURE_ID}",
source: Object.freeze({ kind: "EXTERNAL_PACKAGE" as const, package: SECOND_CONTRACT_PACKAGE }),
http: Object.freeze([
Object.freeze({
contract: Object.freeze({
operationId: "GET_SECOND_ITEM",
method: "GET" as const,
pathTemplate: "/api/second-items/{itemId}",
inputValidator: unchecked("SecondItemParams"),
outputValidator: unchecked("SecondItemPayload"),
problemValidator: unchecked("SecondItemProblem"),
acceptedStatuses: Object.freeze([200]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "SAFE" as const,
requestBody: "NONE" as const,
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "ENVELOPE_V1" as const,
commandRecovery: null,
commandEffect: null,
projectRequest: (input: unknown) =>
Object.freeze({
pathValues: Object.freeze({ itemId: String((input as { itemId: string }).itemId) }),
queryEntries: Object.freeze([]),
body: null,
}),
}),
frontend: Object.freeze({
policyId: "SECOND_ITEM_V1",
requestByteLimit: 0,
responseByteLimit: 16_384,
totalDeadlineMs: 10_000,
retryBudget: 0 as const,
authProfileId: "ANONYMOUS",
diagnosticsOperation: "second.item",
}),
}),
]) as readonly InstalledHttpContract<unknown, unknown, unknown>[],
events: Object.freeze([]),
});
`;
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_CONTRIBUTION,
SECOND_API_SCHEMAS,
} from "./contracts/second-api-contract.ts";
export const FEATURE_RUNTIME = defineFeatureRuntime({
featureId: "${FEATURE_ID}",
schemas: SECOND_API_SCHEMAS,
adapters: [],
contractContributions: [SECOND_API_CONTRIBUTION],
} 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 })));
});
/** A copy of the repository with the second feature written into it. */
async function repositoryWithSecondFeature(featureContract = FEATURE_CONTRACT) {
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",
"config/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`]: featureContract,
[`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);
return root;
}
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 repositoryWithSecondFeature();
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);
it("names the operation and the profile when the auth profile id is wrong (1103/09-07)", async () => {
const root = await repositoryWithSecondFeature(
FEATURE_CONTRACT.replace('authProfileId: "ANONYMOUS"', 'authProfileId: "SECOND_UNKNOWN"'),
);
const checked = spawnSync(
process.execPath,
[path.resolve("scripts/check-registries.ts")],
{ cwd: root, encoding: "utf8" },
);
expect(checked.status).toBe(1);
expect(checked.stderr).toContain(
`${FEATURE_ID}/GET_SECOND_ITEM: unknown authProfileId SECOND_UNKNOWN`,
);
}, 60_000);
});