@smoothbricks/nx-plugin 0.5.5 → 0.5.7

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.
Files changed (58) hide show
  1. package/README.md +59 -11
  2. package/dist/ensure-built-receipt.d.ts +2 -2
  3. package/dist/ensure-built-receipt.d.ts.map +1 -1
  4. package/dist/ensure-built-receipt.js +7 -2
  5. package/dist/ensure-built-witness.d.ts +12 -1
  6. package/dist/ensure-built-witness.d.ts.map +1 -1
  7. package/dist/ensure-built-witness.js +32 -0
  8. package/dist/ensure-built.d.ts +2 -2
  9. package/dist/ensure-built.d.ts.map +1 -1
  10. package/dist/ensure-built.js +27 -5
  11. package/dist/executors/all-verdicts/executor.d.ts +35 -0
  12. package/dist/executors/all-verdicts/executor.d.ts.map +1 -0
  13. package/dist/executors/all-verdicts/executor.js +133 -0
  14. package/dist/executors/all-verdicts/schema.d.ts +10 -0
  15. package/dist/executors/all-verdicts/schema.d.ts.map +1 -0
  16. package/dist/executors/all-verdicts/schema.js +2 -0
  17. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  18. package/dist/executors/bounded-exec/executor.js +48 -11
  19. package/dist/executors/bounded-exec/progress.d.ts +1 -3
  20. package/dist/executors/bounded-exec/progress.d.ts.map +1 -1
  21. package/dist/executors/bounded-exec/progress.js +1 -2
  22. package/dist/executors/bounded-exec/runner-hook.d.ts +2 -0
  23. package/dist/executors/bounded-exec/runner-hook.d.ts.map +1 -0
  24. package/dist/executors/bounded-exec/runner-hook.js +301 -0
  25. package/dist/executors/bounded-exec/runner-lifecycle.d.ts +18 -0
  26. package/dist/executors/bounded-exec/runner-lifecycle.d.ts.map +1 -0
  27. package/dist/executors/bounded-exec/runner-lifecycle.js +92 -0
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +4 -1
  30. package/dist/producer-receipts.d.ts +24 -1
  31. package/dist/producer-receipts.d.ts.map +1 -1
  32. package/dist/producer-receipts.js +91 -60
  33. package/executors.json +5 -0
  34. package/managed/raw/git-format-staged.yml +16 -3
  35. package/managed/raw/patches/nx@23.2.1.patch +397 -33
  36. package/package.json +2 -2
  37. package/src/ensure-built-receipt.ts +8 -2
  38. package/src/ensure-built-witness.ts +29 -1
  39. package/src/ensure-built.ts +39 -7
  40. package/src/executors/all-verdicts/executor.test.ts +135 -0
  41. package/src/executors/all-verdicts/executor.ts +164 -0
  42. package/src/executors/all-verdicts/schema.json +22 -0
  43. package/src/executors/all-verdicts/schema.ts +10 -0
  44. package/src/executors/bounded-exec/cargo-progress-host.test.ts +332 -0
  45. package/src/executors/bounded-exec/executor.test.ts +89 -42
  46. package/src/executors/bounded-exec/executor.ts +45 -11
  47. package/src/executors/bounded-exec/progress.test.ts +1 -14
  48. package/src/executors/bounded-exec/progress.ts +2 -5
  49. package/src/executors/bounded-exec/runner-hook.test.ts +193 -0
  50. package/src/executors/bounded-exec/runner-hook.ts +292 -0
  51. package/src/executors/bounded-exec/runner-lifecycle.test.ts +82 -0
  52. package/src/executors/bounded-exec/runner-lifecycle.ts +102 -0
  53. package/src/index.test.ts +7 -5
  54. package/src/index.ts +4 -1
  55. package/src/nx-daemon-start-never.test.ts +137 -0
  56. package/src/producer-receipts.test.ts +99 -0
  57. package/src/producer-receipts.ts +111 -58
  58. package/test-timings.json +101 -96
@@ -121,7 +121,7 @@ export function readGraphWitness(path: string): GraphWitness | null {
121
121
  }
122
122
  }
123
123
 
