Files
clean-architecture-frontend…/scripts/check-adapter-inventory.ts
DongHyeonka 04eb9a60b0
frontend-quality-gates / merge / static checks (pull_request) Successful in 1m31s
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
frontend-quality-gates / merge / tests (pull_request) Successful in 13m25s
frontend-quality-gates / merge / browser tests (pull_request) Failing after 5m8s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / main / self-tests and removal drills (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
fix(adapters): abort ratchet이 파일별 호출 위치를 센다
primitive를 import한 파일과 줄을 나눈 호출에 리스너가 늘어도 통과한다.
AST로 센 호출 위치를 파일별 표와 같게 고정하고 면제는 kernel 네 파일로
줄인다. 첫 인자는 맨 왼쪽 피연산자로 보고 new 호출도 센다. 합계만
고정하는 안은 파일 사이 옮기기를 놓쳐서 버린다. 13파일에서 29곳으로
바뀌는 것은 단위 변경 한 번이다(decisions.md 2.2절). 실행 가드는 main의
isEntryModule을 쓴다.

한계: 리스너 수가 그대로인 import 제거, 주석·문자열·문서 글자, 변수 첫
인자. adapter를 지운 파생 프로젝트는 표에서 그 줄을 지운다.

검증(노트북, 트리 c90e8bde): check:adapter-inventory(29곳 15파일),
check:types, lint, check:architecture, test:unit 3905,
verify:documentation, verify.sh docs rc=0. 실제 파일 변이와 규칙 변이는
main으로 옮기기 전 트리 197e9362에서 돌렸다.

Refs: REV-FE-0004
2026-11-23 04:46:53 +09:00

392 lines
16 KiB
TypeScript

import { readFile } from "node:fs/promises";
import { readFileSync } from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { parseSync, types } from "@babel/core";
import { CACHEABLE_ASSET_CONTENT_TYPES } from "../src/contracts/service-worker-static-manifest.ts";
import { isEntryModule } from "./lib/entry-module.ts";
import { selectRepositoryPaths } from "./lib/repository-layout.ts";
/**
* GOV-01 / SW-RR-03. Structural gates for facts that a hand-maintained document
* cannot keep true.
*
* The adapter review inventory claimed 118/118 while the tree held 119 files,
* so a whole adapter was outside every review's coverage without anything
* failing. And the Service Worker asset generator and the shared manifest
* decoder each carried their own extension table, so a build could emit an
* asset the runtime contract then refused. Both are now equalities this script
* checks rather than numbers someone has to remember to update.
*/
const INVENTORY_PATH = "docs/reviews/adapters/INVENTORY.md";
const GENERATOR_PATH = "scripts/generate-service-worker-assets.ts";
function trackedAdapterFiles(): readonly string[] {
const listed = spawnSync("git", ["ls-files", "src/adapters"], {
encoding: "utf8",
});
if (listed.status !== 0) {
throw new Error(`git ls-files failed: ${listed.stderr}`);
}
return listed.stdout.split("\n").filter(Boolean).sort();
}
function inventoryRows(markdown: string): readonly string[] {
const rows: string[] = [];
for (const line of markdown.split("\n")) {
const match = /^\|\s*\d+\s*\|\s*`([^`]+)`\s*\|/u.exec(line);
if (match?.[1]) rows.push(match[1]);
}
return rows;
}
function reportDifference(
label: string,
expected: readonly string[],
actual: readonly string[],
): readonly string[] {
const missing = expected.filter((value) => !actual.includes(value));
const extra = actual.filter((value) => !expected.includes(value));
const problems: string[] = [];
for (const value of missing) problems.push(`${label}: missing ${value}`);
for (const value of extra) problems.push(`${label}: unexpected ${value}`);
return problems;
}
// 손수 짠 abort 배선은 줄어들기만 해야 한다.
//
// 커널 `platform/abortable-operation.ts`가 있는데도 어댑터들이
// `addEventListener("abort")`로 같은 race/cleanup을 각자 짠다. 그 전수 이행은
// 동작이 바뀌는 큰 작업이라 한 번에 하지 않는다. 대신 파일마다 호출 위치 수를
// 여기 고정한다. 실제와 다르면 많아도 적어도 실패한다. 이행으로 줄면 수를 같이
// 내리고, 0이 되거나 파일을 지우면 그 줄을 지운다.
//
// 단위를 파일(상한 13)에서 호출 위치로 바꾼 것은 2026-11-22 한 번이다
// (docs/work/reference/decisions.md 2.2절). 수를 올리는 근거로 쓰지 않는다.
const HAND_ROLLED_ABORT_SITES: Readonly<Record<string, number>> = Object.freeze({
"src/adapters/browser-rpc/browser-rpc-runtime.ts": 3,
"src/adapters/browser-transfer/presigned/http-common.ts": 1,
"src/adapters/http/bounded-body-reader.ts": 1,
"src/adapters/http/http-execution-v3.ts": 7,
"src/adapters/query-cache/cursor-pagination-runtime.ts": 1,
"src/adapters/realtime/polling/bounded-poll-coordinator.ts": 1,
"src/adapters/realtime/reconnect-coordinator.ts": 3,
"src/adapters/realtime/result.ts": 1,
"src/adapters/realtime/sse/fetch-sse-connection.ts": 1,
"src/adapters/realtime/stream-coordinator.ts": 2,
"src/adapters/realtime/websocket/websocket-connection.ts": 2,
"src/adapters/service-worker/service-worker-static-assets.ts": 1,
"src/adapters/storage/opfs/opfs-worker-client.ts": 2,
"src/adapters/web-push/inbound/notification-click-adapter.ts": 1,
"src/adapters/web-push/runtime-support.ts": 2,
});
// 면제는 커널의 이 네 파일뿐이다. import 여부나 `platform/` 폴더로 면제하지 않는다.
export const ABORT_KERNEL_FILES: ReadonlySet<string> = new Set([
"src/adapters/platform/abortable-operation.ts",
"src/adapters/platform/indexeddb-connection.ts",
"src/adapters/platform/indexeddb-transaction.ts",
"src/adapters/platform/system-clock.ts",
]);
const CODE_FILE = /\.[cm]?[jt]sx?$/u;
const DECLARATION_FILE = /\.d\.[cm]?ts$/u;
function withoutWrappers(node: types.Node): types.Node {
return types.isTSAsExpression(node) ||
types.isTSSatisfiesExpression(node) ||
types.isTSNonNullExpression(node) ||
types.isTSTypeAssertion(node) ||
types.isTSInstantiationExpression(node)
? withoutWrappers(node.expression)
: node;
}
// 다른 식으로 시작할 수 있는 식 종류를 모두 내려간다. 나머지 종류는 다른 식으로 시작하지 않는다.
function leftmostOperand(node: types.Node): types.Node {
const operand = withoutWrappers(node);
switch (operand.type) {
case "BinaryExpression":
case "LogicalExpression":
case "AssignmentExpression":
return leftmostOperand(operand.left);
case "ConditionalExpression":
return leftmostOperand(operand.test);
case "SequenceExpression":
return leftmostOperand(operand.expressions[0]!);
case "MemberExpression":
case "OptionalMemberExpression":
return leftmostOperand(operand.object);
case "CallExpression":
case "OptionalCallExpression":
return leftmostOperand(operand.callee);
case "TaggedTemplateExpression":
return leftmostOperand(operand.tag);
case "UpdateExpression":
return operand.prefix ? operand : leftmostOperand(operand.argument);
default:
return operand;
}
}
function literalText(node: types.Node): string | null {
if (types.isStringLiteral(node)) return node.value;
if (types.isTemplateLiteral(node) && node.expressions.length === 0) {
return node.quasis[0]?.value.cooked ?? null;
}
return null;
}
function calleeName(node: types.Node): string | null {
const callee = withoutWrappers(node);
let name: types.Node = callee;
if (types.isMemberExpression(callee) || types.isOptionalMemberExpression(callee)) {
if (callee.computed) return literalText(withoutWrappers(callee.property));
name = callee.property;
}
if (types.isPrivateName(name)) return name.id.name;
return types.isIdentifier(name) ? name.name : null;
}
// 문자열이 아닌 첫 인자(변수)는 못 센다.
// 옛 줄 단위 검사가 잡던 꼴이라, 맨 왼쪽 피연산자가 "abort"인 첫 인자와 addEventListener로 끝나는 이름도 센다.
// new 호출도 센다(그렇게 끝나는 이름의 class 생성자가 리스너를 건다).
// 주석·문자열·문서 글자는 세지 않는다.
function abortListenerLines(file: string, source: string): readonly number[] {
if (!CODE_FILE.test(file)) return [];
const tree = parseSync(source, {
filename: file,
babelrc: false,
configFile: false,
sourceType: "module",
parserOpts: {
plugins: [
// A declaration file may declare a const without a value, as in check-architecture.ts.
["typescript", { dts: DECLARATION_FILE.test(file) }],
...(/\.[jt]sx$/u.test(file) ? (["jsx"] as const) : []),
],
},
});
if (!tree) throw new Error(`cannot parse ${file}`);
const lines: number[] = [];
types.traverseFast(tree, (node) => {
if (!types.isCallExpression(node) && !types.isOptionalCallExpression(node) && !types.isNewExpression(node)) return;
const first = node.arguments[0];
if (!first || !calleeName(node.callee)?.endsWith("addEventListener")) return;
if (literalText(leftmostOperand(first)) === "abort") {
lines.push(node.callee.loc?.end.line ?? 0);
}
});
return lines.sort((left, right) => left - right);
}
/** The lines of the call sites in each file that has one, the named kernel files left out. */
export function handRolledAbortSites(
sources: ReadonlyMap<string, string>,
): ReadonlyMap<string, readonly number[]> {
const sites = new Map<string, readonly number[]>();
for (const [file, source] of sources) {
if (ABORT_KERNEL_FILES.has(file)) continue;
const lines = abortListenerLines(file, source);
if (lines.length > 0) sites.set(file, lines);
}
return sites;
}
/** Each file whose call sites differ from its row. A file without a row has 0. */
export function abortSiteProblems(
sites: ReadonlyMap<string, readonly number[]>,
pinned: Readonly<Record<string, number>>,
): readonly string[] {
const problems: string[] = [];
for (const file of [...new Set([...sites.keys(), ...Object.keys(pinned)])].sort()) {
const lines = sites.get(file) ?? [];
const expected = pinned[file] ?? 0;
if (lines.length === expected) continue;
const where = lines.length > 0 ? ` (lines ${lines.join(", ")})` : "";
const remedy =
lines.length > expected
? "Use platform/abortable-operation.ts instead of a new listener."
: lines.length === 0
? "Delete that row."
: `Lower that number to ${lines.length}.`;
problems.push(
`abortable-operation: hand-rolled abort wiring in ${file}: ` +
`${lines.length} call sites${where}, pinned ${expected} in HAND_ROLLED_ABORT_SITES ` +
`(scripts/check-adapter-inventory.ts). ${remedy}`,
);
}
return problems;
}
export async function main(
pinned: Readonly<Record<string, number>> = HAND_ROLLED_ABORT_SITES,
): Promise<void> {
const problems: string[] = [];
const tracked = trackedAdapterFiles();
const markdown = await readFile(INVENTORY_PATH, "utf8");
const listed = inventoryRows(markdown);
problems.push(...reportDifference("adapter inventory", tracked, listed));
if (listed.length !== new Set(listed).size) {
problems.push("adapter inventory: duplicate row");
}
const total = /합계: \*\*(\d+)\/(\d+)\*\*/u.exec(markdown);
if (
!total ||
Number(total[1]) !== tracked.length ||
Number(total[2]) !== tracked.length
) {
problems.push(
`adapter inventory: total does not equal ${tracked.length} tracked files`,
);
}
// SW-RR-03. The generator must read the shared table rather than declare one.
const generator = await readFile(GENERATOR_PATH, "utf8");
if (!generator.includes("CACHEABLE_ASSET_CONTENT_TYPES")) {
problems.push(
"service worker assets: generator does not use the shared extension table",
);
}
if (/const CACHEABLE_EXTENSIONS[^=]*=\s*Object\.freeze\(\{/u.test(generator)) {
problems.push(
"service worker assets: generator declares its own extension table",
);
}
for (const [extension, contentType] of Object.entries(
CACHEABLE_ASSET_CONTENT_TYPES,
)) {
if (!extension.startsWith(".") || contentType.length === 0) {
problems.push(`service worker assets: invalid table row ${extension}`);
}
}
// A fixture that links the repository's node_modules with a single directory
// symlink is destructive: pnpm running inside that fixture purges the modules
// directory it does not recognise, follows the link, and deletes the real
// dependencies mid-run. `linkFixtureNodeModules` is the only sanctioned form.
const sources = spawnSync(
"git",
["grep", "-n", "-e", 'symlink(', "--", ...selectRepositoryPaths("fixture-code")],
{ encoding: "utf8" },
);
if (sources.status === 0) {
for (const line of sources.stdout.split("\n").filter(Boolean)) {
if (!line.includes("node_modules")) continue;
if (line.startsWith("scripts/lib/fixture-node-modules.ts:")) continue;
problems.push(
`fixture node_modules: use linkFixtureNodeModules instead — ${line}`,
);
}
}
const linkedFixtures = spawnSync(
"git",
["grep", "-l", "linkFixtureNodeModules", "--", ...selectRepositoryPaths("fixture-code")],
{ encoding: "utf8" },
);
if (
linkedFixtures.status !== 0 ||
linkedFixtures.stdout.split("\n").filter(Boolean).length < 2
) {
problems.push(
"fixture node_modules: the shared linker has no callers, so it is not the sanctioned path",
);
}
// TR-RR-05 / GOV-04. Every consumer the re-review named must use the shared
// primitive, not merely one file somewhere. Checking `importers.length > 0`
// let an unrelated production import satisfy the gate while Image and
// Resumable kept their own diverging copies of the same mechanics — which is
// exactly how the four hand-written versions drifted apart in the first place.
//
// 이 목록은 재검토가 이름으로 지목한 네 파일만 덮는다. 같은 두 그룹의
// `image-cdn-runtime.ts`와 `resumable-upload-runtime.ts`는 여기 없고 지금도
// 자기 abort 사본을 들고 있다. 어댑터의 다른 파일에도 사본이 있다. 그 전수
// 이행은 abort 의미론을 바꾸는 별도 작업이라 이 목록으로 강제하지 않고,
// 아래 래칫이 파일마다 호출 위치 수를 고정한다.
const REQUIRED_ABORT_CONSUMERS: readonly string[] = [
"src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts",
"src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts",
"src/adapters/browser-transfer/image-cdn/browser-image-probe.ts",
"src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts",
];
const primitiveImporters = spawnSync(
"git",
["grep", "-l", "platform/abortable-operation.ts", "--", "src"],
{ encoding: "utf8" },
);
const importers = (
primitiveImporters.status === 0 ? primitiveImporters.stdout : ""
)
.split("\n")
.filter(Boolean)
.filter((file) => !file.endsWith("platform/abortable-operation.ts"))
.sort();
const importerSet = new Set(importers);
const missingConsumers = REQUIRED_ABORT_CONSUMERS.filter(
(consumer) => !importerSet.has(consumer),
);
if (missingConsumers.length > 0) {
problems.push(
`abortable-operation: required consumers do not import the shared primitive: ${missingConsumers.join(
", ",
)}`,
);
}
// The importer must reach the primitive by a specifier that resolves to the
// primitive itself, so a same-named local helper cannot satisfy the gate.
const PRIMITIVE_PATH = path.resolve(
"src/adapters/platform/abortable-operation.ts",
);
for (const consumer of REQUIRED_ABORT_CONSUMERS) {
if (!importerSet.has(consumer)) continue;
const source = readFileSync(consumer, "utf8");
const specifiers = [
...source.matchAll(/from\s+"([^"]*platform\/abortable-operation\.ts)"/gu),
].map((match) => match[1] ?? "");
const resolved = specifiers.some(
(specifier) =>
path.resolve(path.dirname(consumer), specifier) === PRIMITIVE_PATH,
);
if (!resolved) {
problems.push(
`abortable-operation: ${consumer} does not resolve its import to the shared primitive`,
);
}
}
// A tracked file that cannot be read or parsed throws, so it fails the gate
// instead of counting zero.
const adapterSources = new Map(
tracked.map((file) => [file, readFileSync(file, "utf8")] as const),
);
const abortSites = handRolledAbortSites(adapterSources);
problems.push(...abortSiteProblems(abortSites, pinned));
if (problems.length > 0) {
for (const problem of problems) console.error(problem);
process.exitCode = 1;
return;
}
// GOV-04. The exact importer set is part of the receipt, so a reviewer can
// see which consumers the gate actually verified rather than a bare count.
console.log(
`Adapter inventory: ${tracked.length} files PASS; ` +
`service worker asset table: ${
Object.keys(CACHEABLE_ASSET_CONTENT_TYPES).length
} shared extensions PASS; ` +
`fixture node_modules linking PASS; ` +
`shared abort primitive: ${importers.length} importers ` +
`(${importers.join(", ")}) PASS; ` +
`hand-rolled abort wiring: ${[...abortSites.values()].flat().length} call sites ` +
`in ${abortSites.size} files (ratchet) PASS`,
);
}
// 시험이 import할 때는 돌지 않는다.
if (isEntryModule(import.meta)) await main();