@tayomi/deterministic-gates 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,7 +10,8 @@ const LOCAL_GATES_FILE = ".gates.local.json";
10
10
  const DEFAULT_MAX_TIMEOUT_SECONDS = 45;
11
11
  // The times a turn sends the agent back: enough for a fix that breaks another gate, never a loop.
12
12
  const DEFAULT_MAX_SEND_BACKS = 5;
13
- const FIELDS = new Set(["name", "severity", "files", "run", "compare", "ignoreLines", "timeoutSeconds"]);
13
+ const FIELDS = new Set(["name", "severity", "files", "run", "compare", "ignoreLines", "timeoutSeconds", "watch"]);
14
+ const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed"]);
14
15
 
15
16
  /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
16
17
  export const FILES = "{files}";
@@ -24,6 +25,26 @@ export interface Gate {
24
25
  compare?: "turn-start";
25
26
  ignoreLines?: string;
26
27
  timeoutSeconds: number;
28
+ watch?: Watch;
29
+ }
30
+
31
+ /**
32
+ * A long-running command a gate keeps between turns, such as a test watch, with the patterns of its output that open
33
+ * a cycle, close one, and mark a failure. The gate's own run stays the one-shot command, for a check of the whole repo.
34
+ */
35
+ export interface Watch {
36
+ run: string[];
37
+ cycleStart: string;
38
+ cycleEnd: string;
39
+ /** Absent on a compared gate, which fails on the lines the last cycle added to the one the turn started on. */
40
+ failed?: string;
41
+ }
42
+
43
+ /** A gate that keeps a watch. */
44
+ export type WatchedGate = Gate & { watch: Watch };
45
+
46
+ export function keepsWatch(gate: Gate): gate is WatchedGate {
47
+ return gate.watch !== undefined;
27
48
  }
28
49
 
29
50
  type Entry = Record<string, unknown> & { name: string };
@@ -113,8 +134,27 @@ function isPattern(value: unknown): value is string {
113
134
  }
114
135
  }
115
136
 
137
+ function toWatch(watch: unknown, compared: boolean): Watch {
138
+ if (!isRecord(watch)) return refuse("watch holds run, cycleStart, cycleEnd and failed");
139
+ const unknown = Object.keys(watch).find((key) => !WATCH_FIELDS.has(key));
140
+ if (unknown !== undefined) refuse(`unknown field watch.${unknown}`);
141
+ const { run, cycleStart, cycleEnd, failed } = watch;
142
+ if (!isStringArray(run) || !run.length) refuse("watch.run is a non-empty list of strings");
143
+ if (run.some((argument) => argument.includes(FILES) || argument.includes(TURN)))
144
+ refuse(`a watch outlives the turn: its run takes neither ${FILES} nor ${TURN}`);
145
+ const pattern = (field: string, value: unknown): string =>
146
+ isPattern(value) ? value : refuse(`watch.${field} is a regular expression on a line of its output`);
147
+ if (compared && failed !== undefined) refuse("a compared watch fails on the lines its cycle added: no watch.failed");
148
+ return {
149
+ run,
150
+ cycleStart: pattern("cycleStart", cycleStart),
151
+ cycleEnd: pattern("cycleEnd", cycleEnd),
152
+ ...(compared ? {} : { failed: pattern("failed", failed) }),
153
+ };
154
+ }
155
+
116
156
  function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
117
- const { name, severity, files, run, compare, ignoreLines, timeoutSeconds = maxTimeoutSeconds } = entry;
157
+ const { name, severity, files, run, compare, ignoreLines, watch, timeoutSeconds = maxTimeoutSeconds } = entry;
118
158
  const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
119
159
  if (unknown !== undefined) refuse(`unknown field ${unknown}`);
120
160
  if (!/^[a-z][a-z0-9-]*$/.test(name)) refuse("a name is lowercase words joined by hyphens");
