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