@jskit-ai/jskit-catalog 0.2.126 → 0.2.127

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,135 @@
1
+ // Preloaded (`--import`) by `jskit test` into every process of its node --test runs. In a test file's own process
2
+ // (node --test starts one per file, with NODE_TEST_CONTEXT set), it stops the file at the time `jskit test` gave it
3
+ // (fileStop in time-report.mjs): a file that never finishes, because a test has no timeout or a server, child
4
+ // process, timer or socket was left open, then fails by name and the rest of the run still finishes and reports. It
5
+ // also stops a file whose tests have all ended but whose process is still running `lingerMs` after its last test (the
6
+ // linger bound): something its tests left open, an interval, a server, a socket or a child process, keeps it alive.
7
+ // Before it stops one, it says what is still open, from process.getActiveResourcesInfo() read in that process, or
8
+ // that nothing is: then the process was still busy when its stop got a turn. The runner's own process, worker threads
9
+ // and the processes a test starts do nothing.
10
+ import { fstatSync, readFileSync, writeFileSync } from "node:fs";
11
+ import path from "node:path";
12
+ import process from "node:process";
13
+ import { isatty } from "node:tty";
14
+ import { pathToFileURL } from "node:url";
15
+ import { isMainThread } from "node:worker_threads";
16
+
17
+ const STOPS_VARIABLE = "JSKIT_TEST_FILE_STOPS";
18
+ const STOPPED_PREFIX = "stopped-";
19
+ const LINGERED_PREFIX = "lingered-";
20
+ const EXITED_PREFIX = "exited-";
21
+
22
+ /** The handle a stdio stream on `fd` is, as process.getActiveResourcesInfo() names it, if any. */
23
+ function stdioHandle(fd) {
24
+ if (isatty(fd)) return "TTYWrap";
25
+ const stat = fstatSync(fd);
26
+ return stat.isFIFO() || stat.isSocket() ? "PipeWrap" : null;
27
+ }
28
+
29
+ /**
30
+ * What keeps this process running: process.getActiveResourcesInfo(), less the process's own stdout and stderr, and
31
+ * its stdin unless something reads it. Each stream is made at its first use (an `import` of node:process makes all
32
+ * three), so all are made before counting: then each is one handle, listed whether or not it keeps the process alive.
33
+ */
34
+ function heldOpen() {
35
+ const { stdin } = process;
36
+ const reading = stdin.readableFlowing === true || stdin.listenerCount("readable") > 0;
37
+ const own = [process.stdout, process.stderr, ...(reading ? [] : [stdin])].map((stream) => stdioHandle(stream.fd));
38
+ const resources = process.getActiveResourcesInfo();
39
+ for (const name of own) {
40
+ const at = name ? resources.indexOf(name) : -1;
41
+ if (at >= 0) resources.splice(at, 1);
42
+ }
43
+ return resources;
44
+ }
45
+
46
+ /**
47
+ * What held a process open past its last test, or that nothing did: then it was still working when its stop got a turn.
48
+ * @param {string[]} resources
49
+ */
50
+ function describeHold(resources) {
51
+ return resources.length > 0
52
+ ? `held open by: ${resources.join(", ")}`
53
+ : "busy, not held open: process.getActiveResourcesInfo() lists nothing";
54
+ }
55
+
56
+ const stopsFile = process.env[STOPS_VARIABLE];
57
+ const runsTestFiles = process.execArgv.some((argument) => argument === "--test" || argument.startsWith("--test="));
58
+ if (stopsFile && isMainThread && process.env.NODE_TEST_CONTEXT && !runsTestFiles) {
59
+ // A process this file starts is not one of the run's files.
60
+ delete process.env[STOPS_VARIABLE];
61
+ const entry = path.resolve(process.argv[1] || "");
62
+ const stop = JSON.parse(readFileSync(stopsFile, "utf8"))[entry];
63
+ if (stop) {
64
+ const { lingerMs, ...hang } = stop;
65
+ // Taken now, so a test that fakes timers or stubs process.exit does not change how its file is stopped.
66
+ const { clearTimeout: stopTimer, setTimeout: startTimer } = globalThis;
67
+ const { exit } = process;
68
+ const record = (prefix, value) =>
69
+ writeFileSync(path.join(path.dirname(stopsFile), `${prefix}${process.pid}.json`), JSON.stringify(value));
70
+ const started = performance.now();
71
+ // node:test has run the root's after() hooks; then the file's module had finished loading too.
72
+ let testsEnded = false;
73
+ let loaded = false;
74
+ // Tests running that started after the root's after() hooks: those a file declares after a top-level await.
75
+ let late = 0;
76
+ // When the linger bound last started, and its timer.
77
+ let ended = null;
78
+ let lingering;
79
+ let stopping = false;
80
+ const lingered = () => {
81
+ stopping = true;
82
+ const value = { file: hang.file, ms: Math.round(performance.now() - ended), resources: heldOpen() };
83
+ record(LINGERED_PREFIX, value);
84
+ writeFileSync(2, `\njskit test: stopped ${value.file} ${(value.ms / 1000).toFixed(1)} s after its last test, ` +
85
+ `${describeHold(value.resources)}.\n`);
86
+ exit.call(process, 1);
87
+ };
88
+ const settle = () => {
89
+ if (!loaded || late > 0) return;
90
+ stopTimer(lingering);
91
+ ended = performance.now();
92
+ // Unreferenced, as the stop below: a file that ends exits as it would have. One still busy past the bound with
93
+ // nothing open either ends before this runs, and the run's report fails it from its exit record below, or
94
+ // takes another turn and meets this late, with nothing to name.
95
+ lingering = startTimer(lingered, lingerMs).unref();
96
+ };
97
+ startTimer(() => {
98
+ // A file whose tests have all ended is lingering, however soon its stop came.
99
+ if (ended !== null && late === 0) return lingered();
100
+ stopping = true;
101
+ const stopped = { ...hang, ms: Math.round(performance.now() - started) };
102
+ record(STOPPED_PREFIX, stopped);
103
+ writeFileSync(2, `\njskit test: stopped ${stopped.file} after ${(stopped.ms / 1000).toFixed(1)} s, ${stopped.reason}.\n`);
104
+ exit.call(process, 1);
105
+ }, hang.ms).unref();
106
+ const nodeTest = await import("node:test");
107
+ // node:test runs the root's after() hooks, this one first, as soon as the file's last test so far has ended. A
108
+ // test declared after a top-level await comes later still, so the bound starts once the file's module has also
109
+ // finished loading, when its import settles; a test that starts after that holds the bound until it ends.
110
+ nodeTest.after(() => {
111
+ testsEnded = true;
112
+ const loading = () => {
113
+ loaded = true;
114
+ settle();
115
+ };
116
+ import(pathToFileURL(entry).href).then(loading, loading);
117
+ });
118
+ nodeTest.beforeEach(() => {
119
+ if (!testsEnded) return;
120
+ late += 1;
121
+ stopTimer(lingering);
122
+ });
123
+ nodeTest.afterEach(() => {
124
+ if (!testsEnded) return;
125
+ late = Math.max(0, late - 1);
126
+ settle();
127
+ });
128
+ // How long after its last test the file's process ended, for the run's report.
129
+ process.once("exit", () => {
130
+ if (ended !== null && !stopping) record(EXITED_PREFIX, { file: hang.file, ms: Math.round(performance.now() - ended) });
131
+ });
132
+ }
133
+ }
134
+
135
+ export { EXITED_PREFIX, LINGERED_PREFIX, STOPPED_PREFIX, STOPS_VARIABLE, describeHold };
@@ -1,5 +1,5 @@
1
1
  // Preloaded through NODE_OPTIONS (`--import`) into every process `jskit test` and the browser test servers start, and
