@tayomi/deterministic-gates 0.6.1 → 0.7.1

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,17 +1,21 @@
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, renameSync, rmSync, statSync, utimesSync, writeFileSync, } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
- import { dirname, join } from "node:path";
5
+ import { 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
9
  import { addedLines, cleaned, commandOf, ENGINE_VERSION, toolEnv } 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;
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. Each wait
13
+ // is twice the one before, since a watch on a busy machine takes seconds to say it opens a cycle, and a touch too
14
+ // many is a cycle too many. The wait changes no verdict, which only ever comes from a cycle the watch opened after a
15
+ // touch. The tests of the engine shorten it.
16
+ const RESYNC_MS = 1000;
17
+ // A watch that opens no cycle after this many touches, 31 s after the first, does not look at its sync file.
18
+ const SYNC_TOUCHES = 5;
15
19
  const POLL_MS = 100;
16
20
  // What a watch that stopped leaves the agent: enough to see the error, not the whole history of the session.
17
21
  const LAST_LINES = 20;
@@ -26,6 +30,9 @@ const IDLE_MS = 30 * 60 * 1000;
26
30
  function idleMs() {
27
31
  return Number(process.env.GATES_WATCH_IDLE_MS) || IDLE_MS;
28
32
  }
33
+ function resyncMs() {
34
+ return Number(process.env.GATES_WATCH_RESYNC_MS) || RESYNC_MS;
35
+ }
29
36
  /** Records a prompt or a stop on the repo of a watch, which keeps it from stopping for idleness. */
30
37
  function touch(folder) {
31
38
  writeFileSync(join(folder, "activity"), "");
@@ -52,25 +59,49 @@ function register(folder, session) {
52
59
  mkdirSync(join(folder, "sessions"), { recursive: true });
53
60
  writeFileSync(sessionFile(folder, session), "");
54
61
  }
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;
62
+ /** The process of the watch, as the engine recorded it when it started it, or nothing when it never did. */
63
+ function processOf(folder) {
58
64
  try {
59
- pid = Number(readFileSync(join(folder, "pid"), "utf8"));
65
+ return readFileSync(join(folder, "pid"), "utf8");
60
66
  }
61
67
  catch {
62
- return "absent";
68
+ return undefined;
63
69
  }
70
+ }
71
+ /** Whether the watch runs, has stopped on its own, was stopped by the engine, or was never started. */
72
+ function stateOf(folder) {
73
+ const recorded = processOf(folder);
74
+ if (recorded === undefined)
75
+ return "absent";
64
76
  try {
65
- if (!pid)
77
+ if (!Number(recorded))
66
78
  return "stopped";
67
- process.kill(pid, 0);
79
+ process.kill(Number(recorded), 0);
68
80
  return "running";
69
81
  }
70
82
  catch {
71
83
  return existsSync(join(folder, "idle")) ? "idle" : "stopped";
72
84
  }
73
85
  }
86
+ // Two hooks at once, such as two sessions starting, start one watch: only the one that holds the lock does.
87
+ function lockStart(folder) {
88
+ const lock = join(folder, "starting");
89
+ // Only a lock that is there and old is taken over: removing one on the word of a look that found none would remove
90
+ // the lock another hook has just taken, and both would start a watch.
91
+ const taken = changedAt(lock);
92
+ if (taken && Date.now() - taken >= STALE_START_MS)
93
+ rmSync(lock, { force: true });
94
+ try {
95
+ closeSync(openSync(lock, "wx"));
96
+ return true;
97
+ }
98
+ catch {
99
+ return false;
100
+ }
101
+ }
102
+ function unlockStart(folder) {
103
+ rmSync(join(folder, "starting"), { force: true });
104
+ }
74
105
  /**
75
106
  * Starts the watch of a gate in the background, unless it already runs, and records that the session uses it: it
76
107
  * outlives the hook that starts it, until no session uses it.
@@ -81,40 +112,40 @@ export function startWatch(session, root, gate) {
81
112
  touch(folder);
82
113
  // The sessions of a watch that starts again still use it.
83
114
  register(folder, session);
84
- if (stateOf(folder) === "running")
115
+ if (stateOf(folder) === "running" || !lockStart(folder))
85
116
  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 {
94
- return;
95
- }
96
117
  try {
97
118
  // Another hook may have started it between the look above and the lock.
98
119
  if (stateOf(folder) !== "running")
99
120
  launch(folder, root, gate.watch);
100
121
  }
101
122
  finally {
102
- rmSync(lock, { force: true });
123
+ unlockStart(folder);
103
124
  }
104
125
  }
126
+ /** The files of the repo the watch lists only as it starts, one per line. */
127
+ function frozenFiles(root, watch) {
128
+ if (watch.frozen === undefined)
129
+ return "";
130
+ const frozen = new RegExp(watch.frozen);
131
+ return listFiles(root)
132
+ .filter((file) => frozen.test(file))
133
+ .join("\n");
134
+ }
105
135
  function launch(folder, root, watch) {
106
136
  rmSync(join(folder, "idle"), { force: true });
137
+ // The first cycle of a watch reads every file there is: it owes a cycle for none.
138
+ rmSync(join(folder, "owed"), { recursive: true, force: true });
139
+ // What the watch before this one left of its cycles.
140
+ for (const left of ["cycles", "cycle", "last"])
141
+ rmSync(join(folder, left), { force: true });
107
142
  const [name = "", ...args] = watch.run;
108
143
  const command = commandOf(root, name);
109
144
  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
- ];
145
+ const cycle = [watch.cycleStart, watch.cycleEnd];
146
+ const watched = [folder, String(idleMs()), ...cycle, command.file, ...command.args, ...args];
147
+ // Listed before the watch starts: a file created in between counts as one it may not know, never the other way.
148
+ writeFileSync(join(folder, "frozen"), frozenFiles(root, watch));
118
149
  const log = openSync(join(folder, "output.log"), "w");
119
150
  const child = spawn(supervisor.file, [...supervisor.args, ...watched], {
120
151
  cwd: root,
@@ -127,16 +158,20 @@ function launch(folder, root, watch) {
127
158
  child.unref();
128
159
  writeFileSync(join(folder, "pid"), String(child.pid ?? ""));
129
160
  }
130
- /** The last cycle of a watch: its lines since it opened, and whether it is still open. */
131
- function lastCycle(printed, watch) {
132
- const lines = printed.split("\n");
133
- if (lines.at(-1) === "")
134
- lines.pop();
135
- const opens = new RegExp(watch.cycleStart);
136
- 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 };
161
+ // A watch whose supervisor has written nothing yet is in the cycle its start opens.
162
+ function cyclesOf(folder) {
163
+ const [opened, state] = readText(join(folder, "cycles")).split(" ");
164
+ return { opened: Number(opened), open: state !== "closed" };
165
+ }
166
+ /** Gives the files their date again, as a change of nothing else, for a watch that looks at their date. */
167
+ function touchAgain(paths) {
168
+ const now = new Date();
169
+ for (const path of paths) {
170
+ try {
171
+ utimesSync(path, now, now);
172
+ }
173
+ catch { }
174
+ }
140
175
  }
141
176
  function changedAt(path) {
142
177
  try {
@@ -146,77 +181,185 @@ function changedAt(path) {
146
181
  return 0;
147
182
  }
148
183
  }
149
- function readLog(log) {
184
+ function readText(path) {
150
185
  try {
151
- return readFileSync(log, "utf8");
186
+ return readFileSync(path, "utf8");
152
187
  }
153
188
  catch {
154
189
  return "";
155
190
  }
156
191
  }
192
+ /** Writes a file at once, so that a hook reading it never finds half of it. */
193
+ function writeWhole(path, text) {
194
+ writeFileSync(`${path}.new`, text);
195
+ renameSync(`${path}.new`, path);
196
+ }
157
197
  /**
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.
198
+ * Starts the watch again when a file it lists only as it starts was created or deleted since: its first cycle then
199
+ * reads every file there is. Only one hook does, and only the watch it looked at: another session may be here too.
200
+ */
201
+ async function restartOnFrozenChange(session, root, gate, folder) {
202
+ if (gate.watch.frozen === undefined || stateOf(folder) !== "running")
203
+ return;
204
+ if (readText(join(folder, "frozen")) === frozenFiles(root, gate.watch) || !lockStart(folder))
205
+ return;
206
+ try {
207
+ if (stateOf(folder) !== "running" || readText(join(folder, "frozen")) === frozenFiles(root, gate.watch))
208
+ return;
209
+ // Stopped by the engine, so that another session waiting on the watch does not take it for one that broke.
210
+ writeFileSync(join(folder, "idle"), "");
211
+ stop(folder);
212
+ for (let waited = 0; stateOf(folder) === "running" && waited < STALE_START_MS / 2; waited += POLL_MS)
213
+ await sleep(POLL_MS);
214
+ if (stateOf(folder) !== "running")
215
+ launch(folder, root, gate.watch);
216
+ }
217
+ finally {
218
+ unlockStart(folder);
219
+ }
220
+ register(folder, session);
221
+ }
222
+ /**
223
+ * 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
224
+ * watch takes to see a change. Each round touches files, then waits for the watch to open a cycle after the touch,
225
+ * which only a watch that saw the touch does:
226
+ * 1. the files of the turn, so that a change it missed reaches it, and the sync file. A watch that does not look for
227
+ * changes yet sees neither, and both are touched again;
228
+ * 2. the sync file, once that cycle has closed: the cycle of round 1 may have been on its way before the touch, and
229
+ * this one opens after every change the watch then had waiting;
230
+ * 3. the sync file once more, since the cycle it opens ends the one of round 2, the one that judges, whose last lines
231
+ * may come after the line that closes it.
232
+ * A watch that opens no cycle however often it is touched does not look at its sync file, and is said so. A watch no
233
+ * hook started, as when the hooks were installed mid-session, starts now, and so does one the engine
234
+ * stopped, for idleness or to start it again: it is not to blame. One another session starts again meanwhile is asked
235
+ * again from the first round.
161
236
  */
162
237
  async function settle(session, root, gate, files, limitMs) {
163
238
  const started = performance.now();
164
239
  const folder = folderOf(root, gate);
165
- const log = join(folder, "output.log");
166
- if (["absent", "idle"].includes(stateOf(folder)))
167
- startWatch(session, root, gate);
168
- touch(folder);
240
+ const sync = join(root, gate.watch.sync);
241
+ if (!existsSync(sync)) {
242
+ const stopped = `The watch cannot be asked for a cycle: its watch.sync, ${gate.watch.sync}, does not exist.`;
243
+ return { ms: 0, stopped };
244
+ }
245
+ await restartOnFrozenChange(session, root, gate, folder);
246
+ const turn = files.map((file) => join(root, file)).filter((path) => existsSync(path));
247
+ const rounds = [[...turn, sync], [sync], [sync]];
248
+ let asked;
249
+ let round = 0;
250
+ // The cycles the watch had opened when the round touched its files, when it last did, and how many times: none
251
+ // before its first touch.
252
+ let touched;
169
253
  for (;;) {
170
- // Read once the watch is known stopped, so its last lines are in.
171
- const stopped = stateOf(folder) === "stopped";
172
- const printed = readLog(log);
254
+ const state = stateOf(folder);
255
+ if (state === "absent" || state === "idle")
256
+ startWatch(session, root, gate);
257
+ // Waiting on the watch is using it: it does not stop for idleness under a stop that waits.
258
+ touch(folder);
173
259
  const ms = performance.now() - started;
174
- if (stopped) {
175
- const last = cleaned(root, printed
176
- .split("\n")
177
- .slice(-LAST_LINES - 1)
178
- .join("\n"));
260
+ if (state === "stopped") {
261
+ // Read once the watch is known stopped, so its last lines are in: the ones its supervisor kept, or what the
262
+ // supervisor itself printed when it broke.
263
+ const printed = readText(join(folder, "last")) || readText(join(folder, "output.log"));
264
+ const last = cleaned(root, printed.trimEnd().split("\n").slice(-LAST_LINES).join("\n"));
179
265
  return {
180
266
  ms,
181
267
  stopped: last ? `The watch stopped. Its last lines:\n${last}` : "The watch stopped, with no output.",
182
268
  };
183
269
  }
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")) };
270
+ const running = processOf(folder);
271
+ if (running !== asked) {
272
+ asked = running;
273
+ round = 0;
274
+ touched = undefined;
275
+ }
276
+ const cycles = cyclesOf(folder);
277
+ if (state === "running" && touched === undefined) {
278
+ // A round starts once the cycle before it has closed.
279
+ if (!cycles.open) {
280
+ touchAgain(rounds[round] ?? []);
281
+ touched = { opened: cycles.opened, at: Date.now(), times: 1 };
282
+ }
283
+ }
284
+ else if (touched !== undefined && cycles.opened > touched.opened) {
285
+ // Written before the count of the cycle that ended it: the cycle read is that one, or a later one.
286
+ if (round === rounds.length - 1)
287
+ return { ms, cycle: cleaned(root, readText(join(folder, "cycle"))) };
288
+ round++;
289
+ touched = undefined;
290
+ continue;
291
+ }
292
+ else if (touched !== undefined && Date.now() - touched.at >= resyncMs() * 2 ** (touched.times - 1)) {
293
+ if (touched.times === SYNC_TOUCHES) {
294
+ const stopped = `The watch opens no cycle when the date of its watch.sync, ${gate.watch.sync}, changes: give it a file the watch rebuilds for, such as a source file it reads.`;
295
+ return { ms, stopped };
296
+ }
297
+ touchAgain(rounds[round] ?? []);
298
+ touched = { ...touched, at: Date.now(), times: touched.times + 1 };
299
+ }
190
300
  if (ms >= limitMs)
191
301
  return { ms, timedOut: true };
192
302
  await sleep(POLL_MS);
193
303
  }
194
304
  }
195
305
  /**
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.
306
+ * 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
307
+ * read. Each such stop writes a list of its own, so two sessions never lose the files of each other.
308
+ */
309
+ function owedFiles(folder) {
310
+ const lists = readDir(join(folder, "owed")).map((name) => join(folder, "owed", name));
311
+ const files = lists.flatMap((list) => readText(list).split("\0").filter(Boolean));
312
+ return { lists, files: [...new Set(files)] };
313
+ }
314
+ function owe(folder, files) {
315
+ mkdirSync(join(folder, "owed"), { recursive: true });
316
+ writeFileSync(join(folder, "owed", randomUUID()), files.join("\0"));
317
+ }
318
+ function readDir(folder) {
319
+ try {
320
+ return readdirSync(folder);
321
+ }
322
+ catch {
323
+ return [];
324
+ }
325
+ }
326
+ /**
327
+ * 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
328
+ * 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
329
+ * the gate: out of time, neither green nor red, never judged on an older cycle. The watch then owes a cycle for these
330
+ * files, which the next stop it answers asks for with its own: a change it missed would otherwise stay unseen until
331
+ * the file changes again. Only a stop pays that debt, never the report of a turn start, which would make old a
332
+ * failure no turn was judged on. A watch that stopped fails, with the last lines it printed.
200
333
  */
201
334
  export async function judgeWatch(session, root, gate, files, baseline) {
202
- const settled = await settle(session, root, gate, files, gate.timeoutSeconds * 1000);
335
+ const folder = folderOf(root, gate);
336
+ const owed = owedFiles(folder);
337
+ const asked = [...new Set([...files, ...owed.files])];
338
+ const settled = await settle(session, root, gate, asked, gate.timeoutSeconds * 1000);
203
339
  const { name } = gate;
204
340
  const { ms } = settled;
205
341
  if ("stopped" in settled)
206
342
  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.`;
343
+ if (!("cycle" in settled)) {
344
+ owe(folder, files);
345
+ 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
346
  return { name, ok: false, ms, output, report: undefined, timedOut: true };
210
347
  }
211
- const { cycle } = settled;
348
+ // Paid, less what a stop out of time meanwhile added: only the lists this stop asked for.
349
+ for (const list of owed.lists)
350
+ rmSync(list, { force: true });
351
+ const judged = judgeCycle(gate, settled.cycle, baseline, asked);
352
+ return { name, ms, ...judged, report: judged.ok ? settled.cycle : undefined };
353
+ }
354
+ /** The verdict of a cycle: its failed lines, or for a compared gate, the lines it added to the report of the turn start. */
355
+ function judgeCycle(gate, cycle, baseline, files) {
212
356
  const fails = new RegExp(gate.watch.failed ?? "(?!)");
213
- const judged = isCompared(gate)
357
+ return isCompared(gate)
214
358
  ? addedLines(gate, cycle, baseline, files)
215
359
  : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
216
- return { name, ms, ...judged, report: judged.ok ? cycle : undefined };
217
360
  }
218
361
  /**
219
- * The report a compared watch gives the turn start: its last cycle, once it settles in the time a prompt can wait.
362
+ * The report a compared watch gives the turn start: a cycle it opens once asked, in the time a prompt can wait.
220
363
  * Nothing when it does not, and the turn then counts nothing as new.
221
364
  */
222
365
  export async function watchReport(session, root, gate) {
@@ -241,43 +384,74 @@ function stop(folder) {
241
384
  if (stateOf(folder) !== "running")
242
385
  return;
243
386
  try {
244
- process.kill(-Number(readFileSync(join(folder, "pid"), "utf8")), "SIGTERM");
387
+ process.kill(-Number(processOf(folder)), "SIGTERM");
245
388
  }
246
389
  catch { }
247
390
  }
248
391
  /**
249
- * The supervisor of a watch, which this module runs as when the engine starts one: it runs the watch, its output
250
- * going where its own goes, and stops it with every process it started once its repo has had no prompt nor stop for
251
- * the idle delay. Started detached, it leads a process group of its own, so stopping the group stops the watch and
252
- * the tools under it.
392
+ * The supervisor of a watch, which this module runs as when the engine starts one: it runs the watch and stops it
393
+ * with every process it started once its repo has had no prompt nor stop for the idle delay. Started detached, it
394
+ * leads a process group of its own, so stopping the group stops the watch and the tools under it. It counts the
395
+ * cycles of the watch as it prints them, and keeps only the lines a hook reads: a watch prints thousands of lines per
396
+ * cycle for as long as a session lasts, which no hook could read again at each look.
253
397
  */
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, "");
398
+ function supervise(folder, idle, cycle, command) {
399
+ const [file = "", ...args] = command;
400
+ const opens = new RegExp(cycle.start);
401
+ const closes = new RegExp(cycle.end);
259
402
  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, "");
403
+ // The start of the watch opens the first cycle, and lines after the one that closes a cycle still belong to it. A
404
+ // line that opens a cycle while one is open belongs to that one: Angular says it rebuilds as it starts to, and
405
+ // again once it has, and counting both would end a cycle before its first line.
406
+ let opened = 0;
407
+ let open = true;
408
+ // The lines of the cycle in progress, less the ones that say it opened, which tell the agent nothing.
409
+ let lines = [];
410
+ // What a watch that stopped leaves the agent.
411
+ const last = [];
412
+ const count = () => writeWhole(join(folder, "cycles"), `${opened} ${open ? "open" : "closed"}`);
413
+ const read = (line) => {
414
+ last.push(line);
415
+ if (last.length > LAST_LINES)
416
+ last.shift();
417
+ if (closes.test(line)) {
418
+ if (open) {
419
+ open = false;
420
+ count();
421
+ }
422
+ }
423
+ else if (!open && opens.test(line)) {
424
+ // Nothing is printed in a cycle any more once the next one has opened: its lines are whole, and written before
425
+ // the count that tells a hook of them.
426
+ writeWhole(join(folder, "cycle"), lines.join("\n"));
427
+ lines = [];
428
+ opened++;
429
+ open = true;
430
+ count();
431
+ }
432
+ if (!opens.test(line))
433
+ lines.push(line);
434
+ };
435
+ const end = (code) => {
436
+ writeWhole(join(folder, "last"), last.join("\n"));
437
+ process.exit(code);
265
438
  };
266
- createInterface({ input: watch.stdout }).on("line", forward);
267
- createInterface({ input: watch.stderr }).on("line", forward);
439
+ count();
440
+ createInterface({ input: watch.stdout }).on("line", read);
441
+ createInterface({ input: watch.stderr }).on("line", read);
268
442
  watch.on("error", (error) => {
269
- console.log(error.message);
270
- process.exit(1);
443
+ last.push(error.message);
444
+ end(1);
271
445
  });
272
- watch.on("close", (code) => process.exit(code ?? 1));
446
+ watch.on("close", (code) => end(code ?? 1));
273
447
  setInterval(() => {
274
- if (Date.now() - changedAt(activity) < idle)
448
+ if (Date.now() - changedAt(join(folder, "activity")) < idle)
275
449
  return;
276
- writeFileSync(join(dirname(activity), "idle"), "");
450
+ writeFileSync(join(folder, "idle"), "");
277
451
  process.kill(-process.pid, "SIGTERM");
278
452
  }, Math.min(idle / 4, 10_000));
279
453
  }
280
454
  if (import.meta.main) {
281
- const [activity = "", idle = "", cycleStart = "", file = "", ...args] = process.argv.slice(2);
282
- supervise(activity, Number(idle), cycleStart, file, args);
455
+ const [folder = "", idle = "", start = "", end = "", ...command] = process.argv.slice(2);
456
+ supervise(folder, Number(idle), { start, end }, command);
283
457
  }
@@ -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)