sumlyzer 0.6.0 → 1.0.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/README.md CHANGED
@@ -11,18 +11,13 @@
11
11
  <a href="./LICENSE"><img src="https://img.shields.io/npm/l/sumlyzer.svg" alt="license" /></a>
12
12
  </p>
13
13
 
14
- ## Ever lost a failing test in thousands of lines of workspace output?
15
14
 
16
- ## Ever wished your npm workspaces stopped at the first failure?
15
+ ## Ever wished a faster feedback when testing your npm workspaces?
17
16
 
18
17
  `npm run test --workspaces --if-present` runs every workspace, but gives you no
19
- aggregated summary and no way to fail fast, an early failure just scrolls off
20
- screen once later workspaces print their own output.
18
+ aggregated summary and no way to fail fast, no way to catch an early failure that scrolled off screen.
21
19
 
22
- Sumlyzer runs each workspace's test script, one by one or concurrently.
23
- Passing workspaces collapse to a single line, failing ones print just the
24
- relevant failure detail, and everything ends with an aggregated pass/fail
25
- summary table so nothing scrolls out of the terminal.
20
+ Sumlyzer gives you all those possibilities and even more like concurrency or JUnit reports.
26
21
 
27
22
  ## Requirements
28
23
 
@@ -32,10 +27,18 @@ summary table so nothing scrolls out of the terminal.
32
27
  ## Scope
33
28
 
34
29
  This tool is intentionally narrow: **npm workspaces** running **`node:test`**.
30
+
35
31
  It orchestrates `npm run <script> --workspace=<path>` for every workspace that
36
- declares the target script, and it parses node test's own reporter output to build
37
- the summary. It does not support pnpm/yarn workspaces or other test runners
38
- (Jest, Vitest, Mocha etc.).
32
+ declares the target script, and it parses node test's own output to build
33
+ the global and per workspace summary.
34
+
35
+ It does not support pnpm/yarn workspaces or other test runners
36
+ (Jest, Vitest, Mocha etc.). (for the moment)
37
+
38
+ sumlyzer forces its own `node:test` reporter onto every workspace via
39
+ `NODE_OPTIONS`, so a workspace's `test` script should just run `node --test`
40
+ without configuring its own `--test-reporter`.
41
+ sumlyzer detects this ahead of time and skips that workspace instead of running into it.
39
42
 
40
43
  ## Install
41
44
 
@@ -62,14 +65,12 @@ Options:
62
65
  | `-c, --concurrency <n>` | `1` | run up to `<n>` workspaces at once |
63
66
  | `-h, --help` | | print usage |
64
67
 
