@jskit-ai/jskit-catalog 0.2.126 → 0.2.128

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/jskit-catalog",
3
- "version": "0.2.126",
3
+ "version": "0.2.128",
4
4
  "description": "Published metadata catalog for JSKIT package metadata.",
5
5
  "type": "module",
6
6
  "files": [
@@ -16,7 +16,7 @@
16
16
  ".": "./catalog/packages.json",
17
17
  "./packages": "./catalog/packages.json",
18
18
  "./project-packages": "./scripts/project-packages.mjs",
19
- "./test-budget": "./scripts/test-budget.mjs",
19
+ "./test-budget": "./scripts/testing/budget.mjs",
20
20
  "./browser-tests": "./scripts/browser-tests.mjs",
21
21
  "./package.json": "./package.json"
22
22
  },
@@ -14,7 +14,7 @@
14
14
  // for one server a host starts, with `terminal`: that server's output also reaches the launcher's own. A run takes free
15
15
  // ports of its own, so its worker environments and signed-in states have names of their own; the launcher removes them
16
16
  // when it stops, so they never pile up in the cache, nor outlive the sessions they hold. Each app server, and what it
17
- // starts, reaches only this machine and the test database (test-network-guard.mjs).
17
+ // starts, reaches only this machine and the test database (testing/network-guard.mjs).
18
18
  import { spawn } from "node:child_process";
19
19
  import { once } from "node:events";
20
20
  import { createWriteStream, fstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
@@ -24,8 +24,8 @@ import path from "node:path";
24
24
  import process from "node:process";
25
25
  import { pathToFileURL } from "node:url";
26
26
  import { buildFrontend } from "./browser-test-build.mjs";
27
- import { useTestAppEnvironment } from "./test-environment.mjs";
28
- import { networkGuardEnvironment } from "./test-network-guard.mjs";
27
+ import { useTestAppEnvironment } from "./testing/environment.mjs";
28
+ import { networkGuardEnvironment } from "./testing/network-guard.mjs";
29
29
 
30
30
  const SETTINGS_VARIABLE = "JSKIT_BROWSER_TESTS";
31
31
  const LOG_DIRECTORY = path.join("test-results", "browser-test-servers");
@@ -250,7 +250,10 @@ try {
250
250
  HOST: host,
251
251
  PORT: String(basePort + index),
252
252
  TEST_PARALLEL_INDEX: String(index),
253
- APP_ENV: "test"
253
+ APP_ENV: "test",
254
+ // Every test of this worker reaches its server from this machine's one address, as a different person each time,
255
+ // so the server counts no per-address rate limit (@jskit-ai/kernel's browserTestServer).
256
+ JSKIT_BROWSER_TEST_SERVER: "1"
254
257
  };
255
258
  return { ...serverEnvironment, ...networkGuardEnvironment(serverEnvironment, "jskit browser tests") };
256
259
  });
@@ -4,7 +4,7 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import process from "node:process";
6
6
  import { fileURLToPath } from "node:url";
7
- import { testConcurrency } from "./test-budget.mjs";
7
+ import { testConcurrency } from "./testing/budget.mjs";
8
8
 
9
9
  // An application's Playwright configuration: `defineConfig(browserTestConfig({ ... }))`. A local run builds the
10
10
  // production frontend once (cached by its sources) and starts one app server per Playwright worker, each on its own port
