From e902e657d1b7e272ecd2c46dd2ae2ae95dedae97 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 8 Nov 2026 17:41:27 +0900 Subject: [PATCH] =?UTF-8?q?test(layout):=20=EC=A0=80=EC=9E=A5=EC=86=8C=20?= =?UTF-8?q?=EB=B0=B0=EC=B9=98=20=EA=B7=9C=EC=B9=99=20R3~R9=EB=A5=BC=20?= =?UTF-8?q?=EA=B2=80=EC=82=AC=EB=A1=9C=20=EB=91=90=EA=B3=A0=20=EB=A7=A4?= =?UTF-8?q?=EB=89=B4=EC=96=BC=EC=97=90=20=EC=A0=81=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 소유자가 2026-11-07에 지적한 것(매뉴얼이 생긴 뒤에도 남은 샘플, 역할이 겹치는 루트 폴더, 0파일 검사, 문서 속 인프라 설정)은 매뉴얼과 리뷰가 먼저 잡아야 했다. 지금은 그 규칙이 글로도 검사로도 없다. 그래서 같은 지적이 다시 나와도 게이트가 모른다. 고른 방법(design-docs repo-structure/04-frontend-layout.md 11절, 기계 검사가 「예」인 규칙을 표의 게이트 칸대로): - R4·R5 `tests/unit/example-feature-rules.test.ts`(FE-GATE-005): 샘플 목록은 FE-GATE-020의 `test:sample-removal`(인자 없이, 빌드와 test:all 포함)이 증명한다. 목록 샘플의 기능 ID·라우트가 visual·e2e의 `goto`, gates.json 산출물 경로, `config/scale/`에 나오면 실패한다. 템플릿 목록은 비어 있어 가짜 샘플로 판정 함수를 시험한다. - R6·R7(문서) `verify:documentation`(FE-GATE-017): `docs/manual/`이 목록 샘플 경로를 가리키면, 현재 문서에 ```nginx```·```hcl``` 블록이나 `kind: Deployment` 같은 매니페스트 줄이 있으면 실패한다. 이력 폴더는 보지 않는다. 산출물 `documentation-review.json`에 `layoutRuleViolations`를 더했다. - R7(파일)·R9 `tests/unit/repository-layout.test.ts`(FE-GATE-005): nginx·Terraform·Helm·Kustomize 파일과 Kubernetes 매니페스트 YAML이 추적되면 실패. 옵션이 같은 tsconfig 쌍이 있으면 실패. - R3은 `tests/unit/tracked-artifacts.test.ts`, R8은 앞 커밋의 `check-typecheck-inputs.ts`·`check-type-fixtures.ts`가 맡는다. R10의 기계 몫(루트 *.md 등록)은 R1이다. - 매뉴얼 03에 E절(R1~R10 규칙과 검사, 루트 항목을 더하는 순서)과 C절 「Web Worker를 들일 때 tsconfig 더하기」(결정 D4)를 더했다. 위험: R5는 문자열 검색이라 샘플 ID를 다르게 쓴 대상(예: 라우트 경로를 조립하는 spec)은 놓친다. R7 문서 검사는 코드 블록 언어 태그와 매니페스트 줄로만 본다. R13(리뷰 가이드)은 design-docs 몫이라 넣지 않았다. 검증(desktop): 이 커밋에서 test:unit, check:types, check:ci, lint, verify:documentation, check:architecture를 돌렸다. Refs: design-docs repo-structure/04-frontend-layout.md 11절, README.md 3.4절 --- docs/manual/03-outside-feature-folder.md | 46 ++++++++ scripts/contracts/release-artifacts.ts | 15 ++- scripts/verify-documentation-readiness.ts | 49 +++++++++ tests/unit/example-feature-rules.test.ts | 126 ++++++++++++++++++++++ tests/unit/repository-layout.test.ts | 73 ++++++++++++- 5 files changed, 305 insertions(+), 4 deletions(-) create mode 100644 tests/unit/example-feature-rules.test.ts diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index ecdb4cd9..3e2f4108 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -184,6 +184,28 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE) - 템플릿이 아직 연결하지 않은 것: 활성화 화면(`onUpdateWaiting`·`requestActivation()`). 확인할 것 목록은 `docs/architecture/optional-adapter-recipes.md`의 "Service Worker를 켤 때 확인할 것"에 있다. - realtime·Web Worker·오프라인 명령을 고르면 조립이 `Selected optional capabilities have no runtime to start them`로 거절한다. 템플릿 조립에 아직 그 런타임이 없다. +### Web Worker를 들일 때 tsconfig 더하기 + +템플릿에는 Web Worker 코드가 없다. 그래서 Worker용 tsconfig도 없다. 빈 tsconfig는 0파일을 검사하고 통과한다(아래 E절 R8). 2026-11-08에 지웠다. Worker 코드를 처음 넣는 변경에서 아래를 함께 한다. + +1. Worker 코드를 `src/adapters/web-worker/`에 둔다. 그 폴더의 `index.ts`가 배럴이다. +2. 루트에 `tsconfig.web-worker.json`을 만든다. lib가 `WebWorker`이고 DOM이 없어서, Worker 코드가 `document`·`window`를 쓰면 실패한다. `tsconfig.service-worker.json`과 같은 이유다. + + ```json + { + "extends": "./tsconfig.base.json", + "compilerOptions": { "lib": ["ES2022", "WebWorker"], "types": [], "skipLibCheck": false }, + "include": ["src/adapters/web-worker"], + "exclude": ["src/adapters/web-worker/index.ts"] + } + ``` + +3. Worker 진입 파일을 `tsconfig.app.json`의 `exclude`에 더한다. 배럴처럼 페이지가 import하는 파일은 app 프로그램에 남긴다. +4. `tsconfig.json`의 `references`에 `{ "path": "./tsconfig.web-worker.json" }`을 더한다. 편집기가 Worker 파일에 이 설정을 쓴다. +5. `package.json`에 `"check:types:web-worker": "tsc --project tsconfig.web-worker.json"`을 더하고 `check:types` 사슬에 잇는다. 사슬 끝의 `node scripts/check-typecheck-inputs.ts`가 이 tsconfig의 입력이 0개면 실패시킨다. +6. `config/repository-layout.json`에 `tsconfig.web-worker.json` 항목을 더한다(E절 R1). `sets`는 `tsconfig.service-worker.json`과 같게 `fixture-copy`·`secret-scan`이다. `config/security/secret-scan-policy.json`의 `trackedRoots`에도 같은 이름을 더한다(R2). +7. `scripts/verify-documentation-readiness.ts`의 `NOT_CREATED`에서 `src/adapters/web-worker`를 뺀다. + --- ## D. 고치지 않는다 @@ -199,6 +221,30 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE) --- +## E. 저장소 배치 규칙 (R1~R10) + +기능 밖의 루트 폴더·설정·검사를 더하거나 옮길 때 지킨다. 2026-11-07 소유자 지적(샘플이 남아 있음, 역할이 겹치는 루트 폴더, 0파일 검사, 문서 속 인프라 설정)이 다시 나오지 않게 하는 규칙이다. 설계와 근거는 design-docs `repo-structure/04-frontend-layout.md` 11절이다. + +| ID | 규칙 | 검사 | +| --- | --- | --- | +| R1 | 루트 항목은 모두 `config/repository-layout.json`에 있다. 항목마다 종류(source·tool-convention·gate-input·document·history·output), 역할, 읽는 곳을 적는다 | `tests/unit/repository-layout.test.ts`(FE-GATE-005). 등록부에 없는 루트 항목이 추적되면 실패 | +| R2 | 루트 경로 목록은 등록부의 이름 붙은 집합(`sets`, 하위 경로는 `setPaths`)에서만 고른다. 목록을 코드에 새로 적지 않는다. JSON 정책 파일(`config/security/secret-scan-policy.json`)은 그 집합의 사본을 갖고 시험이 같은지 본다 | 같은 시험. 목록을 쓰던 곳이 `scripts/lib/repository-layout.ts`를 import하는지, 루트 이름 두 개 이상의 문자열 배열이 없는지 | +| R3 | 추적 파일은 읽는 곳이 있다. `artifacts/`는 출력 전용이라 `.gitkeep`만 추적한다. 사람이 쓴 기록은 `docs/` 아래에 둔다(수동 a11y 기록은 `docs/accessibility/route-reviews/`) | `tests/unit/tracked-artifacts.test.ts`(FE-GATE-005). `config/` 아래 고아 JSON은 리뷰가 본다 | +| R4 | 템플릿이나 제품이 넣은 샘플 기능은 `scripts/lib/removable-template-features.ts` 목록에 있고, 복사본에서 지우고 빌드·시험하는 drill로 증명한다. 문서 검사만으로는 안 된다 | `tests/unit/example-feature-rules.test.ts`(FE-GATE-005). FE-GATE-020이 `test:sample-removal`을 목록 전체로 도는지 | +| R5 | 게이트의 검사 대상(visual 골든, e2e 라우트, 게이트 증거 목록, 규모 측정)은 플랫폼 화면·시험 fixture·생성기 출력이다. 지울 샘플 기능이 아니다 | 같은 시험. 샘플의 기능 ID·라우트가 visual·e2e의 `goto`, `config/ci/gates.json` 산출물 경로, `config/scale/`에 나오면 실패 | +| R6 | 매뉴얼의 예제 위치는 `create:feature` 출력이나 매뉴얼 안 코드 조각을 가리킨다. 지울 샘플 기능의 경로를 가리키지 않는다 | `verify:documentation`(FE-GATE-017). `docs/manual/`에 목록 샘플의 경로가 나오면 실패 | +| R7 | 이 repo에 둘 수 있는 실행 환경 파일은 개발 의존 서비스용 compose와 개발 Dockerfile뿐이다. nginx·Kubernetes·Helm·Terraform 설정은 인프라 repo에 두고 링크한다. 호스트에 요구하는 것은 계약(`config/hosting/`)과 검사(FE-GATE-019)로 둔다 | 파일: `tests/unit/repository-layout.test.ts`(FE-GATE-005). 문서: `verify:documentation`(FE-GATE-017)이 현재 문서의 ```` ```nginx ````·```` ```hcl ```` 블록과 `kind: Deployment` 같은 매니페스트 줄을 막는다. 이력 폴더(`docs/history/`, `docs/reviews/`, `docs/superpowers/`)는 기록이라 보지 않는다 | +| R8 | 검사 대상이 0개인 게이트 명령은 실패하거나 SKIP을 출력한다. 통과로 보이면 안 된다 | FE-GATE-003: `scripts/check-typecheck-inputs.ts`(package script가 tsc에 넘기는 tsconfig마다 이 repo 파일이 1개 이상), `scripts/check-type-fixtures.ts`(fixture 0개면 실패) | +| R9 | tsconfig는 lib·types·모듈 해석 중 하나가 다를 때만 새로 만든다. 옵션이 같고 파일만 다르면 실행기 하나로 돈다(예: 음성 타입 fixture는 `check:types:fixtures` 하나) | `tests/unit/repository-layout.test.ts`(FE-GATE-005). 옵션이 같은 tsconfig 쌍이 있으면 실패 | +| R10 | 이력 문서(끝난 라운드의 계획·작업 목록·보고)는 루트나 숨김 폴더에 두지 않고 이력 폴더 한 곳에 둔다. 정본으로 쓰이는 부분은 이력에 두지 않는다 | 루트 `*.md`는 R1 등록부에 종류와 함께 있어야 한다. "정본으로 쓰이는가"는 리뷰가 본다 | + +루트 항목을 더하거나 옮길 때의 순서: + +1. `config/repository-layout.json`에 항목을 더하거나 고친다. 종류·역할·읽는 곳을 적는다(R1). +2. 그 항목이 들어갈 집합을 `sets`(항목 전체)나 `setPaths`(항목 안 경로)에 적는다. 집합의 뜻은 파일 머리의 `sets` 설명에 있다(R2). +3. `secret-scan` 집합을 바꿨으면 `config/security/secret-scan-policy.json`의 `trackedRoots`도 같게 고친다. +4. 새 tsconfig라면 R9를 먼저 본다. 다른 tsconfig와 옵션이 같으면 만들지 않는다. + ## 기능을 지울 때 `corepack pnpm test:sample-removal -- --feature=`는 복사본에서 지워 보고 게이트를 돈다. 실제 저장소에서 지울 때는 아래를 함께 지운다. diff --git a/scripts/contracts/release-artifacts.ts b/scripts/contracts/release-artifacts.ts index 180234d7..13d30bdd 100644 --- a/scripts/contracts/release-artifacts.ts +++ b/scripts/contracts/release-artifacts.ts @@ -1472,6 +1472,18 @@ export const documentationReviewArtifactSchema = z }) .strict(), ).min(1), + // R6·R7 of docs/manual/03-outside-feature-folder.md: a manual example that + // points at a deletable sample feature, or infrastructure configuration + // copied into a current document. + layoutRuleViolations: z.array( + z + .object({ + path: nonEmptyString, + rule: z.enum(["R6", "R7"]), + detail: nonEmptyString, + }) + .strict(), + ), results: z.array( z .object({ @@ -1523,9 +1535,10 @@ export const documentationReviewArtifactSchema = z entry.missingScripts.length === 0 && entry.unknownGateIds.length === 0, ) && + artifact.layoutRuleViolations.length === 0 && artifact.results.every(({ passed }) => passed)) ) { - context.addIssue({ code: "custom", path: ["passed"], message: "must agree with report digest, documented scope, source structure, document references and review results" }); + context.addIssue({ code: "custom", path: ["passed"], message: "must agree with report digest, documented scope, source structure, document references, layout rules and review results" }); } }); diff --git a/scripts/verify-documentation-readiness.ts b/scripts/verify-documentation-readiness.ts index 9bbf0648..470f08bb 100644 --- a/scripts/verify-documentation-readiness.ts +++ b/scripts/verify-documentation-readiness.ts @@ -409,6 +409,48 @@ const documentReferencesValid = documentReferences.every( (entry) => entry.missingPaths.length === 0 && entry.missingScripts.length === 0 && entry.unknownGateIds.length === 0, ); +// Repository layout rules of docs/manual/03-outside-feature-folder.md. +// R6: the manual's examples point at generator output or at code blocks in +// the manual, never at a sample feature a copy is meant to delete (the +// template's own sample took the manual's examples with it on 2026-11-07). +// R7: host, cluster and infrastructure configuration (nginx, Kubernetes, +// Helm, Terraform) lives in the infrastructure repository; a current document +// links to it and states the host contract (config/hosting/, FE-GATE-019) +// instead of carrying a copy. The history folders are records and keep what +// they recorded. +// Built from pieces: tests/unit/deletable-history-documents.test.ts fails on +// code that names a history folder, and this names them to skip them. +const HISTORY_DOCUMENT_FOLDERS = ["history", "reviews", "superpowers"].map((folder) => `docs/${folder}/`); +const INFRASTRUCTURE_FENCE = /^\s*```\s*(nginx|hcl|terraform|helm)\b/iu; +const INFRASTRUCTURE_MANIFEST = + /^\s*kind:\s*(Deployment|StatefulSet|DaemonSet|Ingress|Service|ConfigMap|CronJob|HelmRelease|Kustomization)\s*$/u; +const sampleFeaturePaths = REMOVABLE_TEMPLATE_FEATURES.flatMap((feature) => removableTemplateFeaturePaths(feature)); +const currentDocuments = [ + "README.md", + ...((await readdir("docs", { recursive: true }).catch(() => [])) as string[]) + .filter((name) => name.endsWith(".md")) + .map((name) => `docs/${name}`) + .filter((name) => !HISTORY_DOCUMENT_FOLDERS.some((folder) => name.startsWith(folder))), +].sort(); +const layoutRuleViolations: { path: string; rule: "R6" | "R7"; detail: string }[] = []; +for (const document of currentDocuments) { + const text = await readFile(document, "utf8").catch(() => null); + if (text === null) continue; + let fenced = false; + text.split("\n").forEach((line, index) => { + if (/^\s*```/u.test(line)) fenced = !fenced; + if (INFRASTRUCTURE_FENCE.test(line) || (fenced && INFRASTRUCTURE_MANIFEST.test(line))) { + layoutRuleViolations.push({ path: document, rule: "R7", detail: `line ${index + 1}: ${line.trim()}` }); + } + if (!document.startsWith("docs/manual/")) return; + for (const samplePath of sampleFeaturePaths) { + if (line.includes(samplePath)) { + layoutRuleViolations.push({ path: document, rule: "R6", detail: `line ${index + 1}: ${samplePath}` }); + } + } + }); +} + // 1101/14-06. Each failed check is named, so the stderr points at the file to // fix rather than at the diagram review whatever failed. 1101/14-05: the last // two only compare the two hand-kept copies of the 2026-07-18 diagram review; @@ -419,6 +461,7 @@ const failedChecks = [ ...(missingRuntimeVariables.length === 0 ? [] : ["runtime variables"]), ...(sourceStructureDocumented ? [] : ["source structure"]), ...(documentReferencesValid ? [] : ["document references"]), + ...(layoutRuleViolations.length === 0 ? [] : ["repository layout rules"]), ...(reportDigestValid ? [] : ["2026-07-18 diagram review copy digest"]), ...(results.length === 2 && results.every((result) => result.passed) ? [] @@ -442,6 +485,7 @@ await writeValidatedJsonArtifact({ missingRuntimeVariables, sourceStructure, documentReferences, + layoutRuleViolations, results, passed, }, @@ -479,6 +523,11 @@ if (!passed) { ); } } + for (const violation of layoutRuleViolations) { + process.stderr.write( + `${violation.path} breaks ${violation.rule} of docs/manual/03-outside-feature-folder.md: ${violation.detail}\n`, + ); + } if (documentReferences.some((entry) => entry.missingPaths.some((file) => file.startsWith("../")))) { const checked = [...pairedTrees] .filter(([, tree]) => "paths" in tree) diff --git a/tests/unit/example-feature-rules.test.ts b/tests/unit/example-feature-rules.test.ts new file mode 100644 index 00000000..880abcfe --- /dev/null +++ b/tests/unit/example-feature-rules.test.ts @@ -0,0 +1,126 @@ +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts"; +import { + REMOVABLE_TEMPLATE_FEATURES, + type RemovableTemplateFeature, +} from "../../scripts/lib/removable-template-features.ts"; +import { INSTALLED_FEATURE_CONTRACTS } from "../../src/features/installed-feature-contracts.ts"; + +/** + * R4 and R5 of docs/manual/03-outside-feature-folder.md. A sample feature + * that the template or a project ships is listed in + * scripts/lib/removable-template-features.ts, and the list is proven by a + * drill that builds and tests a copy without it (R4). The gates' own targets + * (visual goldens, e2e routes, the gate evidence list, scale measurements) + * are platform screens, test fixtures and generator output, never a sample a + * copy is meant to delete (R5): the template's reference sample was the + * target of nine gates when it was deleted on 2026-11-07. + */ + +type ExampleFeature = Readonly<{ featureId: string; routeIds: readonly string[]; routePaths: readonly string[] }>; + +type GateTargets = Readonly<{ + gotoTargets: readonly Readonly<{ file: string; target: string }>[]; + artifactPaths: readonly string[]; + scaleFiles: readonly Readonly<{ file: string; text: string }>[]; +}>; + +function exampleFeatures(features: readonly RemovableTemplateFeature[]): ExampleFeature[] { + return features.map(({ featureId }) => { + // The template installs no feature, so the composed list's type is empty. + const contracts = INSTALLED_FEATURE_CONTRACTS as readonly Readonly<{ featureId: string; routes: object }>[]; + const routes = contracts.filter((contract) => contract.featureId === featureId).flatMap( + (contract) => Object.values(contract.routes as Record), + ); + return { + featureId, + routeIds: routes.map(({ routeId }) => routeId), + routePaths: routes.map(({ path: routePath }) => routePath).filter((routePath) => routePath !== "/"), + }; + }); +} + +function gateTargetsNamingExamples(examples: readonly ExampleFeature[], targets: GateTargets): string[] { + return examples.flatMap(({ featureId, routeIds, routePaths }) => [ + ...targets.gotoTargets + .filter(({ target }) => target.includes(featureId) || routePaths.some((routePath) => target === routePath || target.startsWith(`${routePath}/`) || target.startsWith(`${routePath}?`))) + .map(({ file, target }) => `${file}: goto ${target}`), + ...targets.artifactPaths + .filter((artifact) => artifact.includes(featureId) || routeIds.some((routeId) => artifact.includes(`/${routeId}.`))) + .map((artifact) => `config/ci/gates.json: ${artifact}`), + ...targets.scaleFiles.filter(({ text }) => text.includes(featureId)).map(({ file }) => `${file}: ${featureId}`), + ]); +} + +async function specFiles(directory: string): Promise { + return ((await readdir(directory, { recursive: true })) as string[]) + .filter((name) => /\.ts$/u.test(name)) + .map((name) => path.join(directory, name)); +} + +async function repositoryGateTargets(): Promise { + const gotoTargets: { file: string; target: string }[] = []; + for (const file of [...(await specFiles("tests/visual")), ...(await specFiles("tests/e2e"))]) { + const source = await readFile(file, "utf8"); + for (const [, target = ""] of source.matchAll(/\.goto\(\s*["'`]([^"'`]+)["'`]/gu)) gotoTargets.push({ file, target }); + } + const contract = await loadCiGateContract(process.cwd()); + const scaleFiles = await Promise.all( + (await readdir("config/scale")).map(async (name) => ({ + file: `config/scale/${name}`, + text: await readFile(`config/scale/${name}`, "utf8"), + })), + ); + return { gotoTargets, artifactPaths: contract.artifacts.map(({ path: artifact }) => artifact), scaleFiles }; +} + +describe("sample features (R4)", () => { + it("are all proven by the removal drill in FE-GATE-020", async () => { + const contract = await loadCiGateContract(process.cwd()); + const removability = contract.gates.find(({ id }) => id === "FE-GATE-020"); + const scripts = new Set( + contract.commands + .filter(({ id }) => removability?.commandIds.includes(id)) + .map(({ script }) => script), + ); + expect(scripts).toContain("test:sample-removal"); + // Without `--feature` the drill deletes every listed sample. + const packageScripts = (JSON.parse(await readFile("package.json", "utf8")) as { scripts: Record }) + .scripts; + expect(packageScripts["test:sample-removal"]).not.toMatch(/--feature/u); + // It builds and tests the copy; a documents-only check does not prove removal. + const drill = await readFile("scripts/test-sample-removal.ts", "utf8"); + expect(drill).toMatch(/check\(`\$\{prefix\}build`, "build"\)/u); + expect(drill).toMatch(/check\(`\$\{prefix\}unit-integration`, "test:all"\)/u); + }); +}); + +describe("gate targets (R5)", () => { + it("name no sample feature", async () => { + expect(gateTargetsNamingExamples(exampleFeatures(REMOVABLE_TEMPLATE_FEATURES), await repositoryGateTargets())).toEqual( + [], + ); + }); + + it("finds a sample's route in a visual spec, the evidence list and a scale record", () => { + const sample = { featureId: "order-feature", routeIds: ["ORDER_LIST"], routePaths: ["/orders"] }; + expect( + gateTargetsNamingExamples([sample], { + gotoTargets: [ + { file: "tests/visual/a.visual.spec.ts", target: "/orders?page=2" }, + { file: "tests/visual/a.visual.spec.ts", target: "/examples/platform" }, + ], + artifactPaths: ["docs/accessibility/route-reviews/ORDER_LIST.md", "artifacts/quality/bundle.json"], + scaleFiles: [{ file: "config/scale/feature-shape-growth.json", text: '{"sourceFeature":"order-feature"}' }], + }), + ).toEqual([ + "tests/visual/a.visual.spec.ts: goto /orders?page=2", + "config/ci/gates.json: docs/accessibility/route-reviews/ORDER_LIST.md", + "config/scale/feature-shape-growth.json: order-feature", + ]); + }); +}); diff --git a/tests/unit/repository-layout.test.ts b/tests/unit/repository-layout.test.ts index 769dfc31..b6ae701d 100644 --- a/tests/unit/repository-layout.test.ts +++ b/tests/unit/repository-layout.test.ts @@ -1,5 +1,6 @@ import { spawnSync } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; import { describe, expect, it } from "vitest"; @@ -12,9 +13,11 @@ import { } 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. + * The repository layout rules of docs/manual/03-outside-feature-folder.md + * that a file listing can check: R1 (every root item is registered), R2 (root + * path lists are chosen from the registry), R7 for files (no infrastructure + * configuration in this repository) and R9 (a tsconfig differs in its + * options, not only in its files). R3 is tests/unit/tracked-artifacts.test.ts. */ function trackedFiles(): string[] { @@ -133,3 +136,67 @@ describe("root path lists (R2)", () => { ); }); }); + +/** R7. Development compose files and Dockerfiles may live here; host and cluster configuration may not. */ +const INFRASTRUCTURE_FILE = + /(?:^|\/)(?:nginx[^/]*|[^/]+\.tf|[^/]+\.tfvars|Chart\.ya?ml|kustomization\.ya?ml|helmfile\.ya?ml)$/iu; +const KUBERNETES_MANIFEST = /^apiVersion:\s*\S+\s*$[\s\S]*^kind:\s*\S+\s*$/mu; + +describe("infrastructure configuration (R7)", () => { + it("is not tracked in this repository", () => { + const files = trackedFiles(); + const manifests = files + .filter((file) => /\.ya?ml$/u.test(file) && existsSync(file)) + .filter((file) => KUBERNETES_MANIFEST.test(readFileSync(file, "utf8"))); + expect([...files.filter((file) => INFRASTRUCTURE_FILE.test(file)), ...manifests]).toEqual([]); + }); + + it("recognises the file kinds the rule names", () => { + expect(["deploy/nginx.conf", "infra/main.tf", "chart/Chart.yaml", "kustomization.yml"].filter((file) => + INFRASTRUCTURE_FILE.test(file), + )).toHaveLength(4); + expect(KUBERNETES_MANIFEST.test("apiVersion: apps/v1\nkind: Deployment\n")).toBe(true); + expect(INFRASTRUCTURE_FILE.test("compose.yaml")).toBe(false); + }); +}); + +type TsconfigDocument = Readonly<{ + extends?: string; + compilerOptions?: Record; + files?: readonly string[]; + references?: readonly unknown[]; +}>; + +function effectiveCompilerOptions(file: string): Record { + const document = JSON.parse(readFileSync(file, "utf8")) as TsconfigDocument; + const inherited = document.extends?.startsWith(".") + ? effectiveCompilerOptions(path.join(path.dirname(file), document.extends)) + : {}; + return { ...inherited, ...document.compilerOptions }; +} + +/** Pairs of tsconfig files whose options are the same; a solution tsconfig (references only) has none. */ +function sameOptionTsconfigs(files: readonly string[]): string[] { + const options = files + .filter((file) => { + const document = JSON.parse(readFileSync(file, "utf8")) as TsconfigDocument; + return !(document.references && document.files?.length === 0); + }) + .map((file) => ({ + file, + options: JSON.stringify(Object.entries(effectiveCompilerOptions(file)).sort(([a], [b]) => a.localeCompare(b))), + })); + return options.flatMap((left, index) => + options.slice(index + 1).filter((right) => right.options === left.options).map((right) => `${left.file} = ${right.file}`), + ); +} + +describe("tsconfig files (R9)", () => { + // tests/fixtures/typecheck had 23 one-file tsconfigs with one set of + // options until 2026-11-08; scripts/check-type-fixtures.ts runs them now. + it("differ in lib, types or module resolution, not only in their files", () => { + const tsconfigs = trackedFiles().filter((file) => /(?:^|\/)tsconfig[^/]*\.json$/u.test(file) && existsSync(file)); + expect(tsconfigs.length).toBeGreaterThan(1); + expect(sameOptionTsconfigs(tsconfigs)).toEqual([]); + }); +});