65
- Exit code is `1` if any workspace fails (or if the project has no
66
- workspaces), `0` otherwise, wire it straight into CI without extra parsing.
68
+ Exit code is `1` if any workspace fails (even if every workspace's tests passed), `0` otherwise, wire it straight into CI without extra parsing.
67
69
  This also applies when `--junit` can't write its report.
68
- The exit code is `1` even if every workspace's tests passed.
69
70
 
70
71
  ## Features
71
72
 
72
- - Aggregated pass/fail summary table, so nothing scrolls out of the terminal
73
+ - Aggregated pass/fail summary table.
73
74
  - Fail-fast (`--ff`): stop at the first failing workspace
74
75
  - Aggregated JUnit XML report (`--junit`), merging every workspace's own results
75
76
  - GitHub Actions log folding: each workspace's output collapsed into an
@@ -173,8 +174,7 @@ every workspace's own `node:test` results. Each workspace runs with `node:test`'
173
174
  built-in `junit` reporter enabled alongside the terminal one, and sumlyzer combines
174
175
  the resulting files into one document, prefixing every `<testsuite>` name with the
175
176
  workspace it came from so CI test-report UIs (GitLab, Jenkins, Azure DevOps, ...)
176
- can tell them apart. If `<path>` is an existing directory, the report is written
177
- to `<path>/junit.xml`:
177
+ can tell them apart.
178
178
 
179
179
  ```
180
180
  npx sumlyzer --junit reports/junit.xml
@@ -188,16 +188,15 @@ npx sumlyzer --junit reports/ # writes reports/junit.xml
188
188
  </testsuites>
189
189
  ```
190
190
 
191
- A workspace whose script never produces a junit file (for example,
192
- `--script` points at something that isn't `node:test`, or the workspace crashed
193
- before it could write one) is left out of the aggregated report and sumlyzer
191
+ A workspace whose script never produces a junit file is left out of the aggregated report and sumlyzer
194
192
  prints a warning naming it.
195
193
 
196
194
  ### GitHub Actions log folding
197
195
 
198
196
  On GitHub Actions (detected via `GITHUB_ACTIONS=true`), each workspace's full
199
197
  `node:test` output is wrapped in a collapsible `::group::`/`::endgroup::`
200
- section instead of the terminal's collapsed-line-or-failure-detail format.
198
+ section instead of the terminal's formal.
199
+
201
200
  This is automatic, no flag needed, and keeps the job log short by default
202
201
  while still letting you expand any workspace, passing or failing, to see its
203
202
  full suite output.
@@ -209,9 +208,7 @@ only one whose log folding sumlyzer has actually verified end-to-end.
209
208
 
210
209
  `--concurrency <n>` runs up to `<n>` workspaces' scripts at the same time
211
210
  instead of one after another, which can noticeably cut wall-clock time on
212
- projects with many workspaces. There is no ordering dependency to worry about
213
- here: unlike a `build` script, one workspace's `node:test` run never depends
214
- on another workspace's test run, so nothing needs to be sequenced.
211
+ projects with many workspaces.
215
212
 
216
213
  Since workspaces can now finish in any order, their output interleaves in
217
214
  whatever order they complete, rather than following the `workspaces` list
package/bin/sumlyzer.mjs CHANGED
@@ -4,6 +4,7 @@ import path from "node:path";
4
4
  import { availableParallelism } from "node:os";
5
5
 
6
6
  import { main } from "../src/run.mjs";
7
+ import { NoWorkspacesError, InvalidPackageJsonError, WorkspaceLaunchError } from "../src/errors.mjs";
7
8
 
8
9
  let args;
9
10
  try {
@@ -53,10 +54,24 @@ Options:
53
54
  process.exit(0);
54
55
  }
55
56
 
56
- await main({
57
- root: path.resolve(process.cwd()),
58
- scriptName: args.script,
59
- ff: args.ff,
60
- junitPath: args.junit,
61
- concurrency
62
- });
57
+ try {
58
+ await main({
59
+ root: path.resolve(process.cwd()),
60
+ scriptName: args.script,
61
+ ff: args.ff,
62
+ junitPath: args.junit,
63
+ concurrency
64
+ });
65
+ }
66
+ catch (error) {
67
+ if (error instanceof NoWorkspacesError) {
68
+ console.info(error.message);
69
+ }
70
+ else if (error instanceof InvalidPackageJsonError || error instanceof WorkspaceLaunchError) {
71
+ console.error(error.message);
72
+ }
73
+ else {
74
+ throw error;
75
+ }
76
+ process.exitCode = 1;
77
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sumlyzer",
3
- "version": "0.6.0",
3
+ "version": "1.0.0",
4
4
  "description": "Run every npm workspace's test script, only show output for the ones that fail, and finish with an aggregated pass/fail summary.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/errors.mjs ADDED
@@ -0,0 +1,25 @@
1
+ import { red, workspaceName } from "./reporter.mjs";
2
+
3
+ export class NoWorkspacesError extends Error {
4
+ constructor() {
5
+ super("Your project does not have any workspaces.");
6
+ this.name = "NoWorkspacesError";
7
+ }
8
+ }
9
+
10
+ export class InvalidPackageJsonError extends Error {
11
+ constructor(entries) {
12
+ super(entries.map(({ wsPath, message }) => red(`✗ ${workspaceName(wsPath)}: could not read its package.json (${message})`)).join("\n"));
13
+ this.name = "InvalidPackageJsonError";
14
+ this.entries = entries;
15
+ }
16
+ }
17
+
18
+ export class WorkspaceLaunchError extends Error {
19
+ constructor(wsPath, scriptName, cause) {
20
+ super(red(`✗ ${workspaceName(wsPath)}: could not launch "${scriptName}" (${cause.message})`), { cause });
21
+ this.name = "WorkspaceLaunchError";
22
+ this.wsPath = wsPath;
23
+ this.scriptName = scriptName;
24
+ }
25
+ }
@@ -1,53 +1,3 @@
1
- const COUNT_INDEX = 1;
2
-
3
- const countTestsRegex = new RegExp(String.raw`ℹ tests (\d+)`);
4
- const countPassRegex = new RegExp(String.raw`ℹ pass (\d+)`);
5
- const countFailRegex = new RegExp(String.raw`ℹ fail (\d+)`);
6
- const countSkippedRegex = new RegExp(String.raw`ℹ skipped (\d+)`);
7
- const countTodoRegex = new RegExp(String.raw`ℹ todo (\d+)`);
8
- const countCancelledRegex = new RegExp(String.raw`ℹ cancelled (\d+)`);
9
- const countDurationRegex = new RegExp(String.raw`ℹ duration_ms (\d+)`);
10
-
11
- const count = (regex, output) => regex.exec(output)?.[COUNT_INDEX];
12
-
13
- // skip/todo/cancelled fall back to "0" rather than "?": unlike pass/fail, a missing
14
- // line here is far more likely to mean "zero" than "parsing went wrong somehow".
15
- export function parseTestCounts(output) {
16
- const tests = count(countTestsRegex, output);
17
-
18
- if (!tests) {
19
- return null;
20
- }
21
-
22
- return {
23
- tests,
24
- pass: count(countPassRegex, output) ?? "?",
25
- fail: count(countFailRegex, output) ?? "?",
26
- skip: count(countSkippedRegex, output) ?? "0",
27
- todo: count(countTodoRegex, output) ?? "0",
28
- cancelled: count(countCancelledRegex, output) ?? "0",
29
- durationMs: count(countDurationRegex, output)
30
- };
31
- }
32
-
33
- export function parseFailingTests(failureSection) {
34
- if (!failureSection) {
35
- return [];
36
- }
37
-
38
- return [...failureSection.matchAll(/^✖ (.+) \([\d.]+ms\)$/gm)].map((match) => match[1]);
39
- }
40
-
41
1
  export function stripNpmNoise(output) {
42
2
  return output.replace(/^npm warn .*\n?/gm, "");
43
3
  }
44
-
45
- export function extractFailureDetails(output, failureSection) {
46
- if (!failureSection) {
47
- return output.trim();
48
- }
49
-
50
- const details = failureSection.split(/\n(?=npm )/)[0].trim();
51
-
52
- return details.includes("'test failed'") ? output.trim() : details;
53
- }
package/src/run.mjs CHANGED
@@ -1,25 +1,26 @@
1
- import { execFile } from "node:child_process";
1
+ import { spawn, spawnSync } from "node:child_process";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
- import { promisify } from "node:util";
5
+ import { fileURLToPath } from "node:url";
6
6
  import path from "node:path";
7
7
 
8
8
  import { buildJunitReport } from "./junit.mjs";
9
- import { parseTestCounts, parseFailingTests, stripNpmNoise, extractFailureDetails } from "./parseOutput.mjs";
9
+ import { stripNpmNoise } from "./parseOutput.mjs";
10
+ import { parseReporterEvents, renderFailureRecap, renderSummaryText } from "./testEventReporter.mjs";
10
11
  import { red, dim, workspaceName, githubGroupSyntax, printWorkspaceResult, printSummary, reportOutcome } from "./reporter.mjs";
12
+ import { NoWorkspacesError, InvalidPackageJsonError, WorkspaceLaunchError } from "./errors.mjs";
11
13
 
12
- const execFileAsync = promisify(execFile);
14
+ const TEST_EVENT_REPORTER_PATH = fileURLToPath(new URL("./testEventReporter.mjs", import.meta.url));
13
15
 
14
- const SPEC_REPORTER_FLAGS = "--test-reporter=spec --test-reporter-destination=stdout";
15
-
16
- export function envWithSpecReporter(env, junitDestPath) {
16
+ export function envWithTestReporter(env, junitDestPath) {
17
17
  const existing = env.NODE_OPTIONS ? `${env.NODE_OPTIONS} ` : "";
18
+ const testReporterFlags = `--test-reporter=${TEST_EVENT_REPORTER_PATH} --test-reporter-destination=stdout`;
18
19
  const junitFlags = junitDestPath ? ` --test-reporter=junit --test-reporter-destination=${junitDestPath}` : "";
19
20
  // Drop NODE_TEST_CONTEXT: if sumlyzer itself is invoked from inside a node:test run, this var would otherwise leak.
20
21
  const rest = { ...env };
21
22
  delete rest.NODE_TEST_CONTEXT;
22
- return { ...rest, NODE_OPTIONS: `${existing}${SPEC_REPORTER_FLAGS}${junitFlags}` };
23
+ return { ...rest, NODE_OPTIONS: `${existing}${testReporterFlags}${junitFlags}` };
23
24
  }
24
25
 
25
26
  // Rethink this synchronous approach in case of very large package.json files, or huge amount of workspaces,
@@ -28,55 +29,122 @@ function readJson(file) {
28
29
  return JSON.parse(readFileSync(file, "utf8"));
29
30
  }
30
31
 
32
+ const OWN_TEST_REPORTER_FLAG = /--test-reporter(?!-destination)\b/;
33
+
34
+ export function hasOwnTestReporter(scriptCommand) {
35
+ return OWN_TEST_REPORTER_FLAG.test(scriptCommand);
36
+ }
37
+
31
38
  function listEligibleWorkspaces(root, workspaces, scriptName) {
32
- return workspaces.filter((wsPath) => {
39
+ const eligible = [];
40
+ const ownReporterConflicts = [];
41
+ const invalidPackageJson = [];
42
+
43
+ for (const wsPath of workspaces) {
33
44
  const pkgFile = path.join(root, wsPath, "package.json");
45
+ let pkg;
34
46
  try {
35
- return Boolean(readJson(pkgFile).scripts?.[scriptName]);
47
+ pkg = readJson(pkgFile);
36
48
  }
37
- catch {
38
- return false;
49
+ catch (error) {
50
+ if (error.code === "ENOENT") {
51
+ continue;
52
+ }
53
+ invalidPackageJson.push({ wsPath, message: error.message });
54
+ continue;
55
+ }
56
+
57
+ const script = pkg.scripts?.[scriptName];
58
+ if (!script) {
59
+ continue;
60
+ }
61
+ if (hasOwnTestReporter(script)) {
62
+ ownReporterConflicts.push(wsPath);
39
63
  }
40
- });
64
+ else {
65
+ eligible.push(wsPath);
66
+ }
67
+ }
68
+
69
+ return { eligible, ownReporterConflicts, invalidPackageJson };
41
70
  }
42
71
 
43
- async function runWorkspaceScript(root, wsPath, scriptName, junitDestPath) {
44
- const start = Date.now();
72
+ // npm spawns the actual test runner as its own child, so killing just the "npm"
73
+ // process leaves that grandchild running. Giving it its own process group (POSIX)
74
+ // or asking Windows to kill the whole tree ensures nothing is left behind.
75
+ function killWorkspaceChild(child) {
76
+ if (process.platform === "win32") {
77
+ spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"]);
78
+ return;
79
+ }
80
+
81
+ try {
82
+ process.kill(-child.pid, "SIGTERM");
83
+ }
84
+ catch {
85
+ child.kill("SIGTERM");
86
+ }
87
+ }
88
+
89
+ async function captureWorkspaceOutput(root, wsPath, scriptName, junitDestPath, activeChildren) {
45
90
  const options = {
46
91
  cwd: root,
47
92
  shell: process.platform === "win32",
48
- maxBuffer: 20 * 1024 * 1024,
49
- env: envWithSpecReporter(process.env, junitDestPath)
93
+ detached: process.platform !== "win32",
94
+ env: envWithTestReporter(process.env, junitDestPath)
50
95
  };
51
96
 
52
- let exitCode = 0;
53
- let output;
97
+ const child = spawn("npm", ["run", scriptName, "--workspace=" + wsPath], options);
98
+ activeChildren.add(child);
99
+ const stdoutChunks = [];
100
+ const stderrChunks = [];
101
+
102
+ child.stdout.on("data", (chunk) => stdoutChunks.push(chunk));
103
+ child.stderr.on("data", (chunk) => stderrChunks.push(chunk));
104
+
54
105
  try {
55
- const { stdout, stderr } = await execFileAsync("npm", ["run", scriptName, "--workspace=" + wsPath], options);
56
- output = stripNpmNoise(stdout + stderr);
106
+ const exitCode = await new Promise((resolve, reject) => {
107
+ child.on("error", reject);
108
+ child.on("close", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
109
+ });
110
+
111
+ return {
112
+ exitCode,
113
+ stdout: Buffer.concat(stdoutChunks).toString("utf8"),
114
+ stderr: Buffer.concat(stderrChunks).toString("utf8")
115
+ };
57
116
  }
58
- catch (error) {
59
- if (typeof error.code !== "number") {
60
- throw error;
61
- }
62
- exitCode = error.code;
63
- output = stripNpmNoise((error.stdout ?? "") + (error.stderr ?? ""));
117
+ finally {
118
+ activeChildren.delete(child);
64
119
  }
120
+ }
121
+
122
+ function buildWorkspaceResult(wsPath, junitDestPath, durationMs, { exitCode, stdout, stderr }) {
123
+ const { counts, failingTests, failures } = parseReporterEvents(stdout);
65
124
 
66
- const [, failureSection] = output.split("✖ failing tests:");
125
+ // Workspaces that don't run through node:test never emit our JSON events; fall
126
+ // back to their raw (npm-noise-stripped) output so failures are still visible.
127
+ const fallbackOutput = stripNpmNoise(stdout + stderr).trim();
128
+ const failureRecap = failures.length > 0 ? renderFailureRecap(failures) : null;
67
129
 
68
130
  return {
69
131
  wsPath,
70
132
  exitCode,
71
- failureDetails: exitCode === 0 ? null : extractFailureDetails(output, failureSection),
72
- durationMs: Date.now() - start,
73
- counts: parseTestCounts(output),
74
- failingTests: parseFailingTests(failureSection),
133
+ failureDetails: exitCode === 0 ? null : (failureRecap ?? fallbackOutput),
134
+ durationMs,
135
+ counts,
136
+ failingTests,
75
137
  junitDestPath,
76
- rawOutput: output
138
+ rawOutput: counts ? [renderSummaryText(counts), failureRecap].filter(Boolean).join("\n\n") : fallbackOutput
77
139
  };
78
140
  }
79
141
 
142
+ async function runWorkspaceScript(root, wsPath, scriptName, junitDestPath, activeChildren) {
143
+ const start = Date.now();
144
+ const captured = await captureWorkspaceOutput(root, wsPath, scriptName, junitDestPath, activeChildren);
145
+ return buildWorkspaceResult(wsPath, junitDestPath, Date.now() - start, captured);
146
+ }
147
+
80
148
  async function collectJunitEntries(results) {
81
149
  const entries = [];
82
150
  const missing = [];
@@ -99,9 +167,19 @@ async function collectJunitEntries(results) {
99
167
  async function runWorkspaces({ root, workspacesToRun, scriptName, ff, junitDir, concurrency }) {
100
168
  const results = new Array(workspacesToRun.length);
101
169
  const ciGroup = githubGroupSyntax(process.env);
170
+ const activeChildren = new Set();
102
171
  let stopScheduling = false;
103
172
  let nextIndex = 0;
104
173
 
174
+ // --ff only stops scheduling new workspaces; ones already running are left to
175
+ // finish and report their real result. A launch error is different: it means
176
+ // sumlyzer itself can't go on, so nothing still running should keep spawning.
177
+ function killActiveChildren() {
178
+ for (const child of activeChildren) {
179
+ killWorkspaceChild(child);
180
+ }
181
+ }
182
+
105
183
  async function worker() {
106
184
  while (!stopScheduling && nextIndex < workspacesToRun.length) {
107
185
  const index = nextIndex++;
@@ -113,11 +191,12 @@ async function runWorkspaces({ root, workspacesToRun, scriptName, ff, junitDir,
113
191
 
114
192
  let result;
115
193
  try {
116
- result = await runWorkspaceScript(root, wsPath, scriptName, junitDestPath);
194
+ result = await runWorkspaceScript(root, wsPath, scriptName, junitDestPath, activeChildren);
117
195
  }
118
196
  catch (error) {
119
- console.error(red(`✗ ${name}: could not launch "${scriptName}" (${error.message})`));
120
- process.exit(1);
197
+ stopScheduling = true;
198
+ killActiveChildren();
199
+ throw new WorkspaceLaunchError(wsPath, scriptName, error);
121
200
  }
122
201
  results[index] = result;
123
202
  printWorkspaceResult(name, result, ciGroup);
@@ -128,8 +207,25 @@ async function runWorkspaces({ root, workspacesToRun, scriptName, ff, junitDir,
128
207
  }
129
208
  }
130
209
 
210
+ // Spawned children run detached (their own process group) so a launch error can kill
211
+ // a whole npm subtree via killWorkspaceChild. That isolation means Ctrl-C no longer
212
+ // reaches them for free the way it would in the same group, so handle it explicitly:
213
+ // kill whatever's still running, then exit with the conventional 128+signal code.
214
+ function onInterrupt(signal) {
215
+ killActiveChildren();
216
+ process.exit(signal === "SIGINT" ? 130 : 143);
217
+ }
218
+ process.once("SIGINT", onInterrupt);
219
+ process.once("SIGTERM", onInterrupt);
220
+
131
221
  const workerCount = Math.max(1, Math.min(concurrency, workspacesToRun.length));
132
- await Promise.all(Array.from({ length: workerCount }, worker));
222
+ try {
223
+ await Promise.all(Array.from({ length: workerCount }, worker));
224
+ }
225
+ finally {
226
+ process.off("SIGINT", onInterrupt);
227
+ process.off("SIGTERM", onInterrupt);
228
+ }
133
229
 
134
230
  return results.filter((result) => result !== undefined);
135
231
  }
@@ -165,11 +261,19 @@ export async function main({ root, scriptName, ff, junitPath, concurrency = 1 })
165
261
  const { workspaces } = readJson(path.join(root, "package.json"));
166
262
 
167
263
  if (!workspaces || workspaces.length === 0) {
168
- console.info("Your project does not have any workspaces.");
169
- process.exit(1);
264
+ throw new NoWorkspacesError();
265
+ }
266
+
267
+ const { eligible: workspacesToRun, ownReporterConflicts, invalidPackageJson } = listEligibleWorkspaces(root, workspaces, scriptName);
268
+
269
+ if (invalidPackageJson.length > 0) {
270
+ throw new InvalidPackageJsonError(invalidPackageJson);
271
+ }
272
+
273
+ for (const wsPath of ownReporterConflicts) {
274
+ console.log(dim(`⊘ ${workspaceName(wsPath)}: skipped, own --test-reporter detected in its "${scriptName}" script`));
170
275
  }
171
276
 
172
- const workspacesToRun = listEligibleWorkspaces(root, workspaces, scriptName);
173
277
  const junitDir = junitPath ? await mkdtemp(path.join(tmpdir(), "sumlyzer-junit-")) : null;
174
278
 
175
279
  let results;
@@ -0,0 +1,185 @@
1
+ /**
2
+ * @typedef {object} NodeTestFailEvent
3
+ * @property {"test:fail"} type
4
+ * @property {object} data
5
+ * @property {string} data.name
6
+ * @property {object} [data.details]
7
+ * @property {number} [data.details.duration_ms]
8
+ * @property {Error & { cause?: Error }} [data.details.error]
9
+ */
10
+
11
+ /**
12
+ * @typedef {object} NodeTestSummaryEvent
13
+ * @property {"test:summary"} type
14
+ * @property {object} data
15
+ * @property {string} [data.file] absent only on the one aggregate summary emitted at the end of the run
16
+ * @property {number} data.duration_ms
17
+ * @property {object} data.counts
18
+ * @property {number} data.counts.tests
19
+ * @property {number} data.counts.passed
20
+ * @property {number} data.counts.failed
21
+ * @property {number} data.counts.skipped
22
+ * @property {number} data.counts.todo
23
+ * @property {number} data.counts.cancelled
24
+ */
25
+
26
+ /** @typedef {NodeTestFailEvent | NodeTestSummaryEvent | { type: string, data: object }} NodeTestEvent */
27
+
28
+ /**
29
+ * @typedef {object} ReportedError
30
+ * @property {string} message
31
+ * @property {string | null} stack
32
+ */
33
+
34
+ /**
35
+ * @typedef {object} ReportedFailure
36
+ * @property {string} name
37
+ * @property {number} durationMs
38
+ * @property {ReportedError | null} error
39
+ */
40
+
41
+ /**
42
+ * @typedef {object} ReportedCounts
43
+ * @property {number} tests
44
+ * @property {number} pass
45
+ * @property {number} fail
46
+ * @property {number} skip
47
+ * @property {number} todo
48
+ * @property {number} cancelled
49
+ * @property {number} [durationMs] present once merged with the summary's own duration in parseReporterEvents
50
+ */
51
+
52
+ /**
53
+ * @param {Error & { cause?: Error }} [error]
54
+ * @returns {ReportedError | null}
55
+ */
56
+ function pickError(error) {
57
+ if (!error) {
58
+ return null;
59
+ }
60
+ // node:test wraps assertion failures in an ERR_TEST_FAILURE error whose own .stack
61
+ // has no frames; the actual file:line trace lives on .cause (e.g. an AssertionError).
62
+ return { message: error.message ?? String(error), stack: error.cause?.stack ?? error.stack ?? null };
63
+ }
64
+
65
+ /**
66
+ * node:test emits a "test:summary" per file plus one aggregate at the end;
67
+ * the aggregate is the only one without a "file" attached.
68
+ * @param {NodeTestSummaryEvent["data"]} data
69
+ * @returns {boolean}
70
+ */
71
+ function isAggregateSummary(data) {
72
+ return data.file == null;
73
+ }
74
+
75
+ /**
76
+ * The node:test custom reporter itself (`--test-reporter=<this file>`). Runs inside the
77
+ * spawned workspace's process; only test:fail and the aggregate test:summary are kept,
78
+ * each re-emitted as one JSON line on stdout for the parent process to read back.
79
+ * @param {AsyncIterable<NodeTestEvent>} source
80
+ * @returns {AsyncGenerator<string>}
81
+ */
82
+ export default async function* testEventReporter(source) {
83
+ for await (const event of source) {
84
+ if (event.type === "test:fail") {
85
+ const line = {
86
+ type: "test:fail",
87
+ name: event.data.name,
88
+ durationMs: event.data.details?.duration_ms ?? 0,
89
+ error: pickError(event.data.details?.error)
90
+ };
91
+ yield `${JSON.stringify(line)}\n`;
92
+ continue;
93
+ }
94
+
95
+ if (event.type === "test:summary" && isAggregateSummary(event.data)) {
96
+ const { counts, duration_ms: durationMs } = event.data;
97
+ const line = {
98
+ type: "test:summary",
99
+ counts: {
100
+ tests: counts.tests,
101
+ pass: counts.passed,
102
+ fail: counts.failed,
103
+ skip: counts.skipped,
104
+ todo: counts.todo,
105
+ cancelled: counts.cancelled
106
+ },
107
+ durationMs
108
+ };
109
+ yield `${JSON.stringify(line)}\n`;
110
+ }
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Parses the JSON lines emitted by {@link testEventReporter} back out of a workspace's
116
+ * captured stdout, running in the parent process. Lines that aren't valid JSON (npm noise,
117
+ * or a workspace script that never runs node:test at all) are silently skipped rather than
118
+ * treated as a parsing error.
119
+ * @param {string} output
120
+ * @returns {{ counts: ReportedCounts | null, failingTests: string[], failures: ReportedFailure[] }}
121
+ */
122
+ export function parseReporterEvents(output) {
123
+ let counts = null;
124
+ let durationMs = null;
125
+ const failures = [];
126
+
127
+ for (const rawLine of output.split("\n")) {
128
+ const line = rawLine.trim();
129
+ if (!line) {
130
+ continue;
131
+ }
132
+
133
+ let event;
134
+ try {
135
+ event = JSON.parse(line);
136
+ }
137
+ catch {
138
+ continue;
139
+ }
140
+
141
+ if (event?.type === "test:fail" && typeof event.name === "string") {
142
+ failures.push({ name: event.name, durationMs: event.durationMs, error: event.error });
143
+ }
144
+ else if (event?.type === "test:summary" && event.counts) {
145
+ counts = event.counts;
146
+ durationMs = event.durationMs;
147
+ }
148
+ }
149
+
150
+ return {
151
+ counts: counts ? { ...counts, durationMs } : null,
152
+ failingTests: failures.map((failure) => failure.name),
153
+ failures
154
+ };
155
+ }
156
+
157
+ /**
158
+ * @param {ReportedFailure[]} failures
159
+ * @returns {string}
160
+ */
161
+ export function renderFailureRecap(failures) {
162
+ return failures
163
+ .map(({ name, durationMs, error }) => {
164
+ const header = `✖ ${name} (${Number(durationMs ?? 0).toFixed(1)}ms)`;
165
+ const detail = error?.stack ?? error?.message ?? "";
166
+ return detail ? `${header}\n${detail}` : header;
167
+ })
168
+ .join("\n\n");
169
+ }
170
+
171
+ /**
172
+ * @param {ReportedCounts} counts
173
+ * @returns {string}
174
+ */
175
+ export function renderSummaryText(counts) {
176
+ return [
177
+ `ℹ tests ${counts.tests}`,
178
+ `ℹ pass ${counts.pass}`,
179
+ `ℹ fail ${counts.fail}`,
180
+ `ℹ skipped ${counts.skip}`,
181
+ `ℹ todo ${counts.todo}`,
182
+ `ℹ cancelled ${counts.cancelled}`,
183
+ `ℹ duration_ms ${counts.durationMs}`
184
+ ].join("\n");
185
+ }