Files
clean-architecture-frontend…/scripts/check-typecheck-inputs.ts
DongHyeonka 12c079841e fix(typecheck): tsc 호출의 프로젝트를 인자로 읽고 못 읽으면 실패로 둔다
R8이 `tsc --project X`·`-p X`만 읽어 옵션이 낀 꼴과 build 꼴은 빈
tsconfig여도 통과한다. 낱말로만 나누면 옆 호출의 `-p`를 빌리고, 토큰화
함수가 따옴표 정보를 버려 따옴표 속 괄호·`#`에서 호출이 끊긴다.

읽기와 요구를 나눈다. 옛 정규식이 읽던 것은 계속 읽고, 실행되는
호출마다 자기 프로젝트를 요구한다. 못 읽으면 실패로 두고, 인자에
`$@`·`$*`가 있어도 못 읽은 것으로 본다. 따옴표·escape 속 글자는
토큰화 전에 붙들어 둔다. script 이름은 관리자 바로 뒤, 경로 값은 출력
경로 옵션과 `-b` 목록에서만 실행으로 보지 않는다. 새 셸 파서는
중복이라 버리고 있는 함수를 export한다. `$`가 든 인자를 모두 막는
안은 `--outDir "$OUT"`을 잘못 막아 버린다.

위험·한계: 목록 밖 명령 인자의 낱말 tsc는 실패한다. `$ARGS`의 -p,
script에 `$@`나 다른 이름으로 넘긴 -p, `echo tsc | sh`, `$(echo tsc)`,
리다이렉션 뒤의 -p, `sh -c tsc x`, `-b` 목록의 빈 낱말, `cd` 뒤 루트와
이름이 같은 tsconfig, 이름이 다른 binary는 못 잡는다.

검증(노트북, 트리 ea65ba08): 이 시험 파일을 main b0939586의 검사기로
돌리면 96개 중 63개가 실패하고, 고친 뒤 96개가 통과한다. 확인 리뷰
뒤 더한 조건을 하나씩 바꾼 변이 14개가 모두 실패한다.

Refs: REV-FE-0005
2026-11-23 03:53:33 +09:00