@@ -351,7 +351,10 @@ function browserTestConfig({
351
351
  headless: true,
352
352
  actionTimeout,
353
353
  navigationTimeout,
354
- // A failed test keeps its trace to read; no screencast is recorded while tests run.
354
+ // A failed test keeps its trace to read; no screencast is recorded while tests run. Its DOM snapshots make
355
+ // Playwright run a script in every frame, which a frame sandboxed without allow-scripts refuses, and Chromium logs
356
+ // "Blocked script execution in 'about:srcdoc' ..." as a console error the app did not cause (the typed features
357
+ // guide's test files section says so).
355
358
  trace: { mode: "retain-on-failure", screenshots: false, snapshots: true, sources: true },
356
359
  ...(storageState ? { storageState } : {})
357
360
  },
package/scripts/jskit.mjs CHANGED
@@ -18,10 +18,10 @@ import { checkManifestCapabilities, formatManifestCapabilitiesReport } from "./m
18
18
  import { checkMaterial3, formatMaterial3Report } from "./material3.mjs";
19
19
  import { checkPackageNix, formatPackageNixReport, packageNix } from "./package-nix.mjs";
20
20
  import { checkProject, updateProject } from "./project-packages.mjs";
21
- import { runTests } from "./test-command.mjs";
22
- import { runMigrationHistory } from "./test-databases.mjs";
23
- import { checkTestRuns, formatTestRunsReport } from "./test-runs.mjs";
24
- import { checkTestSources, formatTestSourcesReport } from "./test-sources.mjs";
21
+ import { runTests } from "./testing/command.mjs";
22
+ import { runMigrationHistory } from "./testing/databases.mjs";
23
+ import { checkTestRuns, formatTestRunsReport } from "./testing/runs.mjs";
24
+ import { checkTestSources, formatTestSourcesReport } from "./testing/sources.mjs";
25
25
 
26
26
  const SCRIPT_PATH = fileURLToPath(import.meta.url);
27
27
  const PACKAGE_ROOT = path.resolve(path.dirname(SCRIPT_PATH), "..");
@@ -4,7 +4,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import { toPosixPath } from "./files.mjs";
5
5
 
6
6
  // What the app's ESLint config ignores, read as `eslint .` reads it, for the parts of `jskit check` that read the app's
7
- // own files: the data part (data-access-files.mjs) and the test-source part (test-sources.mjs). Each leaves out what the
7
+ // own files: the data part (data-access-files.mjs) and the test-source part (testing/sources.mjs). Each leaves out what the
8
8
  // config ignores outside server source (lintIgnores), which no lint reads either, such as a vendored copy of old code
9
9
  // kept beside the app, and lists the paths it left out (formatSkipped).
10
10
 
@@ -1,45 +1,65 @@
1
1
  import { spawn } from "node:child_process";
2
- import { globSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
2
+ import { globSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import process from "node:process";
6
+ import { Readable } from "node:stream";
6
7
  import { pathToFileURL } from "node:url";
7
- import { toPosixPath } from "./files.mjs";
8
- import { BUDGET_VARIABLE, testConcurrency } from "./test-budget.mjs";
9
- import { DATABASES_OPTION, testDatabaseRunFor } from "./test-databases.mjs";
10
- import { useTestAppEnvironment } from "./test-environment.mjs";
11
- import { networkGuardEnvironment, withoutNetworkGuard } from "./test-network-guard.mjs";
12
- import { STOPS_VARIABLE } from "./test-file-stop.mjs";
13
- import { reportTestTimes, writeFileStops } from "./test-time-report.mjs";
8
+ import { toPosixPath } from "../files.mjs";
9
+ import { BUDGET_VARIABLE, testConcurrency } from "./budget.mjs";
10
+ import { DATABASES_OPTION, testDatabaseRunFor } from "./databases.mjs";
11
+ import { useTestAppEnvironment } from "./environment.mjs";
12
+ import { networkGuardEnvironment, withoutNetworkGuard } from "./network-guard.mjs";
13
+ import { STOPS_VARIABLE } from "./file-stop.mjs";
14
+ import {
15
+ checkTestTimes,
16
+ readRecordedTimes,
17
+ readTestTimeBounds,
18
+ recordTestTimes,
19
+ reportTestTimes,
20
+ testTimesOf,
21
+ writeFileStops
22
+ } from "./time-report.mjs";
14
23
 
15
24
  // `jskit test [node options] [files or globs]`: node --test, running test files in parallel within the machine's test
16
- // budget (test-budget.mjs). Its arguments go to node --test unchanged. A file that truly must run alone says why on its
25
+ // budget (budget.mjs). Its arguments go to node --test unchanged. A file that truly must run alone says why on its
17
26
  // first line, `// jskit-test: alone - <reason>`, and runs after the others, one such file at a time. That second run
18
27
  // writes a reporter's file destination beside the first run's (`<name>.alone<ext>`) instead of over it, and with
19
28
  // --test-shard=<index>/<total> it runs only its shard's alone files, picked the way node --test picks a shard's files.
20
- // Given no files, it fails instead of leaving out a file under tests/ named as a test that node's default misses.
21
- // Every run also reports to test-time-report.mjs, which times the command's files against coarse bounds, and preloads
22
- // test-file-stop.mjs, which stops a file still running at a generous multiple of its time. With --databases, a run whose
29
+ // Given no files, it takes node's default files less the helpers and fixtures under a support/ or fixtures/ folder or
30
+ // src/test/, names them to node --test, and fails instead of leaving out a file under tests/ named as a test that
31
+ // node's default misses, or when it finds no test file at all, before preparing any test database; the run's report
32
+ // fails a file it takes that declares no tests.
33
+ // Every run also reports to time-report.mjs, which times the command's files against coarse bounds, and preloads
34
+ // file-stop.mjs, which stops a file still running at a generous multiple of its time, or at the linger bound
35
+ // after its last test, naming what its process still has open. Marked files get the same. With --databases, a run whose
23
36
  // test databases let fewer files run at once than the budget asked for (no usable TEST_DB_NAME, or copies the database
24
37
  // user may not create) says so, and why, at its start and its end, and fails once its tests have run: a machine that
25
38
  // should run files in parallel never silently runs them one at a time. A budget set to what the databases allow
26
39
  // (V64_TEST_CONCURRENCY) runs that way on purpose. With --list it prints the files that run would take, one per line,
27
40
  // then `Total: <n> file(s)` (the closing line Playwright's --list prints), and runs nothing: a host checks that a run
28
41
  // of named files takes exactly those before it sends them anywhere. Every test file, and every process it starts with
29
- // its environment, reaches only this machine and the test database (test-network-guard.mjs); a file that must reach
42
+ // its environment, reaches only this machine and the test database (network-guard.mjs); a file that must reach
30
43
  // an outside service says why on its first line, `// jskit-test: network - <reason>`, and runs without that guard, in
31
44
  // a parallel run of its own after the others.
32
45
 
33
- // node --test's own default (Node 26) when it is given no files.
34
- const DEFAULT_PATTERN = "**/{test,test/**/*,test-*,*[._-]test}.{js,mjs,cjs,ts,mts,cts}";
46
+ // node --test's own default (Node 26) when it is given no files: files named as tests, and every file under a test/
47
+ // folder, of which jskit test leaves out those under a support/ or fixtures/ folder or src/test/ (a package's published
48
+ // test helpers), where only a file named as a test is one.
49
+ const NAMED_PATTERN = "**/{test,test-*,*[._-]test}.{js,mjs,cjs,ts,mts,cts}";
50
+ const FOLDER_PATTERN = "**/test/**/*.{js,mjs,cjs,ts,mts,cts}";
51
+ const SET_APART = /(?:^|\/)(?:support|fixtures)\/|(?:^|\/)src\/test\//u;
52
+ // Those files as the command's messages name them.
53
+ const DEFAULT_FILES = "test.js, test-*.js, *.test.js, *_test.js, *-test.js, or any file under a test/ folder; jskit test " +
54
+ "leaves out the helpers under a support/ or fixtures/ folder and src/test/";
35
55
  // Files under a tests/ folder named as tests that the default leaves out (`x.integration.js`, `x.spec.js`, `x.tests.js`);
36
- // every file under a test/ folder already matches it. Files in Playwright's e2e and browser folders, and files that
37
- // import Vitest or Playwright, belong to those runners.
56
+ // every file under a test/ folder already matches it, or is set apart as a helper. Files in Playwright's e2e and browser
57
+ // folders, and files that import Vitest or Playwright, belong to those runners.
38
58
  const TEST_LIKE_PATTERN = "**/tests/**/*[._-]{integration,spec,specs,tests}.{js,mjs,cjs,ts,mts,cts}";
39
59
  const OTHER_RUNNER_FOLDER = /(?:^|\/)(?:e2e|browser)\//u;
40
60
  const OTHER_RUNNER_IMPORT = /\b(?:from|import|require)\s*\(?\s*["'](?:vitest|@playwright\/test)["']/u;
41
61
  const MARKER = /^\s*\/\/\s*jskit-test:(.*)$/u;
42
- // jskit check's marker for the wait on the line after it (test-sources.mjs), wherever that is: not a file marker.
62
+ // jskit check's marker for the wait on the line after it (sources.mjs), wherever that is: not a file marker.
43
63
  const CHECK_MARKER = /^\s*fixed-wait\b/u;
44
64
  const MARKED = /^\s*(alone|network)\s+-\s+(\S.*)$/u;
45
65
  const MARKER_FORMS = Object.freeze({
@@ -51,8 +71,8 @@ const SHARD = "--test-shard";
51
71
  const TEST_FILTER = /^--test-(?:name-pattern|skip-pattern|only)(?:=|$)/u;
52
72
  const REPORTER = "--test-reporter";
53
73
  const DESTINATION = "--test-reporter-destination";
54
- const TIME_REPORTER = new URL("./test-time-report.mjs", import.meta.url).href;
55
- const FILE_STOP = new URL("./test-file-stop.mjs", import.meta.url).href;
74
+ const TIME_REPORTER = new URL("./time-report.mjs", import.meta.url).href;
75
+ const FILE_STOP = new URL("./file-stop.mjs", import.meta.url).href;
56
76
  // Every test file's process compiles the same modules; Node's compile cache keeps them for the next process and run.
57
77
  // A cache the environment names, or NODE_DISABLE_COMPILE_CACHE=1, wins.
58
78
  const COMPILE_CACHE = path.join("node_modules", ".cache", "jskit-node-compile-cache");
@@ -66,6 +86,12 @@ function findTestFiles(patterns, cwd) {
66
86
  return [...new Set(files)].sort();
67
87
  }
68
88
 
89
+ /** The test files a run given no files takes: node's default files, less the helpers and fixtures set apart. */
90
+ function defaultTestFiles(cwd) {
91
+ const inTestFolders = findTestFiles([FOLDER_PATTERN], cwd).filter((file) => !SET_APART.test(file));
92
+ return [...new Set([...findTestFiles([NAMED_PATTERN], cwd), ...inTestFolders])].sort();
93
+ }
94
+
69
95
  /** The files named as Node tests that a run of node's default files would silently leave out. */
70
96
  function missedTestFiles(defaultFiles, cwd) {
71
97
  const found = new Set(defaultFiles);
@@ -150,23 +176,23 @@ function planTestRuns(args, { cwd = process.cwd(), concurrency = testConcurrency
150
176
  }
151
177
  const candidates = args.filter((argument) => !argument.startsWith("-"));
152
178
  // An argument that matches no file is an option's value (--test-reporter spec) or a typo node reports itself; with
153
- // none that matches, the run is node's default files.
179
+ // none that matches, the run is the default files (defaultTestFiles).
154
180
  const matched = new Map(candidates.map((candidate) => [candidate, findTestFiles([candidate], cwd)]));
155
181
  const named = [...new Set([...matched.values()].flat())].sort();
156
- const files = named.length > 0 ? named : findTestFiles([DEFAULT_PATTERN], cwd);
182
+ const files = named.length > 0 ? named : defaultTestFiles(cwd);
157
183
  const missed = named.length > 0 ? [] : missedTestFiles(files, cwd);
158
184
  if (missed.length > 0) {
159
185
  throw new Error("jskit test: given no files, node --test runs only the files its default pattern matches " +
160
- "(test.js, test-*.js, *.test.js, *_test.js, *-test.js, or any file under a test/ folder), so these test files " +
161
- "would never run:\n" +
162
- `- ${missed.join("\n- ")}\nRename each to end in .test.js (a database test: <name>.integration.test.js), or ` +
163
- "name the files to run.");
186
+ `(${DEFAULT_FILES}), so these test files would never run:\n- ${missed.join("\n- ")}\n` +
187
+ "Rename each to end in .test.js (a database test: <name>.integration.test.js), or name the files to run.");
164
188
  }
165
189
  const { alone, network, problems } = readMarkedFiles(files, cwd);
166
190
  if (problems.length > 0) throw new Error(`jskit test:\n- ${problems.join("\n- ")}`);
167
191
  const parallel = ["--test", `--test-concurrency=${concurrency}`];
168
192
  if (alone.length < 1 && network.length < 1) {
169
- return { concurrency, files: files.length, paths: files, alone, network, runs: [[...parallel, ...args]], guarded: [true] };
193
+ // Given no files, node --test is given this run's, since its own default takes the helpers this one leaves out.
194
+ const runs = named.length > 0 ? [[...parallel, ...args]] : files.length > 0 ? [[...parallel, ...args, ...files]] : [];
195
+ return { concurrency, files: files.length, paths: files, alone, network, runs, guarded: runs.map(() => true) };
170
196
  }
171
197
 
172
198
  const options = args.filter((argument) => !(matched.get(argument)?.length > 0));
@@ -245,7 +271,7 @@ function runNode(args, env) {
245
271
 
246
272
  /**
247
273
  * Runs `jskit test` and resolves to its exit code: the first failing run's, or 0. With `--databases`, each file running
248
- * at once has a test database of its own (test-databases.mjs), and the run's concurrency is how many there are.
274
+ * at once has a test database of its own (databases.mjs), and the run's concurrency is how many there are.
249
275
  * @param {string[]} args
250
276
  */
251
277
  const LIST_OPTION = "--list";
@@ -263,10 +289,21 @@ async function runTests(args) {
263
289
  useTestAppEnvironment(process.env, "jskit test");
264
290
  const nodeArgs = args.filter((argument) => argument !== DATABASES_OPTION);
265
291
  let plan = planTestRuns(nodeArgs);
292
+ // A run of no files would test nothing and pass: it fails, before it prepares a test database for nothing.
293
+ if (plan.paths.length < 1) {
294
+ throw new Error(`jskit test: ${process.cwd()} holds no test files, so this run would test nothing. Given no files, ` +
295
+ `jskit test runs the files node --test's default pattern matches (${DEFAULT_FILES}). ` +
296
+ "Add the tests, or name the files to run.");
297
+ }
266
298
  const source = process.env[BUDGET_VARIABLE] ? BUDGET_VARIABLE : "half of this machine";
267
299
  // A database for each file that can run at once: a focused run of one file prepares one.
268
300
  const asked = Math.max(1, Math.min(plan.concurrency, plan.files));
269
- const databases = nodeArgs.length < args.length ? await testDatabaseRunFor(asked) : null;
301
+ // When files follow others, spares the run keeps ready, so a file that ends leaves its database to be restored in the
302
+ // background while the next starts at once: one for each four files at once, since a restore takes under a quarter
303
+ // of a file's time (12-17% of the slot time measured on an application's suite), so about that share of the
304
+ // databases are being restored at any moment.
305
+ const spares = plan.files > asked ? Math.ceil(asked / 4) : 0;
306
+ const databases = nodeArgs.length < args.length ? await testDatabaseRunFor(asked, { spares }) : null;
270
307
  const shortfall = databases ? databaseShortfall(databases, asked) : "";
271
308
  if (databases) {
272
309
  process.stderr.write(`jskit test: ${databases.summary}.\n`);
@@ -305,17 +342,217 @@ async function runTests(args) {
305
342
  : reportTestTimes({ cwd: process.cwd(), collected, directory: timesDirectory, wallMs: performance.now() - started,
306
343
  filtered: nodeArgs.some((argument) => TEST_FILTER.test(argument)) });
307
344
  if (times) process.stderr.write(times.report);
308
- if (times?.overruns.length > 0 && exitCode === 0) exitCode = 1;
345
+ if ((times?.overruns.length > 0 || times?.empty.length > 0) && exitCode === 0) exitCode = 1;
309
346
  if (shortfall && !interrupted) {
310
347
  process.stderr.write(`jskit test: ${shortfall}\njskit test: the run fails: its test databases cost it concurrency.\n`);
311
348
  if (exitCode === 0) exitCode = 1;
312
349
  }
313
350
  } finally {
314
- // However the run ended, its settings go; its test databases stay for the next run, which restores them.
315
- await databases?.cleanup();
351
+ // However the run ended, its settings go; its test databases stay for the next run, which restores them. A restore
352
+ // of the run's own that failed fails it.
353
+ const ended = await databases?.cleanup();
354
+ if (ended?.summary) process.stderr.write(`jskit test: ${ended.summary}.\n`);
355
+ if (ended?.failure) {
356
+ process.stderr.write(`jskit test: ${ended.failure}\n`);
357
+ if (exitCode === 0) exitCode = 1;
358
+ }
359
+ rmSync(timesDirectory, { recursive: true, force: true });
360
+ }
361
+ return exitCode;
362
+ }
363
+
364
+ /** A pooled file's name in the pool's output: its group's name, then its path in the group's directory. */
365
+ const pooledName = ({ group, file }) => `${group.name}: ${file}`;
366
+
367
+ // The longest recorded time first, a file with none (Infinity) before them all; equal times keep their order.
368
+ const longestFirst = (first, second) => (first.ms === second.ms ? 0 : first.ms < second.ms ? 1 : -1);
369
+
370
+ /**
371
+ * The files of a pool's groups (runTestPool), each with its group, why it runs alone or reaches the network (or
372
+ * undefined), and its time in its group's record, the longest first. A group takes files and globs only: a node option
373
+ * would apply to all of its files in a run of its own, which a pool has not.
374
+ * @param {Array<{ name: string, cwd: string, args?: string[] }>} groups
375
+ */
376
+ function planTestPool(groups, { concurrency = testConcurrency() } = {}) {
377
+ return groups.flatMap((group) => {
378
+ const args = group.args ?? [];
379
+ const options = args.filter((argument) => argument.startsWith("-"));
380
+ if (options.length > 0) {
381
+ throw new Error(`${group.name}: runTestPool takes test files and globs, not node options (${options.join(", ")}).`);
382
+ }
383
+ const plan = planTestRuns(args, { cwd: group.cwd, concurrency });
384
+ const alone = new Map(plan.alone.map(({ file, reason }) => [file, reason]));
385
+ const network = new Map(plan.network.map(({ file, reason }) => [file, reason]));
386
+ const recorded = readRecordedTimes(group.cwd);
387
+ return plan.paths.map((file) => ({ group, file, alone: alone.get(file), network: network.get(file), ms: recorded[file] ?? Infinity }));
388
+ }).sort(longestFirst);
389
+ }
390
+
391
+ /**
392
+ * Records each group's file times where `jskit test` in its directory reads them, and checks them all as one run: each
393
+ * file against its own group's bound, the whole pool against the bound of this process's directory; a file stopped
394
+ * past its linger bound, and one that declares no tests, are named by their group and path, as `jskit test` names them.
395
+ */
396
+ function reportPoolTimes(groups, wallMs) {
397
+ const files = {};
398
+ const fileBounds = {};
399
+ const tests = [];
400
+ const stopped = [];
401
+ const lingered = [];
402
+ const exited = [];
403
+ const empty = [];
404
+ for (const { group, directory, collected } of groups) {
405
+ const times = recordTestTimes({ cwd: group.cwd, collected, directory });
406
+ if (!times) continue;
407
+ const bounds = readTestTimeBounds(group.cwd);
408
+ const name = (file) => pooledName({ group, file });
409
+ const named = (entry) => ({ ...entry, file: name(entry.file) });
410
+ for (const [file, ms] of Object.entries(times.files)) {
411
+ files[name(file)] = ms;
412
+ fileBounds[name(file)] = bounds.files[file] ?? bounds.fileMs;
413
+ }
414
+ tests.push(...times.tests.map(named));
415
+ stopped.push(...times.stopped.map(named));
416
+ lingered.push(...times.lingered.map(named));
417
+ exited.push(...times.exited.map(named));
418
+ empty.push(...times.empty.map(name));
419
+ }
420
+ if (Object.keys(files).length === 0 && stopped.length === 0 && lingered.length === 0) return null;
421
+ return checkTestTimes({ bounds: { ...readTestTimeBounds(process.cwd()), files: fileBounds }, files, tests, wallMs, stopped,
422
+ lingered, exited, empty });
423
+ }
424
+
425
+ /** All a stream's chunks as one string. */
426
+ async function textOf(stream) {
427
+ let text = "";
428
+ for await (const chunk of stream) text += chunk;
429
+ return text;
430
+ }
431
+
432
+ // node:test's run() gives each file's process its own environment (`env`) from Node 24.14.
433
+ const POOL_NODE = Object.freeze({ major: 24, minor: 14 });
434
+
435
+ /**
436
+ * Runs the files of several `jskit test` runs as one pool within the machine's test budget, so many packages' tests take
437
+ * about their files' summed time over the budget, not the sum of one run after another. Each group, `{ name, cwd, args,
438
+ * env }`, is one such run: its directory, its files and globs as its `jskit test` script names them (none: node's
439
+ * default files) and what it adds to this process's environment. Every file runs as `jskit test` in the group's
440
+ * directory would run it, in a process of its own with the group's environment, the file stop and the network guard,
441
+ * reported by node --test's spec reporter: the longest first by its group's record (a file with none before them), as
442
+ * many at once as the budget allows, a network file without the guard, and the alone files after every other file of
443
+ * every group, one at a time. node:test's run() of one file, in this process, starts it: a runner process for each
444
+ * file cost kernel's 87 files 0.14 s of CPU each on office. Each file's report is printed whole when it ends, under
445
+ * `# <group>: <file>`. Then the files that failed, and one time report over every file, each group recording its own
446
+ * files' times. Resolves to the exit code: 1 when a file failed, was stopped or went past a bound.
447
+ * @param {Array<{ name?: string, cwd: string, args?: string[], env?: Record<string, string> }>} groups `name`: by
448
+ * default, the directory relative to this process's
449
+ */
450
+ async function runTestPool(groups) {
451
+ const [major, minor] = process.versions.node.split(".").map(Number);
452
+ if (major < POOL_NODE.major || (major === POOL_NODE.major && minor < POOL_NODE.minor)) {
453
+ throw new Error(`runTestPool needs Node ${POOL_NODE.major}.${POOL_NODE.minor} or later, where node:test's run() gives ` +
454
+ `each file its own environment; this is Node ${process.versions.node}.`);
455
+ }
456
+ const { run: runTestFiles } = await import("node:test");
457
+ const { spec } = await import("node:test/reporters");
458
+ const named = groups.map((group) => {
459
+ const cwd = path.resolve(group.cwd);
460
+ return { ...group, cwd, name: group.name ?? (toPosixPath(path.relative(process.cwd(), cwd)) || ".") };
461
+ });
462
+ const concurrency = testConcurrency();
463
+ const files = planTestPool(named, { concurrency });
464
+ // Every run, and so every pooled file, is APP_ENV=test.
465
+ useTestAppEnvironment(process.env, "jskit test");
466
+ const source = process.env[BUDGET_VARIABLE] ? BUDGET_VARIABLE : "half of this machine";
467
+ process.stderr.write(`jskit test: ${files.length} test file(s) of ${named.length} group(s), ${concurrency} at a time ` +
468
+ `(${source}), the longest first.\n`);
469
+ for (const entry of files.filter(({ alone }) => alone)) process.stderr.write(`jskit test: ${pooledName(entry)} runs alone: ${entry.alone}\n`);
470
+ for (const entry of files.filter(({ network }) => network)) {
471
+ process.stderr.write(`jskit test: ${pooledName(entry)} reaches the network: ${entry.network}\n`);
472
+ }
473
+ const timesDirectory = mkdtempSync(path.join(os.tmpdir(), "jskit-test-times-"));
474
+ const runs = new Map(named.map((group, index) => {
475
+ const directory = path.join(timesDirectory, String(index));
476
+ mkdirSync(directory);
477
+ const stops = writeFileStops({ cwd: group.cwd, files: files.filter((entry) => entry.group === group).map(({ file }) => file), directory });
478
+ return [group, { group, directory, stops, collected: [] }];
479
+ }));
480
+ const abort = new AbortController();
481
+ const failed = [];
482
+ let interruption = null;
483
+ const interrupt = (signal) => {
484
+ interruption = signal;
485
+ abort.abort();
486
+ };
487
+ process.on("SIGINT", interrupt);
488
+ process.on("SIGTERM", interrupt);
489
+
490
+ // A file runs as node --test's own run of that one file (node:test's run(), the runner `jskit test` starts), here
491
+ // instead of in a runner process of its own: one process per file, as in a run of a group's files.
492
+ async function runFile(entry) {
493
+ const { group, file } = entry;
494
+ const run = runs.get(group);
495
+ const groupEnv = { ...process.env, ...group.env };
496
+ const env = {
497
+ ...groupEnv,
498
+ NODE_COMPILE_CACHE: groupEnv.NODE_COMPILE_CACHE || path.resolve(group.cwd, COMPILE_CACHE),
499
+ [STOPS_VARIABLE]: run.stops,
500
+ // The file, and what it starts, reach only this machine and the test database; a network file, anywhere.
501
+ ...(entry.network ? { NODE_OPTIONS: withoutNetworkGuard(groupEnv.NODE_OPTIONS) } : networkGuardEnvironment(groupEnv, "jskit test"))
502
+ };
503
+ const events = await Array.fromAsync(runTestFiles({
504
+ // By its absolute path, so each event names it whatever directory reads them.
505
+ files: [path.resolve(group.cwd, file)],
506
+ cwd: group.cwd,
507
+ env,
508
+ concurrency: 1,
509
+ execArgv: ["--import", FILE_STOP],
510
+ signal: abort.signal
511
+ }));
512
+ const collected = path.join(run.directory, `run-${run.collected.length}.json`);
513
+ run.collected.push(collected);
514
+ writeFileSync(collected, await textOf(testTimesOf(Readable.from(events), group.cwd)));
515
+ process.stdout.write(`\n# ${pooledName(entry)}\n${await textOf(Readable.from(events).compose(spec()))}`);
516
+ // The run's own summary, as node --test sets its exit code from it: no failed or cancelled test, no other error.
517
+ const summary = events.find((event) => event.type === "test:summary" && !event.data.file)?.data;
518
+ if (!summary || summary.success === false || summary.counts.failed > 0 || summary.counts.cancelled > 0) failed.push(entry);
519
+ }
520
+
521
+ // A file whose run could not start or report fails with what went wrong, and the pool goes on with the others.
522
+ function runFileOrFail(entry) {
523
+ return runFile(entry).catch((error) => {
524
+ process.stdout.write(`\n# ${pooledName(entry)}\n${error?.stack ?? error}\n`);
525
+ failed.push(entry);
526
+ });
527
+ }
528
+
529
+ const started = performance.now();
530
+ let exitCode = 0;
531
+ try {
532
+ const pending = files.filter(({ alone }) => !alone);
533
+ await Promise.all(Array.from({ length: Math.min(concurrency, pending.length) }, async () => {
534
+ while (!interruption && pending.length > 0) await runFileOrFail(pending.shift());
535
+ }));
536
+ for (const entry of files.filter(({ alone }) => alone)) {
537
+ if (interruption) break;
538
+ await runFileOrFail(entry);
539
+ }
540
+ if (failed.length > 0) {
541
+ process.stderr.write(`jskit test: ${failed.length} of ${files.length} test file(s) failed:\n` +
542
+ `${failed.map((entry) => ` ${pooledName(entry)}`).sort().join("\n")}\n`);
543
+ exitCode = 1;
544
+ }
545
+ // An interrupted pool ends with the signal's code, and records no times: its files did not all run.
546
+ if (interruption) return 128 + (os.constants.signals[interruption] ?? 0);
547
+ const times = reportPoolTimes([...runs.values()], performance.now() - started);
548
+ if (times) process.stderr.write(times.report);
549
+ if (times?.overruns.length > 0 || times?.empty.length > 0) exitCode = 1;
550
+ } finally {
551
+ process.off("SIGINT", interrupt);
552
+ process.off("SIGTERM", interrupt);
316
553
  rmSync(timesDirectory, { recursive: true, force: true });
317
554
  }
318
555
  return exitCode;
319
556
  }
320
557
 
321
- export { DEFAULT_PATTERN, findTestFiles, planTestRuns, runTests, withTimeReporter };
558
+ export { defaultTestFiles, findTestFiles, missedTestFiles, planTestPool, planTestRuns, runTestPool, runTests, withTimeReporter };
@@ -3,8 +3,8 @@ import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
  import process from "node:process";
5
5
  import { pathToFileURL } from "node:url";
6
- import { readTableResourceSources } from "./data-access.mjs";
7
- import { useTestAppEnvironment } from "./test-environment.mjs";
6
+ import { readTableResourceSources } from "../data-access.mjs";
7
+ import { useTestAppEnvironment } from "./environment.mjs";
8
8
 
9
9
  // `jskit test --databases`: each test file running at once gets a database of its own, a copy of TEST_DB_NAME restored
10
10
  // from a schema snapshot, from the application's installed @jskit-ai/database-runtime and its knexfile.js, which loads
@@ -123,17 +123,20 @@ async function applicationTestDatabases(cwd, command) {
123
123
  }
124
124
 
125
125
  /**
126
- * The run's databases for `count` files at once, or one file at a time on the connected database. Its `cleanup()` ends
127
- * the run: it removes the run's settings, and the databases stay for the next run (an installed
128
- * @jskit-ai/database-runtime from before drops the numbered copies, and answers what it dropped).
126
+ * The run's databases for `count` files at once, and `spares` more that the run keeps ready for the files that follow
127
+ * (testDatabaseRun() in @jskit-ai/database-runtime), or one file at a time on the connected database. Its `cleanup()`
128
+ * ends the run: it waits for the run's restores, removes its settings, and answers their summary and any restore of its
129
+ * own that failed; the databases stay for the next run. An installed @jskit-ai/database-runtime from before keeps no
130
+ * spares, and its cleanup answers nothing, or what it dropped.
129
131
  * @param {number} count at most the run's test budget, and no more than its test files
130
- * @param {string} [cwd]
132
+ * @param {{ spares?: number, cwd?: string }} [options]
131
133
  * @returns {Promise<{ concurrency: number, env: Record<string, string>, preload: string, summary: string,
132
- * cleanup(): Promise<string> | void }>}
134
+ * cleanup(): Promise<{ summary: string, failure: string } | string | void> | void }>}
133
135
  */
134
- async function testDatabaseRunFor(count, cwd = process.cwd()) {
136
+ async function testDatabaseRunFor(count, { spares = 0, cwd = process.cwd() } = {}) {
135
137
  const { knexConfig, schema, environment, runtime } = await applicationTestDatabases(cwd, `jskit test ${OPTION}`);
136
- return runtime.testDatabaseRun({ knexConfig, environment, count, schema, appRoot: cwd, checkDatabase: foreignKeyCheckFor(cwd) });
138
+ return runtime.testDatabaseRun({ knexConfig, environment, count, spares, schema, appRoot: cwd,
139
+ checkDatabase: foreignKeyCheckFor(cwd) });
137
140
  }
138
141
 
139
142
  /**