2
- // so into the processes those start with the same environment: guards its outbound connections (test-network-guard.mjs).
3
- import { installNetworkGuard } from "./test-network-guard.mjs";
2
+ // so into the processes those start with the same environment: guards its outbound connections (network-guard.mjs).
3
+ import { installNetworkGuard } from "./network-guard.mjs";
4
4
 
5
5
  installNetworkGuard();
@@ -1,6 +1,6 @@
1
1
  // The test network guard: a test, and every app server and process it starts, reaches only this machine and the test
2
2
  // database. `jskit test` and the browser test servers give their processes NODE_OPTIONS with the guard's preload
3
- // (test-network-guard-preload.mjs), so a process those start with the same environment is guarded too. Every outbound
3
+ // (network-guard-preload.mjs), so a process those start with the same environment is guarded too. Every outbound
4
4
  // TCP connection a guarded Node process makes passes through net.Socket.prototype.connect (net.connect, tls.connect,
5
5
  // http and https agents, fetch); the guard lets through loopback addresses, `localhost` names, unix sockets and named
6
6
  // pipes, and the database host the environment names (DB_HOST, DATABASE_URL's host, read when the connection is made),
@@ -9,14 +9,14 @@
9
9
  // it. A test that reaches a real outside service (an AI provider, a payment or mail API, a hosting API) costs money,
10
10
  // sends real messages or changes real data whenever a developer's keys sit in the environment the test inherits. A file
11
11
  // that must reach one says why on its first line, `// jskit-test: network - <reason>`, and `jskit test` runs it