238 lines
11 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import path from "node:path";
import { isEntryModule } from "./lib/entry-module.ts";
import { tokenizeShellSegments } from "./lib/package-script-graph.ts";
/**
* 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), and a tsc call
* whose tsconfig cannot be read from the script fails.
*
* A project is read wherever it follows a word like `tsc`, run or not. It is
* demanded only of a word that runs tsc: a script name straight after the
* package manager or its `run`, the path of an output option or of a build
* list, and the words of `echo` or `rm` do not. A package whose projects are
* only printed checks no types. A call found that way fails when its own words hide
* the project: an unclosed quote, a joined line, `$` in a project, an `@`
* file, `$@` or `$*`. The shell is not run, so these are not seen: options in
* another variable or behind a redirection, options handed to a script by
* `$@` or under another name, words after `sh -c <command>`, an empty word of
* a build list, the directory after `cd`, a tsc that the words of `echo` hand
* to the shell, and another name of the binary.
*/
type Scripts = Readonly<Record<string, string>>;
type TscCall = Readonly<{ runs: boolean; args: string[] }>;
/** A project straight after `tsc`, up to a quote or an operator. Also read in a comment. */
const TSC_PROJECT = /\btsc\s+(?:--project|-p)\s+((?:[^\s"'`\\;&|()<>]|\\\w)+)(?![^\s"'`;&|()<>])/gu;
/** A word whose arguments are read: `tsc`, a path to it, `vue-tsc`, `check:tsc`. */
const TSC_WORD = /(?:^|\W)tsc(?:\.js)?$/u;
/** Of those, `<name>:tsc` names a script. */
const SCRIPT_NAME = /:tsc$/u;
const TSC_MENTION = /\btsc\b/u;
/** Straight before a script name. Behind any other word, `pnpm <binary> run -- tsc` included, tsc runs. */
const SCRIPT_POSITION = /(?:^| )(?:(?:pnpm|npm|yarn) (?:run|run-script)|pnpm|yarn)$/u;
/** The value of these is a path, so a path that ends in `tsc` there is no call. */
const PATH_OPTION = /^--?(?:outdir|rootdir|rootdirs|declarationdir|outfile|tsbuildinfofile|typeroots)$/iu;
/** These only print or touch files. The list stays short: any other command fails closed. */
const DOES_NOT_RUN_WORDS = new Set(["cd", "cp", "echo", "mkdir", "mv", "printf", "rimraf", "rm", "touch"]);
const SUBSTITUTION = /\$\(|`/u;
/** A token holds one of these only if it was quoted, so it can be a whole command. */
const QUOTED = /[\s;&|'"]/u;
/** The tokenizer leaves a subshell, a substitution and a redirection inside the token. */
const COMMAND_BREAK = /^\d*[<>]|[()`<>]/u;
const COMMAND_END = /[)`]$/u;
/** A word with one of these can hold a command of its own. */
const NESTED = /[\s;&|'"()<>`]/u;
/** Quoted or escaped, these are held as characters of the private use area until the words are cut. */
const HELD = "()<>`#";
const HELD_FROM = 0xe000;
const HELD_CHARACTER = /[-]/gu;
/** In build mode these take the next word (`tsc --build --help`, and WATCH OPTIONS of `tsc --all`). */
const BUILD_VALUE_OPTION =
/^--?(?:builders|checkers|locale|pprofdir|generatecpuprofile|generatetrace|watchinterval|watchfile|watchdirectory|fallbackpolling|excludedirectories|excludefiles)$/iu;
const BUILD = /^--?(?:b|build)$/iu;
const OPTION = /^--?([a-z]+)(?:=(.*))?$/iu;
/** `$@` and `$*` hand a call whole arguments, a project among them, that the script does not hold. */
const HANDED_ARGUMENTS = /\$\{?[@*]/u;
/**
* The tokenizer drops quotes, so a quoted bracket would end a command, and it starts a comment at
* any `#`, the shell only at the start of a word. A bracket is inside a word here: reading a
* comment fails closed.
*/
function holdLiterals(script: string): string {
let held = "";
let quote = "";
let escaped = false;
let comment = false;
let wordStart = true;
for (const character of script) {
const literal = escaped || quote !== "";
const at = HELD.indexOf(character);
const hold = !comment && at >= 0 && (literal || (character === "#" && !wordStart));
held += hold ? String.fromCharCode(HELD_FROM + at) : character;
if (comment) comment = character !== "\n" && character !== "\r";
else if (escaped) escaped = false;
else if (character === "\\" && quote !== "'") escaped = true;
else if (quote) quote = character === quote ? "" : quote;
else if (character === "'" || character === '"') quote = character;
else comment = character === "#" && wordStart;
wordStart = !literal && /[\s;&|]/u.test(character);
}
return held;
}
function releaseLiterals(word: string): string {
return word.replace(HELD_CHARACTER, (character) => HELD[character.charCodeAt(0) - HELD_FROM]!);
}
function commandsOfSegment(tokens: readonly string[]): string[][] {
const commands: string[][] = [[]];
for (const token of tokens) {
const [first, ...rest] = QUOTED.test(token) ? [token] : token.split(COMMAND_BREAK);
if (first) commands.at(-1)!.push(first);
for (const word of rest) commands.push(word ? [word] : []);
if (COMMAND_END.test(token)) commands.push([]);
}
return commands;
}
/** yarn runs a binary when no script has the name, so the name must be a script of this package. */
function namesScript(before: readonly string[], word: string, scripts: Scripts): boolean {
if (SCRIPT_NAME.test(word)) return true;
const words = before.filter((previous) => !previous.startsWith("-"));
return Object.hasOwn(scripts, word) && SCRIPT_POSITION.test(words.join(" "));
}
/** Each call owns the words up to the next call or quoted command. */
function tscCalls(script: string, scripts: Scripts): TscCall[] {
// The tokenizer does not join a line that ends in a backslash.
const shell = script.includes("\\\n")
? null
: tokenizeShellSegments(holdLiterals(script));
if (!shell) return TSC_MENTION.test(script) ? [{ runs: true, args: [] }] : [];
const commands = shell.segments.flatMap(({ tokens }) => commandsOfSegment(tokens));
return commands.map((held) => held.map(releaseLiterals)).flatMap((words) => {
const calls: TscCall[] = [];
let call: TscCall | undefined;
// A quote inside a substitution splits its words, so with one all of them count as run.
const runs = !DOES_NOT_RUN_WORDS.has(words[0] ?? "") || words.some((word) => SUBSTITUTION.test(word));
for (const [index, word] of words.entries()) {
// `--outDir .cache/tsc` and `-b lib packages/tsc`: such a path is an argument of the running call.
const ownPath =
call?.runs &&
word.includes("/") &&
!SUBSTITUTION.test(word) &&
(PATH_OPTION.test(call.args.at(-1) ?? "") || BUILD.test(call.args[0] ?? ""));
const inner = !ownPath && NESTED.test(word) ? tscCalls(word, scripts) : [];
if (inner.length > 0) {
calls.push(...inner.map((found) => ({ ...found, runs: runs && found.runs })));
call = undefined;
} else if (!ownPath && TSC_WORD.test(word)) {
call = { runs: runs && !namesScript(words.slice(0, index), word, scripts), args: [] };
calls.push(call);
} else {
call?.args.push(word);
}
}
return calls;
});
}
/**
* The value of each `-p` or `--project`, and in build mode each word that is
* neither an option nor its value. An empty string is a project left out.
*/
function projectsOfCall(words: readonly string[]): string[] {
const projects: string[] = [];
let build = false;
for (const [index, word] of words.entries()) {
const [, name, value] = OPTION.exec(word) ?? [];
const option = name?.toLowerCase();
if (option === "p" || option === "project") {
const project = value ?? words[index + 1] ?? "";
projects.push(project.startsWith("-") ? "" : project);
} else if (option === "b" || option === "build") {
build = true;
if (value) projects.push(value);
} else if (build && !word.startsWith("-") && word !== "true" && word !== "false") {
if (!BUILD_VALUE_OPTION.test(words[index - 1] ?? "")) projects.push(word);
}
}
return projects;
}
function readScript(script: string, scripts: Scripts): { projects: string[]; unread: boolean; checks: boolean } {
const calls = tscCalls(script, scripts).map(({ runs, args }) => ({
runs,
named: projectsOfCall(args),
responseFile: args.some((word) => word.startsWith("@")),
handed: runs && args.some((word) => HANDED_ARGUMENTS.test(word)),
}));
const written = [...script.matchAll(TSC_PROJECT)].map((match) => match[1]!);
// `written` is only read. It is no project of a call that names none.
const named = [...written, ...calls.flatMap((call) => call.named)];
const projects = named.filter((project) => project !== "" && !project.includes("$"));
const unread =
projects.length < named.length ||
calls.some((call) => call.responseFile || call.handed || (call.runs && call.named.length === 0));
// A project only printed, `echo tsc -b x.json`, is read but checks no types.
const checks = written.length > 0 || calls.some((call) => call.runs && call.named.length > 0);
return { projects, unread, checks };
}
export function typecheckProjects(scripts: Scripts): string[] {
const projects = Object.values(scripts).flatMap((script) => readScript(script, scripts).projects);
return [...new Set(projects)].sort();
}
function scriptsWithUnreadProject(scripts: Scripts): string[] {
return Object.entries(scripts)
.filter(([, script]) => readScript(script, scripts).unread)
.map(([name]) => name);
}
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 (isEntryModule(import.meta)) {
const scripts = (JSON.parse(readFileSync("package.json", "utf8")) as { scripts: Record<string, string> }).scripts;
const projects = typecheckProjects(scripts);
const failures: string[] = [];
const unread = scriptsWithUnreadProject(scripts);
if (unread.length > 0) failures.push(`cannot read the project of tsc in: ${unread.join(", ")}`);
else if (!Object.values(scripts).some((script) => readScript(script, scripts).checks))
failures.push("no package script runs tsc --project");
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;
// A failed listing prints its error to stdout, where it would count as a file.
if (result.status !== 0) failures.push(`cannot list input files: ${project} (${result.stdout.split("\n", 1)[0]})`);
return { project, listed: result.status === 0, files: ownInputFiles(result.stdout).length };
});
const empty = counts.filter(({ listed, files }) => listed && files === 0);
if (empty.length > 0) failures.push(`no input files: ${empty.map(({ project }) => project).join(", ")}`);
if (failures.length > 0) {
process.stderr.write(`Typecheck inputs: FAIL (${failures.join("; ")})\n`);
process.exitCode = 1;
} else {
process.stdout.write(
`Typecheck inputs: PASS (${counts.map(({ project, files }) => `${project} ${files}`).join(", ")})\n`,
);
}
}