@@ -136,6 +176,7 @@ function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
136
176
  timeoutSeconds: Math.min(timeoutSeconds, maxTimeoutSeconds),
137
177
  ...(compare === undefined ? {} : { compare }),
138
178
  ...(ignoreLines === undefined ? {} : { ignoreLines }),
179
+ ...(watch === undefined ? {} : { watch: toWatch(watch, compare !== undefined) }),
139
180
  };
140
181
  }
141
182
 
package/src/core/run.ts CHANGED
@@ -21,6 +21,8 @@ export function failed(outcome: Outcome): boolean {
21
21
  }
22
22
 
23
23
  const ENGINE = resolve(import.meta.dirname, "..", "..");
24
+ /** What a tool runs with: no colour, which some tools print anyway. */
25
+ export const TOOL_ENV = { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" };
24
26
  const MAX_OUTPUT_MB = 16;
25
27
  const ENGINE_PREFIX = "{engine}/";
26
28
 
@@ -97,20 +99,24 @@ function executable(file: string): boolean {
97
99
  });
98
100
  }
99
101
 
100
- /**
101
- * Why the program of a gate cannot run on this machine, or nothing when it can: looked up as the gate would start it,
102
- * without starting it. A command the engine cannot resolve is left to the run, which reports it.
103
- */
104
- export function missingTool(root: string, gate: Gate): string | undefined {
102
+ function missingProgram(root: string, name: string): string | undefined {
105
103
  let command: Command;
106
104
  try {
107
- command = commandOf(root, gate.run[0] ?? "");
105
+ command = commandOf(root, name);
108
106
  } catch {
109
107
  return undefined;
110
108
  }
111
109
  return command.missing && !executable(command.file) ? command.missing : undefined;
112
110
  }
113
111
 
112
+ /**
113
+ * Why the program of a gate, or of its watch, cannot run on this machine, or nothing when they can: looked up as the
114
+ * gate would start it, without starting it. A command the engine cannot resolve is left to the run, which reports it.
115
+ */
116
+ export function missingTool(root: string, gate: Gate): string | undefined {
117
+ return missingProgram(root, gate.run[0] ?? "") ?? (gate.watch && missingProgram(root, gate.watch.run[0] ?? ""));
118
+ }
119
+
114
120
  export function argumentsOf(gate: Gate, files: string[], turn: string): string[] {
115
121
  return gate.run.slice(1).flatMap((argument) => (argument === FILES ? files : [argument.replaceAll(TURN, turn)]));
116
122
  }
@@ -159,7 +165,7 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
159
165
  cwd: root,
160
166
  timeout: gate.timeoutSeconds * 1000,
161
167
  maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
162
- env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" },
168
+ env: TOOL_ENV,
163
169
  },
