From 1f57c38e401b071c6d4d6f37743b9b323458faec Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 11 Nov 2026 22:50:23 +0900 Subject: [PATCH] =?UTF-8?q?test(layout):=20R5=EB=A5=BC=20=EA=B2=8C?= =?UTF-8?q?=EC=9D=B4=ED=8A=B8=20=EB=8C=80=EC=83=81=EC=9D=98=20=EC=86=8C?= =?UTF-8?q?=EC=9C=A0=EC=9E=90=EB=A5=BC=20=EB=94=B0=EB=9D=BC=EA=B0=80?= =?UTF-8?q?=EB=8A=94=20=EA=B2=80=EC=82=AC=EB=A1=9C=20=EB=B0=94=EA=BE=BC?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit R5 검사는 샘플의 기능 ID와 라우트 경로가 goto 문자열, 증거 경로, 규모 기록 본문에 들어 있는지 찾았다. 조립한 경로, 여러 줄 goto, origin을 붙인 template 문자열, import로 샘플을 쓰는 spec은 놓쳤다. 이제 대상마다 소유자를 따라간다. - visual·e2e goto 경로 → 라우트 표(ROUTE_REGISTRY)의 라우트와 기능. 선언된 경로가 없으면 catch-all. - workshop story id → title이 그 id를 만드는 stories 파일. - spec의 import → 불러오는 파일을 끝까지. src/.generated/에서 멈춘다. - gates.json의 라우트 기록 → 라우트. 라우트 표에 없으면 실패. - 게이트 명령 → package script 그래프로 닿는 script, 경로 인자, --feature 인자. - config/scale/feature-shape-growth.json의 sourceFeature → 기능. 실제 저장소로 돈 결과가 비지 않는지, 샘플이 플랫폼 화면·디자인 시스템·메시지 카탈로그를 소유했다면 실제 spec·게이트에서 무엇이 걸리는지, 합성 샘플로 각 경로가 잡히는지를 시험한다. 검증(desktop): test:unit, check:types, check:ci, lint, verify:documentation. --- tests/unit/example-feature-rules.test.ts | 331 ++++++++++++++++++----- 1 file changed, 269 insertions(+), 62 deletions(-) diff --git a/tests/unit/example-feature-rules.test.ts b/tests/unit/example-feature-rules.test.ts index 880abcfe..6fac3dbe 100644 --- a/tests/unit/example-feature-rules.test.ts +++ b/tests/unit/example-feature-rules.test.ts @@ -1,14 +1,18 @@ -import { readdir, readFile } from "node:fs/promises"; +import { spawnSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; import { describe, expect, it } from "vitest"; import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts"; +import { reachablePackageScripts } from "../../scripts/lib/package-script-graph.ts"; import { REMOVABLE_TEMPLATE_FEATURES, + removableTemplateFeaturePaths, type RemovableTemplateFeature, } from "../../scripts/lib/removable-template-features.ts"; -import { INSTALLED_FEATURE_CONTRACTS } from "../../src/features/installed-feature-contracts.ts"; +import { PLATFORM_ROUTE_REGISTRY } from "../../src/contracts/routes.ts"; +import { ROUTE_FEATURE_OWNER, ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts"; /** * R4 and R5 of docs/manual/03-outside-feature-folder.md. A sample feature @@ -19,63 +23,208 @@ import { INSTALLED_FEATURE_CONTRACTS } from "../../src/features/installed-featur * 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. + * + * R5 follows each target to what owns it, so a sample is found by what it + * owns, not by its name appearing in a string: a route path resolves through + * the route table to a route and its feature, a story id to the stories file + * that defines it, a spec's imports to the files they load, a route review in + * the evidence list to its route, and a gate's commands through the package + * script graph to the scripts and paths they run. */ -type ExampleFeature = Readonly<{ featureId: string; routeIds: readonly string[]; routePaths: readonly string[] }>; +const PLATFORM = "platform"; +type Sample = Readonly<{ featureId: string; paths: readonly string[]; scripts: readonly string[] }>; +type RouteRow = Readonly<{ routeId: string; path: string; owner: string }>; + +/** What the gates point at, each with where it was found. */ type GateTargets = Readonly<{ - gotoTargets: readonly Readonly<{ file: string; target: string }>[]; - artifactPaths: readonly string[]; - scaleFiles: readonly Readonly<{ file: string; text: string }>[]; + routeTargets: readonly Readonly<{ where: string; target: string }>[]; + reachedFiles: readonly Readonly<{ where: string; file: string }>[]; + artifacts: readonly string[]; + gateScripts: readonly Readonly<{ gateId: string; script: string; command: string }>[]; + scaleSourceFeature: 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), +function samplesOf(features: readonly RemovableTemplateFeature[]): Sample[] { + return features.map((feature) => ({ + featureId: feature.featureId, + paths: removableTemplateFeaturePaths(feature), + scripts: feature.scripts, + })); +} + +function owningSample(samples: readonly Sample[], file: string): Sample | undefined { + return samples.find(({ paths }) => paths.some((owned) => file === owned || file.startsWith(`${owned}/`))); +} + +/** The route table the app boots with: each route and the feature that declares it. */ +function repositoryRoutes(): RouteRow[] { + const routes = Object.values(ROUTE_REGISTRY) as readonly Readonly<{ routeId: string; path: string }>[]; + return routes.map(({ routeId, path: routePath }) => ({ + routeId, + path: routePath, + owner: ROUTE_FEATURE_OWNER[routeId] ?? (routeId in PLATFORM_ROUTE_REGISTRY ? PLATFORM : "unknown"), + })); +} + +/** The route the router renders for `target`: a declared path, else the catch-all. */ +function resolveRoute(target: string, routes: readonly RouteRow[]): RouteRow | undefined { + const pathname = target.split(/[?#]/u)[0] ?? ""; + const segments = pathname.split("/").filter(Boolean); + const declared = routes.find((route) => { + if (route.path === "*") return false; + const pattern = route.path.split("/").filter(Boolean); + return ( + pattern.length === segments.length && + pattern.every((part, index) => (part.startsWith(":") ? segments[index] !== "" : part === segments[index])) ); - return { - featureId, - routeIds: routes.map(({ routeId }) => routeId), - routePaths: routes.map(({ path: routePath }) => routePath).filter((routePath) => routePath !== "/"), - }; + }); + return declared ?? routes.find((route) => route.path === "*"); +} + +/** + * The app paths a spec opens literally. A target computed at run time is left + * out: the a11y spec walks the whole route table, which names every installed + * feature and none in particular, and a generated feature's path is generator + * output. A sample module such a spec imports is still found by the import walk. + */ +function literalGotoTargets(source: string): string[] { + return [...source.matchAll(/\.goto\(\s*(["'`])((?:\\.|(?!\1)[^\\])*)\1/gu)].flatMap(([, , raw = ""]) => { + // `${server.origin}/` is the served build's origin, then the app path. + const target = raw.replace(/^\$\{[^}]*\}/u, ""); + if (target.includes("${")) return []; + if (target === "") return ["/"]; + return target.startsWith("/") ? [target] : []; }); } -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}`), - ]); +const IMPORT_SPECIFIER = + /(?:\bimport\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s*)?|\bexport\s+(?:type\s+)?[^'"`;]*?\sfrom\s*|\bimport\(\s*)["']([^"']+)["']/gu; + +/** Repository files `file` imports, resolved; package imports are not followed. */ +function importedFiles(file: string, source: string, exists: (file: string) => boolean): string[] { + return [...source.matchAll(IMPORT_SPECIFIER)].flatMap(([, specifier = ""]) => { + if (!specifier.startsWith(".")) return []; + const base = path.posix.normalize(path.posix.join(path.posix.dirname(file), specifier)); + const resolved = [base, `${base}.ts`, `${base}.tsx`, `${base}/index.ts`].find(exists); + return resolved === undefined ? [] : [resolved]; + }); } -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)); +/** + * Every file the entries load. The walk stops at `src/.generated/`: the + * feature index there is generator output that imports each installed + * feature, and removing a sample writes it again without that sample. + */ +function reachableFiles( + entries: readonly string[], + read: (file: string) => string, + exists: (file: string) => boolean, +): Readonly<{ where: string; file: string }>[] { + const reached = new Map(); + const queue = entries.map((entry) => ({ where: entry, file: entry })); + for (let next = queue.shift(); next !== undefined; next = queue.shift()) { + if (reached.has(next.file) || next.file.startsWith("src/.generated/")) continue; + reached.set(next.file, next.where); + for (const imported of importedFiles(next.file, read(next.file), exists)) { + queue.push({ where: next.where, file: imported }); + } + } + return [...reached].map(([file, where]) => ({ where, file })); +} + +/** Storybook's id prefix for a stories file's title: "Platform/Galleries" is "platform-galleries". */ +function storyIdPrefix(title: string): string { + return title.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, ""); +} + +/** Gate targets that a sample owns, or that point at nothing. Empty when R5 holds. */ +function sampleGateTargets(samples: readonly Sample[], routes: readonly RouteRow[], targets: GateTargets): string[] { + const sampleIds = new Set(samples.map(({ featureId }) => featureId)); + const findings: string[] = []; + for (const { where, target } of targets.routeTargets) { + const route = resolveRoute(target, routes); + if (route === undefined) findings.push(`${where}: goto ${target} matches no route`); + else if (sampleIds.has(route.owner)) findings.push(`${where}: goto ${target} is ${route.routeId} of sample ${route.owner}`); + } + for (const { where, file } of targets.reachedFiles) { + const sample = owningSample(samples, file); + if (sample) findings.push(`${where} loads ${file} of sample ${sample.featureId}`); + } + for (const artifact of targets.artifacts) { + const review = /^docs\/accessibility\/route-reviews\/([^/]+)\.md$/u.exec(artifact)?.[1]; + const route = review === undefined ? undefined : routes.find(({ routeId }) => routeId === review); + if (review !== undefined && route === undefined) { + findings.push(`config/ci/gates.json: ${artifact} reviews no route in the route table`); + } else if (route !== undefined && sampleIds.has(route.owner)) { + findings.push(`config/ci/gates.json: ${artifact} reviews ${route.routeId} of sample ${route.owner}`); + } + const sample = owningSample(samples, artifact); + if (sample) findings.push(`config/ci/gates.json: ${artifact} is in sample ${sample.featureId}`); + } + for (const { gateId, script, command } of targets.gateScripts) { + for (const sample of samples) { + if (sample.scripts.includes(script)) findings.push(`${gateId} runs ${script}, a script of sample ${sample.featureId}`); + } + const words = command.split(/\s+/u).map((word) => word.replace(/^["']|["']$/gu, "")); + for (const [index, word] of words.entries()) { + const feature = /^--feature=(.+)$/u.exec(word)?.[1] ?? (word === "--feature" ? words[index + 1] : undefined); + if (feature !== undefined && sampleIds.has(feature)) findings.push(`${gateId} runs ${script} on sample ${feature}`); + const sample = owningSample(samples, word.replace(/^\.\//u, "")); + if (sample) findings.push(`${gateId} runs ${script} on ${word} of sample ${sample.featureId}`); + } + } + if (sampleIds.has(targets.scaleSourceFeature)) { + findings.push(`config/scale/feature-shape-growth.json: sourceFeature is sample ${targets.scaleSourceFeature}`); + } + return findings; +} + +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 !== "" && existsSync(file)); } 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 tracked = trackedFiles(); + const specs = tracked.filter((file) => /^tests\/(?:visual|e2e)\/.+\.tsx?$/u.test(file)); + const read = (file: string) => readFileSync(file, "utf8"); + const routeTargets = specs.flatMap((file) => literalGotoTargets(read(file)).map((target) => ({ where: file, target }))); + + // A workshop story a visual spec opens is drawn by the stories file whose title gives its id. + const stories = tracked + .filter((file) => file.endsWith(".stories.tsx")) + .flatMap((file) => { + const title = /^\s*title:\s*["']([^"']+)["']/mu.exec(read(file))?.[1]; + return title === undefined ? [] : [{ file, prefix: storyIdPrefix(title) }]; + }); + const storyFiles = specs + .filter((file) => file.startsWith("tests/visual/")) + .flatMap((file) => + [...read(file).matchAll(/["'`]([a-z0-9-]+)--[a-z0-9-]+["'`]/gu)].map(([story = "", prefix = ""]) => { + const owner = stories.find((candidate) => candidate.prefix === prefix); + return { where: `${file} (story ${story.slice(1, -1)})`, file: owner?.file ?? `` }; + }), + ); + 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"), - })), + const packageScripts = (JSON.parse(read("package.json")) as { scripts: Record }).scripts; + const gateScripts = contract.gates.flatMap(({ id, commandIds }) => + reachablePackageScripts( + packageScripts, + contract.commands.filter((command) => commandIds.includes(command.id)).map(({ script }) => script), + ).map((script) => ({ gateId: id, script, command: packageScripts[script] ?? "" })), ); - return { gotoTargets, artifactPaths: contract.artifacts.map(({ path: artifact }) => artifact), scaleFiles }; + const scale = JSON.parse(read("config/scale/feature-shape-growth.json")) as { sourceFeature: string }; + return { + routeTargets, + reachedFiles: [...reachableFiles(specs, read, existsSync), ...storyFiles], + artifacts: contract.artifacts.map(({ path: artifact }) => artifact), + gateScripts, + scaleSourceFeature: scale.sourceFeature, + }; } describe("sample features (R4)", () => { @@ -89,38 +238,96 @@ describe("sample features (R4)", () => { ); 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 }) + const packageScripts = (JSON.parse(readFileSync("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"); + const drill = readFileSync("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("are owned by no sample feature and each points at something", async () => { + const targets = await repositoryGateTargets(); + // The walk reaches the real targets: an empty one would pass anything. + expect(targets.routeTargets.length).toBeGreaterThan(10); + expect(targets.reachedFiles.some(({ file }) => file.startsWith("src/"))).toBe(true); + expect(targets.artifacts.some((artifact) => artifact.startsWith("docs/accessibility/route-reviews/"))).toBe(true); + expect(targets.gateScripts.length).toBeGreaterThan(20); + expect(sampleGateTargets(samplesOf(REMOVABLE_TEMPLATE_FEATURES), repositoryRoutes(), targets)).toEqual([]); + }); + + it("finds this repository's targets once a sample owns what they point at", async () => { + // As if the platform overview screen, the design system and the message catalog were a sample's. + const sample: Sample = { + featureId: "overview-sample", + paths: ["src/presentation/design-system", "src/presentation/i18n"], + scripts: ["test:visual"], + }; + const routes = repositoryRoutes().map((route) => + route.routeId === "EXAMPLES_PLATFORM" ? { ...route, owner: sample.featureId } : route, + ); + const findings = sampleGateTargets([sample], routes, await repositoryGateTargets()); + expect(findings).toEqual( + expect.arrayContaining([ + "tests/e2e/platform-overview.spec.ts: goto /examples/platform is EXAMPLES_PLATFORM of sample overview-sample", + "tests/visual/platform.visual.spec.ts (story platform-galleries--design-system) loads src/presentation/design-system/galleries.stories.tsx of sample overview-sample", + "tests/e2e/accessibility.spec.ts loads src/presentation/i18n/catalog.ts of sample overview-sample", + "FE-GATE-008 runs test:visual, a script of sample overview-sample", + ]), ); }); - 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", + it("follows routes, imports, route reviews, scripts and the scale record of a synthetic sample", () => { + const sample: Sample = { + featureId: "order-feature", + paths: ["src/features/order-feature", "tests/features/order-feature"], + scripts: ["test:orders"], + }; + const routes: RouteRow[] = [ + { routeId: "APP_HOME", path: "/", owner: PLATFORM }, + { routeId: "ORDER_DETAIL", path: "/orders/:orderId", owner: "order-feature" }, + { routeId: "NOT_FOUND", path: "*", owner: PLATFORM }, + ]; + const sources: Record = { + "tests/e2e/orders.spec.ts": [ + `import { ORDER } from "../../src/features/order-feature/order-contract.ts";`, + `import { INDEX } from "../../src/.generated/product-feature-index.ts";`, + `await page.goto(\`\${server.origin}/orders/7?tab=items\`);`, + `await page.goto("/");`, + `await page.goto("/no-such-page");`, + `await page.goto(route);`, + ].join("\n"), + "src/features/order-feature/order-contract.ts": `export const ORDER = 1;`, + }; + const exists = (file: string) => file in sources || file === "src/.generated/product-feature-index.ts"; + const targets: GateTargets = { + routeTargets: literalGotoTargets(sources["tests/e2e/orders.spec.ts"]!).map((target) => ({ + where: "tests/e2e/orders.spec.ts", + target, + })), + reachedFiles: reachableFiles(["tests/e2e/orders.spec.ts"], (file) => sources[file] ?? "", exists), + artifacts: ["docs/accessibility/route-reviews/ORDER_DETAIL.md", "docs/accessibility/route-reviews/GONE.md"], + gateScripts: [ + { gateId: "FE-GATE-008", script: "test:orders", command: "playwright test" }, + { gateId: "FE-GATE-005", script: "test:unit", command: "vitest run tests/features/order-feature" }, + { gateId: "FE-GATE-020", script: "test:sample-removal", command: "node drill.ts --feature=order-feature" }, + ], + scaleSourceFeature: "order-feature", + }; + expect(sampleGateTargets([sample], routes, targets)).toEqual([ + "tests/e2e/orders.spec.ts: goto /orders/7?tab=items is ORDER_DETAIL of sample order-feature", + "tests/e2e/orders.spec.ts loads src/features/order-feature/order-contract.ts of sample order-feature", + "config/ci/gates.json: docs/accessibility/route-reviews/ORDER_DETAIL.md reviews ORDER_DETAIL of sample order-feature", + "config/ci/gates.json: docs/accessibility/route-reviews/GONE.md reviews no route in the route table", + "FE-GATE-008 runs test:orders, a script of sample order-feature", + "FE-GATE-005 runs test:unit on tests/features/order-feature of sample order-feature", + "FE-GATE-020 runs test:sample-removal on sample order-feature", + "config/scale/feature-shape-growth.json: sourceFeature is sample order-feature", ]); + // `/no-such-page` is the catch-all's, a platform screen; the generated index ends the walk. + expect(targets.reachedFiles.map(({ file }) => file)).not.toContain("src/.generated/product-feature-index.ts"); }); });