124
- export function writeWitness(path: string, value: GraphWitness | ArtifactWitness): void {
124
+ export function writeWitness(path: string, value: GraphWitness | ArtifactWitness | GraphInstallationCensus): void {
125
125
  const temporary = `${path}.${randomUUID()}`;
126
126
  try {
127
127
  writeFileSync(temporary, JSON.stringify(value), { flag: 'wx', mode: 0o600 });
@@ -296,6 +296,34 @@ export function recordedInstallationCensus(
296
296
  }
297
297
  }
298
298
 
299
+ /** The census a caller recorded at `path`, `unproven` included: a hash source for {@link graphInstallationCensus}, never a
300
+ * proof. An absent, unreadable or malformed record is no hash source, and the next census reads every file.
301
+ */
302
+ export function readInstallationCensus(path: string): GraphInstallationCensus | undefined {
303
+ try {
304
+ return typia.json.isParse<GraphInstallationCensus>(readFileSync(path, 'utf8')) ?? undefined;
305
+ } catch (error) {
306
+ if (error instanceof SyntaxError || systemError(error)) return undefined;
307
+ throw error;
308
+ }
309
+ }
310
+
311
+ /**
312
+ * The hash `census` read of the file at `path`, while `stats` is the stamp it read the file at and it did not read the
313
+ * file in the tick it changed in ({@link unproven}); otherwise `undefined`, and the caller reads the bytes. A second
314
+ * reader of a file the census holds takes this instead of reading it again: a write landing between two reads could
315
+ * make them disagree, and a write since the census moves the stamp, so it is read again.
316
+ */
317
+ export function censusFileHashes(
318
+ census: GraphInstallationCensus,
319
+ ): (path: string, stats: StampFields) => string | undefined {
320
+ const unprovenFiles = new Set(census.unproven);
321
+ const stamps = new Map(census.nodes.map(({ path, stamp }) => [path, stamp]));
322
+ const hashes = new Map(census.files.map(({ path, sha256 }) => [path, sha256]));
323
+ return (path, stats) =>
324
+ unprovenFiles.has(path) || stamps.get(path) !== nodeStamp(stats) ? undefined : hashes.get(path);
325
+ }
326
+
299
327
  /**
300
328
  * A {@link graphInstallationCensus} that no node moved during: every node is read again after the census, and one
301
329
  * whose stamp moved fails it, unless only its ctime moved and its bytes are the ones hashed. `previous` is what the
@@ -20,8 +20,8 @@ import type { NxJsonConfiguration } from 'nx/src/config/nx-json';
20
20
  import type { ProjectGraph, ProjectGraphProjectNode } from 'nx/src/config/project-graph';
21
21
  import type { Task, TaskGraph } from 'nx/src/config/task-graph';
22
22
  import type * as NxDaemonClient from 'nx/src/daemon/client/client';
23
+ import type * as NxCreateTaskHasher from 'nx/src/hasher/create-task-hasher';
23
24
  import type * as NxHashTask from 'nx/src/hasher/hash-task';
24
- import type * as NxTaskHasher from 'nx/src/hasher/task-hasher';
25
25
  import type * as NxNative from 'nx/src/native';
26
26
  import type * as NxTransformObjects from 'nx/src/native/transform-objects';
27
27
  import type * as NxExecutionHooks from 'nx/src/project-graph/plugins/tasks-execution-hooks';
@@ -67,7 +67,7 @@ interface NxRuntimeModules {
67
67
  readonly 'nx/src/config/nx-json': typeof NxConfiguration;
68
68
  readonly 'nx/src/daemon/client/client': typeof NxDaemonClient;
69
69
  readonly 'nx/src/hasher/hash-task': typeof NxHashTask;
70
- readonly 'nx/src/hasher/task-hasher': typeof NxTaskHasher;
70
+ readonly 'nx/src/hasher/create-task-hasher': typeof NxCreateTaskHasher;
71
71
  readonly 'nx/src/native': typeof NxNative;
72
72
  readonly 'nx/src/native/transform-objects': typeof NxTransformObjects;
73
73
  readonly 'nx/src/project-graph/utils/find-project-for-path': typeof NxProjectRootMappings;
@@ -834,8 +834,32 @@ async function withTaskHooks<Result>(
834
834
  return result;
835
835
  }
836
836
 
837
+ /**
838
+ * `work`, or `withoutDaemon` when the daemon it was using stopped under a client
839
+ * that may never start one (NX_DAEMON_START=never): the patched client's error
840
+ * carries `daemonStartForbidden`, and has already turned the daemon off for
841
+ * this process. The probe then answers as it does without a daemon.
842
+ */
843
+ async function orNoDaemon<Result>(work: () => Promise<Result>, withoutDaemon: () => Result): Promise<Result> {
844
+ try {
845
+ return await work();
846
+ } catch (error) {
847
+ if (error instanceof Error && 'daemonStartForbidden' in error && error.daemonStartForbidden === true) {
848
+ return withoutDaemon();
849
+ }
850
+ throw error;
851
+ }
852
+ }
853
+
854
+ function noDaemonProbe(selector: TargetSelector): Extract<PreparedWorkspaceProbe, { kind: 'no-daemon' }> {
855
+ return { kind: 'no-daemon', reason: { kind: 'no-daemon', taskId: selectorTaskId(selector) } };
856
+ }
857
+
837
858
  async function ensureBuiltInWorkspace(workspaceRoot: string, selector: TargetSelector): Promise<EnsureBuiltResult> {
838
- const prepared = await prepareWorkspaceProbe(workspaceRoot, selector, 'build');
859
+ const prepared = await orNoDaemon(
860
+ () => prepareWorkspaceProbe(workspaceRoot, selector, 'build'),
861
+ (): PreparedWorkspaceProbe => noDaemonProbe(selector),
862
+ );
839
863
  if (prepared.kind === 'no-daemon') return runViaCli(workspaceRoot, selector, prepared.reason);
840
864
  return withTaskHooks(workspaceRoot, selector, prepared, buildPreparedTarget);
841
865
  }
@@ -849,7 +873,10 @@ async function buildPreparedTarget(
849
873
  performance.mark('ensureBuilt:probe:start');
850
874
  const reason =
851
875
  missBeforeProbe(process.env, selectorTaskId(selector)) ??
852
- (await probe(workspaceRoot, nxJson, nxArgs, projectGraph, taskGraph, tasks, requireNx));
876
+ (await orNoDaemon(
877
+ () => probe(workspaceRoot, nxJson, nxArgs, projectGraph, taskGraph, tasks, requireNx),
878
+ (): MissReason => noDaemonProbe(selector).reason,
879
+ ));
853
880
  performance.measure('ensureBuilt:probe', 'ensureBuilt:probe:start');
854
881
  return reason === null ? HIT : runViaCli(workspaceRoot, selector, reason);
855
882
  }
@@ -861,7 +888,10 @@ async function probeBuiltInWorkspace(workspaceRoot: string, selector: TargetSele
861
888
  // A failed publication proof asks a serving Nx daemon for the authoritative
862
889
  // generation, but never hashes against the consumer environment, starts a
863
890
  // provider runner or starts the provider's daemon.
864
- const prepared = await prepareWorkspaceProbe(workspaceRoot, selector, 'read-only');
891
+ const prepared = await orNoDaemon(
892
+ () => prepareWorkspaceProbe(workspaceRoot, selector, 'read-only'),
893
+ (): PreparedWorkspaceProbe => noDaemonProbe(selector),
894
+ );
865
895
  const detail =
866
896
  prepared.kind === 'no-daemon'
867
897
  ? `${receipt.detail}; authoritative graph unavailable: ${describeMiss(prepared.reason)}`
@@ -1167,7 +1197,7 @@ async function probe(
1167
1197
  verifyAllArtifacts = false,
1168
1198
  ): Promise<MissReason | null> {
1169
1199
  const { daemonClient } = requireNx('nx/src/daemon/client/client');
1170
- const { DaemonBasedTaskHasher } = requireNx('nx/src/hasher/task-hasher');
1200
+ const { createTaskHasher } = requireNx('nx/src/hasher/create-task-hasher');
1171
1201
  const { getTaskDetails, hashTasks } = requireNx('nx/src/hasher/hash-task');
1172
1202
  const { getTaskSpecificEnv } = requireNx('nx/src/tasks-runner/task-env');
1173
1203
  const { getCache } = requireNx('nx/src/tasks-runner/cache');
@@ -1180,7 +1210,9 @@ async function probe(
1180
1210
  // flag would add belong to the cloud runner, and the run path calls Nx's own
1181
1211
  // `getRunner` to obtain them.
1182
1212
  const runnerOptions = getRunnerOptions('default', nxJson, nxArgs, false);
1183
- const hasher = new DaemonBasedTaskHasher(daemonClient, runnerOptions);
1213
+ // Nx's own composition: the daemon's hasher, which continues in this process
1214
+ // if the daemon stops under NX_DAEMON_START=never.
1215
+ const hasher = createTaskHasher(projectGraph, nxJson, runnerOptions);
1184
1216
  performance.mark('ensureBuilt:hash:start');
1185
1217
  // Every task, each against its own environment — per-project and per-target
1186
1218
  // `.env` files and custom hashers that read env participate in the hash, so
@@ -0,0 +1,135 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ import allVerdictsExecutor, { verdictReport } from './executor.js';
9
+
10
+ const here = dirname(fileURLToPath(import.meta.url));
11
+ const executorModule = join(here, 'executor.ts');
12
+ const repoRoot = resolve(here, '../../../../..');
13
+ /** The workspace's own installed tool, quoted for the shell. */
14
+ const tool = (name: string): string => `'${join(repoRoot, 'node_modules', '.bin', name)}'`;
15
+
16
+ interface Finished {
17
+ readonly stdout: string;
18
+ readonly stderr: string;
19
+ readonly code: number | null;
20
+ readonly signal: NodeJS.Signals | null;
21
+ }
22
+
23
+ /** The executor in a process of its own, as Nx runs it: how it ended, and a wait for text it prints. */
24
+ function startExecutor(root: string, commands: readonly string[], cwd = '.') {
25
+ const script = [
26
+ `const { default: run } = await import(${JSON.stringify(executorModule)});`,
27
+ `const { success } = await run(${JSON.stringify({ commands, cwd })}, { root: ${JSON.stringify(root)} });`,
28
+ 'process.exitCode = success ? 0 : 1;',
29
+ ].join('\n');
30
+ const child = spawn(process.execPath, ['--eval', script], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
31
+ let stdout = '';
32
+ let stderr = '';
33
+ const waits: { readonly text: string; readonly printed: () => void }[] = [];
34
+ child.stdout.setEncoding('utf8');
35
+ child.stdout.on('data', (text: string) => {
36
+ stdout += text;
37
+ for (const wait of waits) if (stdout.includes(wait.text)) wait.printed();
38
+ });
39
+ child.stderr.setEncoding('utf8');
40
+ child.stderr.on('data', (text: string) => {
41
+ stderr += text;
42
+ });
43
+ const finished = new Promise<Finished>((settle) => {
44
+ child.once('close', (code, signal) => settle({ stdout, stderr, code, signal }));
45
+ });
46
+ const printed = (text: string): Promise<void> =>
47
+ new Promise((settle) => {
48
+ if (stdout.includes(text)) settle();
49
+ else waits.push({ text, printed: settle });
50
+ });
51
+ return { child, finished, printed };
52
+ }
53
+
54
+ async function withRoot(body: (root: string) => Promise<void>): Promise<void> {
55
+ const root = await mkdtemp(join(tmpdir(), 'all-verdicts-'));
56
+ try {
57
+ await body(root);
58
+ } finally {
59
+ await rm(root, { recursive: true, force: true });
60
+ }
61
+ }
62
+
63
+ describe('all-verdicts executor', () => {
64
+ it('lets Biome and ESLint each reach a verdict when both find errors in one run', () =>
65
+ withRoot(async (root) => {
66
+ await writeFile(join(root, 'checked.js'), 'debugger;\n');
67
+ await writeFile(join(root, 'eslint.config.mjs'), "export default [{ rules: { 'no-debugger': 'error' } }];\n");
68
+ const biome = `${tool('biome')} check checked.js`;
69
+ const eslint = `${tool('eslint')} checked.js`;
70
+ const { stdout, stderr, code } = await startExecutor(root, [biome, eslint]).finished;
71
+ // Each tool's own diagnostics, not only its exit status: neither run ended the other.
72
+ expect(stdout, stderr).toContain('lint/suspicious/noDebugger');
73
+ expect(stdout, stderr).toContain("Unexpected 'debugger' statement");
74
+ expect(stdout, stderr).toEndWith(
75
+ verdictReport([
76
+ { command: biome, verdict: { kind: 'fail', code: 1 } },
77
+ { command: eslint, verdict: { kind: 'fail', code: 1 } },
78
+ ]),
79
+ );
80
+ expect(code).toBe(1);
81
+ }));
82
+
83
+ it('reports a command a signal ended UNJUDGED by name, beside the verdicts of the rest', () =>
84
+ withRoot(async (root) => {
85
+ const killed = 'kill -TERM $$';
86
+ const { stdout, stderr, code } = await startExecutor(root, [killed, 'exit 0', 'exit 2']).finished;
87
+ expect(stdout, stderr).toEndWith(
88
+ verdictReport([
89
+ { command: killed, verdict: { kind: 'unjudged', cause: 'SIGTERM ended it before it gave a verdict' } },
90
+ { command: 'exit 0', verdict: { kind: 'pass' } },
91
+ { command: 'exit 2', verdict: { kind: 'fail', code: 2 } },
92
+ ]),
93
+ );
94
+ expect(code).toBe(1);
95
+ }));
96
+
97
+ it('reports a command that never ran UNJUDGED by name', () =>
98
+ withRoot(async (root) => {
99
+ const { stdout, stderr, code } = await startExecutor(root, ['exit 0'], 'missing').finished;
100
+ expect(stdout, stderr).toMatch(/\n {2}UNJUDGED +exit 0 \(it never ran: .+\)\n$/);
101
+ expect(code).toBe(1);
102
+ }));
103
+
104
+ it('ends every command still running when the run is signalled, and reports each one UNJUDGED', () =>
105
+ withRoot(async (root) => {
106
+ const ready = join(root, 'ready.fifo');
107
+ const lifetime = join(root, 'lifetime.fifo');
108
+ expect(spawnSync('mkfifo', [ready, lifetime]).status).toBe(0);
109
+ // Only the shell's background sleep holds the lifetime FIFO open, so its EOF observes that the signal reached
110
+ // the command's whole process group, not only the shell that leads it.
111
+ const holding = 'sleep 3600 3>lifetime.fifo & echo up > ready.fifo; wait';
112
+ const closed = readFile(lifetime, 'utf8');
113
+ const run = startExecutor(root, ['exit 3', holding]);
114
+ expect(await readFile(ready, 'utf8')).toBe('up\n');
115
+ await run.printed('\n> exit 3\n');
116
+ run.child.kill('SIGTERM');
117
+ const { stdout, stderr, signal } = await run.finished;
118
+ expect(await closed).toBe('');
119
+ expect(signal, stderr).toBe('SIGTERM');
120
+ expect(stdout, stderr).toContain(`\n> ${holding}\n\n`);
121
+ expect(stdout, stderr).toEndWith(
122
+ verdictReport([
123
+ { command: 'exit 3', verdict: { kind: 'fail', code: 3 } },
124
+ {
125
+ command: holding,
126
+ verdict: { kind: 'unjudged', cause: 'the run received SIGTERM before it gave a verdict' },
127
+ },
128
+ ]),
129
+ );
130
+ }));
131
+
132
+ it('refuses an empty command list, which could never fail', async () => {
133
+ expect(await allVerdictsExecutor({ commands: [], cwd: '.' }, { root: tmpdir() })).toEqual({ success: false });
134
+ });
135
+ });
@@ -0,0 +1,164 @@
1
+ import { type ChildProcessByStdio, spawn } from 'node:child_process';
2
+ import { resolve } from 'node:path';
3
+ import type { Readable } from 'node:stream';
4
+
5
+ import type { AllVerdictsOptions } from './schema.js';
6
+
7
+ /**
8
+ * A command's verdict. Only a command that exited reached one. A command a signal ended, one that never started and
9
+ * one still running when the run itself was signalled are unjudged: never a pass, and never left out of the report.
10
+ */
11
+ export type Verdict =
12
+ | { readonly kind: 'pass' }
13
+ | { readonly kind: 'fail'; readonly code: number }
14
+ | { readonly kind: 'unjudged'; readonly cause: string };
15
+
16
+ export interface CommandVerdict {
17
+ readonly command: string;
18
+ readonly verdict: Verdict;
19
+ }
20
+
21
+ /** The verdict of a process that closed with exit `code`, or, when `code` is null, was ended by `signal`. */
22
+ export function closedVerdict(code: number | null, signal: NodeJS.Signals | null): Verdict {
23
+ if (code === 0) return { kind: 'pass' };
24
+ if (code !== null) return { kind: 'fail', code };
25
+ return { kind: 'unjudged', cause: `${signal ?? 'an unreported signal'} ended it before it gave a verdict` };
26
+ }
27
+
28
+ /** How much of a command the verdict list quotes; the command's output block names it whole. */
29
+ const LABEL_LENGTH = 120;
30
+
31
+ function label(command: string): string {
32
+ return command.length <= LABEL_LENGTH ? command : `${command.slice(0, LABEL_LENGTH - 1)}…`;
33
+ }
34
+
35
+ function tag(verdict: Verdict): string {
36
+ switch (verdict.kind) {
37
+ case 'pass':
38
+ return 'PASS';
39
+ case 'fail':
40
+ return `FAIL (exit ${verdict.code})`;
41
+ case 'unjudged':
42
+ return 'UNJUDGED';
43
+ }
44
+ }
45
+
46
+ /** Every command's verdict, in the order the target lists the commands, under a count of each verdict. */
47
+ export function verdictReport(verdicts: readonly CommandVerdict[]): string {
48
+ const count = (kind: Verdict['kind']): number => verdicts.filter(({ verdict }) => verdict.kind === kind).length;
49
+ const lines = verdicts.map(({ command, verdict }) => {
50
+ const line = ` ${tag(verdict).padEnd(15)} ${label(command)}`;
51
+ return verdict.kind === 'unjudged' ? `${line} (${verdict.cause})` : line;
52
+ });
53
+ const counts = `${count('pass')} passed, ${count('fail')} failed, ${count('unjudged')} unjudged`;
54
+ return `\nall-verdicts: ${counts} of ${verdicts.length}\n${lines.join('\n')}\n`;
55
+ }
56
+
57
+ /** On POSIX each command leads a process group of its own, so a signal reaches every process the command started. */
58
+ const OWN_GROUP = process.platform !== 'win32';
59
+
60
+ function signalCommand(pid: number, signal: NodeJS.Signals): void {
61
+ try {
62
+ process.kill(OWN_GROUP ? -pid : pid, signal);
63
+ } catch (error) {
64
+ // ESRCH: every process of the command has already exited.
65
+ if (!(error instanceof Error && 'code' in error && error.code === 'ESRCH')) throw error;
66
+ }
67
+ }
68
+
69
+ const TERMINATION_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const satisfies readonly NodeJS.Signals[];
70
+
71
+ interface Run {
72
+ readonly command: string;
73
+ readonly output: string[];
74
+ pid: number | undefined;
75
+ verdict: Verdict | null;
76
+ }
77
+
78
+ /** A command's output as one block, headed by the command the way Nx's run-commands heads it. */
79
+ function block(run: Run): string {
80
+ return `\n> ${run.command}\n\n${run.output.join('')}`;
81
+ }
82
+
83
+ /** Starts `run`'s command and settles with its verdict once it closes; its output prints as one block then. */
84
+ function judge(run: Run, cwd: string): Promise<Verdict> {
85
+ return new Promise((settle) => {
86
+ const close = (verdict: Verdict): void => {
87
+ // A run the signal handler already judged keeps that verdict: the run is ending by the signal.
88
+ if (run.verdict !== null) return;
89
+ run.verdict = verdict;
90
+ process.stdout.write(block(run));
91
+ settle(verdict);
92
+ };
93
+ let child: ChildProcessByStdio<null, Readable, Readable>;
94
+ try {
95
+ child = spawn(run.command, {
96
+ cwd,
97
+ shell: true,
98
+ stdio: ['ignore', 'pipe', 'pipe'],
99
+ detached: OWN_GROUP,
100
+ windowsHide: true,
101
+ });
102
+ } catch (error) {
103
+ close({ kind: 'unjudged', cause: `it never ran: ${error instanceof Error ? error.message : String(error)}` });
104
+ return;
105
+ }
106
+ run.pid = child.pid;
107
+ for (const stream of [child.stdout, child.stderr]) {
108
+ stream.setEncoding('utf8');
109
+ stream.on('data', (text: string) => run.output.push(text));
110
+ }
111
+ child.once('error', (error) => close({ kind: 'unjudged', cause: `it never ran: ${error.message}` }));
112
+ child.once('close', (code, signal) => close(closedVerdict(code, signal)));
113
+ });
114
+ }
115
+
116
+ /**
117
+ * Starts every command at once and lets each reach its own verdict. Nx's run-commands cannot: in parallel it terminates
118
+ * the other commands once one fails, and serially it never starts the ones after a failure, so one tool's errors hide
119
+ * another's until a later run. Here no command ends another. Each command's output prints as one block when it closes,
120
+ * then every command's verdict. A signal to the run ends every command's process group, reports each command still
121
+ * running UNJUDGED, and ends the run by the same signal. The run succeeds only when every command passed.
122
+ */
123
+ export default async function allVerdictsExecutor(
124
+ options: AllVerdictsOptions,
125
+ context: { readonly root: string },
126
+ ): Promise<{ success: boolean }> {
127
+ if (options.commands.length === 0) {
128
+ process.stderr.write('all-verdicts: no commands: an empty set of checks cannot fail, so it cannot pass\n');
129
+ return { success: false };
130
+ }
131
+ const cwd = resolve(context.root, options.cwd);
132
+ const runs: Run[] = options.commands.map((command) => ({ command, output: [], pid: undefined, verdict: null }));
133
+ const onExit = (): void => {
134
+ for (const run of runs) {
135
+ if (run.verdict === null && run.pid !== undefined) signalCommand(run.pid, 'SIGTERM');
136
+ }
137
+ };
138
+ const onSignal = (signal: NodeJS.Signals): void => {
139
+ detach();
140
+ const verdicts = runs.map((run): CommandVerdict => {
141
+ if (run.verdict === null) {
142
+ if (run.pid !== undefined) signalCommand(run.pid, signal);
143
+ run.verdict = { kind: 'unjudged', cause: `the run received ${signal} before it gave a verdict` };
144
+ process.stdout.write(block(run));
145
+ }
146
+ return { command: run.command, verdict: run.verdict };
147
+ });
148
+ process.stdout.write(verdictReport(verdicts), () => process.kill(process.pid, signal));
149
+ };
150
+ const listeners = TERMINATION_SIGNALS.map((signal) => [signal, () => onSignal(signal)] as const);
151
+ const detach = (): void => {
152
+ process.removeListener('exit', onExit);
153
+ for (const [signal, listener] of listeners) process.removeListener(signal, listener);
154
+ };
155
+ process.on('exit', onExit);
156
+ for (const [signal, listener] of listeners) process.on(signal, listener);
157
+
158
+ const verdicts = await Promise.all(
159
+ runs.map(async (run): Promise<CommandVerdict> => ({ command: run.command, verdict: await judge(run, cwd) })),
160
+ );
161
+ detach();
162
+ process.stdout.write(verdictReport(verdicts));
163
+ return { success: verdicts.every(({ verdict }) => verdict.kind === 'pass') };
164
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "https://json-schema.org/schema",
3
+ "version": 2,
4
+ "title": "All Verdicts Executor",
5
+ "description": "Run every command at once to its own verdict: none ends another, and each command a signal ended or that never ran is reported UNJUDGED by name.",
6
+ "type": "object",
7
+ "cli": "nx",
8
+ "required": ["commands", "cwd"],
9
+ "properties": {
10
+ "commands": {
11
+ "type": "array",
12
+ "items": { "type": "string" },
13
+ "minItems": 1,
14
+ "description": "Shell commands, all started at once. An empty list is refused: it could never fail."
15
+ },
16
+ "cwd": {
17
+ "type": "string",
18
+ "description": "Where every command runs, relative to the workspace root."
19
+ }
20
+ },
21
+ "additionalProperties": false
22
+ }
@@ -0,0 +1,10 @@
1
+ /** The executor the inferred `lint` target runs its tool commands with. */
2
+ export const ALL_VERDICTS_EXECUTOR = '@smoothbricks/nx-plugin:all-verdicts';
3
+
4
+ /** Options of `@smoothbricks/nx-plugin:all-verdicts`. */
5
+ export interface AllVerdictsOptions {
6
+ /** Shell commands, all started at once; none ends another. An empty list is refused: it could never fail. */
7
+ readonly commands: readonly string[];
8
+ /** Where every command runs, relative to the workspace root. */
9
+ readonly cwd: string;
10
+ }