12
- // without the guard (test-command.mjs).
12
+ // without the guard (command.mjs).
13
13
  import net from "node:net";
14
14
  import process from "node:process";
15
15
 
16
16
  const NETWORK_REFUSED_CODE = "JSKIT_TEST_NETWORK_REFUSED";
17
17
  // Names the command whose processes are guarded, for the refusal: `jskit test` or `jskit browser tests`.
18
18
  const NETWORK_GUARD_VARIABLE = "JSKIT_TEST_NETWORK_GUARD";
19
- const NETWORK_GUARD_PRELOAD = new URL("./test-network-guard-preload.mjs", import.meta.url).href;
19
+ const NETWORK_GUARD_PRELOAD = new URL("./network-guard-preload.mjs", import.meta.url).href;
20
20
  const PRELOAD_OPTION = `--import=${NETWORK_GUARD_PRELOAD}`;
21
21
  const INSTALLED = Symbol.for("@jskit-ai/jskit-catalog/testNetworkGuard");
22
22
  const BROWSER_TESTS = "jskit browser tests";
@@ -1,6 +1,6 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { fileExists, toPosixPath } from "./files.mjs";
3
+ import { fileExists, toPosixPath } from "../files.mjs";
4
4
 
5
5
  // The test-run part of plain `jskit check`: every test run uses the machine's test budget, so a suite neither runs one
6
6
  // file at a time nor overwhelms the machine. A package script runs node's test runner through `jskit test`, passes no
