Files
clean-architecture-frontend…/scripts/lib/documentation-readiness-checks.ts
DongHyeonka f04ea3b30a refactor(docs): 문서 검사의 src 구조·참조·R6·R7을 순수 함수로 나눈다
verify-documentation-readiness.ts는 export 없는 621줄 최상위 script라
검사 하나를 고칠 때마다 시험이 script를 자식 프로세스로 통째로 띄운다
(한 번에 최대 15.8 s). R7(문서 안 인프라 설정) 거절을 기대하는 시험이
없어, R7 줄을 지워도 실패하는 시험이 없다.

src 구조(checkSourceStructure), 문서 참조(checkDocumentReferences,
namedPath·명령 경로·verify.sh script·생성물 판정 포함), R6·R7
(checkLayoutRules)을 scripts/lib/documentation-readiness-checks.ts로
옮긴다. docs-system.ts의 runDocsSystemChecks처럼 문서와 사실(facts)을
받아 문제 목록을 돌려준다. script는 저장소에서 사실을 읽고(파일 존재,
package.json script, gates.json ID, .gitignore, 짝 저장소 pin과 git
tree) 출력만 한다. 검사 규칙과 출력 문구는 그대로다.

새 시험 tests/unit/documentation-readiness-checks.test.ts는 메모리
입력으로 검사마다 통과·거절을 본다. 문서를 읽지 않으므로 제거 드릴의
문서 시험 목록(REMOVAL_FIXTURE_DOCUMENT_TESTS)에 넣지 않는다.
documentation-readiness.test.ts에서는 그 시험이 덮는 자식 프로세스
사례 11개(경로·명령·생성물·src 구조)를 빼고, 옮긴 검사 셋을 진짜
문서에서 한 번에 깨뜨려 stderr 줄과 실패 검사 이름을 보는 사례 하나로
배선을 본다. 색인 링크, README 삭제 표, script·게이트 ID 사실, 짝
저장소(git), 출력 사례는 그대로 자식 프로세스로 남는다.

버린 안: R7 거절 시험만 자식 프로세스로 더하기 — 15 s짜리 실행이 하나
더 는다. 자식 프로세스 사례를 「이 repo 그대로 통과」 하나만 남기기 —
짝 저장소 pin 조회와 README 삭제 표처럼 script가 사실을 읽는 배선은
메모리 시험이 보지 못한다.

위험·한계: 옮기며 동작이 바뀌면 출력이 달라진다. 옛 script와 새
script를 같은 문서(통과·여러 검사를 깨뜨린 상태)에 돌려 rc·stdout·
stderr·보고서가 같은지 PR의 desktop RED 묶음에서 본다.

검증: 노트북 node 탐침으로 새 시험의 문서 참조·R7 사례 9개가 기대값과
같다. 단위 시험·변이·옛/새 출력 비교는 PR의 desktop 묶음에서 돈다.

Refs: REV-FE-0011, REV-FE-0022
2026-11-21 15:45:23 +09:00

296 lines
14 KiB
TypeScript

