Files
clean-architecture-frontend…/tests/unit/repository-layout.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

136 lines
6.0 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import {
parseRepositoryLayout,
REPOSITORY_LAYOUT,
REPOSITORY_LAYOUT_FILE,
selectRepositoryEntries,
selectRepositoryPaths,
} from "../../scripts/lib/repository-layout.ts";
/**
* The repository root registry: R1 (every root item is registered) and R2
* (root path lists are chosen from the registry) of
* design-docs repo-structure/04-frontend-layout.md §11.
*/
function trackedFiles(): string[] {
const listed = spawnSync("git", ["ls-files", "-z"], { encoding: "utf8" });
if (listed.error || listed.status !== 0) {
throw new Error(`git ls-files failed: ${listed.error?.message ?? listed.stderr}`);
}
return listed.stdout.split("\0").filter((file) => file !== "");
}
const rootItemNames = new Set(REPOSITORY_LAYOUT.map((entry) => entry.path));
describe("repository layout registry (R1)", () => {
// A removal fixture copies part of the repository, so the claim is one way:
// whatever is tracked at the root is registered. A registered path that is
// gone fails where a set uses it (a copy or the secret scan cannot find it).
it("has an entry for every tracked root item", () => {
const roots = new Set(trackedFiles().map((file) => file.split("/")[0]!));
expect(
[...roots].filter((root) => !rootItemNames.has(root)).sort(),
`add an entry with its role to ${REPOSITORY_LAYOUT_FILE}`,
).toEqual([]);
});
it("rejects an entry that is not a root item, a duplicate and a path outside its item", () => {
const entry = { path: "src", kind: "source", role: "app", readBy: "build" };
expect(() => parseRepositoryLayout({ schemaVersion: 1, entries: [{ ...entry, path: "src/app" }] })).toThrow(
/no slash/u,
);
expect(() => parseRepositoryLayout({ schemaVersion: 1, entries: [entry, entry] })).toThrow(/duplicate/u);
expect(() =>
parseRepositoryLayout({
schemaVersion: 1,
entries: [{ ...entry, setPaths: { "vite-build": ["scripts/lib/run-isolation.ts"] } }],
}),
).toThrow(/not inside src/u);
expect(() => parseRepositoryLayout({ schemaVersion: 1, entries: [{ ...entry, kind: "misc" }] })).toThrow(
/unknown kind/u,
);
expect(() => parseRepositoryLayout({ schemaVersion: 1, entries: [{ ...entry, sets: ["everything"] }] })).toThrow(
/unknown set/u,
);
});
it("selects whole items and paths inside items in registry order", () => {
const layout = parseRepositoryLayout({
schemaVersion: 1,
entries: [
{ path: ".gitea", kind: "tool-convention", role: "ci", readBy: "gitea", setPaths: { "secret-scan": [".gitea/workflows/a.yml"] } },
{ path: "recipes", kind: "source", role: "recipes", readBy: "tsc", optional: true, sets: ["secret-scan"] },
{ path: "src", kind: "source", role: "app", readBy: "build", sets: ["secret-scan", "vite-build"] },
],
});
expect(selectRepositoryPaths("secret-scan", layout)).toEqual([".gitea/workflows/a.yml", "recipes", "src"]);
expect(selectRepositoryPaths("vite-build", layout)).toEqual(["src"]);
expect(selectRepositoryEntries("secret-scan", layout).filter(({ optional }) => optional)).toEqual([
{ path: "recipes", optional: true },
]);
});
});
/**
* design-docs repo-structure/04-frontend-layout.md §2.4: seven places kept
* their own literal lists of root paths, each a different subset. Six are
* code; the seventh is the secret scan policy, a JSON document the release
* candidate carries, which keeps a copy of its set held equal here.
*/
const LAYOUT_CONSUMERS = Object.freeze([
"scripts/lib/removal-fixture.ts",
"scripts/lib/vite-build-inputs.ts",
"scripts/verify-extreme-scale.ts",
"scripts/check-architecture.ts",
"tests/unit/deletable-history-documents.test.ts",
]);
/** It checked the policy against a list of its own; the copy check below replaces it. */
const FORMER_CONSUMERS = Object.freeze(["tests/unit/supply-chain.test.ts"]);
const STRING = String.raw`(?:"[^"\n]*"|'[^'\n]*'|` + "`[^`\\n]*`)";
const STRING_ARRAY = new RegExp(String.raw`\[\s*${STRING}(?:\s*,\s*${STRING})+\s*,?\s*\]`, "gu");
/** Array literals of two or more string literals that are root item names. */
function literalRootLists(source: string, roots: ReadonlySet<string>): string[] {
const code = source.replace(/^\s*\/\/.*$/gmu, "");
return [...code.matchAll(STRING_ARRAY)]
.map(([literal]) => [...literal.matchAll(new RegExp(STRING, "gu"))].map(([value]) => value.slice(1, -1)))
.filter((values) => new Set(values.filter((value) => roots.has(value))).size >= 2)
.map((values) => values.join(", "));
}
describe("root path lists (R2)", () => {
it.each(LAYOUT_CONSUMERS)("%s chooses a set from the registry", (consumer) => {
const source = readFileSync(consumer, "utf8");
expect(source).toMatch(/repository-layout\.ts/u);
expect(literalRootLists(source, rootItemNames)).toEqual([]);
});
it.each(FORMER_CONSUMERS)("%s keeps no list of root paths", (consumer) => {
expect(literalRootLists(readFileSync(consumer, "utf8"), rootItemNames)).toEqual([]);
});
it("finds a literal root list", () => {
expect(literalRootLists(`const ROOTS = ["src", "tests", "other"];`, rootItemNames)).toEqual(["src, tests, other"]);
expect(literalRootLists(`const ROOTS = ["src"];\nconst X = ["a", "b"];`, rootItemNames)).toEqual([]);
});
// A removal fixture deletes some of these inputs on purpose — removing the
// browser file/storage capability takes the whole browser-capability harness
// with it — and prunes the policy to match. The claim is about the inputs
// this checkout has.
it("keeps the secret scan policy's roots equal to the secret-scan set", () => {
const policy = JSON.parse(readFileSync("config/security/secret-scan-policy.json", "utf8")) as {
trackedRoots: string[];
};
expect([...policy.trackedRoots].sort()).toEqual(
[...selectRepositoryPaths("secret-scan").filter((input) => existsSync(input))].sort(),
);
});
});