sumlyzer 1.4.1 → 1.6.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.
@@ -0,0 +1,35 @@
1
+ import path from "node:path";
2
+
3
+ import { npmScriptEnv } from "./npmScriptEnv.mjs";
4
+ import { withPath } from "./pathEnv.mjs";
5
+ import { runner } from "./runner.mjs";
6
+
7
+ // node_modules/.bin of the workspace and each parent up to the root, like npm run.
8
+ function binPath(root, cwd) {
9
+ const rootDir = path.resolve(root);
10
+ const binDirs = [];
11
+ let dir = path.resolve(cwd);
12
+
13
+ while (true) {
14
+ binDirs.push(path.join(dir, "node_modules", ".bin"));
15
+ const parent = path.dirname(dir);
16
+ if (dir === rootDir || parent === dir) {
17
+ break;
18
+ }
19
+ dir = parent;
20
+ }
21
+
22
+ return [...binDirs, process.env.PATH].join(path.delimiter);
23
+ }
24
+
25
+ // Only the main script gets the runner's reporter: a hook running its own
26
+ // `node --test` would otherwise overwrite the main script's counts and JUnit report.
27
+ export function scriptEnv({ root, workspace, phase, junitDestPath }) {
28
+ const cwd = path.join(root, workspace.path);
29
+ const base = phase.isMain ? runner.prepareEnv(process.env, junitDestPath) : process.env;
30
+
31
+ return withPath(
32
+ { ...base, ...npmScriptEnv({ pkg: workspace.pkg, pkgDir: cwd, event: phase.event, script: phase.command }) },
33
+ binPath(root, cwd)
34
+ );
35
+ }
@@ -62,6 +62,22 @@ function pickError(error) {
62
62
  return { message: error.message ?? String(error), stack: error.cause?.stack ?? error.stack ?? null };
63
63
  }
64
64
 
65
+ /**
66
+ * @param {NodeTestEvent} event
67
+ * @returns {event is NodeTestFailEvent}
68
+ */
69
+ function isFailEvent(event) {
70
+ return event.type === "test:fail";
71
+ }
72
+
73
+ /**
74
+ * @param {NodeTestEvent} event
75
+ * @returns {event is NodeTestSummaryEvent}
76
+ */
77
+ function isSummaryEvent(event) {
78
+ return event.type === "test:summary";
79
+ }
80
+
65
81
  /**
66
82
  * node:test emits a "test:summary" per file plus one aggregate at the end.
67
83
  * the aggregate is the only one without a "file" attached.
@@ -79,7 +95,7 @@ function isAggregateSummary(data) {
79
95
  */
