refactor(typecheck): 음성 타입 fixture 23개를 실행기 하나로 돈다

음성 타입 fixture마다 옵션이 같은 tsconfig 하나, package script 하나,
게이트 명령 하나가 있었다(23벌). 옵션은 모두 같고 파일 하나만 달라서
fixture를 더할 때마다 세 곳을 같이 고쳤다. `tsconfig.recipes.json`도
`tsconfig.test.json`과 lib가 같고 types만 하나 적었다.
`tsconfig.web-worker.json`은 `files: []`로 0파일을 검사하고 통과했다
(2026-09-25 리뷰가 기록, FE-GATE-003이 통과로 보였다).

고른 방법(design-docs repo-structure/04-frontend-layout.md 5.3절 (가),
소유자 승인 2026-11-07):
- fixture 첫 줄에 기대(`// expect: TS2322`, `// expect: pass`)를 쓰고
  `scripts/check-type-fixtures.ts`가 fixture마다 `.tmp/type-fixtures/`에
  한 파일 tsconfig를 써서 tsc를 돈다. 판정은 run-ci-gate.ts가 명령마다
  하던 것과 같다(exit 1과 `error TS<code>:`). 결과를 fixture별로 출력한다.
  기대 줄이 없는 fixture와 fixture 0개는 실패한다.
- recipes는 `tsconfig.test.json` include로 옮긴다.
- web-worker tsconfig와 script는 지운다(결정 D4). Worker를 들일 때 더하는
  단계는 매뉴얼 03에 쓴다(뒤 커밋).
- `scripts/check-typecheck-inputs.ts`를 `check:types` 끝에 둔다. package
  script가 tsc에 넘기는 tsconfig마다 이 repo 파일이 1개 이상인지 본다.
  `files: []` tsconfig가 통과로 보이던 구멍을 막는다(R8).

버린 것: TypeScript API로 한 프로세스에서 돌리는 방법. 이 repo의
TypeScript 7.0(네이티브판)은 JS API를 싣지 않는다. 위반마다
`@ts-expect-error`를 쓰는 방법(5.3절 (나))은 오류 코드 고정을 잃는다.

위험: recipe가 이제 `vite/client` 타입이 있는 프로그램에서 검사된다.
recipe가 `import.meta.env`를 쓰면 전에는 실패했고 이제는 통과한다
(복사한 제품도 Vite라 가치가 작다, 설계 5.1절). CI 계약 기준선을 다시
받았다(명령 99 → 76).

검증(desktop): `check:types:fixtures` 23개 PASS, 각 fixture의 기대 코드가
출력에 그대로 나온다. `TelemetryPort.emit` 인자를 `string`으로 넓히는
변이(2026-09-25 리뷰 07-05)에서 `invalid-diagnostics-port.ts`가 TS2578로
FAIL, 실행기 rc=1. 되돌린 뒤 작업 트리 0줄. `check:types` rc=0
(Typecheck inputs: app 379, node 312, service-worker 22, test 915).

