sumlyzer 1.4.0 → 1.5.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/watch.mjs CHANGED
@@ -1,6 +1,9 @@
1
1
  import { watch } from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
+ import { buildDependentsGraph, expandWithDependents } from "./graph.mjs";
5
+ import { dim, workspaceName } from "./reporter.mjs";
6
+
4
7
  const IGNORED_SEGMENTS = new Set(["node_modules", "coverage", ".git"]);
5
8
 
6
9
  function isIgnored(relPath) {
@@ -12,7 +15,7 @@ function matchWorkspace(relPath, workspaces) {
12
15
  return workspaces.find((wsPath) => normalized === wsPath || normalized.startsWith(`${wsPath}/`));
13
16
  }
14
17
 
15
- export function watchWorkspaces({ root, workspaces, onChange, debounceMs = 300, isSuppressed = () => false }) {
18
+ function watchWorkspaces({ root, workspaces, onChange, debounceMs = 300, isSuppressed = () => false }) {
16
19
  const pending = new Set();
17
20
  let timer = null;
18
21
 
@@ -42,3 +45,54 @@ export function watchWorkspaces({ root, workspaces, onChange, debounceMs = 300,
42
45
  }
43
46
  };
44
47
  }
48
+
49
+ // A run can write files inside its own workspace (coverage, artifacts) just after it
50
+ // exits; ignoring them briefly stops the workspace from re-triggering itself forever.
51
+ const SETTLE_COOLDOWN_MS = 500;
52
+
53
+ // Runs `rerun` on each change, for the changed workspaces and their dependents,
54
+ // until SIGINT/SIGTERM.
55
+ export function watchAndRerun({ root, allPaths, workspaces, rerun }) {
56
+ const dependentsGraph = buildDependentsGraph(root, allPaths);
57
+ const byPath = new Map(workspaces.map((workspace) => [workspace.path, workspace]));
58
+ const settling = new Set();
59
+
60
+ async function onChange(changedPaths) {
61
+ const affected = [...expandWithDependents(changedPaths, dependentsGraph)]
62
+ .map((wsPath) => byPath.get(wsPath))
63
+ .filter(Boolean);
64
+ if (affected.length === 0) {
65
+ return;
66
+ }
67
+
68
+ const changedNames = [...changedPaths].map(workspaceName).join(", ");
69
+ const affectedNames = affected.map((workspace) => workspace.name).join(", ");
70
+ console.log(dim(`\n[watch] change detected in ${changedNames} → re-running: ${affectedNames}\n`));
71
+
72
+ for (const workspace of affected) {
73
+ settling.add(workspace.path);
74
+ }
75
+ try {
76
+ await rerun(affected);
77
+ }
78
+ finally {
79
+ setTimeout(() => {
80
+ for (const workspace of affected) {
81
+ settling.delete(workspace.path);
82
+ }
83
+ }, SETTLE_COOLDOWN_MS).unref();
84
+ }
85
+ }
86
+
87
+ const watcher = watchWorkspaces({ root, workspaces: allPaths, isSuppressed: (wsPath) => settling.has(wsPath), onChange });
88
+
89
+ return new Promise((resolve) => {
90
+ const stop = () => {
91
+ console.log(dim("\n[watch] stopping.\n"));
92
+ watcher.close();
93
+ resolve();
94
+ };
95
+ process.once("SIGINT", stop);
96
+ process.once("SIGTERM", stop);
97
+ });
98
+ }
@@ -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
+ wsPath: workspace.path,
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 { workspaceName } from "./reporter.mjs";
7
+ import { runner } from "./runner.mjs";
8
+ import { NoWorkspacesError, InvalidPackageJsonError, RootPackageJsonError } from "./errors.mjs";
9
+
10
+ function readJson(file) {
11
+ return JSON.parse(readFileSync(file, "utf8"));
12
+ }
13
+
14
+ // npm's interpretation of "workspaces": directory globs, "!" entries excluded.
15
+ function splitWorkspacePatterns(entries) {
16
+ const patterns = [];
17
+ const ignore = ["**/node_modules/**"];
18
+
19
+ for (const entry of entries) {
20
+ if (entry.startsWith("!")) {
21
+ ignore.push(entry.slice(1));
22
+ }
23
+ else {
24
+ patterns.push(entry.endsWith("/") ? entry : `${entry}/`);
25
+ }
26
+ }
27
+
28
+ return { patterns, ignore };
29
+ }
30
+
31
+ export async function resolveWorkspacePaths(root) {
32
+ let rootPkg;
33
+ try {
34
+ rootPkg = readJson(path.join(root, "package.json"));
35
+ }
36
+ catch (error) {
37
+ throw new RootPackageJsonError(root, error);
38
+ }
39
+
40
+ if (!rootPkg.workspaces || rootPkg.workspaces.length === 0) {
41
+ throw new NoWorkspacesError();
42
+ }
43
+
44
+ const { patterns, ignore } = splitWorkspacePatterns(rootPkg.workspaces);
45
+ const resolved = new Set();
46
+
47
+ for (const pattern of patterns) {
48
+ // posix: "/" separators on Windows too, like git and fs.watch.
49
+ const matches = await glob(pattern, { cwd: root, ignore, posix: true });
50
+
51
+ for (const match of matches.sort((a, b) => a.localeCompare(b, "en"))) {
52
+ resolved.add(match);
53
+ }
54
+ }
55
+
56
+ return [...resolved];
57
+ }
58
+
59
+ // pre/post hooks run like npm run does, around the main script.
60
+ function scriptPhases(scripts, scriptName) {
61
+ return [
62
+ { event: `pre${scriptName}`, command: scripts[`pre${scriptName}`] },
63
+ { event: scriptName, command: scripts[scriptName], isMain: true },
64
+ { event: `post${scriptName}`, command: scripts[`post${scriptName}`] }
65
+ ].filter((phase) => phase.command);
66
+ }
67
+
68
+ function loadWorkspace(root, wsPath, scriptName) {
69
+ let pkg;
70
+ try {
71
+ pkg = readJson(path.join(root, wsPath, "package.json"));
72
+ }
73
+ catch (error) {
74
+ return error.code === "ENOENT" ? { kind: "absent" } : { kind: "invalid", message: error.message };
75
+ }
76
+
77
+ if (!pkg.scripts?.[scriptName]) {
78
+ return { kind: "absent" };
79
+ }
80
+
81
+ const phases = scriptPhases(pkg.scripts, scriptName);
82
+ if (phases.some((phase) => runner.hasOwnReporter(phase.command))) {
83
+ return { kind: "ownReporterConflict" };
84
+ }
85
+
86
+ return { kind: "runnable", workspace: { path: wsPath, name: workspaceName(wsPath), pkg, phases } };
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(wsPath);
101
+ }
102
+ else if (loaded.kind === "invalid") {
103
+ invalid.push({ wsPath, message: loaded.message });
104
+ }
105
+ }
106
+
107
+ if (invalid.length > 0) {
108
+ throw new InvalidPackageJsonError(invalid);
109
+ }
110
+
111
+ return { runnable, ownReporterConflicts };
112
+ }