80
96
  export default async function* testEventReporter(source) {
81
97
  for await (const event of source) {
82
- if (event.type === "test:fail") {
98
+ if (isFailEvent(event)) {
83
99
  const line = {
84
100
  type: "test:fail",
85
101
  name: event.data.name,
@@ -90,7 +106,7 @@ export default async function* testEventReporter(source) {
90
106
  continue;
91
107
  }
92
108
 
93
- if (event.type === "test:summary" && isAggregateSummary(event.data)) {
109
+ if (isSummaryEvent(event) && isAggregateSummary(event.data)) {
94
110
  const { counts, duration_ms: durationMs } = event.data;
95
111
  const line = {
96
112
  type: "test:summary",
package/src/watch.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  import { watch } from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
+ import { buildDependentsGraph, expandWithDependents } from "./graph.mjs";
5
+
4
6
  const IGNORED_SEGMENTS = new Set(["node_modules", "coverage", ".git"]);
5
7
 
6
8
  function isIgnored(relPath) {
@@ -12,7 +14,7 @@ function matchWorkspace(relPath, workspaces) {
12
14
  return workspaces.find((wsPath) => normalized === wsPath || normalized.startsWith(`${wsPath}/`));
13
15
  }
14
16
 
15
- export function watchWorkspaces({ root, workspaces, onChange, debounceMs = 300, isSuppressed = () => false }) {
17
+ function watchWorkspaces({ root, workspaces, onChange, isSuppressed, debounceMs = 300 }) {
16
18
  const pending = new Set();
17
19
  let timer = null;
18
20
 
@@ -42,3 +44,52 @@ export function watchWorkspaces({ root, workspaces, onChange, debounceMs = 300,
42
44
  }
43
45
  };
44
46
  }
47
+
48
+ // A run can write files inside its own workspace (coverage, artifacts) just after it
49
+ // exits; ignoring them briefly stops the workspace from re-triggering itself forever.
50
+ const SETTLE_COOLDOWN_MS = 500;
51
+
52
+ /**
53
+ * Calls `rerun(affected, changedPaths)` on each change, with the changed workspaces
54
+ * and their dependents, until SIGINT/SIGTERM.
55
+ * @returns {Promise<void>}
56
+ */
57
+ export function watchAndRerun({ root, allPaths, workspaces, rerun }) {
58
+ const dependentsGraph = buildDependentsGraph(root, allPaths);
59
+ const byPath = new Map(workspaces.map((workspace) => [workspace.path, workspace]));
60
+ const settling = new Set();
61
+
62
+ async function onChange(changedPaths) {
63
+ const affected = [...expandWithDependents(changedPaths, dependentsGraph)]
64
+ .map((wsPath) => byPath.get(wsPath))
65
+ .filter(Boolean);
66
+ if (affected.length === 0) {
67
+ return;
68
+ }
69
+
70
+ for (const workspace of affected) {
71
+ settling.add(workspace.path);
72
+ }
73
+ try {
74
+ await rerun(affected, changedPaths);
75
+ }
76
+ finally {
77
+ setTimeout(() => {
78
+ for (const workspace of affected) {
79
+ settling.delete(workspace.path);
80
+ }
81
+ }, SETTLE_COOLDOWN_MS).unref();
82
+ }
83
+ }
84
+
85
+ const watcher = watchWorkspaces({ root, workspaces: allPaths, isSuppressed: (wsPath) => settling.has(wsPath), onChange });
86
+
87
+ return new Promise((resolve) => {
88
+ const stop = () => {
89
+ watcher.close();
90
+ resolve();
91
+ };
92
+ process.once("SIGINT", stop);
93
+ process.once("SIGTERM", stop);
94
+ });
95
+ }
@@ -0,0 +1,108 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import path from "node:path";
3
+
4
+ import { runner } from "./runner.mjs";
5
+ import { scriptEnv } from "./scriptEnv.mjs";
6
+
7
+ // The shell is the test runner's parent: kill the whole process group (POSIX)
8
+ // or tree (Windows), otherwise the runner outlives it.
9
+ function killTree(child) {
10
+ if (process.platform === "win32") {
11
+ spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"]);
12
+ return;
13
+ }
14
+
15
+ try {
16
+ process.kill(-child.pid, "SIGTERM");
17
+ }
18
+ catch {
19
+ child.kill("SIGTERM");
20
+ }
21
+ }
22
+
23
+ export function killAll(activeChildren) {
24
+ for (const child of activeChildren) {
25
+ killTree(child);
26
+ }
27
+ }
28
+
29
+ export async function withInterruptHandling(activeChildren, run) {
30
+ function onInterrupt(signal) {
31
+ killAll(activeChildren);
32
+ process.exit(signal === "SIGINT" ? 130 : 143);
33
+ }
34
+
35
+ process.once("SIGINT", onInterrupt);
36
+ process.once("SIGTERM", onInterrupt);
37
+
38
+ try {
39
+ return await run();
40
+ }
41
+ finally {
42
+ process.off("SIGINT", onInterrupt);
43
+ process.off("SIGTERM", onInterrupt);
44
+ }
45
+ }
46
+
47
+ function waitForExit(child) {
48
+ return new Promise((resolve, reject) => {
49
+ child.on("error", reject);
50
+ child.on("close", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
51
+ });
52
+ }
53
+
54
+ async function runPhase(command, options, activeChildren) {
55
+ const child = spawn(command, options);
56
+ activeChildren.add(child);
57
+ const stdout = [];
58
+ const stderr = [];
59
+
60
+ child.stdout.on("data", (chunk) => stdout.push(chunk));
61
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
62
+
63
+ try {
64
+ return { exitCode: await waitForExit(child), stdout, stderr };
65
+ }
66
+ finally {
67
+ activeChildren.delete(child);
68
+ }
69
+ }
70
+
71
+ // Phases stop at the first failure, like npm run.
72
+ async function runPhases({ root, workspace, junitDestPath, activeChildren }) {
73
+ const cwd = path.join(root, workspace.path);
74
+ const stdout = [];
75
+ const stderr = [];
76
+ let exitCode = 0;
77
+
78
+ for (const phase of workspace.phases) {
79
+ const options = { cwd, shell: true, detached: process.platform !== "win32", env: scriptEnv({ root, workspace, phase, junitDestPath }) };
80
+ const result = await runPhase(phase.command, options, activeChildren);
81
+ exitCode = result.exitCode;
82
+ stdout.push(...result.stdout);
83
+ stderr.push(...result.stderr);
84
+
85
+ if (exitCode !== 0) {
86
+ break;
87
+ }
88
+ }
89
+
90
+ return {
91
+ exitCode,
92
+ stdout: Buffer.concat(stdout).toString("utf8"),
93
+ stderr: Buffer.concat(stderr).toString("utf8")
94
+ };
95
+ }
96
+
97
+ export async function runWorkspace({ root, workspace, junitDestPath, activeChildren }) {
98
+ const start = Date.now();
99
+ const captured = await runPhases({ root, workspace, junitDestPath, activeChildren });
100
+
101
+ return {
102
+ workspace,
103
+ exitCode: captured.exitCode,
104
+ durationMs: Date.now() - start,
105
+ junitDestPath,
106
+ ...runner.parseResult(captured)
107
+ };
108
+ }
@@ -0,0 +1,112 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import { glob } from "glob";
5
+
6
+ import { runner } from "./runner.mjs";
7
+ import { NoWorkspacesError, InvalidPackageJsonError, RootPackageJsonError } from "./errors.mjs";
8
+
9
+ export function workspaceName(wsPath) {
10
+ return (wsPath ?? "").replace(/^workspaces[\\/]/, "");
11
+ }
12
+
13
+ function readJson(file) {
14
+ return JSON.parse(readFileSync(file, "utf8"));
15
+ }
16
+
17
+ // npm's interpretation of "workspaces": directory globs, "!" entries excluded.
18
+ function splitWorkspacePatterns(entries) {
19
+ const patterns = [];
20
+ const ignore = ["**/node_modules/**"];
21
+
22
+ for (const entry of entries) {
23
+ if (entry.startsWith("!")) {
24
+ ignore.push(entry.slice(1));
25
+ }
26
+ else {
27
+ patterns.push(entry.endsWith("/") ? entry : `${entry}/`);
28
+ }
29
+ }
30
+
31
+ return { patterns, ignore };
32
+ }
33
+
34
+ export async function resolveWorkspacePaths(root) {
35
+ let rootPkg;
36
+ try {
37
+ rootPkg = readJson(path.join(root, "package.json"));
38
+ }
39
+ catch (error) {
40
+ throw new RootPackageJsonError(root, error);
41
+ }
42
+
43
+ if (!rootPkg.workspaces || rootPkg.workspaces.length === 0) {
44
+ throw new NoWorkspacesError();
45
+ }
46
+
47
+ const { patterns, ignore } = splitWorkspacePatterns(rootPkg.workspaces);
48
+ const resolved = new Set();
49
+
50
+ for (const pattern of patterns) {
51
+ // posix: "/" separators on Windows too, like git and fs.watch.
52
+ const matches = await glob(pattern, { cwd: root, ignore, posix: true });
53
+
54
+ for (const match of matches.sort((a, b) => a.localeCompare(b, "en"))) {
55
+ resolved.add(match);
56
+ }
57
+ }
58
+
59
+ return [...resolved];
60
+ }
61
+
62
+ // pre/post hooks run like npm run does, around the main script.
63
+ function scriptPhases(scripts, scriptName) {
64
+ return [
65
+ { event: `pre${scriptName}`, command: scripts[`pre${scriptName}`] },
66
+ { event: scriptName, command: scripts[scriptName], isMain: true },
67
+ { event: `post${scriptName}`, command: scripts[`post${scriptName}`] }
68
+ ].filter((phase) => phase.command);
69
+ }
70
+
71
+ function loadWorkspace(root, wsPath, scriptName) {
72
+ const workspace = { path: wsPath, name: workspaceName(wsPath), pkg: null, phases: [] };
73
+ try {
74
+ workspace.pkg = readJson(path.join(root, wsPath, "package.json"));
75
+ }
76
+ catch (error) {
77
+ return error.code === "ENOENT" ? { kind: "absent", workspace } : { kind: "invalid", workspace, message: error.message };
78
+ }
79
+
80
+ if (!workspace.pkg.scripts?.[scriptName]) {
81
+ return { kind: "absent", workspace };
82
+ }
83
+
84
+ workspace.phases = scriptPhases(workspace.pkg.scripts, scriptName);
85
+ const kind = workspace.phases.some((phase) => runner.hasOwnReporter(phase.command)) ? "ownReporterConflict" : "runnable";
86
+ return { kind, workspace };
87
+ }
88
+
89
+ export function loadWorkspaces(root, wsPaths, scriptName) {
90
+ const runnable = [];
91
+ const ownReporterConflicts = [];
92
+ const invalid = [];
93
+
94
+ for (const wsPath of wsPaths) {
95
+ const loaded = loadWorkspace(root, wsPath, scriptName);
96
+ if (loaded.kind === "runnable") {
97
+ runnable.push(loaded.workspace);
98
+ }
99
+ else if (loaded.kind === "ownReporterConflict") {
100
+ ownReporterConflicts.push(loaded.workspace);
101
+ }
102
+ else if (loaded.kind === "invalid") {
103
+ invalid.push({ workspace: loaded.workspace, message: loaded.message });
104
+ }
105
+ }
106
+
107
+ if (invalid.length > 0) {
108
+ throw new InvalidPackageJsonError(invalid);
109
+ }
110
+
111
+ return { runnable, ownReporterConflicts };
112
+ }