Refs: design-docs repo-structure/04-frontend-layout.md 5.3·9.2·9.3절, README.md 3.4절 D4
This commit is contained in:
2026-11-08 17:40:12 +09:00
parent ad3a071f61
commit bf485f449a
69 changed files with 316 additions and 460 deletions
-62
View File
@@ -1,62 +0,0 @@
import { spawnSync } from "node:child_process";
import { readdir } from "node:fs/promises";
import { extname, resolve } from "node:path";
const recipeRoot = resolve("recipes");
const pnpmCli = requireEnvironment("npm_execpath");
if (!(await containsTypeScriptSource(recipeRoot))) {
process.stdout.write(
"Optional recipe typecheck: SKIP (no recipe TypeScript sources installed)\n",
);
} else {
const result = spawnSync(
process.execPath,
[pnpmCli, "exec", "tsc", "--project", "tsconfig.recipes.json"],
{ stdio: "inherit" },
);
if (result.error) {
throw result.error;
}
process.exitCode = result.status ?? 1;
}
function requireEnvironment(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`${name} is required to typecheck optional recipes`);
}
return value;
}
async function containsTypeScriptSource(directory: string): Promise<boolean> {
let entries;
try {
entries = await readdir(directory, { withFileTypes: true });
} catch (error) {
if (hasErrorCode(error, "ENOENT")) {
return false;
}
throw error;
}
for (const entry of entries) {
const target = resolve(directory, entry.name);
if (entry.isDirectory() && (await containsTypeScriptSource(target))) {
return true;
}
if (entry.isFile() && [".ts", ".tsx", ".mts", ".cts"].includes(extname(entry.name))) {
return true;
}
}
return false;
}
function hasErrorCode(error: unknown, code: string): boolean {
return (
typeof error === "object" &&
error !== null &&
"code" in error &&
error.code === code
);
}
+141
View File
@@ -0,0 +1,141 @@
import { spawn } from "node:child_process";
import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
/**
* 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 (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
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`);
}
}
+55
View File
@@ -0,0 +1,55 @@
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
/**
* R8 of docs/manual/03-outside-feature-folder.md: a check with nothing to
* check fails. tsc passes a tsconfig whose `files` is empty when it extends
* another one, so `check:types:web-worker` compiled zero files and passed
* FE-GATE-003 from 2026-09-25 until it was deleted on 2026-11-08. Every
* tsconfig a package script hands to tsc must list at least one file of this
* repository (lib and node_modules declarations do not count).
*/
const TSC_PROJECT = /\btsc\s+(?:--project|-p)\s+(\S+)/gu;
export function typecheckProjects(scripts: Readonly<Record<string, string>>): string[] {
const projects = new Set<string>();
for (const command of Object.values(scripts)) {
for (const match of command.matchAll(TSC_PROJECT)) projects.add(match[1]!);
}
return [...projects].sort();
}
export function ownInputFiles(listed: string): string[] {
return listed
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0 && !line.split(path.sep).includes("node_modules"));
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const scripts = (JSON.parse(readFileSync("package.json", "utf8")) as { scripts: Record<string, string> }).scripts;
const projects = typecheckProjects(scripts);
const counts = projects.map((project) => {
const result = spawnSync(path.resolve("node_modules/.bin/tsc"), ["--project", project, "--listFilesOnly"], {
encoding: "utf8",
});
if (result.error) throw result.error;
return { project, files: ownInputFiles(result.stdout).length };
});
const empty = counts.filter(({ files }) => files === 0);
if (projects.length === 0 || empty.length > 0) {
process.stderr.write(
projects.length === 0
? "Typecheck inputs: FAIL (no package script runs tsc --project)\n"
: `Typecheck inputs: FAIL (no input files: ${empty.map(({ project }) => project).join(", ")})\n`,
);
process.exitCode = 1;
} else {
process.stdout.write(
`Typecheck inputs: PASS (${counts.map(({ project, files }) => `${project} ${files}`).join(", ")})\n`,
);
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ export const REMOVAL_FIXTURE_COPY_TARGETS = Object.freeze([
"src", "tests", "recipes", "scripts", "schemas", "config", "public",
".gitea", ".storybook", "index.html", "package.json", "tsconfig.base.json",
"tsconfig.json", "tsconfig.app.json", "tsconfig.node.json", "tsconfig.test.json",
"tsconfig.recipes.json", "tsconfig.web-worker.json", "tsconfig.service-worker.json",
"tsconfig.service-worker.json",
"vite.service-worker.config.ts", "vite.config.ts", "vitest.config.ts",
"playwright.config.ts", "playwright.capabilities.config.ts", "playwright.dev.config.ts",
"playwright.storybook.config.ts", "playwright.visual.config.ts", "eslint.config.ts",
-1
View File
@@ -42,7 +42,6 @@ try {
});
const removedCiScripts = new Set([
"check:types:recipes",
"test:recipes",
"check:optional-recipes",
"check:optional-recipes:source",
+2 -1
View File
@@ -165,7 +165,8 @@ const DOCUMENT_INDEX = "docs/README.md";
const UNCHECKED_DOCUMENTS = new Set(["CHANGELOG.md"]);
const NOT_CREATED = new Set([
// Reserved by generic-worker-has-no-network-or-credentials. The generic CPU
// worker is NOT_SELECTED (tsconfig.web-worker.json).
// 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.