Files
clean-architecture-frontend…/scripts/check-type-fixtures.ts
DongHyeonka c2fb6cf7c2
frontend-quality-gates / merge / static checks (pull_request) Successful in 1m15s
frontend-quality-gates / merge / tests (pull_request) Successful in 13m20s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 5m16s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (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 / external-vulnerability-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
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
fix(scripts): 실행 가드를 실패로 닫히는 helper 하나로 바꾼다
스크립트 22곳이 argv[1]로 직접 실행을 판정해서, checkout 경로에
공백·한글이 있거나 symlink 절대 경로로 부르면 18곳이 검사 없이 rc=0으로
끝날 수 있다. merge 게이트 명령 셋이 여기 걸린다.

isEntryModule(import.meta) 하나로 바꾸고, process.argv 둘째 값 읽기와
helper 밖 판정은 시험으로 막는다. 맨 import.meta.main은 그 값이 없는
Node에서 같은 거짓 통과가 나서 버렸다. realpath 비교는 같은 판정의 사본
22개가 남고, argv 값의 쓰임을 따라가는 시험은 return·대입으로 피할 수
있어 버렸다.

위험·한계: 건너뛰던 검사가 실패하기 시작할 수 있고, 실행 판정이 아닌
process.argv[1] 읽기도 실패한다. import.meta.main이 없는 Node에서 직접
실행하거나 import하면 실패한다. verify-extreme-scale도 그 Node에서는
rc=2보다 먼저 rc=1로 끝나고, 이전 기록(passed일 수 있다)이 그대로
남아 종료 code로 본다. 코드로 읽은 것이고 그 Node로 돌려 보지 않았다.
막는 시험은 process·argv 별칭과 계산한 index를 따라가지 않는다.

검증(노트북, main으로 옮기기 전 트리 a806088b): 새 시험 고치기 전 실패,
고친 뒤 통과. test:unit 3707개, types, lint, check:ci,
verify:documentation rc=0. desktop merge 단계는 따로 확인한다.

Refs: REV-FE-0040
2026-11-23 02:25:03 +09:00

143 lines
6.0 KiB
TypeScript

import { spawn } from "node:child_process";
import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { isEntryModule } from "./lib/entry-module.ts";
/**
* The negative type fixtures (FE-GATE-003). Each fixture under
* tests/fixtures/typecheck states on its first line what tsc must say about
* it: `// expect: TS2322` (compilation fails and reports TS2322) or
* `// expect: pass` (it compiles; tests/fixtures/typecheck/invalid-diagnostics-port.ts
* holds one `@ts-expect-error` per violation). Every fixture compiles alone
* with tests/fixtures/typecheck/tsconfig.base.json, as the 23 one-file
* tsconfigs and package scripts this runner replaces did (design-docs
* repo-structure/04-frontend-layout.md §5.3 (가)).
*
* The check is the one run-ci-gate.ts applied to each of those commands:
* tsc exits 1 and its output contains `error TS<code>:`. A fixture without an
* expectation line fails, and so does a directory with no fixtures, so a new
* fixture cannot be skipped and an empty run cannot pass (R8).
*/
export const TYPE_FIXTURE_ROOT = "tests/fixtures/typecheck";
const BASE_CONFIG = `${TYPE_FIXTURE_ROOT}/tsconfig.base.json`;
/**
* tsc resolves `types` from the tsconfig's directory upwards, so the one-file
* tsconfigs are written inside the repository, in the ignored `.tmp/`.
*/
const CONFIG_ROOT = ".tmp/type-fixtures";
const EXPECTATION = /^\/\/ expect: (pass|TS\d{4,5})$/u;
/** Helpers that fixtures import are not fixtures. */
const FIXTURE_FILE = /^invalid-[\w-]+\.tsx?$/u;
const CONCURRENCY = 4;
export type TypeFixtureExpectation = { kind: "pass" } | { kind: "fail"; code: string };
export interface TypeFixtureResult {
file: string;
expectation: TypeFixtureExpectation | undefined;
passed: boolean;
/** The diagnostic lines that met the expectation, or all output on failure. */
evidence: string[];
}
export function parseTypeFixtureExpectation(source: string): TypeFixtureExpectation | undefined {
const match = EXPECTATION.exec(source.split("\n", 1)[0]?.trimEnd() ?? "");
if (!match?.[1]) return undefined;
return match[1] === "pass" ? { kind: "pass" } : { kind: "fail", code: match[1] };
}
export async function listTypeFixtures(root: string): Promise<string[]> {
return (await readdir(path.join(root, TYPE_FIXTURE_ROOT)))
.filter((name) => FIXTURE_FILE.test(name))
.sort()
.map((name) => `${TYPE_FIXTURE_ROOT}/${name}`);
}
export function judgeTypeFixture(
expectation: TypeFixtureExpectation,
exitCode: number | null,
output: string,
): Pick<TypeFixtureResult, "passed" | "evidence"> {
const lines = output.split("\n").filter((line) => line.trim().length > 0);
if (expectation.kind === "pass") {
return { passed: exitCode === 0, evidence: lines };
}
const matching = lines.filter((line) => line.includes(`error ${expectation.code}:`));
return exitCode === 1 && matching.length > 0
? { passed: true, evidence: matching }
: { passed: false, evidence: [`tsc exit ${exitCode}`, ...lines] };
}
function runTsc(root: string, config: string): Promise<{ exitCode: number | null; output: string }> {
return new Promise((resolve, reject) => {
const child = spawn(path.join(root, "node_modules/.bin/tsc"), ["--project", config, "--pretty", "false"], {
cwd: root,
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString("utf8")));
child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString("utf8")));
child.on("error", reject);
child.on("close", (exitCode) => resolve({ exitCode, output }));
});
}
async function checkTypeFixture(root: string, file: string): Promise<TypeFixtureResult> {
const expectation = parseTypeFixtureExpectation(await readFile(path.join(root, file), "utf8"));
if (!expectation) {
return { file, expectation, passed: false, evidence: ["missing `// expect:` first line"] };
}
const config = path.join(CONFIG_ROOT, `tsconfig.${path.basename(file).replace(/\.tsx?$/u, "")}.json`);
const fromConfig = (target: string) => path.relative(path.dirname(config), target);
await writeFile(
path.join(root, config),
`${JSON.stringify({ extends: fromConfig(BASE_CONFIG), files: [fromConfig(file)] }, null, 2)}\n`,
);
const { exitCode, output } = await runTsc(root, config);
return { file, expectation, ...judgeTypeFixture(expectation, exitCode, output) };
}
export async function checkTypeFixtures(root: string): Promise<TypeFixtureResult[]> {
const fixtures = await listTypeFixtures(root);
await rm(path.join(root, CONFIG_ROOT), { recursive: true, force: true });
await mkdir(path.join(root, CONFIG_ROOT), { recursive: true });
const results: TypeFixtureResult[] = new Array(fixtures.length);
let next = 0;
await Promise.all(
Array.from({ length: Math.min(CONCURRENCY, fixtures.length) }, async () => {
while (next < fixtures.length) {
const index = next++;
results[index] = await checkTypeFixture(root, fixtures[index]!);
}
}),
);
return results;
}
function describeExpectation(expectation: TypeFixtureExpectation | undefined): string {
if (!expectation) return "no expectation";
return expectation.kind === "pass" ? "expect pass" : `expect ${expectation.code}`;
}
if (isEntryModule(import.meta)) {
const results = await checkTypeFixtures(process.cwd());
for (const result of results) {
process.stdout.write(
`${result.passed ? "PASS" : "FAIL"} ${result.file} (${describeExpectation(result.expectation)})\n`,
);
for (const line of result.evidence) process.stdout.write(` ${line}\n`);
}
const failed = results.filter(({ passed }) => !passed);
if (results.length === 0) {
process.stderr.write(`Type fixtures: FAIL (no fixtures under ${TYPE_FIXTURE_ROOT})\n`);
process.exitCode = 1;
} else if (failed.length > 0) {
process.stderr.write(`Type fixtures: FAIL (${failed.length} of ${results.length})\n`);
process.exitCode = 1;
} else {
process.stdout.write(`Type fixtures: PASS (${results.length} fixtures)\n`);
}
}