@tayomi/deterministic-gates 0.6.0 → 0.7.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.
@@ -1,22 +1,22 @@
1
1
  import { spawn } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, } from "node:fs";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync, } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
  import { createInterface } from "node:readline";
7
7
  import { setTimeout as sleep } from "node:timers/promises";
8
8
  import { isCompared } from "./config.js";
9
- import { addedLines, cleaned, commandOf, ENGINE_VERSION, TOOL_ENV } from "./run.js";
10
- // Once a cycle closes, the lines a watch prints after it, such as the errors of a failed build, come within this long.
11
- const QUIET_MS = 1000;
12
- // 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:
13
- // it cannot change the last cycle, which then judges the turn.
14
- const UNSEEN_MS = 5000;
9
+ import { addedLines, cleaned, commandOf, ENGINE_VERSION, toolEnv } from "./run.js";
10
+ import { listFiles } from "./snapshot.js";
11
+ // A watch that has not opened a cycle this long after the engine touched its sync file is touched again: it may look
12
+ // for changes only once its first cycle is over, as Angular and tsc do, and never see a touch made before. The wait
13
+ // changes no verdict, which only ever comes from a cycle the watch opened after a touch.
14
+ const RESYNC_MS = 1000;
15
15
  const POLL_MS = 100;
16
16
  // What a watch that stopped leaves the agent: enough to see the error, not the whole history of the session.
17
17
  const LAST_LINES = 20;
18
- // A prompt waits this long at most for a compared watch to settle, under the 60 s its hook has.
19
- const TURN_START_MS = 45_000;
18
+ // A prompt waits this long at most for the reports of its compared gates, under the 60 s its hook has.
19
+ export const TURN_START_MS = 45_000;
20
20
  const PREFIX = "gates-watch-";
21
21
  // A start that holds its lock longer than this died on the way: the next hook takes the lock over.
22
22
  const STALE_START_MS = 10_000;
@@ -52,25 +52,49 @@ function register(folder, session) {
52
52
  mkdirSync(join(folder, "sessions"), { recursive: true });
53
53
  writeFileSync(sessionFile(folder, session), "");
54
54
  }