164
170
  (error, stdout, stderr) => {
165
171
  resolve({
@@ -185,12 +191,16 @@ function outputOf(
185
191
  if (error?.killed === true)
186
192
  return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
187
193
  if (error?.code === "ENOENT") return command.missing;
188
- // Some tools colour despite NO_COLOR, and absolute paths only cost the agent tokens.
189
- const said = stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
194
+ const said = cleaned(root, printed);
190
195
  if (said || !error) return said;
191
196
  return `exit code ${String(error.code)}, no output`;
192
197
  }
193
198
 
199
+ /** What a tool printed, for the agent: some tools colour despite NO_COLOR, and absolute paths only cost it tokens. */
200
+ export function cleaned(root: string, printed: string): string {
201
+ return stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
202
+ }
203
+
194
204
  /** Runs a compared gate on the whole project, as the turn starts. */
195
205
  export function wholeProject(root: string, gate: Gate): Promise<{ ok: boolean; output: string }> {
196
206
  return execute(root, gate, gate.run.slice(1));
@@ -211,7 +221,15 @@ export async function check(
211
221
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
212
222
  if (timedOut) return { ...ran, ok, output, timedOut };
213
223
  if (!isCompared(gate) || !ok) return { ...ran, ok, output };
214
- if (baseline === undefined) return { ...ran, ok: true, output: "" };
224
+ return { ...ran, ...addedLines(gate, output, baseline) };
225
+ }
226
+
227
+ /**
228
+ * Judges the output of a compared gate that ran clean: it fails on the lines the turn added to the report of the turn
229
+ * start. Without that report, nothing counts but the exit code.
230
+ */
231
+ export function addedLines(gate: Gate, output: string, baseline: string | undefined): { ok: boolean; output: string } {
232
+ if (baseline === undefined) return { ok: true, output: "" };
215
233
  const added = newLines(baseline, output, gate.ignoreLines);
216
- return { ...ran, ok: added.length === 0, output: added.join("\n") };
234
+ return { ok: added.length === 0, output: added.join("\n") };
217
235
  }
@@ -0,0 +1,310 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import {
4
+ closeSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ openSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ rmSync,
11
+ statSync,
12
+ writeFileSync,
13
+ } from "node:fs";
14
+ import { tmpdir } from "node:os";
15
+ import { dirname, join } from "node:path";
16
+ import { createInterface } from "node:readline";
17
+ import { setTimeout as sleep } from "node:timers/promises";
18
+ import { type Gate, isCompared, type Watch, type WatchedGate } from "./config.ts";
19
+ import { addedLines, cleaned, commandOf, type Outcome, TOOL_ENV } from "./run.ts";
20
+
21
+ // Once a cycle closes, the lines a watch prints after it, such as the errors of a failed build, come within this long.
22
+ const QUIET_MS = 1000;
23
+ // A change no cycle started after in this long is one the watch does not look at, such as a spec its build leaves out:
24
+ // it cannot change the last cycle, which then judges the turn.
25
+ const UNSEEN_MS = 5000;
26
+ const POLL_MS = 100;
27
+ // What a watch that stopped leaves the agent: enough to see the error, not the whole history of the session.
28
+ const LAST_LINES = 20;
29
+ // A prompt waits this long at most for a compared watch to settle, under the 60 s its hook has.
30
+ const TURN_START_MS = 45_000;
31
+
32
+ const PREFIX = "gates-watch-";
33
+ // A start that holds its lock longer than this died on the way: the next hook takes the lock over.
34
+ const STALE_START_MS = 10_000;
35
+ // A watch stops by itself after this long without a prompt nor a stop on its repo, as for a session left open. The
36
+ // tests of the engine shorten it.
37
+ const IDLE_MS = 30 * 60 * 1000;
38
+
39
+ function idleMs(): number {
40
+ return Number(process.env.GATES_WATCH_IDLE_MS) || IDLE_MS;
41
+ }
42
+
43
+ /** Records a prompt or a stop on the repo of a watch, which keeps it from stopping for idleness. */
44
+ function touch(folder: string): void {
45
+ writeFileSync(join(folder, "activity"), "");
46
+ }
47
+
48
+ /** Records a stop on the repo of the watch of a gate, if it has one, whether the stop judges it or not. */
49
+ export function keepWatch(root: string, gate: Gate): void {
50
+ const folder = folderOf(root, gate);
51
+ if (existsSync(folder)) touch(folder);
52
+ }
53
+
54
+ /** Where a watch keeps its process, its output and the sessions that use it, outside the repo: one per repo and gate. */
55
+ function folderOf(root: string, gate: Gate): string {
56
+ const key = createHash("sha256").update(`${root}\0${gate.name}`).digest("hex").slice(0, 16);
57
+ return join(tmpdir(), `${PREFIX}${key}`);
58
+ }
59
+
60
+ // A file per session that uses the watch: two hooks at once each write their own, and neither loses the other's.
61
+ function sessionFile(folder: string, session: string): string {
62
+ return join(folder, "sessions", session.replace(/[^\w-]/g, ""));
63
+ }
64
+
65
+ function register(folder: string, session: string): void {
66
+ mkdirSync(join(folder, "sessions"), { recursive: true });
67
+ writeFileSync(sessionFile(folder, session), "");
68
+ }
69
+
70
+ /** Whether the watch runs, has stopped on its own, was stopped for idleness, or was never started. */
71
+ function stateOf(folder: string): "running" | "stopped" | "idle" | "absent" {
72
+ let pid: number;
73
+ try {
74
+ pid = Number(readFileSync(join(folder, "pid"), "utf8"));
75
+ } catch {
76
+ return "absent";
77
+ }
78
+ try {
79
+ if (!pid) return "stopped";
80
+ process.kill(pid, 0);
81
+ return "running";
82
+ } catch {
83
+ return existsSync(join(folder, "idle")) ? "idle" : "stopped";
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Starts the watch of a gate in the background, unless it already runs, and records that the session uses it: it
89
+ * outlives the hook that starts it, until no session uses it.
90
+ */
91
+ export function startWatch(session: string, root: string, gate: WatchedGate): void {
92
+ const folder = folderOf(root, gate);
93
+ mkdirSync(folder, { recursive: true });
94
+ touch(folder);
95
+ // The sessions of a watch that starts again still use it.
96
+ register(folder, session);
97
+ if (stateOf(folder) === "running") return;
98
+ // Two hooks at once, such as two sessions starting, start one watch: the other only registers its session.
99
+ const lock = join(folder, "starting");
100
+ if (Date.now() - changedAt(lock) >= STALE_START_MS) rmSync(lock, { force: true });
101
+ try {
102
+ closeSync(openSync(lock, "wx"));
103
+ } catch {
104
+ return;
105
+ }
106
+ try {
107
+ // Another hook may have started it between the look above and the lock.
108
+ if (stateOf(folder) !== "running") launch(folder, root, gate.watch);
109
+ } finally {
110
+ rmSync(lock, { force: true });
111
+ }
112
+ }
113
+
114
+ function launch(folder: string, root: string, watch: Watch): void {
115
+ rmSync(join(folder, "idle"), { force: true });
116
+ const [name = "", ...args] = watch.run;
117
+ const command = commandOf(root, name);
118
+ const supervisor = commandOf(root, "{engine}/src/core/watch.ts");
119
+ const watched = [
120
+ join(folder, "activity"),
121
+ String(idleMs()),
122
+ watch.cycleStart,
123
+ command.file,
124
+ ...command.args,
125
+ ...args,
126
+ ];
127
+ const log = openSync(join(folder, "output.log"), "w");
128
+ const child = spawn(supervisor.file, [...supervisor.args, ...watched], {
129
+ cwd: root,
130
+ detached: true,
131
+ stdio: ["ignore", log, log],
132
+ env: TOOL_ENV,
133
+ });
134
+ closeSync(log);
135
+ child.on("error", () => {});
136
+ child.unref();
137
+ writeFileSync(join(folder, "pid"), String(child.pid ?? ""));
138
+ }
139
+
140
+ /** The last cycle of a watch: its lines since it opened, and whether it is still open. */
141
+ function lastCycle(printed: string, watch: Watch): { open: boolean; lines: string[] } {
142
+ const lines = printed.split("\n");
143
+ if (lines.at(-1) === "") lines.pop();
144
+ const opens = new RegExp(watch.cycleStart);
145
+ const closes = new RegExp(watch.cycleEnd);
146
+ // The start of the watch opens the first cycle, and lines after the one that closes it still belong to it.
147
+ const cycle = lines.slice(lines.findLastIndex((line) => opens.test(line)) + 1);
148
+ return { open: !cycle.some((line) => closes.test(line)), lines: cycle };
149
+ }
150
+
151
+ function changedAt(path: string): number {
152
+ try {
153
+ return statSync(path).mtimeMs;
154
+ } catch {
155
+ return 0;
156
+ }
157
+ }
158
+
159
+ function readLog(log: string): string {
160
+ try {
161
+ return readFileSync(log, "utf8");
162
+ } catch {
163
+ return "";
164
+ }
165
+ }
166
+
167
+ /** Where a watch is once it has settled, with the lines of its last cycle, or once it can no longer settle. */
168
+ type Settled = { ms: number } & ({ cycle: string } | { stopped: string } | { timedOut: true });
169
+
170
+ /**
171
+ * Waits for the watch of a gate to settle: no cycle open, and for a quiet while neither new output nor a new change to
172
+ * one of the files. A watch no hook started, as when the hooks were installed mid-session, starts now, and so does one
173
+ * stopped for idleness, as during a turn longer than the idle delay: it is not to blame.
174
+ */
175
+ async function settle(
176
+ session: string,
177
+ root: string,
178
+ gate: WatchedGate,
179
+ files: string[],
180
+ limitMs: number,
181
+ ): Promise<Settled> {
182
+ const started = performance.now();
183
+ const folder = folderOf(root, gate);
184
+ const log = join(folder, "output.log");
185
+ if (["absent", "idle"].includes(stateOf(folder))) startWatch(session, root, gate);
186
+ touch(folder);
187
+ for (;;) {
188
+ // Read once the watch is known stopped, so its last lines are in.
189
+ const stopped = stateOf(folder) === "stopped";
190
+ const printed = readLog(log);
191
+ const ms = performance.now() - started;
192
+ if (stopped) {
193
+ const last = cleaned(
194
+ root,
195
+ printed
196
+ .split("\n")
197
+ .slice(-LAST_LINES - 1)
198
+ .join("\n"),
199
+ );
200
+ return {
201
+ ms,
202
+ stopped: last ? `The watch stopped. Its last lines:\n${last}` : "The watch stopped, with no output.",
203
+ };
204
+ }
205
+ // A cycle that started after the last change read it, however long the watch took to see it.
206
+ const changed = Math.max(0, ...files.map((file) => changedAt(join(root, file))));
207
+ const seen = changedAt(join(folder, "cycle")) >= changed || Date.now() - changed >= UNSEEN_MS;
208
+ const cycle = lastCycle(printed, gate.watch);
209
+ if (seen && !cycle.open && Date.now() - changedAt(log) >= QUIET_MS)
210
+ return { ms, cycle: cleaned(root, cycle.lines.join("\n")) };
211
+ if (ms >= limitMs) return { ms, timedOut: true };
212
+ await sleep(POLL_MS);
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Judges a turn on the last cycle of the watch of a gate, once the watch has settled with the files of the turn the
218
+ * gate looks at: on its failed lines, or for a compared gate, on the lines it added to the report of the turn start.
219
+ * Not settled in the time of the gate: out of time, neither green nor red. A watch that stopped fails, with the last
220
+ * lines it printed.
221
+ */
222
+ export async function judgeWatch(
223
+ session: string,
224
+ root: string,
225
+ gate: WatchedGate,
226
+ files: string[],
227
+ baseline: string | undefined,
228
+ ): Promise<Outcome> {
229
+ const settled = await settle(session, root, gate, files, gate.timeoutSeconds * 1000);
230
+ const { name } = gate;
231
+ const { ms } = settled;
232
+ if ("stopped" in settled) return { name, ok: false, ms, output: settled.stopped, report: undefined };
233
+ if ("timedOut" in settled) {
234
+ const output = `The watch did not settle within ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
235
+ return { name, ok: false, ms, output, report: undefined, timedOut: true };
236
+ }
237
+ const { cycle } = settled;
238
+ const fails = new RegExp(gate.watch.failed ?? "(?!)");
239
+ const judged = isCompared(gate)
240
+ ? addedLines(gate, cycle, baseline)
241
+ : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
242
+ return { name, ms, ...judged, report: judged.ok ? cycle : undefined };
243
+ }
244
+
245
+ /**
246
+ * The report a compared watch gives the turn start: its last cycle, once it settles in the time a prompt can wait.
247
+ * Nothing when it does not, and the turn then counts nothing as new.
248
+ */
249
+ export async function watchReport(session: string, root: string, gate: WatchedGate): Promise<string | undefined> {
250
+ const settled = await settle(session, root, gate, [], Math.min(gate.timeoutSeconds * 1000, TURN_START_MS));
251
+ return "cycle" in settled ? settled.cycle : undefined;
252
+ }
253
+
254
+ /** Stops each watch the session was the last to use, in any repo: the watch and every process it started. */
255
+ export function endSession(session: string): void {
256
+ for (const entry of readdirSync(tmpdir())) {
257
+ if (!entry.startsWith(PREFIX)) continue;
258
+ const folder = join(tmpdir(), entry);
259
+ const file = sessionFile(folder, session);
260
+ if (!existsSync(file)) continue;
261
+ rmSync(file, { force: true });
262
+ if (!readdirSync(join(folder, "sessions")).length) stop(folder);
263
+ }
264
+ }
265
+
266
+ function stop(folder: string): void {
267
+ if (stateOf(folder) !== "running") return;
268
+ try {
269
+ process.kill(-Number(readFileSync(join(folder, "pid"), "utf8")), "SIGTERM");
270
+ } catch {}
271
+ }
272
+
273
+ /**
274
+ * The supervisor of a watch, which this module runs as when the engine starts one: it runs the watch, its output
275
+ * going where its own goes, and stops it with every process it started once its repo has had no prompt nor stop for
276
+ * the idle delay. Started detached, it leads a process group of its own, so stopping the group stops the watch and
277
+ * the tools under it.
278
+ */
279
+ function supervise(activity: string, idle: number, cycleStart: string, file: string, args: string[]): void {
280
+ // The time the last cycle started, which the stop compares with the changes of the turn. The start opens the first.
281
+ const cycle = join(dirname(activity), "cycle");
282
+ const opens = new RegExp(cycleStart);
283
+ writeFileSync(cycle, "");
284
+ const watch = spawn(file, args, { stdio: ["ignore", "pipe", "pipe"] });
285
+ const forward = (line: string) => {
286
+ // Printed before the time is kept, so a stop that sees the time also finds the cycle in the output.
287
+ console.log(line);
288
+ if (opens.test(line)) writeFileSync(cycle, "");
289
+ };
290
+ createInterface({ input: watch.stdout }).on("line", forward);
291
+ createInterface({ input: watch.stderr }).on("line", forward);
292
+ watch.on("error", (error) => {
293
+ console.log(error.message);
294
+ process.exit(1);
295
+ });
296
+ watch.on("close", (code) => process.exit(code ?? 1));
297
+ setInterval(
298
+ () => {
299
+ if (Date.now() - changedAt(activity) < idle) return;
300
+ writeFileSync(join(dirname(activity), "idle"), "");
301
+ process.kill(-process.pid, "SIGTERM");
302
+ },
303
+ Math.min(idle / 4, 10_000),
304
+ );
305
+ }
306
+
307
+ if (import.meta.main) {
308
+ const [activity = "", idle = "", cycleStart = "", file = "", ...args] = process.argv.slice(2);
309
+ supervise(activity, Number(idle), cycleStart, file, args);
310
+ }
@@ -0,0 +1,50 @@
1
+ import { spawn } from "node:child_process";
2
+ import { extname, join } from "node:path";
3
+ import { createInterface } from "node:readline";
4
+ import { commandOf } from "../core/run.ts";
5
+ import { COUNTS, HEADER } from "./vitest-state-reporter.ts";
6
+
7
+ // The watch of an Angular project tested with Vitest: ng test in watch mode, with the reporter of the engine that
8
+ // prints the state of every spec at each run, and NG_TEST_LOG, which makes Angular say when a run ends. A change that
9
+ // leaves the build as it was reruns no spec, so no state prints: the last one is printed again, so that the cycle
10
+ // still tells which specs are red.
11
+
12
+ const NO_RERUN = /No test specifications to rerun/;
13
+
14
+ /**
15
+ * What to print for each line of the watch: the line, and before a run that reruns no spec, the last state of the
16
+ * specs, so that the cycle still tells which specs are red.
17
+ */
18
+ export function replaying(): (line: string) => string[] {
19
+ let state: string[] = [];
20
+ let reading: string[] | undefined;
21
+ return (line) => {
22
+ if (line === HEADER) reading = [];
23
+ reading?.push(line);
24
+ if (reading !== undefined && line.startsWith(COUNTS)) {
25
+ state = reading;
26
+ reading = undefined;
27
+ }
28
+ return NO_RERUN.test(line) ? [...state, line] : [line];
29
+ };
30
+ }
31
+
32
+ function main(root: string, args: string[]): void {
33
+ const ng = commandOf(root, "@angular/cli");
34
+ if (ng.missing) {
35
+ console.log(ng.missing);
36
+ process.exit(1);
37
+ }
38
+ const reporter = join(import.meta.dirname, `vitest-state-reporter${extname(import.meta.filename)}`);
39
+ const watch = spawn(ng.file, [...ng.args, "test", "--watch", `--reporters=${reporter}`, ...args], {
40
+ env: { ...process.env, NG_TEST_LOG: "1" },
41
+ stdio: ["ignore", "pipe", "pipe"],
42
+ });
43
+ const replay = replaying();
44
+ const forward = (line: string) => console.log(replay(line).join("\n"));
45
+ createInterface({ input: watch.stdout }).on("line", forward);
46
+ createInterface({ input: watch.stderr }).on("line", forward);
47
+ watch.on("exit", (code) => process.exit(code ?? 1));
48
+ }
49
+
50
+ if (import.meta.main) main(process.cwd(), process.argv.slice(2));
@@ -0,0 +1,70 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createInterface } from "node:readline";
3
+ import { commandOf } from "../core/run.ts";
4
+
5
+ // tsc, with the options it is given, such as strict ones a project turned off, printing its errors so that a gate can
6
+ // compare them with the ones of the turn start: one line per error, with its file and none of its line and column, so
7
+ // an error a change moves down is not new, and a count after an error its file already has, so one more of it is.
8
+ // With --watch, tsc keeps watching, and each compilation prints between a line that starts it and one that ends it.
9
+
10
+ const STARTS = /Starting (compilation in watch mode|incremental compilation)/;
11
+ const ENDS = /Found \d+ errors?\. Watching for file changes/;
12
+ const POSITION = /^(.+)\(\d+,\d+\): (error TS\d+: .*)$/;
13
+
14
+ /** The errors tsc printed, each on one line, as the gate compares them. */
15
+ export function typeErrors(printed: string[]): string[] {
16
+ const errors: string[] = [];
17
+ for (const line of printed) {
18
+ if (!line.trim()) continue;
19
+ // The lines under an error explain it.
20
+ if (/^\s/.test(line) && errors.length) errors.push(`${errors.pop()} ${line.trim()}`);
21
+ else errors.push(line.replace(POSITION, "$1: $2"));
22
+ }
23
+ const seen = new Map<string, number>();
24
+ return errors.map((error) => {
25
+ const count = (seen.get(error) ?? 0) + 1;
26
+ seen.set(error, count);
27
+ return count === 1 ? error : `${error} (${count})`;
28
+ });
29
+ }
30
+
31
+ /** What to print for each line of tsc in watch mode: nothing until a compilation ends, then its errors. */
32
+ export function watching(): (line: string) => string[] {
33
+ let compiled: string[] = [];
34
+ return (line) => {
35
+ if (STARTS.test(line)) {
36
+ compiled = [];
37
+ return ["Type check started"];
38
+ }
39
+ if (ENDS.test(line)) return [...typeErrors(compiled), "Type check done"];
40
+ compiled.push(line);
41
+ return [];
42
+ };
43
+ }
44
+
45
+ function main(root: string, args: string[]): void {
46
+ const tsc = commandOf(root, "typescript");
47
+ if (tsc.missing) {
48
+ console.log(tsc.missing);
49
+ process.exit(1);
50
+ }
51
+ const watch = args.includes("--watch");
52
+ const options = ["--noEmit", "--pretty", "false", ...(watch ? ["--preserveWatchOutput"] : []), ...args];
53
+ const child = spawn(tsc.file, [...tsc.args, ...options], { stdio: ["ignore", "pipe", "inherit"] });
54
+ const printed: string[] = [];
55
+ const print = watching();
56
+ createInterface({ input: child.stdout }).on("line", (line) => {
57
+ if (watch) for (const shown of print(line)) console.log(shown);
58
+ else printed.push(line);
59
+ });
60
+ child.on("close", (code) => {
61
+ // 1 and 2 are tsc saying it found errors: the gate counts them, so only a tsc that broke fails.
62
+ if (watch || code === null || code > 2) {
63
+ console.log(printed.join("\n"));
64
+ process.exit(code ?? 1);
65
+ }
66
+ console.log(typeErrors(printed).join("\n"));
67
+ });
68
+ }
69
+
70
+ if (import.meta.main) main(process.cwd(), process.argv.slice(2));
@@ -0,0 +1,48 @@
1
+ import { relative } from "node:path";
2
+
3
+ // A Vitest reporter for a watch: at the end of each run, the state of every spec Vitest has run so far, not only the
4
+ // ones it reran. A rerun of one spec then never hides another that is still red: the last run alone tells the state.
5
+ // It prints a header line, one FAIL line per failed test with its error under it, then the counts.
6
+
7
+ interface TestError {
8
+ message?: string;
9
+ }
10
+
11
+ interface TestCase {
12
+ fullName: string;
13
+ result(): { state: string; errors?: readonly TestError[] };
14
+ }
15
+
16
+ interface TestModule {
17
+ moduleId: string;
18
+ errors(): readonly TestError[];
19
+ children: { allTests(): Iterable<TestCase> };
20
+ }
21
+
22
+ /** The header of the state, which the watch helper of the engine looks for. */
23
+ export const HEADER = "Spec states:";
24
+ export const COUNTS = "Specs:";
25
+
26
+ function indented(error: TestError): string[] {
27
+ return (error.message ?? "").split("\n").map((line) => ` ${line}`);
28
+ }
29
+
30
+ function failuresOf(module: TestModule): string[] {
31
+ const spec = relative(process.cwd(), module.moduleId);
32
+ const lines = module.errors().flatMap((error) => [`FAIL ${spec}`, ...indented(error)]);
33
+ for (const test of module.children.allTests()) {
34
+ const { state, errors = [] } = test.result();
35
+ if (state === "failed") lines.push(`FAIL ${spec} > ${test.fullName}`, ...errors.flatMap(indented));
36
+ }
37
+ return lines;
38
+ }
39
+
40
+ export default class StateReporter {
41
+ private readonly failures = new Map<string, string[]>();
42
+
43
+ onTestRunEnd(modules: readonly TestModule[]): void {
44
+ for (const module of modules) this.failures.set(module.moduleId, failuresOf(module));
45
+ const red = [...this.failures.values()].filter((lines) => lines.length);
46
+ console.log([HEADER, ...red.flat(), `${COUNTS} ${red.length} red of ${this.failures.size}`].join("\n"));
47
+ }
48
+ }