@@ -1,15 +1,15 @@
1
1
  import { readdir, readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { fileExists } from "./files.mjs";
4
- import { formatSkipped, lintSkipped } from "./lint-ignores.mjs";
5
- import { DEFAULT_PATTERN, findTestFiles } from "./test-command.mjs";
6
- import { excusedWait, scanSource } from "./test-sources-scan.mjs";
3
+ import { fileExists } from "../files.mjs";
4
+ import { formatSkipped, lintSkipped } from "../lint-ignores.mjs";
5
+ import { defaultTestFiles, findTestFiles, missedTestFiles } from "./command.mjs";
6
+ import { excusedWait, scanSource } from "./sources-scan.mjs";
7
7
 
8
8
  // The test-source part of plain `jskit check`: what an app's tests, test scripts, CI workflows and Vite config hold that
9
9
  // makes a run slow, fragile or unsafe, each found by its shape:
10
10
  // - test/fixed-sleep: a test file waits a fixed time instead of for its condition. A timer racing another wait in
11
11
  // `Promise.race([...])` bounds that wait, and a wait in a loop that re-reads its condition each round is a poll's
12
- // interval: neither is reported (test-sources-scan.mjs). The fixed waits a test needs, a window that proves nothing
12
+ // interval: neither is reported (sources-scan.mjs). The fixed waits a test needs, a window that proves nothing
13
13
  // happens (no second read within it) or the latency a stand-in simulates, say so on the line before:
14
14
  // `// jskit-test: fixed-wait - <what the window proves, or the latency the stand-in simulates>`; a marker without a
15
15
  // reason is a finding itself.
@@ -18,9 +18,11 @@ import { excusedWait, scanSource } from "./test-sources-scan.mjs";
18
18
  // or its host names it, `jskit test --databases` gives each file its own copy, and browserTestConfig()'s prepare module
19
19
  // derives each browser worker's. A name in a thrown error's message text names no database.
20
20
  // - test/test-database-is-app-database: a CI workflow gives TEST_DB_NAME or BROWSER_TEST_DB_NAME the value of its DB_NAME.
21
- // - test/script-files: a script gives `jskit test` the files node's default pattern selects anyway, so `npm test --
22
- // <file>` runs every file and that one. A script that runs some of them, or files the pattern leaves out, names them
23
- // for a reason.
21
+ // - test/script-files: a script gives `jskit test` the files it takes given none anyway (node's default pattern, less
22
+ // the helpers and fixtures it sets apart), so `npm test -- <file>` runs every file and that one. While a tests/ file
23
+ // named as a test is one the pattern leaves out (x.integration.js), which jskit test given no files refuses, the
24
+ // finding names it to rename first. A script that runs some of them, or files the pattern leaves out (x.bench.js),
25
+ // names them for a reason.
24
26
  // - test/generated-into-src: the app's Vite config writes a generated file (`dts`) into src, which the browser tests'
25
27
  // frontend build reads, so a build is never kept for reuse.
26
28
  // No other comment excuses them. Like the data part, it reads none of what the app's ESLint config ignores outside server
@@ -173,8 +175,9 @@ function jskitTestFiles(script) {
173
175
  }
174
176
 
175
177
  /**
176
- * Whether the files a script names are the ones `jskit test` runs given none: node's default pattern. A glob or folder
177
- * that matches no file leaves `jskit test` with the default's files too.
178
+ * Whether the files a script names are the ones `jskit test` runs given none: node's default pattern, less the helpers
179
+ * and fixtures it sets apart (defaultTestFiles). A glob or folder that matches no file leaves `jskit test` with the
180
+ * default's files too.
178
181
  */
179
182
  function selectsDefaultFiles(directory, files, defaults) {
180
183
  const named = findTestFiles(files, directory);
@@ -191,15 +194,23 @@ function checkScripts(root, file, contents, report) {
191
194
  }
192
195
  const directory = path.join(root, path.posix.dirname(file));
193
196
  let defaultFiles;
194
- const defaults = () => (defaultFiles ??= findTestFiles([DEFAULT_PATTERN], directory));
197
+ const defaults = () => (defaultFiles ??= defaultTestFiles(directory));
195
198
  for (const [name, script] of Object.entries(manifest?.scripts || {})) {
196
199
  const line = lineOf(contents, `"${name}"`, '"scripts"');
197
200
  const files = jskitTestFiles(script);
198
201
  if (files.length > 0 && selectsDefaultFiles(directory, files, defaults)) {
199
202
  const run = name === "test" ? "npm test" : `npm run ${name}`;
203
+ // Given no files, jskit test refuses while a tests/ file named as a test is one the pattern leaves out: the list
204
+ // goes once those files are renamed, which the finding says first.
205
+ const missed = missedTestFiles(defaults(), directory);
200
206
  report({ file, line, rule: "test/script-files",
201
- message: `${file}'s ${name} script names ${files.join(" ")}: drop ${files.length > 1 ? "them" : "it"}. \`jskit test\` finds ` +
202
- `test files by node's default pattern, so \`${run} -- <file>\` runs exactly that file.` });
207
+ message: missed.length > 0
208
+ ? `${file}'s ${name} script names ${files.join(" ")}, the files \`jskit test\` takes given none, but given none it ` +
209
+ "refuses to run while these test files under tests/ end in no .test.js, so node's default pattern leaves them " +
210
+ `out: ${missed.join(", ")}. Rename each to end in .test.js (a database test: <name>.integration.test.js), then ` +
211
+ `drop ${files.join(" ")}, so \`${run} -- <file>\` runs exactly that file.`
212
+ : `${file}'s ${name} script names ${files.join(" ")}: drop ${files.length > 1 ? "them" : "it"}. \`jskit test\` ` +
213
+ `finds test files by node's default pattern, so \`${run} -- <file>\` runs exactly that file.` });
203
214
  }
204
215
  if (!TEST_SCRIPT_NAME.test(name) && !TEST_COMMAND.test(String(script))) continue;
205
216
  for (const token of String(script).split(/\s+/u).map((part) => part.replace(/^['"(]+|['");]+$/gu, ""))) {
@@ -0,0 +1,245 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import process from "node:process";
4
+ import { toPosixPath } from "../files.mjs";
5
+ import { EXITED_PREFIX, LINGERED_PREFIX, STOPPED_PREFIX, describeHold } from "./file-stop.mjs";
6
+
7
+ // How long `jskit test` took, file by file. The node --test reporter below runs beside a run's own reporters and writes
8
+ // the run's file and top-level test durations to the file `jskit test` names. After its last run, `jskit test` lists the
9
+ // ten slowest files and tests, records each file's time in node_modules/.cache/jskit-test/file-times.json, and fails
10
+ // when a file or the whole command went past a coarse bound that only a clearly broken suite reaches: a file waiting
11
+ // out its timeouts, a suite that would run for hours. An application whose measured suite needs more writes its own
12
+ // bounds in test-time-bounds.json, `{ "runMs": ..., "fileMs": ..., "lingerMs": ..., "files": { "<path>": ... } }`, with
13
+ // the measurement. A file that has not finished by a generous multiple of its time is stopped while it runs
14
+ // (file-stop.mjs), so one file that never ends fails by name instead of holding up the whole run until a runner's
15
+ // own ceiling ends it; so is a file still running `lingerMs` after its last test, naming what keeps it running, and a
16
+ // file still busy then that ends by itself before its stop gets a turn fails the run too. So does a file the run took
17
+ // as a test file that declares no tests, a helper or fixture outside the folders `jskit test` sets apart.
18
+ const SHOWN = 10;
19
+ // Stops a file at twice its bound (at least two seconds, well past any file's start-up), or at ten times its recorded
20
+ // time (at least two minutes, more than a cold compile cache or a loaded machine needs), whichever comes first. A file
21
+ // with its own bound in test-time-bounds.json is stopped at twice that bound.
22
+ const STOP_BOUND_TIMES = 2;
23
+ const STOP_BOUND_MIN_MS = 2000;
24
+ const STOP_RECORDED_TIMES = 10;
25
+ const STOP_RECORDED_MIN_MS = 2 * 60_000;
26
+ const BOUNDS_FILE = "test-time-bounds.json";
27
+ // The linger bound: a file's process ends within moments of its last test and its after hooks, so one still running
28
+ // LINGER_MS later has something open that its tests left running, or is still working. Measured on the office test
29
+ // host (27 Nov 2026, every JSKIT workspace's suite, 1221 files three at a time, load 4-12): the longest any suite's
30
+ // file lived after its last test was 2.0 s (oidc-issuer-core's backchannel.test.js, whose test leaves a 2 s race timer
31
+ // running), then 1.0 s (realtime's providerRuntime.test.js, a 1 s one), 0.2 s in six suites and 0.1 s or less in the
32
+ // other 42.
33
+ const LINGER_MS = 10_000;
34
+ // What a file past the linger bound is told to do: close what its tests left open, or finish the work it still does.
35
+ const CLOSE_WHAT_IS_OPEN = "Close what its tests leave open (an interval, a server, a socket, a child process) in the test or an after hook.";
36
+ const FINISH_THE_WORK = "Find the work it still does after its last test (an after hook, or work a test started without waiting for " +
37
+ "it) and finish it within the tests.";
38
+ const DEFAULT_BOUNDS = Object.freeze({ runMs: 45 * 60_000, fileMs: 10 * 60_000, lingerMs: LINGER_MS, files: Object.freeze({}) });
39
+ const FILE_TIMES = path.join("node_modules", ".cache", "jskit-test", "file-times.json");
40
+
41
+ const seconds = (ms) => (ms >= 60_000 ? `${(ms / 60_000).toFixed(1)} min` : `${(ms / 1000).toFixed(1)} s`);
42
+
43
+ /** @param {AsyncIterable<{ type: string, data: any }>} source node --test's events */
44
+ export default async function* collectTestTimes(source) {
45
+ yield* testTimesOf(source, process.cwd());
46
+ }
47
+
48
+ /**
49
+ * What collectTestTimes writes, for events of files whose paths are relative to `cwd`: the run's directory, which is
50
+ * not this process's in jskit test's pool.
51
+ * @param {AsyncIterable<{ type: string, data: any }>} source
52
+ * @param {string} cwd
53
+ */
54
+ async function* testTimesOf(source, cwd) {
55
+ const relative = (file) => toPosixPath(path.relative(cwd, file));
56
+ const files = {};
57
+ const tests = [];
58
+ // Files that skipped a test: their time says little about how long they take when every test runs.
59
+ const skipped = new Set();
60
+ // Files that passed declaring neither a test nor a suite.
61
+ const empty = new Set();
62
+ for await (const event of source) {
63
+ if (event.type === "test:summary" && event.data.file) {
64
+ files[relative(event.data.file)] = event.data.duration_ms;
65
+ const { counts } = event.data;
66
+ if (event.data.success && counts?.tests === 0 && counts.suites === 0) empty.add(relative(event.data.file));
67
+ } else if ((event.type === "test:pass" || event.type === "test:fail") && event.data.file) {
68
+ if (event.data.skip != null && event.data.skip !== false) skipped.add(relative(event.data.file));
69
+ if (event.data.nesting === 0) {
70
+ tests.push({ file: relative(event.data.file), name: event.data.name, ms: event.data.details?.duration_ms ?? 0 });
71
+ }
72
+ }
73
+ }
74
+ yield `${JSON.stringify({ files, tests, skipped: [...skipped], empty: [...empty] })}\n`;
75
+ }
76
+
77
+ /** Each file's last recorded time in `cwd`, in milliseconds by its path relative to `cwd`; none before a first run. */
78
+ function readRecordedTimes(cwd) {
79
+ const record = path.join(cwd, FILE_TIMES);
80
+ return existsSync(record) ? JSON.parse(readFileSync(record, "utf8")) : {};
81
+ }
82
+
83
+ /** The application's bounds over JSKIT's defaults; each must be a positive number of milliseconds. */
84
+ function readTestTimeBounds(cwd) {
85
+ const file = path.join(cwd, BOUNDS_FILE);
86
+ if (!existsSync(file)) return DEFAULT_BOUNDS;
87
+ const own = JSON.parse(readFileSync(file, "utf8"));
88
+ const bounds = { ...DEFAULT_BOUNDS, ...own, files: { ...own.files } };
89
+ for (const [name, ms] of [["runMs", bounds.runMs], ["fileMs", bounds.fileMs], ["lingerMs", bounds.lingerMs],
90
+ ...Object.entries(bounds.files)]) {
91
+ if (!(Number.isFinite(ms) && ms > 0)) throw new Error(`${BOUNDS_FILE}: ${name} must be a positive number of milliseconds.`);
92
+ }
93
+ return bounds;
94
+ }
95
+
96
+ /**
97
+ * When a file still running is stopped, and why: twice its bound, or ten times its recorded time when that comes first.
98
+ * @param {{ bound: number, recorded?: number }} times milliseconds; `recorded` is the file's last time, if any
99
+ * @returns {{ ms: number, reason: string }}
100
+ */
101
+ function fileStop({ bound, recorded }) {
102
+ const byBound = Math.max(STOP_BOUND_MIN_MS, STOP_BOUND_TIMES * bound);
103
+ const byRecorded = recorded > 0 ? Math.max(STOP_RECORDED_MIN_MS, STOP_RECORDED_TIMES * recorded) : Infinity;
104
+ return byRecorded < byBound
105
+ ? { ms: byRecorded, reason: `past ten times its last time of ${seconds(recorded)}` }
106
+ : { ms: byBound, reason: `past twice its ${seconds(bound)} bound` };
107
+ }
108
+
109
+ /**
110
+ * Writes when each of the run's files is stopped, keyed by its absolute path, for file-stop.mjs, and how long
111
+ * after its last test (`lingerMs`, the same for every file); returns the file.
112
+ * @param {{ cwd: string, files: string[], directory: string }} options `files`: the run's test files, relative to cwd
113
+ */
114
+ function writeFileStops({ cwd, files, directory }) {
115
+ const bounds = readTestTimeBounds(cwd);
116
+ const recorded = readRecordedTimes(cwd);
117
+ const stops = Object.fromEntries(files.map((file) => [
118
+ path.resolve(cwd, file),
119
+ // A file's own bound is the application's measured statement of its time, so it alone sets the stop.
120
+ {
121
+ file,
122
+ ...fileStop(file in bounds.files ? { bound: bounds.files[file] } : { bound: bounds.fileMs, recorded: recorded[file] }),
123
+ lingerMs: bounds.lingerMs
124
+ }
125
+ ]));
126
+ const stopsFile = path.join(directory, "file-stops.json");
127
+ writeFileSync(stopsFile, JSON.stringify(stops));
128
+ return stopsFile;
129
+ }
130
+
131
+ /**
132
+ * The slowest files and tests of a `jskit test` command against its bounds, the bounds it went past, and the files it
133
+ * took that declare no tests.
134
+ * @param {{ bounds: { runMs: number, fileMs: number, lingerMs?: number, files: Record<string, number> },
135
+ * files: Record<string, number>, tests: Array<{ file: string, name: string, ms: number }>, wallMs: number,
136
+ * stopped?: Array<{ file: string, ms: number, reason: string }>,
137
+ * lingered?: Array<{ file: string, ms: number, resources: string[] }>,
138
+ * exited?: Array<{ file: string, ms: number }>, empty?: string[] }} times `stopped`: the files stopped while running;
139
+ * `lingered`: those stopped after their last test, with what was still open; `exited`: how long after its last test
140
+ * each other file's process ended, failing one past `lingerMs`, which was still busy then with nothing holding it
141
+ * open; `empty`: the files that passed declaring no tests, which fail too
142
+ */
143
+ function checkTestTimes({ bounds, files, tests, wallMs, stopped = [], lingered = [], exited = [], empty = [] }) {
144
+ const rows = Object.entries(files).map(([name, ms]) => ({ name, ms, bound: bounds.files[name] ?? bounds.fileMs }));
145
+ const ended = new Set([...stopped, ...lingered].map((stop) => stop.file));
146
+ const lingerMs = bounds.lingerMs ?? LINGER_MS;
147
+ const overruns = [
148
+ ...stopped.map((stop) => `${stop.file} was stopped after ${seconds(stop.ms)}, ${stop.reason}: it did not finish.`),
149
+ ...lingered.map((stop) => `${stop.file} outlived its last test by ${seconds(stop.ms)} and was stopped, ` +
150
+ `${describeHold(stop.resources)}. ${stop.resources.length > 0 ? CLOSE_WHAT_IS_OPEN : FINISH_THE_WORK}`),
151
+ // Its stop never got a turn: the process was still working when the bound passed, then ended with nothing open.
152
+ ...exited.filter((exit) => exit.ms > lingerMs).map((exit) => `${exit.file} ended ${seconds(exit.ms)} after its last ` +
153
+ `test, past its ${seconds(lingerMs)} linger bound: busy, not held open. ${FINISH_THE_WORK}`),
154
+ ...rows.filter((row) => row.ms > row.bound && !ended.has(row.name))
155
+ .map((row) => `${row.name} took ${seconds(row.ms)}, past its ${seconds(row.bound)} bound.`)
156
+ ];
157
+ if (wallMs > bounds.runMs) overruns.push(`The run took ${seconds(wallMs)}, past its ${seconds(bounds.runMs)} bound.`);
158
+ const lines = [
159
+ `jskit test: ${rows.length} test file(s) in ${seconds(wallMs)} (bound ${seconds(bounds.runMs)}); the slowest, time / bound:`,
160
+ ...rows.sort((a, b) => b.ms - a.ms).slice(0, SHOWN).map((row) => ` ${seconds(row.ms)} / ${seconds(row.bound)} ${row.name}`),
161
+ "jskit test: the slowest tests:",
162
+ ...[...tests].sort((a, b) => b.ms - a.ms).slice(0, SHOWN)
163
+ .map((entry) => ` ${seconds(entry.ms)} ${entry.file}: ${entry.name.slice(0, 120)}`)
164
+ ];
165
+ const longest = [...exited].sort((a, b) => b.ms - a.ms)[0];
166
+ if (longest) {
167
+ lines.push(`jskit test: the longest a file's process lived after its last test, time / bound: ` +
168
+ `${seconds(longest.ms)} / ${seconds(lingerMs)} ${longest.file}`);
169
+ }
170
+ if (empty.length > 0) {
171
+ lines.push(
172
+ `jskit test: ${empty.length} file(s) it takes as test files declare no tests: move each under a support/ or ` +
173
+ "fixtures/ folder, named as no test file is (test.js, test-*, *.test.*, *_test.*, *-test.*), or give it its tests.",
174
+ ...empty.map((file) => ` ${file}`)
175
+ );
176
+ }
177
+ if (overruns.length > 0) {
178
+ lines.push(
179
+ "jskit test: past a time bound, so something is clearly broken:",
180
+ ...overruns.map((overrun) => ` ${overrun}`),
181
+ `Find what got slow and fix it; raise a bound in ${BOUNDS_FILE} only when the work itself grew, with the measurement.`
182
+ );
183
+ }
184
+ return { overruns, empty, report: `${lines.join("\n")}\n` };
185
+ }
186
+
187
+ /**
188
+ * Reads what the runs' reporters wrote, which files file-stop.mjs stopped and how long after its last test each
189
+ * other file's process ended, and records each finished file's time for the next command (a stopped file, one that
190
+ * skipped a test, and every file of a run filtered to some of its tests keep the time they last finished all their
191
+ * tests in, since the next stop is reckoned from it). A run whose reporters were replaced (inside another node --test
192
+ * run) wrote nothing, and has no times unless a file was stopped.
193
+ * @param {{ cwd: string, collected: string[], directory: string, filtered?: boolean }} options
194
+ * `collected`: the reporters' destination files; `directory`: where the stopped files are written; `filtered`: the run
195
+ * ran only the tests a name pattern or `only` picked, so a file whose tests it left out declares none it ran
196
+ * @returns {{ files: Record<string, number>, tests: Array<{ file: string, name: string, ms: number }>,
197
+ * stopped: Array<{ file: string, ms: number, reason: string }>,
198
+ * lingered: Array<{ file: string, ms: number, resources: string[] }>, exited: Array<{ file: string, ms: number }>,
199
+ * empty: string[] } | null} `empty`: the files that passed declaring no test
200
+ */
201
+ function recordTestTimes({ cwd, collected, directory, filtered = false }) {
202
+ const runs = collected.filter((file) => existsSync(file) && readFileSync(file, "utf8").trim())
203
+ .map((file) => JSON.parse(readFileSync(file, "utf8")));
204
+ const written = readdirSync(directory).sort();
205
+ const read = (prefix) => written.filter((name) => name.startsWith(prefix))
206
+ .map((name) => JSON.parse(readFileSync(path.join(directory, name), "utf8")));
207
+ const stopped = read(STOPPED_PREFIX);
208
+ const lingered = read(LINGERED_PREFIX);
209
+ const files = Object.assign({}, ...runs.map((run) => run.files));
210
+ if (Object.keys(files).length === 0 && stopped.length === 0 && lingered.length === 0) return null;
211
+ const unrepresentative = new Set([...stopped, ...lingered].map((stop) => stop.file)
212
+ .concat(runs.flatMap((run) => run.skipped ?? [])));
213
+ const finished = filtered ? {} : Object.fromEntries(Object.entries(files).filter(([name]) => !unrepresentative.has(name)));
214
+ const record = path.join(cwd, FILE_TIMES);
215
+ const recorded = readRecordedTimes(cwd);
216
+ mkdirSync(path.dirname(record), { recursive: true });
217
+ // Written whole, then renamed, so a command beside this one never reads half a file.
218
+ writeFileSync(`${record}.${process.pid}`, `${JSON.stringify({ ...recorded, ...finished }, null, 2)}\n`);
219
+ renameSync(`${record}.${process.pid}`, record);
220
+ const empty = filtered ? [] : [...new Set(runs.flatMap((run) => run.empty ?? []))].sort();
221
+ return { files, tests: runs.flatMap((run) => run.tests), stopped, lingered, exited: read(EXITED_PREFIX), empty };
222
+ }
223
+
224
+ /**
225
+ * Records the run's times (recordTestTimes) and checks them against the bounds in `cwd`.
226
+ * @param {{ cwd: string, collected: string[], directory: string, wallMs: number, filtered?: boolean }} options
227
+ * @returns {{ overruns: string[], empty: string[], report: string } | null}
228
+ */
229
+ function reportTestTimes({ cwd, collected, directory, wallMs, filtered = false }) {
230
+ const times = recordTestTimes({ cwd, collected, directory, filtered });
231
+ return times && checkTestTimes({ bounds: readTestTimeBounds(cwd), ...times, wallMs });
232
+ }
233
+
234
+ export {
235
+ BOUNDS_FILE,
236
+ FILE_TIMES,
237
+ checkTestTimes,
238
+ fileStop,
239
+ readRecordedTimes,
240
+ readTestTimeBounds,
241
+ recordTestTimes,
242
+ reportTestTimes,
243
+ testTimesOf,
244
+ writeFileStops
245
+ };
@@ -10,7 +10,7 @@ import {
10
10
  } from "./pattern-assets.mjs";
11
11
  import { collectSingletonPackageIds, discoverFrameworkPackages } from "./framework-packages.mjs";
12
12
  import { discoverProjectManifests, readJsonRecord } from "./project-manifests.mjs";
13
- import { checkTestRuns, formatTestRunsReport } from "./test-runs.mjs";
13
+ import { checkTestRuns, formatTestRunsReport } from "./testing/runs.mjs";
14
14
 
15
15
  const SCRIPT_PATH = fileURLToPath(import.meta.url);
16
16
  const REPO_ROOT = path.resolve(path.dirname(SCRIPT_PATH), "../../..");
@@ -1,32 +0,0 @@
1
- // Preloaded (`--import`) by `jskit test` into every process of its node --test runs. In a test file's own process
2
- // (node --test starts one per file, with NODE_TEST_CONTEXT set), it stops the file at the time `jskit test` gave it
3
- // (fileStop in test-time-report.mjs): a file that never finishes, because a test has no timeout or a server, child
4
- // process, timer or socket was left open, then fails by name and the rest of the run still finishes and reports. The
5
- // runner's own process, worker threads and the processes a test starts do nothing.
6
- import { readFileSync, writeFileSync } from "node:fs";
7
- import path from "node:path";
8
- import process from "node:process";
9
- import { isMainThread } from "node:worker_threads";
10
-
11
- const STOPS_VARIABLE = "JSKIT_TEST_FILE_STOPS";
12
- const STOPPED_PREFIX = "stopped-";
13
-
14
- const stopsFile = process.env[STOPS_VARIABLE];
15
- const runsTestFiles = process.execArgv.some((argument) => argument === "--test" || argument.startsWith("--test="));
16
- if (stopsFile && isMainThread && process.env.NODE_TEST_CONTEXT && !runsTestFiles) {
17
- // A process this file starts is not one of the run's files.
18
- delete process.env[STOPS_VARIABLE];
19
- const stop = JSON.parse(readFileSync(stopsFile, "utf8"))[path.resolve(process.argv[1] || "")];
20
- if (stop) {
21
- const started = performance.now();
22
- // Unreferenced: a file that finishes exits as it would have.
23
- setTimeout(() => {
24
- const stopped = { ...stop, ms: Math.round(performance.now() - started) };
25
- writeFileSync(path.join(path.dirname(stopsFile), `${STOPPED_PREFIX}${process.pid}.json`), JSON.stringify(stopped));
26
- writeFileSync(2, `\njskit test: stopped ${stopped.file} after ${(stopped.ms / 1000).toFixed(1)} s, ${stopped.reason}.\n`);
27
- process.exit(1);
28
- }, stop.ms).unref();
29
- }
30
- }
31
-
32
- export { STOPPED_PREFIX, STOPS_VARIABLE };