55
- /** Whether the watch runs, has stopped on its own, was stopped for idleness, or was never started. */
56
- function stateOf(folder) {
57
- let pid;
55
+ /** The process of the watch, as the engine recorded it when it started it, or nothing when it never did. */
56
+ function processOf(folder) {
58
57
  try {
59
- pid = Number(readFileSync(join(folder, "pid"), "utf8"));
58
+ return readFileSync(join(folder, "pid"), "utf8");
60
59
  }
61
60
  catch {
62
- return "absent";
61
+ return undefined;
63
62
  }
63
+ }
64
+ /** Whether the watch runs, has stopped on its own, was stopped by the engine, or was never started. */
65
+ function stateOf(folder) {
66
+ const recorded = processOf(folder);
67
+ if (recorded === undefined)
68
+ return "absent";
64
69
  try {
65
- if (!pid)
70
+ if (!Number(recorded))
66
71
  return "stopped";
67
- process.kill(pid, 0);
72
+ process.kill(Number(recorded), 0);
68
73
  return "running";
69
74
  }
70
75
  catch {
71
76
  return existsSync(join(folder, "idle")) ? "idle" : "stopped";
72
77
  }
73
78
  }
79
+ // Two hooks at once, such as two sessions starting, start one watch: only the one that holds the lock does.
80
+ function lockStart(folder) {
81
+ const lock = join(folder, "starting");
82
+ // Only a lock that is there and old is taken over: removing one on the word of a look that found none would remove
83
+ // the lock another hook has just taken, and both would start a watch.
84
+ const taken = changedAt(lock);
85
+ if (taken && Date.now() - taken >= STALE_START_MS)
86
+ rmSync(lock, { force: true });
87
+ try {
88
+ closeSync(openSync(lock, "wx"));
89
+ return true;
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
95
+ function unlockStart(folder) {
96
+ rmSync(join(folder, "starting"), { force: true });
97
+ }
74
98
  /**
75
99
  * Starts the watch of a gate in the background, unless it already runs, and records that the session uses it: it
76
100
  * outlives the hook that starts it, until no session uses it.
@@ -81,62 +105,84 @@ export function startWatch(session, root, gate) {
81
105
  touch(folder);
82
106
  // The sessions of a watch that starts again still use it.
83
107
  register(folder, session);
84
- if (stateOf(folder) === "running")
85
- return;
86
- // Two hooks at once, such as two sessions starting, start one watch: the other only registers its session.
87
- const lock = join(folder, "starting");
88
- if (Date.now() - changedAt(lock) >= STALE_START_MS)
89
- rmSync(lock, { force: true });
90
- try {
91
- closeSync(openSync(lock, "wx"));
92
- }
93
- catch {
108
+ if (stateOf(folder) === "running" || !lockStart(folder))
94
109
  return;
95
- }
96
110
  try {
97
111
  // Another hook may have started it between the look above and the lock.
98
112
  if (stateOf(folder) !== "running")
99
113
  launch(folder, root, gate.watch);
100
114
  }
101
115
  finally {
102
- rmSync(lock, { force: true });
116
+ unlockStart(folder);
103
117
  }
104
118
  }
119
+ /** The files of the repo the watch lists only as it starts, one per line. */
120
+ function frozenFiles(root, watch) {
121
+ if (watch.frozen === undefined)
122
+ return "";
123
+ const frozen = new RegExp(watch.frozen);
124
+ return listFiles(root)
125
+ .filter((file) => frozen.test(file))
126
+ .join("\n");
127
+ }
105
128
  function launch(folder, root, watch) {
106
129
  rmSync(join(folder, "idle"), { force: true });
130
+ // The first cycle of a watch reads every file there is: it owes a cycle for none.
131
+ rmSync(join(folder, "owed"), { recursive: true, force: true });
107
132
  const [name = "", ...args] = watch.run;
108
133
  const command = commandOf(root, name);
109
134
  const supervisor = commandOf(root, "{engine}/src/core/watch.ts");
110
- const watched = [
111
- join(folder, "activity"),
112
- String(idleMs()),
113
- watch.cycleStart,
114
- command.file,
115
- ...command.args,
116
- ...args,
117
- ];
135
+ const watched = [join(folder, "activity"), String(idleMs()), command.file, ...command.args, ...args];
136
+ // Listed before the watch starts: a file created in between counts as one it may not know, never the other way.
137
+ writeFileSync(join(folder, "frozen"), frozenFiles(root, watch));
118
138
  const log = openSync(join(folder, "output.log"), "w");
119
139
  const child = spawn(supervisor.file, [...supervisor.args, ...watched], {
120
140
  cwd: root,
121
141
  detached: true,
122
142
  stdio: ["ignore", log, log],
123
- env: TOOL_ENV,
143
+ env: toolEnv(root),
124
144
  });
125
145
  closeSync(log);
126
146
  child.on("error", () => { });
127
147
  child.unref();
128
148
  writeFileSync(join(folder, "pid"), String(child.pid ?? ""));
129
149
  }
130
- /** The last cycle of a watch: its lines since it opened, and whether it is still open. */
131
- function lastCycle(printed, watch) {
150
+ function cyclesOf(printed, watch) {
132
151
  const lines = printed.split("\n");
133
152
  if (lines.at(-1) === "")
134
153
  lines.pop();
135
154
  const opens = new RegExp(watch.cycleStart);
136
155
  const closes = new RegExp(watch.cycleEnd);
137
- // The start of the watch opens the first cycle, and lines after the one that closes it still belong to it.
138
- const cycle = lines.slice(lines.findLastIndex((line) => opens.test(line)) + 1);
139
- return { open: !cycle.some((line) => closes.test(line)), lines: cycle };
156
+ // The start of the watch opens the first cycle, and lines after the one that closes a cycle still belong to it. A
157
+ // line that opens a cycle while one is open belongs to that one: Angular says it rebuilds as it starts to, and
158
+ // again once it has, and counting both would end a cycle before its first line.
159
+ const starts = [];
160
+ let open = true;
161
+ lines.forEach((line, at) => {
162
+ if (closes.test(line))
163
+ open = false;
164
+ else if (!open && opens.test(line)) {
165
+ starts.push(at);
166
+ open = true;
167
+ }
168
+ });
169
+ const last = starts.at(-1);
170
+ return {
171
+ opened: starts.length,
172
+ open,
173
+ // Less the lines that say it opened, which tell the agent nothing.
174
+ complete: last === undefined ? [] : lines.slice((starts.at(-2) ?? -1) + 1, last).filter((line) => !opens.test(line)),
175
+ };
176
+ }
177
+ /** Gives the files their date again, as a change of nothing else, for a watch that looks at their date. */
178
+ function touchAgain(paths) {
179
+ const now = new Date();
180
+ for (const path of paths) {
181
+ try {
182
+ utimesSync(path, now, now);
183
+ }
184
+ catch { }
185
+ }
140
186
  }
141
187
  function changedAt(path) {
142
188
  try {
@@ -155,23 +201,70 @@ function readLog(log) {
155
201
  }
156
202
  }
157
203
  /**
158
- * 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
159
- * one of the files. A watch no hook started, as when the hooks were installed mid-session, starts now, and so does one
160
- * stopped for idleness, as during a turn longer than the idle delay: it is not to blame.
204
+ * Starts the watch again when a file it lists only as it starts was created or deleted since: its first cycle then
205
+ * reads every file there is. Only one hook does, and only the watch it looked at: another session may be here too.
206
+ */
207
+ async function restartOnFrozenChange(session, root, gate, folder) {
208
+ if (gate.watch.frozen === undefined || stateOf(folder) !== "running")
209
+ return;
210
+ if (readLog(join(folder, "frozen")) === frozenFiles(root, gate.watch) || !lockStart(folder))
211
+ return;
212
+ try {
213
+ if (stateOf(folder) !== "running" || readLog(join(folder, "frozen")) === frozenFiles(root, gate.watch))
214
+ return;
215
+ // Stopped by the engine, so that another session waiting on the watch does not take it for one that broke.
216
+ writeFileSync(join(folder, "idle"), "");
217
+ stop(folder);
218
+ for (let waited = 0; stateOf(folder) === "running" && waited < STALE_START_MS / 2; waited += POLL_MS)
219
+ await sleep(POLL_MS);
220
+ if (stateOf(folder) !== "running")
221
+ launch(folder, root, gate.watch);
222
+ }
223
+ finally {
224
+ unlockStart(folder);
225
+ }
226
+ register(folder, session);
227
+ }
228
+ /**
229
+ * Asks the watch of a gate for a cycle that read the files of the turn, and waits for it, with no guess on how long a
230
+ * watch takes to see a change. Each round touches files, then waits for the watch to open a cycle after the touch,
231
+ * which only a watch that saw the touch does:
232
+ * 1. the sync file, which proves the watch now looks for changes;
233
+ * 2. the files of the turn, so that a change it missed reaches it, then the sync file;
234
+ * 3. the sync file, once that cycle has closed: the cycle of round 2 may have been on its way before the touch, and
235
+ * this one opens after every change the watch then had waiting;
236
+ * 4. the sync file once more, since the cycle it opens ends the one of round 3, the one that judges, whose last lines
237
+ * may come after the line that closes it.
238
+ * A watch no hook started, as when the hooks were installed mid-session, starts now, and so does one the engine
239
+ * stopped, for idleness or to start it again: it is not to blame. One another session starts again meanwhile is asked
240
+ * again from the first round.
161
241
  */
162
242
  async function settle(session, root, gate, files, limitMs) {
163
243
  const started = performance.now();
164
244
  const folder = folderOf(root, gate);
165
245
  const log = join(folder, "output.log");
166
- if (["absent", "idle"].includes(stateOf(folder)))
167
- startWatch(session, root, gate);
168
- touch(folder);
246
+ const sync = join(root, gate.watch.sync);
247
+ if (!existsSync(sync)) {
248
+ const stopped = `The watch cannot be asked for a cycle: its watch.sync, ${gate.watch.sync}, does not exist.`;
249
+ return { ms: 0, stopped };
250
+ }
251
+ await restartOnFrozenChange(session, root, gate, folder);
252
+ const turn = files.map((file) => join(root, file)).filter((path) => existsSync(path));
253
+ const rounds = [[sync], ...(turn.length ? [[...turn, sync]] : []), [sync], [sync]];
254
+ let asked;
255
+ let round = 0;
256
+ // The cycles the watch had opened when the round touched its files, and when it did: none before its first touch.
257
+ let touched;
169
258
  for (;;) {
259
+ const state = stateOf(folder);
260
+ if (state === "absent" || state === "idle")
261
+ startWatch(session, root, gate);
262
+ // Waiting on the watch is using it: it does not stop for idleness under a stop that waits.
263
+ touch(folder);
170
264
  // Read once the watch is known stopped, so its last lines are in.
171
- const stopped = stateOf(folder) === "stopped";
172
265
  const printed = readLog(log);
173
266
  const ms = performance.now() - started;
174
- if (stopped) {
267
+ if (state === "stopped") {
175
268
  const last = cleaned(root, printed
176
269
  .split("\n")
177
270
  .slice(-LAST_LINES - 1)
@@ -181,42 +274,94 @@ async function settle(session, root, gate, files, limitMs) {
181
274
  stopped: last ? `The watch stopped. Its last lines:\n${last}` : "The watch stopped, with no output.",
182
275
  };
183
276
  }
184
- // A cycle that started after the last change read it, however long the watch took to see it.
185
- const changed = Math.max(0, ...files.map((file) => changedAt(join(root, file))));
186
- const seen = changedAt(join(folder, "cycle")) >= changed || Date.now() - changed >= UNSEEN_MS;
187
- const cycle = lastCycle(printed, gate.watch);
188
- if (seen && !cycle.open && Date.now() - changedAt(log) >= QUIET_MS)
189
- return { ms, cycle: cleaned(root, cycle.lines.join("\n")) };
277
+ const running = processOf(folder);
278
+ if (running !== asked) {
279
+ asked = running;
280
+ round = 0;
281
+ touched = undefined;
282
+ }
283
+ const cycles = cyclesOf(printed, gate.watch);
284
+ if (state === "running" && touched === undefined) {
285
+ // A round starts once the cycle before it has closed.
286
+ if (!cycles.open) {
287
+ touchAgain(rounds[round] ?? []);
288
+ touched = { opened: cycles.opened, at: Date.now() };
289
+ }
290
+ }
291
+ else if (touched !== undefined && cycles.opened > touched.opened) {
292
+ if (round === rounds.length - 1)
293
+ return { ms, cycle: cleaned(root, cycles.complete.join("\n")) };
294
+ round++;
295
+ touched = undefined;
296
+ continue;
297
+ }
298
+ else if (touched !== undefined && Date.now() - touched.at >= RESYNC_MS) {
299
+ touchAgain(rounds[round] ?? []);
300
+ touched.at = Date.now();
301
+ }
190
302
  if (ms >= limitMs)
191
303
  return { ms, timedOut: true };
192
304
  await sleep(POLL_MS);
193
305
  }
194
306
  }
195
307
  /**
196
- * 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
197
- * gate looks at: on its failed lines, or for a compared gate, on the lines it added to the report of the turn start.
198
- * Not settled in the time of the gate: out of time, neither green nor red. A watch that stopped fails, with the last
199
- * lines it printed.
308
+ * The files the watch owes a cycle for: the ones of the stops it was out of time for, which no cycle is known to have
309
+ * read. Each such stop writes a list of its own, so two sessions never lose the files of each other.
310
+ */
311
+ function owedFiles(folder) {
312
+ const lists = readDir(join(folder, "owed")).map((name) => join(folder, "owed", name));
313
+ const files = lists.flatMap((list) => readLog(list).split("\0").filter(Boolean));
314
+ return { lists, files: [...new Set(files)] };
315
+ }
316
+ function owe(folder, files) {
317
+ mkdirSync(join(folder, "owed"), { recursive: true });
318
+ writeFileSync(join(folder, "owed", randomUUID()), files.join("\0"));
319
+ }
320
+ function readDir(folder) {
321
+ try {
322
+ return readdirSync(folder);
323
+ }
324
+ catch {
325
+ return [];
326
+ }
327
+ }
328
+ /**
329
+ * Judges a turn on a cycle of the watch of a gate that read the files of the turn the gate looks at: on its failed
330
+ * lines, or for a compared gate, on the lines it added to the report of the turn start. No such cycle in the time of
331
+ * the gate: out of time, neither green nor red, never judged on an older cycle. The watch then owes a cycle for these
332
+ * files, which the next stop it answers asks for with its own: a change it missed would otherwise stay unseen until
333
+ * the file changes again. Only a stop pays that debt, never the report of a turn start, which would make old a
334
+ * failure no turn was judged on. A watch that stopped fails, with the last lines it printed.
200
335
  */
201
336
  export async function judgeWatch(session, root, gate, files, baseline) {
202
- const settled = await settle(session, root, gate, files, gate.timeoutSeconds * 1000);
337
+ const folder = folderOf(root, gate);
338
+ const owed = owedFiles(folder);
339
+ const asked = [...new Set([...files, ...owed.files])];
340
+ const settled = await settle(session, root, gate, asked, gate.timeoutSeconds * 1000);
203
341
  const { name } = gate;
204
342
  const { ms } = settled;
205
343
  if ("stopped" in settled)
206
344
  return { name, ok: false, ms, output: settled.stopped, report: undefined };
207
- if ("timedOut" in settled) {
208
- const output = `The watch did not settle within ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
345
+ if (!("cycle" in settled)) {
346
+ owe(folder, files);
347
+ const output = `The watch opened no cycle for the turn within ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
209
348
  return { name, ok: false, ms, output, report: undefined, timedOut: true };
210
349
  }
211
- const { cycle } = settled;
350
+ // Paid, less what a stop out of time meanwhile added: only the lists this stop asked for.
351
+ for (const list of owed.lists)
352
+ rmSync(list, { force: true });
353
+ const judged = judgeCycle(gate, settled.cycle, baseline, asked);
354
+ return { name, ms, ...judged, report: judged.ok ? settled.cycle : undefined };
355
+ }
356
+ /** The verdict of a cycle: its failed lines, or for a compared gate, the lines it added to the report of the turn start. */
357
+ function judgeCycle(gate, cycle, baseline, files) {
212
358
  const fails = new RegExp(gate.watch.failed ?? "(?!)");
213
- const judged = isCompared(gate)
214
- ? addedLines(gate, cycle, baseline)
359
+ return isCompared(gate)
360
+ ? addedLines(gate, cycle, baseline, files)
215
361
  : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
216
- return { name, ms, ...judged, report: judged.ok ? cycle : undefined };
217
362
  }
218
363
  /**
219
- * The report a compared watch gives the turn start: its last cycle, once it settles in the time a prompt can wait.
364
+ * The report a compared watch gives the turn start: a cycle it opens once asked, in the time a prompt can wait.
220
365
  * Nothing when it does not, and the turn then counts nothing as new.
221
366
  */
222
367
  export async function watchReport(session, root, gate) {
@@ -241,7 +386,7 @@ function stop(folder) {
241
386
  if (stateOf(folder) !== "running")
242
387
  return;
243
388
  try {
244
- process.kill(-Number(readFileSync(join(folder, "pid"), "utf8")), "SIGTERM");
389
+ process.kill(-Number(processOf(folder)), "SIGTERM");
245
390
  }
246
391
  catch { }
247
392
  }
@@ -251,18 +396,9 @@ function stop(folder) {
251
396
  * the idle delay. Started detached, it leads a process group of its own, so stopping the group stops the watch and
252
397
  * the tools under it.
253
398
  */
254
- function supervise(activity, idle, cycleStart, file, args) {
255
- // The time the last cycle started, which the stop compares with the changes of the turn. The start opens the first.
256
- const cycle = join(dirname(activity), "cycle");
257
- const opens = new RegExp(cycleStart);
258
- writeFileSync(cycle, "");
399
+ function supervise(activity, idle, file, args) {
259
400
  const watch = spawn(file, args, { stdio: ["ignore", "pipe", "pipe"] });
260
- const forward = (line) => {
261
- // Printed before the time is kept, so a stop that sees the time also finds the cycle in the output.
262
- console.log(line);
263
- if (opens.test(line))
264
- writeFileSync(cycle, "");
265
- };
401
+ const forward = (line) => console.log(line);
266
402
  createInterface({ input: watch.stdout }).on("line", forward);
267
403
  createInterface({ input: watch.stderr }).on("line", forward);
268
404
  watch.on("error", (error) => {
@@ -278,6 +414,6 @@ function supervise(activity, idle, cycleStart, file, args) {
278
414
  }, Math.min(idle / 4, 10_000));
279
415
  }
280
416
  if (import.meta.main) {
281
- const [activity = "", idle = "", cycleStart = "", file = "", ...args] = process.argv.slice(2);
282
- supervise(activity, Number(idle), cycleStart, file, args);
417
+ const [activity = "", idle = "", file = "", ...args] = process.argv.slice(2);
418
+ supervise(activity, Number(idle), file, args);
283
419
  }
@@ -4,25 +4,48 @@ import { createInterface } from "node:readline";
4
4
  import { commandOf } from "../core/run.js";
5
5
  import { COUNTS, HEADER } from "./vitest-state-reporter.js";
6
6
  // The watch of an Angular project tested with Vitest: ng test in watch mode, with the reporter of the engine that
7
- // prints the state of every spec at each run, and NG_TEST_LOG, which makes Angular say when a run ends. A change that
8
- // leaves the build as it was reruns no spec, so no state prints: the last one is printed again, so that the cycle
9
- // still tells which specs are red.
7
+ // prints the state of every spec at each run, and NG_TEST_LOG, which makes Angular say when a run ends. It prints
8
+ // only what judges a run: the build also prints the files it built, a table longer than the report of the specs in a
9
+ // large project, whose names change at each build.
10
10
  const NO_RERUN = /No test specifications to rerun/;
11
+ const KEPT = [/Changes detected\. Rebuilding/, /bundle generation failed/, NO_RERUN];
12
+ const ENDS = /Test run finished with success/;
13
+ // Angular says why a run ended, and says all tests passed of a run with failed specs.
14
+ const REASON = /\s*Reason: .*$/;
15
+ const ERROR = /^\S+ \[ERROR\] /;
16
+ // What a watch that stopped leaves, so that a crash still says why.
17
+ const LAST_LINES = 20;
11
18
  /**
12
- * What to print for each line of the watch: the line, and before a run that reruns no spec, the last state of the
13
- * specs, so that the cycle still tells which specs are red.
19
+ * What to print for each line of ng test: the lines that open a run, the state of the specs, the errors of a build
20
+ * that failed, with the lines under each, and the line that ends a run, less its reason. A change that leaves the
21
+ * build as it was reruns no spec, so no state prints: the last one is printed again, so that the cycle still tells
22
+ * which specs are red.
14
23
  */
15
- export function replaying() {
24
+ export function reporting() {
16
25
  let state = [];
17
26
  let reading;
27
+ let inError = false;
18
28
  return (line) => {
19
29
  if (line === HEADER)
20
30
  reading = [];
21
- reading?.push(line);
22
- if (reading !== undefined && line.startsWith(COUNTS)) {
23
- state = reading;
24
- reading = undefined;
31
+ if (reading !== undefined) {
32
+ reading.push(line);
33
+ if (line.startsWith(COUNTS)) {
34
+ state = reading;
35
+ reading = undefined;
36
+ }
37
+ return [line];
25
38
  }
39
+ if (ERROR.test(line))
40
+ inError = true;
41
+ else if (line.trim() && !/^\s/.test(line))
42
+ inError = false;
43
+ if (inError)
44
+ return [line];
45
+ if (ENDS.test(line))
46
+ return [line.replace(REASON, "")];
47
+ if (!KEPT.some((kept) => kept.test(line)))
48
+ return [];
26
49
  return NO_RERUN.test(line) ? [...state, line] : [line];
27
50
  };
28
51
  }
@@ -37,11 +60,21 @@ function main(root, args) {
37
60
  env: { ...process.env, NG_TEST_LOG: "1" },
38
61
  stdio: ["ignore", "pipe", "pipe"],
39
62
  });
40
- const replay = replaying();
41
- const forward = (line) => console.log(replay(line).join("\n"));
63
+ const report = reporting();
64
+ const last = [];
65
+ const forward = (line) => {
66
+ last.push(line);
67
+ if (last.length > LAST_LINES)
68
+ last.shift();
69
+ for (const shown of report(line))
70
+ console.log(shown);
71
+ };
42
72
  createInterface({ input: watch.stdout }).on("line", forward);
43
73
  createInterface({ input: watch.stderr }).on("line", forward);
44
- watch.on("exit", (code) => process.exit(code ?? 1));
74
+ watch.on("exit", (code) => {
75
+ console.log(["ng test stopped. Its last lines:", ...last].join("\n"));
76
+ process.exit(code ?? 1);
77
+ });
45
78
  }
46
79
  if (import.meta.main)
47
80
  main(process.cwd(), process.argv.slice(2));
@@ -0,0 +1,85 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { createRequire } from "node:module";
10
+ import { join, relative } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { configOf, nothingChecked } from "./tsc.js";
13
+ import { strictErrorLines } from "./type-errors.js";
14
+ /** A code as Angular prints it: its own codes are negative, -99 then their number, as -998001 for NG8001. */
15
+ function codeOf(code) {
16
+ return code < 0 ? `NG${String(-code).slice(2)}` : `TS${code}`;
17
+ }
18
+ /** The errors of the templates, each on one line, as the gate compares them. */
19
+ export function templateErrors(root, diagnostics) {
20
+ return strictErrorLines(diagnostics.map(({ file, start = 0, code, messageText }) => {
21
+ const message = typeof messageText === "string" ? messageText : messageText.messageText;
22
+ if (file === undefined)
23
+ return message;
24
+ const line = file.text.slice(0, start).split("\n").length - 1;
25
+ return {
26
+ file: relative(root, file.fileName),
27
+ code: codeOf(code),
28
+ source: file.text.split("\n")[line] ?? "",
29
+ message: message.split("\n")[0] ?? "",
30
+ };
31
+ }));
32
+ }
33
+ /** The options forced on top of the project's: strict templates, and each --option the gate gives. */
34
+ function forced(args) {
35
+ const options = { strictTemplates: true };
36
+ for (const arg of args)
37
+ if (arg.startsWith("--") && arg !== "--project")
38
+ options[arg.slice(2)] = true;
39
+ return options;
40
+ }
41
+ /**
42
+ * The Angular compiler of the repo, once it is known to check files with the API this helper calls: otherwise, why
43
+ * not. That API is not a public one of Angular, so a version that changed it refuses the gate, never passes it green.
44
+ */
45
+ export async function compilerOf(root, args) {
46
+ const nothing = nothingChecked(root, args);
47
+ if (nothing)
48
+ return { refused: nothing };
49
+ const required = createRequire(join(root, "package.json"));
50
+ const ng = await import(__rewriteRelativeImportExtension(pathToFileURL(required.resolve("@angular/compiler-cli")).href));
51
+ const { version } = required("@angular/compiler-cli/package.json");
52
+ const program = ng.NgtscProgram?.prototype;
53
+ const missing = [
54
+ ["NgtscProgram", ng.NgtscProgram],
55
+ ["NgtscProgram.loadNgStructureAsync", program?.loadNgStructureAsync],
56
+ ["NgtscProgram.getNgSemanticDiagnostics", program?.getNgSemanticDiagnostics],
57
+ ["readConfiguration", ng.readConfiguration],
58
+ ["createCompilerHost", ng.createCompilerHost],
59
+ ].find(([, found]) => typeof found !== "function")?.[0];
60
+ if (missing !== undefined)
61
+ return {
62
+ refused: `The API of @angular/compiler-cli ${version} is not the one this gate knows: it has no ${missing}. Update deterministic-gates.`,
63
+ };
64
+ return {
65
+ compiler: {
66
+ async diagnostics() {
67
+ const config = ng.readConfiguration(configOf(root, args));
68
+ const options = { ...config.options, ...forced(args) };
69
+ const program = new ng.NgtscProgram(config.rootNames, options, ng.createCompilerHost({ options }));
70
+ await program.loadNgStructureAsync();
71
+ return program.getNgSemanticDiagnostics();
72
+ },
73
+ },
74
+ };
75
+ }
76
+ async function main(root, args) {
77
+ const found = await compilerOf(root, args);
78
+ if ("refused" in found) {
79
+ console.log(found.refused);
80
+ process.exit(1);
81
+ }
82
+ console.log(templateErrors(root, await found.compiler.diagnostics()).join("\n"));
83
+ }
84
+ if (import.meta.main)
85
+ await main(process.cwd(), process.argv.slice(2));
@@ -7,7 +7,7 @@ import { commandOf } from "../core/run.js";
7
7
  // project, checks no file, and tsc says nothing of it: the gate would be green without checking anything, so it is
8
8
  // refused, with the tsconfigs it references.
9
9
  /** The tsconfig tsc reads: the one of -p or --project, a folder meaning its tsconfig.json, or the one of the root. */
10
- function configOf(root, args) {
10
+ export function configOf(root, args) {
11
11
  const at = args.findIndex((arg) => arg === "-p" || arg === "--project");
12
12
  const given = at === -1 ? undefined : args[at + 1];
13
13
  if (given === undefined)