import { dirname, join, matchesGlob, normalize } from "node:path/posix";
/**
* The checks of scripts/verify-documentation-readiness.ts that read documents
* and facts and return what is wrong, as runDocsSystemChecks in
* scripts/lib/docs-system.ts does. The script reads the repository (files,
* package.json, gates.json, the paired checkouts) and reports; the tests give
* these functions inputs in memory (tests/unit/documentation-readiness-checks.test.ts).
*/
// ---------------------------------------------------------------- src structure
// 1101/14-03. The entry documents drew a `src/domain` layer that does not
// exist and left out `src/platform`, `src/apps` and `src/contexts`; layers.md
// said its table "cannot drift" from the rules while most rule names were
// missing. The folder and rule lists come from the code. layers.md describes
// each folder in one table row, and the other entry documents repeat that
// description verbatim as "`src/<folder>` — <description>", so a new folder or
// rule must be documented, the descriptions cannot diverge, and no document
// may name a top-level folder that is gone.
export const RULES_DOCUMENT = "docs/architecture/layers.md";
export const STRUCTURE_DOCUMENTS = Object.freeze([
RULES_DOCUMENT,
"README.md",
"docs/architecture/overview.md",
"docs/architecture/frontend-application-foundation.md",
]);
export type SourceStructureEntry = Readonly<{
path: string;
missingFolders: string[];
unknownFolders: string[];
missingRules: string[];
}>;
/** One entry per STRUCTURE_DOCUMENTS; a document missing from `texts` reads as empty. */
export function checkSourceStructure(
input: Readonly<{
texts: ReadonlyMap<string, string>;
sourceFolders: readonly string[];
architectureRules: readonly string[];
}>,
): SourceStructureEntry[] {
const rulesText = input.texts.get(RULES_DOCUMENT) ?? "";
const folderDescriptions = new Map(
[...rulesText.matchAll(/^\| `src\/([\w-]+)` \| (.+) \|$/gmu)].map((match) => [match[1], match[2]]),
);
return STRUCTURE_DOCUMENTS.map((path) => {
const text = path === RULES_DOCUMENT ? rulesText : (input.texts.get(path) ?? "");
const namedFolders = new Set([...text.matchAll(/\bsrc\/([\w-]+)/gu)].map((match) => match[1] ?? ""));
return {
path,
missingFolders: input.sourceFolders.filter((folder) => {
const description = folderDescriptions.get(folder);
if (description === undefined) return true;
return path !== RULES_DOCUMENT && !text.includes(`\`src/${folder}\` — ${description}`);
}),
unknownFolders: [...namedFolders].filter((folder) => !input.sourceFolders.includes(folder)).sort(),
missingRules:
path === RULES_DOCUMENT ? input.architectureRules.filter((rule) => !text.includes(`\`${rule}\``)) : [],
};
});
}
// ---------------------------------------------------------------- document references
export const NOT_CREATED: ReadonlySet<string> = new Set([
// Reserved by generic-worker-has-no-network-or-credentials. The generic CPU
// worker is NOT_SELECTED; docs/manual/03-outside-feature-folder.md says how
// to add it with its own tsconfig.
"src/adapters/web-worker",
]);
// pnpm's own commands, which are not package scripts.
const PNPM_COMMANDS = new Set(["add", "dlx", "exec", "install", "list", "why"]);
/** What the reference check looks a document's names up in; the script reads it from this repository. */
export type ReferenceFacts = Readonly<{
/** Whether a path relative to the repository root exists (file or folder). */
exists: (path: string) => boolean;
/** The names in the repository root. */
topLevelEntries: ReadonlySet<string>;
/** Package scripts (package.json). */
scripts: ReadonlySet<string>;
/** Gate IDs config/ci/gates.json defines, and the retired ones. */
gateIds: ReadonlySet<string>;
/** The paired repositories config/contracts/backend-contract-pin.json pins. */
pairedRepositories: ReadonlySet<string>;
/** Whether `reference` (`../<name>/<path>`) is in the pinned tree, or null when it cannot be checked here. */
pairedReferenceExists: (reference: string) => boolean | null;
/** The pattern lines of .gitignore. */
ignorePatterns: readonly string[];
/** History a copy deleted (README 「복사한 뒤 지워도 되는 것」); a path under one is not drift. */
deletedHistory: readonly string[];
/** Paths of the removable sample features that are not installed. */
removedFeaturePaths: readonly string[];
/** Scripts of the removable sample features that are not installed. */
removedFeatureScripts: ReadonlySet<string>;
}>;
export type DocumentReferences = Readonly<{
path: string;
missingPaths: string[];
unverifiedLinks: string[];
missingScripts: string[];
unknownGateIds: string[];
}>;
// Generated output is what git ignores, so a document may name it before a
// run has written it.
export function ignoredByGit(file: string, ignorePatterns: readonly string[]): boolean {
let ignored = false;
for (const line of ignorePatterns) {
const pattern = line.replace(/^!/u, "").replace(/^\/|\/$/gu, "");
const glob = pattern.includes("/") ? pattern : `**/${pattern}`;
if (matchesGlob(file, glob) || matchesGlob(file, `${glob}/**`)) ignored = !line.startsWith("!");
}
return ignored;
}
// A backtick span is a path when it starts at a top-level entry, at an entry
// beside the document or at a paired repository; line numbers and anchors are
// dropped. A path into a paired repository is returned relative to this one
// (`../<name>/…`).
export function namedPath(token: string, document: string, facts: ReferenceFacts): string | null {
const candidate = token.replace(/#.*$/u, "").replace(/:\d[\d,:-]*$/u, "");
// An ellipsis, `...` or `…`, stands for any name, as in scripts/lib/docs-system.ts.
if (!candidate.includes("/") || candidate.startsWith("/") || /[\s*<>{}$()|…]|\.\.\./u.test(candidate)) return null;
const first = candidate.split("/")[0] ?? "";
if (facts.topLevelEntries.has(first)) return candidate;
if (facts.pairedRepositories.has(first)) return `../${candidate}`;
return first !== "." && first !== ".." && facts.exists(join(dirname(document), first))
? join(dirname(document), candidate)
: null;
}
// A link that leaves the repository is kept (`../…`); the caller looks it up
// in the paired repositories.
function linkedPath(target: string, document: string): string | null {
if (/^(?:[a-z][a-z+.-]*:|#)/iu.test(target)) return null;
return normalize(join(dirname(document), target.replace(/#.*$/u, "")));
}
// 1103/12-05. A command span is not a path, so the paths it takes as
// arguments (`corepack pnpm exec vitest run tests/…`, `node scripts/…`) were
// never looked up. Leading `NAME=value` assignments are skipped, a
// `--flag=value` argument is read as its value, and placeholders (`<id>`,
// globs, `$VAR`) are left alone by namedPath.
const COMMAND_HEADS = new Set([
"corepack", "pnpm", "npx", "node", "vitest", "playwright", "tsc", "eslint", "bash", "sh", "python3",
]);
// 1112/08-06. `scripts/verify.sh` is this repository's main entry and most
// documented commands go through it: the entry is itself a path, `exec --`
// runs a command whose paths are looked up like any other, and `script`
// names package scripts (verifyScripts).
const VERIFY_ENTRY = /^(?:\.\/)?scripts\/verify\.sh$/u;
function commandWords(command: string): Readonly<{ words: string[]; head: number }> {
const words = command.trim().replace(/^\$\s+/u, "").split(/\s+/u);
let head = 0;
while (/^[A-Z_][A-Z0-9_]*=/u.test(words[head] ?? "")) head += 1;
return { words, head };
}
function commandPaths(command: string, document: string, facts: ReferenceFacts): (string | null)[] {
const { words, head } = commandWords(command);
const first = words[head] ?? "";
if (VERIFY_ENTRY.test(first)) {
const separator = words.indexOf("--", head + 1);
const executed = words[head + 1] === "exec" && separator > head ? words.slice(separator + 1).join(" ") : "";
return [namedPath(first, document, facts), ...(executed === "" ? [] : commandPaths(executed, document, facts))];
}
if (!COMMAND_HEADS.has(first)) return [];
return words
.slice(head + 1)
.map((word) => namedPath(word.replace(/^--?[\w.-]+=/u, "").replace(/^["']|["']$/gu, ""), document, facts));
}
/** The package scripts `scripts/verify.sh script <name>… [-- args]` runs; placeholders are left alone. */
function verifyScripts(command: string): string[] {
const { words, head } = commandWords(command);
if (!VERIFY_ENTRY.test(words[head] ?? "") || words[head + 1] !== "script") return [];
const names: string[] = [];
for (const word of words.slice(head + 2)) {
if (word.startsWith("-")) break;
names.push(word);
}
return names.filter((name) => /^[a-z](?:[\w:-]*\w)?$/u.test(name));
}
// Lines of fenced shell blocks (```bash, ```sh, ```shell, ```console or no
// language), which is where most documented commands are.
function fencedCommands(text: string): string[] {
const commands: string[] = [];
let fence: string | null = null;
for (const line of text.split("\n")) {
const marker = /^\s*```(\w*)/u.exec(line);
if (marker) {
fence = fence === null ? (marker[1] ?? "") : null;
continue;
}
if (fence !== null && /^(?:bash|sh|shell|console|zsh)?$/u.test(fence)) commands.push(line);
}
return commands;
}
/** The paths, links, package scripts and gate IDs `document` names that do not exist. */
export function checkDocumentReferences(document: string, text: string, facts: ReferenceFacts): DocumentReferences {
const scriptPrefixes = new Set([...facts.scripts].map((name) => name.split(":")[0]));
const missingScript = (name: string) => !facts.scripts.has(name) && !facts.removedFeatureScripts.has(name);
const named = [
...[...text.matchAll(/`([^`\n]+)`/gu)].flatMap(([, token = ""]) => [
namedPath(token, document, facts),
...commandPaths(token, document, facts),
]),
...fencedCommands(text).flatMap((command) => commandPaths(command, document, facts)),
...[...text.matchAll(/\]\(([^)\s]+)\)/gu)].map(([, target = ""]) => linkedPath(target, document)),
];
const missingPaths = new Set<string>();
const unverifiedLinks = new Set<string>();
for (const file of named) {
if (file === null) continue;
const trimmed = file.replace(/\/$/u, "");
if (trimmed.startsWith("../")) {
// Outside this repository: `../<paired repository>/<path at its pin>`.
const found = facts.pairedReferenceExists(trimmed);
if (found === null) unverifiedLinks.add(trimmed);
else if (!found) missingPaths.add(trimmed);
continue;
}
if (
!facts.exists(trimmed) &&
!NOT_CREATED.has(trimmed) &&
!ignoredByGit(trimmed, facts.ignorePatterns) &&
!facts.deletedHistory.some((entry) => trimmed === entry || trimmed.startsWith(`${entry}/`)) &&
!facts.removedFeaturePaths.some((entry) => trimmed === entry || trimmed.startsWith(`${entry}/`))
) {
missingPaths.add(trimmed);
}
}
const missingScripts = new Set<string>();
for (const [, name = ""] of text.matchAll(/(?:corepack pnpm|`pnpm) (?:run )?([a-z](?:[\w:-]*\w)?)/gu)) {
if (!PNPM_COMMANDS.has(name) && missingScript(name)) missingScripts.add(name);
}
for (const [, name = ""] of text.matchAll(/`([a-z][\w-]*:[\w:-]*\w)(?=[` ])/gu)) {
if (scriptPrefixes.has(name.split(":")[0]) && missingScript(name)) missingScripts.add(name);
}
const commands = [...[...text.matchAll(/`([^`\n]+)`/gu)].map(([, token = ""]) => token), ...fencedCommands(text)];
for (const name of commands.flatMap(verifyScripts)) {
if (missingScript(name)) missingScripts.add(name);
}
return {
path: document,
missingPaths: [...missingPaths].sort(),
unverifiedLinks: [...unverifiedLinks].sort(),
missingScripts: [...missingScripts].sort(),
unknownGateIds: [...new Set([...text.matchAll(/\bFE-GATE-\d+\b/gu)].map(([id]) => id))]
.filter((id) => !facts.gateIds.has(id))
.sort(),
};
}
// ---------------------------------------------------------------- repository layout rules
// 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: the current documents are the living documents
// scripts/lib/docs-system.ts reads for drift (records and decision records out).
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;
export type LayoutRuleViolation = Readonly<{ path: string; rule: "R6" | "R7"; detail: string }>;
/** R6 and R7 in one current document; `sampleFeaturePaths` are the removable sample features' paths. */
export function checkLayoutRules(
document: string,
text: string,
sampleFeaturePaths: readonly string[],
): LayoutRuleViolation[] {
const violations: LayoutRuleViolation[] = [];
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))) {
violations.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)) {
violations.push({ path: document, rule: "R6", detail: `line ${index + 1}: ${samplePath}` });
}
}
});
return violations;
}