Files
clean-architecture-frontend…/scripts/lib/v8-coverage-counter-semantics.ts
T
DongHyeonka 543518ad2a
frontend-quality-gates / merge / static checks (pull_request) Canceled after 0s
frontend-quality-gates / merge / tests (pull_request) Canceled after 0s
frontend-quality-gates / merge / browser tests (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Canceled after 0s
frontend-quality-gates / external-vulnerability-provider (pull_request) Canceled after 0s
frontend-quality-gates / external-provenance-provider (pull_request) Canceled after 0s
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Canceled after 0s
frontend-quality-gates / deploy-promoted-release (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Canceled after 0s
frontend-quality-gates / main / checker self-tests (pull_request) Canceled after 0s
fix(coverage): coverage 대상 패턴을 저장소 루트에 고정한다
문제: vitest는 coverage include·exclude를 모듈의 절대 경로에 picomatch
`contains: true`로 맞춘다. 그래서 `src/**/*.{ts,tsx}`가 경로 어디에서나
맞는다. checkout이 이름이 `src`로 끝나는 폴더(`~/work/app-src/`)에
있으면 `vite.config.ts`·`scripts/**` 같은 루트 파일이 coverage에 들어가
risk-coverage가 저장소 목록 밖의 행으로 실패한다(tech-log 동기화 때
desktop에서 본 일). CI 경로에는 `src`가 없어 runner에서는 안 보였다.

고른 방법: `scripts/lib/coverage-scope.ts`의 `rootAnchoredGlobs`가
패턴 앞에 루트를 붙인다. 루트는 vitest의 glob 라이브러리(tinyglobby
0.2)가 cwd를 escape하는 식 그대로 escape해, 괄호 같은 glob 문자가 든
루트도 자기 자신에만 맞고 안 불린 파일 glob도 `src/...`로 풀린다.
`vitest.config.ts`와 `check:v8-coverage-counter-semantics`의 자식
설정이 이 함수를 쓴다.
- 막는 시험: counter-semantics 검사가 fixture를
  `checkout (copy)-src/` 아래로 복사하고, fixture 시험이 `src/` 밖
  모듈(`outside-src.ts`)도 불러온다. 고정이 빠지면 그 모듈이 행으로
  들어와 행 집합 검사가 실패한다. 이 검사는 test:coverage 첫 단계에서
  이미 자식 vitest를 띄우므로 프로세스가 늘지 않는다. 단위 시험은
  repo 설정의 모든 패턴이 루트로 시작하는지와 escape를 본다.
- 버린 대안: picomatch로 vitest의 판정을 흉내 내는 단위 시험. 직접
  의존성이 아니고, vitest가 옵션을 바꾸면 거짓 통과한다.

위험·한계: Windows 루트는 `/`로 바꾼 뒤 같은 식으로 escape한다.
올바른 Windows 경로에서는 tinyglobby의 Windows escape와 결과가 같다고
보았지만 Windows에서 돌려 보지는 않았다.

검증(desktop): coverage-scope·v8-coverage-counter-semantics 시험 통과,
check:v8-coverage-counter-semantics rc=0. 변이: 자식 설정을 예전
`["src/**/*.ts"]`로 되돌리면 같은 검사가 `additional: outside-src.ts`로
rc=1. check:types·eslint rc=0. 로그 /tmp/claude-gates/w2fe2-cov1/.
2026-11-12 22:03:08 +09:00

308 lines
9.7 KiB
TypeScript

import { execFile } from "node:child_process";
import {
cp,
mkdtemp,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { rootAnchoredGlobs } from "./coverage-scope.ts";
const execFileAsync = promisify(execFile);
const coverageMetrics = [
"lines",
"statements",
"functions",
"branches",
] as const;
const runtimeModule = "src/runtime.ts";
const counterlessModules = Object.freeze([
"src/import-empty.ts",
"src/import-side-effect.ts",
"src/import-type-empty.ts",
"src/import-value.ts",
"src/reexport-named.ts",
"src/reexport-star.ts",
"src/type-only.ts",
] as const);
const expectedModules = Object.freeze(
[runtimeModule, ...counterlessModules].sort(),
);
const childOutputLimit = 1_800;
/**
* The fixture is copied into a folder whose name ends in `src` and has glob
* characters. Vitest matches coverage patterns anywhere in an absolute path,
* so an unanchored `src/**` also counts the fixture's root-level
* `outside-src.ts`, which the row-set check then reports as additional. The
* repository's own coverage patterns are anchored the same way
* (vitest.config.ts, scripts/lib/coverage-scope.ts).
*/
const fixtureCheckoutName = "checkout (copy)-src";
type ChildOutput = Readonly<{ stdout: string; stderr: string }>;
type ChildInput = Readonly<{
repositoryRoot: string;
ownedRoot: string;
fixtureRoot: string;
configPath: string;
}>;
type CheckerOptions = Readonly<{
repositoryRoot?: string;
createOwnedRoot?: () => Promise<string>;
runVitest?: (input: ChildInput) => Promise<ChildOutput>;
}>;
export type V8CoverageCounterSemantics = Readonly<{
counterBearingModules: readonly string[];
counterlessModules: readonly string[];
}>;
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function hasErrorCode(error: unknown, code: string): boolean {
return isRecord(error) && error.code === code;
}
function normalizeSummaryPath(value: string, fixtureRoot: string): string {
const relative = path.isAbsolute(value) ? path.relative(fixtureRoot, value) : value;
const normalized = relative.split(path.sep).join("/");
if (
normalized.length === 0 ||
normalized === ".." ||
normalized.startsWith("../") ||
path.posix.isAbsolute(normalized)
) {
throw new TypeError(`V8 coverage row is outside the owned fixture: ${value}`);
}
return normalized;
}
function coverageCounter(
value: unknown,
label: string,
): Readonly<{ total: number; covered: number; skipped: number; pct: number }> {
if (!isRecord(value)) throw new TypeError(`${label} must be an object`);
const { total, covered, skipped, pct } = value;
if (
typeof total !== "number" ||
!Number.isSafeInteger(total) ||
typeof covered !== "number" ||
!Number.isSafeInteger(covered) ||
typeof skipped !== "number" ||
!Number.isSafeInteger(skipped) ||
typeof pct !== "number" ||
!Number.isFinite(pct) ||
total < 0 ||
covered < 0 ||
skipped < 0 ||
covered + skipped > total
) {
throw new TypeError(`${label} contains invalid coverage counters`);
}
const expectedPercentage =
total === 0 ? 100 : Math.floor((covered / total) * 10_000) / 100;
if (pct !== expectedPercentage) {
throw new TypeError(`${label} contains invalid coverage counters`);
}
return { total, covered, skipped, pct };
}
function coverageRow(
value: unknown,
label: string,
): Readonly<Record<(typeof coverageMetrics)[number], ReturnType<typeof coverageCounter>>> {
if (!isRecord(value)) throw new TypeError(`${label} must be an object`);
return Object.fromEntries(
coverageMetrics.map((metric) => [
metric,
coverageCounter(value[metric], `${label}.${metric}`),
]),
) as Readonly<
Record<(typeof coverageMetrics)[number], ReturnType<typeof coverageCounter>>
>;
}
export function assertV8CoverageCounterSemantics(
value: unknown,
fixtureRoot: string,
): V8CoverageCounterSemantics {
if (!isRecord(value)) throw new TypeError("V8 coverage summary must be an object");
coverageRow(value.total, "V8 coverage total");
const rows = new Map<string, ReturnType<typeof coverageRow>>();
for (const [producerPath, producerRow] of Object.entries(value)) {
if (producerPath === "total") continue;
const normalizedPath = normalizeSummaryPath(producerPath, fixtureRoot);
if (rows.has(normalizedPath)) {
throw new TypeError(`V8 coverage row is duplicated: ${normalizedPath}`);
}
rows.set(
normalizedPath,
coverageRow(producerRow, `V8 coverage row ${normalizedPath}`),
);
}
const actualModules = [...rows.keys()].sort();
const missing = expectedModules.filter((modulePath) => !rows.has(modulePath));
const additional = actualModules.filter(
(modulePath) => !expectedModules.includes(modulePath),
);
if (missing.length > 0 || additional.length > 0) {
throw new Error(
`V8 coverage row set mismatch; missing: ${missing.join(", ") || "none"}; additional: ${additional.join(", ") || "none"}`,
);
}
const runtimeRow = rows.get(runtimeModule)!;
if (!coverageMetrics.some((metric) => runtimeRow[metric].total > 0)) {
throw new Error(`V8 runtime module is not counter-bearing: ${runtimeModule}`);
}
for (const modulePath of counterlessModules) {
const row = rows.get(modulePath)!;
const exactAllZero = coverageMetrics.every((metric) => {
const counter = row[metric];
return (
counter.total === 0 &&
counter.covered === 0 &&
counter.skipped === 0 &&
counter.pct === 100
);
});
if (!exactAllZero) {
throw new Error(
`V8 counterless module must have exact all-zero counters: ${modulePath}`,
);
}
}
return Object.freeze({
counterBearingModules: Object.freeze([runtimeModule]),
counterlessModules: Object.freeze([...counterlessModules]),
});
}
function boundedChildOutput(value: unknown): string {
const output =
typeof value === "string"
? value
: value instanceof Uint8Array
? new TextDecoder().decode(value)
: "";
if (output.length <= childOutputLimit) return output;
return `${output.slice(0, childOutputLimit)}\n[truncated ${output.length - childOutputLimit} characters]`;
}
async function defaultRunVitest(input: ChildInput): Promise<ChildOutput> {
const result = await execFileAsync(
process.execPath,
[
path.join(input.repositoryRoot, "node_modules/vitest/vitest.mjs"),
"run",
"--config",
input.configPath,
"--coverage",
"--reporter=dot",
"--no-color",
],
{
cwd: input.fixtureRoot,
encoding: "utf8",
timeout: 30_000,
maxBuffer: 256 * 1024,
},
);
return { stdout: result.stdout, stderr: result.stderr };
}
function assertOwnedTemporaryRoot(value: string): string {
const temporaryRoot = path.resolve(tmpdir());
const ownedRoot = path.resolve(value);
const relative = path.relative(temporaryRoot, ownedRoot);
if (
relative.length === 0 ||
relative === ".." ||
relative.startsWith(`..${path.sep}`) ||
path.isAbsolute(relative)
) {
throw new TypeError(`V8 coverage fixture root is not an owned temp path: ${ownedRoot}`);
}
return ownedRoot;
}
export async function checkV8CoverageCounterSemantics(
options: CheckerOptions = {},
): Promise<V8CoverageCounterSemantics> {
const repositoryRoot = path.resolve(options.repositoryRoot ?? process.cwd());
const createOwnedRoot =
options.createOwnedRoot ??
(() => mkdtemp(path.join(tmpdir(), "v8-counter-semantics-")));
const runVitest = options.runVitest ?? defaultRunVitest;
const ownedRoot = assertOwnedTemporaryRoot(await createOwnedRoot());
const fixtureSource = path.join(
repositoryRoot,
"tests/fixtures/v8-coverage-counter-semantics",
);
const fixtureRoot = path.join(ownedRoot, fixtureCheckoutName);
const configPath = path.join(fixtureRoot, "vitest.config.mjs");
const reportsDirectory = path.join(ownedRoot, "coverage");
try {
await cp(fixtureSource, fixtureRoot, { recursive: true });
await writeFile(
configPath,
`export default ${JSON.stringify(
{
root: fixtureRoot,
test: {
globals: true,
include: ["counter-semantics.fixture.ts"],
setupFiles: [],
coverage: {
provider: "v8",
reportsDirectory,
reporter: ["json-summary"],
include: rootAnchoredGlobs(fixtureRoot, ["src/**/*.ts"]),
},
},
},
null,
2,
)};\n`,
"utf8",
);
try {
await runVitest({ repositoryRoot, ownedRoot, fixtureRoot, configPath });
} catch (error) {
const record = isRecord(error) ? error : {};
throw new Error(
`V8 coverage counter semantics child Vitest failed\nstdout:\n${boundedChildOutput(record.stdout)}\nstderr:\n${boundedChildOutput(record.stderr)}`,
{ cause: error },
);
}
const summaryPath = path.join(reportsDirectory, "coverage-summary.json");
let summaryText: string;
try {
summaryText = await readFile(summaryPath, "utf8");
} catch (error) {
if (hasErrorCode(error, "ENOENT")) {
throw new Error("V8 coverage counter semantics coverage summary is missing", {
cause: error,
});
}
throw error;
}
let summary: unknown;
try {
summary = JSON.parse(summaryText) as unknown;
} catch (error) {
throw new TypeError("V8 coverage counter semantics summary is invalid JSON", {
cause: error,
});
}
return assertV8CoverageCounterSemantics(summary, fixtureRoot);
} finally {
await rm(ownedRoot, { recursive: true, force: true });
}
}