@jskit-ai/jskit-catalog 0.2.104 → 0.2.106

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.104",
3
+ "version": "0.2.106",
4
4
  "description": "Published metadata catalog for JSKIT package metadata.",
5
5
  "type": "module",
6
6
  "files": [
@@ -2,12 +2,19 @@
2
2
  // does: a page then loads a few bundled files instead of every source module from a development server. The build goes where the app
3
3
  // server serves it from (dist/), never a folder of its own: the server tells every page which build it serves from
4
4
  // dist/index.html, and a page from any other build offers a reload over the screen. It is reused while its inputs' contents
5
- // are unchanged and dist/index.html is still the one it made, so a repeated focused run does not rebuild, even though a
6
- // build rewrites files it generates among its inputs (vue-router's src/typed-router.d.ts). Two runs in one tree build one
5
+ // are unchanged and dist/index.html is still the one it made, so a repeated focused run does not rebuild. Its inputs are
6
+ // what the build read: the modules it bundled, which @jskit-ai/kernel's createJskitClientBootstrapPlugin (in every JSKIT
7
+ // app's Vite config) records, the listing of every folder they came from, so an added file counts, and the files every
8
+ // build reads; an edit to server code alone reuses the build. Those are read after the build, so a build during which
9
+ // one of them changed is not kept for reuse: it may hold code from before the change. A build that records no modules (a
10
+ // Vite config without that plugin, or a build that is not Vite's) is keyed on every source file instead, taken before it
11
+ // runs, as it rewrites files it generates among them (vue-router's src/typed-router.d.ts). Two runs in one tree build one
7
12
  // at a time: the second waits, then reuses the first one's build.
8
13
  import { spawn } from "node:child_process";
9
14
  import { createHash } from "node:crypto";
10
- import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
15
+ import {
16
+ closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, writeSync
17
+ } from "node:fs";
11
18
  import path from "node:path";
12
19
  import process from "node:process";
13
20
 
@@ -17,23 +24,42 @@ const FINGERPRINT_FILE = path.join("node_modules", ".cache", "jskit-browser-test
17
24
  const BUILD_LOCK = path.join("node_modules", ".cache", "jskit-browser-test-build.lock");
18
25
  const BUILD_WAIT_MS = 10 * 60_000;
19
26
  const SERVED_INDEX = path.join("dist", "index.html");
20
- // The app's folders a frontend build reads, and the installed packages it bundles. Every file at the app's root is an
21
- // input too (index.html, vite.config.*, favicon.svg, package.json, the .env files Vite reads), except other dotfiles,
22
- // such as caches, and notes.
23
- const BUILD_DIRECTORIES = Object.freeze(["src", "packages", "shared", "config", "public", "node_modules/@jskit-ai"]);
27
+ // The file a build appends the ids of the modules it read to, one per line, when this variable names it
28
+ // (createJskitClientBootstrapPlugin in @jskit-ai/kernel/client/vite).
29
+ const BUILD_MODULES_VARIABLE = "JSKIT_BUILD_MODULES_FILE";
30
+ const BUILD_MODULES_FILE = path.join("node_modules", ".cache", "jskit-browser-test-build-modules.txt");
31
+ // Read by every build: Vite copies public/, and the installed packages decide the bundled code. Every file at the app's
32
+ // root is an input too (index.html, vite.config.*, favicon.svg, package.json, the .env files Vite reads), except other
33
+ // dotfiles, such as caches, and notes.
24
34
  const INSTALLED_PACKAGES = "node_modules/.package-lock.json";
35
+ const ALWAYS_READ = Object.freeze(["public", INSTALLED_PACKAGES]);
36
+ // Without the modules a build read: the app's folders a frontend build may read, and the installed packages it bundles.
37
+ const SOURCE_DIRECTORIES = Object.freeze(["src", "packages", "shared", "config", "node_modules/@jskit-ai"]);
25
38
  const NOT_AN_INPUT = /^\.(?!env(?:\.|$))|\.(?:md|log|txt)$/u;
26
39
 
27
40
  const seconds = (since) => `${((performance.now() - since) / 1000).toFixed(1)}s`;
28
41
  const digest = (file) => (existsSync(file) ? createHash("sha256").update(readFileSync(file)).digest("hex") : "");
29
42
 
30
- /** Every build input's path and contents, the build command and the VITE_ settings, hashed. */
31
- function buildFingerprint(appRoot, build, env = process.env) {
43
+ /**
44
+ * Every build input's path and contents, the build command and the VITE_ settings, hashed, and the input changed last.
45
+ * The inputs are the files the last build read, with the listing of each folder they came from and the manifest
46
+ * (package.json) of any such folder that has one, or, without them, every source file.
47
+ * @param {string} appRoot
48
+ * @param {string} build
49
+ * @param {{ files: string[], directories: string[] } | null} [read] what the build read, relative to appRoot
50
+ * @returns {{ inputs: string, newest: { path: string, time: number } }}
51
+ */
52
+ function buildFingerprint(appRoot, build, read = null, env = process.env) {
32
53
  const hash = createHash("sha256").update(`${build}\n`);
54
+ const newest = { path: "", time: 0 };
55
+ const changed = (relative, stats) => {
56
+ if (stats.mtimeMs > newest.time) Object.assign(newest, { path: relative, time: stats.mtimeMs });
57
+ return stats;
58
+ };
33
59
  const visit = (relative) => {
34
60
  const absolute = path.join(appRoot, relative);
35
61
  if (!existsSync(absolute)) return;
36
- const stats = statSync(absolute);
62
+ const stats = changed(relative, statSync(absolute));
37
63
  if (!stats.isDirectory()) {
38
64
  hash.update(`${relative}\0${stats.size}\0`).update(readFileSync(absolute));
39
65
  return;
@@ -45,20 +71,56 @@ function buildFingerprint(appRoot, build, env = process.env) {
45
71
  for (const entry of readdirSync(appRoot, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
46
72
  if (!entry.isDirectory() && !NOT_AN_INPUT.test(entry.name)) visit(entry.name);
47
73
  }
48
- [INSTALLED_PACKAGES, ...BUILD_DIRECTORIES].forEach(visit);
74
+ ALWAYS_READ.forEach(visit);
75
+ if (!read) {
76
+ SOURCE_DIRECTORIES.forEach(visit);
77
+ } else {
78
+ read.files.forEach(visit);
79
+ for (const directory of read.directories) {
80
+ const absolute = path.join(appRoot, directory);
81
+ let listing = "(missing)";
82
+ if (existsSync(absolute)) {
83
+ changed(directory, statSync(absolute));
84
+ listing = readdirSync(absolute).sort().join("\0");
85
+ }
86
+ hash.update(`${directory}/\0${listing}\0`);
87
+ visit(path.join(directory, "package.json"));
88
+ }
89
+ }
49
90
  for (const [name, value] of Object.entries(env).filter(([key]) => key.startsWith("VITE_")).sort()) {
50
91
  hash.update(`${name}=${value}\n`);
51
92
  }
52
- return hash.digest("hex");
93
+ return { inputs: hash.digest("hex"), newest };
53
94
  }
54
95
 
55
- function runToCompletion(command, appRoot) {
96
+ /**
97
+ * The files and folders the build recorded reading, relative to appRoot, or null when it recorded no module. Virtual
98
+ * modules and queries (`?vue&type=style`) are not files; installed packages' folders are left to their record.
99
+ */
100
+ function readModules(appRoot, modulesFile) {
101
+ if (!existsSync(modulesFile)) return null;
102
+ // Vite names modules by their real paths.
103
+ const root = realpathSync(appRoot);
104
+ const files = new Set();
105
+ const directories = new Set();
106
+ for (const id of readFileSync(modulesFile, "utf8").split("\n")) {
107
+ const file = id.split("?")[0];
108
+ if (!path.isAbsolute(file) || !existsSync(file) || !statSync(file).isFile()) continue;
109
+ const relative = path.relative(root, file);
110
+ files.add(relative);
111
+ if (relative.split(path.sep).includes("node_modules")) continue;
112
+ for (let directory = path.dirname(relative); directory !== "."; directory = path.dirname(directory)) directories.add(directory);
113
+ }
114
+ return files.size ? { files: [...files].sort(), directories: [...directories].sort() } : null;
115
+ }
116
+
117
+ function runToCompletion(command, appRoot, environment = {}) {
56
118
  const [program, ...args] = String(command).trim().split(/\s+/u);
57
119
  return new Promise((resolve, reject) => {
58
120
  // The build a staging or production server serves, whatever NODE_ENV the launcher was given.
59
121
  const child = spawn(program, args, {
60
122
  cwd: appRoot,
61
- env: { ...process.env, NODE_ENV: "production" },
123
+ env: { ...process.env, ...environment, NODE_ENV: "production" },
62
124
  stdio: ["ignore", "ignore", "inherit"]
63
125
  });
64
126
  child.once("error", reject);
@@ -115,35 +177,51 @@ async function lockBuild(appRoot) {
115
177
  }
116
178
  }
117
179
 
118
- function isCurrent(appRoot, inputs) {
180
+ function isCurrent(appRoot, build) {
119
181
  const last = lastBuild(appRoot);
120
- return last.inputs === inputs && Boolean(last.index) && last.index === digest(path.join(appRoot, SERVED_INDEX));
182
+ return Boolean(last.index) && last.index === digest(path.join(appRoot, SERVED_INDEX)) &&
183
+ last.inputs === buildFingerprint(appRoot, build, last.read || null).inputs;
121
184
  }
122
185
 
123
186
  /**
124
187
  * Builds the frontend with `build` unless dist/ already holds the build of the current inputs.
125
- * @param {{ appRoot?: string, build?: string, run?: (command: string, appRoot: string) => Promise<void> }} [options]
188
+ * @param {{ appRoot?: string, build?: string,
189
+ * run?: (command: string, appRoot: string, environment: Record<string, string>) => Promise<void> }} [options]
126
190
  * @returns {Promise<{ built: boolean }>}
127
191
  */
128
192
  async function buildFrontend({ appRoot = process.cwd(), build = "npm run build", run = runToCompletion } = {}) {
129
193
  const started = performance.now();
130
- const inputs = buildFingerprint(appRoot, build);
131
- if (isCurrent(appRoot, inputs)) {
194
+ if (isCurrent(appRoot, build)) {
132
195
  console.log(`[browser-tests] Frontend build unchanged, reused (${seconds(started)}).`);
133
196
  return { built: false };
134
197
  }
135
198
  const unlock = await lockBuild(appRoot);
136
199
  try {
137
200
  // The run that held the lock may have just built these inputs.
138
- if (isCurrent(appRoot, inputs)) {
201
+ if (isCurrent(appRoot, build)) {
139
202
  console.log(`[browser-tests] Frontend built by another run, reused (${seconds(started)}).`);
140
203
  return { built: false };
141
204
  }
142
- await run(build, appRoot);
205
+ const modulesFile = path.join(appRoot, BUILD_MODULES_FILE);
206
+ // Made empty as the build starts: its modification time is the start by the file system's own clock, which stamps
207
+ // the inputs' times too.
208
+ writeFileSync(modulesFile, "");
209
+ const buildStart = statSync(modulesFile).mtimeMs;
210
+ const everySource = buildFingerprint(appRoot, build).inputs;
211
+ await run(build, appRoot, { [BUILD_MODULES_VARIABLE]: modulesFile });
143
212
  const index = digest(path.join(appRoot, SERVED_INDEX));
144
213
  if (!index) throw new Error(`${build} made no ${SERVED_INDEX}, which the app server serves.`);
145
- writeFileSync(path.join(appRoot, FINGERPRINT_FILE), JSON.stringify({ inputs, index }));
146
- console.log(`[browser-tests] Frontend built in ${seconds(started)}.`);
214
+ const read = readModules(appRoot, modulesFile);
215
+ rmSync(modulesFile, { force: true });
216
+ let inputs = everySource;
217
+ let note = "; it recorded no modules, so every source file is its input";
218
+ if (read) {
219
+ const { inputs: readInputs, newest } = buildFingerprint(appRoot, build, read);
220
+ inputs = newest.time >= buildStart ? "" : readInputs;
221
+ note = inputs ? "" : `; not kept for reuse, as ${newest.path} changed while it ran`;
222
+ }
223
+ writeFileSync(path.join(appRoot, FINGERPRINT_FILE), JSON.stringify({ inputs, index, read }));
224
+ console.log(`[browser-tests] Frontend built in ${seconds(started)}${note}.`);
147
225
  return { built: true };
148
226
  } finally {
149
227
  unlock();
@@ -9,10 +9,12 @@
9
9
  // Playwright gives its webServer (a Playwright that ended without stopping it), the launcher stops its servers and
10
10
  // waits for them, then drops the numbered database copies the prepare module made, within Playwright's grace, before it
11
11
  // exits; it drops them too when its start fails. `jskit browser-test-server` (browser-test-server.mjs) runs it
12
- // for one server a host starts, with `terminal`: that server's output also reaches the launcher's own.
12
+ // for one server a host starts, with `terminal`: that server's output also reaches the launcher's own. A run takes free
13
+ // ports of its own, so its worker environments and signed-in states have names of their own; the launcher removes them
14
+ // when it stops, so they never pile up in the cache, nor outlive the sessions they hold.
13
15
  import { spawn } from "node:child_process";
14
16
  import { once } from "node:events";
15
- import { createWriteStream, fstatSync, mkdirSync, writeFileSync } from "node:fs";
17
+ import { createWriteStream, fstatSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
16
18
  import { createRequire } from "node:module";
17
19
  import net from "node:net";
18
20
  import path from "node:path";
@@ -102,6 +104,8 @@ async function waitUntilReady(url, server, name) {
102
104
 
103
105
  const servers = [];
104
106
  let stopping = false;
107
+ // The files this run leaves for its workers, which it removes when it stops.
108
+ let runFiles = [];
105
109
  // The prepare module's work, which a stop waits for (within DROP_WAIT_MS) so the copies it is making are dropped too.
106
110
  let preparing = Promise.resolve();
107
111
  const running = (server) => server.exitCode === null && server.signalCode === null;
@@ -129,6 +133,7 @@ async function stopAndExit(code) {
129
133
  console.error(`[browser-tests] The prepared test database copies were not all dropped within ${DROP_WAIT_MS / 1000}s; ` +
130
134
  "the next run makes them afresh and drops them.");
131
135
  }
136
+ for (const file of runFiles) rmSync(file, { force: true });
132
137
  process.exit(code);
133
138
  }
134
139
  process.once("SIGINT", () => stopAndExit(130));
@@ -152,6 +157,8 @@ useTestAppEnvironment(process.env, "jskit browser tests");
152
157
  const baseEnvironment = { ...process.env };
153
158
  delete baseEnvironment[SETTINGS_VARIABLE];
154
159
  const baseUrls = Array.from({ length: workers }, (_, index) => `http://${host}:${basePort + index}`);
160
+ runFiles = [workerEnvironmentsFile, ...(signedInStates ? baseUrls.map((_, index) => `${signedInStates}-${index}.json`) : [])]
161
+ .filter(Boolean);
155
162
  try {
156
163
  await refuseBusyPorts(host, baseUrls.map((_, index) => basePort + index));
157
164
  preparing = prepareWorkers(appRoot, prepare, workers, baseUrls);
@@ -1,3 +1,4 @@
1
+ import { spawnSync } from "node:child_process";
1
2
  import { readFileSync } from "node:fs";
2
3
  import path from "node:path";
3
4
  import process from "node:process";
@@ -17,10 +18,11 @@ const SLOWEST_TESTS = fileURLToPath(new URL("./browser-test-times.mjs", import.m
17
18
  const SETTINGS_VARIABLE = "JSKIT_BROWSER_TESTS";
18
19
  const READY = /^jskit browser tests: \d+ server\(s\) ready/mu;
19
20
  const HOST = "127.0.0.1";
20
- const DEFAULT_PORT = 4173;
21
- // A whole run's default bound: a suite that would take hours stops instead, and says so. A suite measured to need
22
- // longer passes its own globalTimeout, with the measurement beside it.
23
- const GLOBAL_TIMEOUT_MS = 20 * 60_000;
21
+ // A whole run's default bound, as work: 80 worker-minutes, so 20 minutes on 4 workers and 80 on one, never under 20
22
+ // minutes, so a run with fewer browsers is not cut short for the host's size. A suite that would take hours stops
23
+ // instead, and says so. A suite measured to need longer passes its own globalTimeout, with the measurement beside it.
24
+ const WORKER_MINUTES_MS = 80 * 60_000;
25
+ const MIN_GLOBAL_TIMEOUT_MS = 20 * 60_000;
24
26
  // A click, fill or navigation waiting on something that never comes (a stale locator) fails in seconds, with its own
25
27
  // error, instead of holding the test until its 60 s timeout. Over 652 passing app tests the slowest action or page
26
28
  // load took 9.0 s, and expect already waits 10 s.
@@ -66,6 +68,39 @@ function browserTestWorkers({ env = process.env, argv = process.argv } = {}) {
66
68
  (managedBaseUrl(env) ? 1 : Math.max(1, Math.floor(testConcurrency({ env }) / 2)));
67
69
  }
68
70
 
71
+ // Finds `count` consecutive ports nothing listens on, at a random place below Linux's ephemeral range, and prints the
72
+ // first. A child process, since a Playwright configuration is built synchronously.
73
+ const FREE_PORTS = `
74
+ const net = require("node:net");
75
+ const [host, count] = [process.argv[1], Number(process.argv[2])];
76
+ const listen = (port) => new Promise((resolve) => {
77
+ const server = net.createServer();
78
+ server.once("error", () => resolve(null));
79
+ server.listen(port, host, () => resolve(server));
80
+ });
81
+ (async () => {
82
+ for (let attempt = 0; attempt < 50; attempt += 1) {
83
+ const base = 20000 + Math.floor(Math.random() * (12000 - count));
84
+ const held = [];
85
+ while (held.length < count) {
86
+ const server = await listen(base + held.length);
87
+ if (!server) break;
88
+ held.push(server);
89
+ }
90
+ await Promise.all(held.map((server) => new Promise((resolve) => server.close(resolve))));
91
+ if (held.length === count) return process.stdout.write(String(base));
92
+ }
93
+ process.exitCode = 1;
94
+ })();`;
95
+
96
+ /** The first of `count` consecutive free ports on host: a local run's default, so two runs on one machine never share. */
97
+ function freeConsecutivePorts(host, count) {
98
+ const found = spawnSync(process.execPath, ["-e", FREE_PORTS, host, String(count)], { encoding: "utf8", timeout: 30_000 });
99
+ const port = positiveInteger(found.stdout);
100
+ if (!port) throw new Error(`browserTestConfig() found no ${count} consecutive free port(s) on ${host}; set PLAYWRIGHT_PORT to free ports.`);
101
+ return port;
102
+ }
103
+
69
104
  /** The environment the launcher gave worker `index`'s server, from the app's prepare module, or none. */
70
105
  function preparedWorkerEnvironment(file, index) {
71
106
  try {
@@ -80,7 +115,8 @@ function preparedWorkerEnvironment(file, index) {
80
115
  * The Playwright configuration of an application's browser tests.
81
116
  * @param {object} [options]
82
117
  * @param {string} [options.testDir] Where the specs are.
83
- * @param {number} [options.port] The first worker's port; worker n uses port + n. PLAYWRIGHT_PORT overrides it.
118
+ * @param {number} [options.port] The first worker's port; worker n uses port + n. PLAYWRIGHT_PORT overrides it. By
119
+ * default a local run takes free ports and gives them to its workers in PLAYWRIGHT_PORT.
84
120
  * @param {string} [options.server] The command that starts the app server, reading PORT and HOST.
85
121
  * @param {string} [options.build] The command that builds the production frontend into the folder the server serves.
86
122
  * @param {string} [options.prepare] An app module, run once before the servers start, whose default export
@@ -94,7 +130,8 @@ function preparedWorkerEnvironment(file, index) {
94
130
  * out or ends sessions signs in on its own first, so the worker's shared session lives on.
95
131
  * @param {Record<string, string>} [options.env] Environment every server gets, such as its test-only drivers.
96
132
  * @param {string} [options.health] The path that answers 200 once a server is ready.
97
- * @param {number} [options.globalTimeout] The whole run's bound in milliseconds (20 minutes); never 0.
133
+ * @param {number} [options.globalTimeout] The whole run's bound in milliseconds (80 worker-minutes, never under 20
134
+ * minutes); never 0.
98
135
  * @param {number} [options.actionTimeout] One click, fill or other action's bound in milliseconds (15 s); never 0.
99
136
  * @param {number} [options.navigationTimeout] One navigation's bound in milliseconds (30 s); never 0.
100
137
  * @param {Record<string, string | undefined>} [options.environment] Read, and given a worker's prepared environment,
@@ -103,20 +140,20 @@ function preparedWorkerEnvironment(file, index) {
103
140
  */
104
141
  function browserTestConfig({
105
142
  testDir = "./tests/e2e",
106
- port = DEFAULT_PORT,
143
+ port = 0,
107
144
  server = "node ./bin/server.js",
108
145
  build = "npm run build",
109
146
  prepare = "",
110
147
  signIn = "",
111
148
  env = {},
112
149
  health = "/api/health",
113
- globalTimeout = GLOBAL_TIMEOUT_MS,
150
+ globalTimeout,
114
151
  actionTimeout = ACTION_TIMEOUT_MS,
115
152
  navigationTimeout = NAVIGATION_TIMEOUT_MS,
116
153
  environment = process.env,
117
154
  cwd = process.cwd()
118
155
  } = {}) {
119
- if (!Number.isInteger(globalTimeout) || globalTimeout < 1) {
156
+ if (globalTimeout !== undefined && (!Number.isInteger(globalTimeout) || globalTimeout < 1)) {
120
157
  throw new Error("browserTestConfig() needs a globalTimeout of at least 1 ms; a run is always bounded.");
121
158
  }
122
159
  for (const [name, value] of Object.entries({ actionTimeout, navigationTimeout })) {
@@ -126,7 +163,16 @@ function browserTestConfig({
126
163
  }
127
164
  const managed = managedBaseUrl(environment);
128
165
  const workers = browserTestWorkers({ env: environment });
129
- const basePort = positiveInteger(environment.PLAYWRIGHT_PORT) || port;
166
+ const runTimeout = globalTimeout ?? Math.max(MIN_GLOBAL_TIMEOUT_MS, Math.ceil(WORKER_MINUTES_MS / workers));
167
+ let basePort = positiveInteger(environment.PLAYWRIGHT_PORT) || port;
168
+ if (!basePort && !managed) {
169
+ // Playwright's workers load this config again: they take the ports the run took, which only the run finds.
170
+ if (String(environment.TEST_PARALLEL_INDEX ?? "").trim() !== "") {
171
+ throw new Error("A Playwright worker found no PLAYWRIGHT_PORT: the run's own configuration sets it before its workers start.");
172
+ }
173
+ basePort = freeConsecutivePorts(HOST, workers);
174
+ environment.PLAYWRIGHT_PORT = String(basePort);
175
+ }
130
176
  // A Playwright worker loads this config again, with its own TEST_PARALLEL_INDEX, and reaches its own server; its
131
177
  // process takes the environment prepare gave that server, such as its DB_NAME, before any test file loads.
132
178
  const workerIndex = managed ? 0 : Number.parseInt(String(environment.TEST_PARALLEL_INDEX || "0"), 10) || 0;
@@ -151,7 +197,7 @@ function browserTestConfig({
151
197
  return {
152
198
  testDir,
153
199
  workers,
154
- globalTimeout,
200
+ globalTimeout: runTimeout,
155
201
  timeout: 60_000,
156
202
  expect: { timeout: 10_000 },
157
203
  // Every run ends with its 10 slowest tests and their times.
package/scripts/jskit.mjs CHANGED
@@ -326,6 +326,14 @@ async function main(argv = process.argv.slice(2)) {
326
326
  `${result.addedMigrations.map((entry) => `- ${entry}`).join("\n")}\n`
327
327
  );
328
328
  }
329
+ if (result.uncomparedPackages.length > 0) {
330
+ process.stdout.write(
331
+ `The update could not tell whether ${result.uncomparedPackages.length} updated package(s) add migrations, since ` +
332
+ `node_modules did not hold their previous versions; run npm run db:migrate before the app serves requests:\n` +
333
+ `${result.uncomparedPackages.map(({ packageId, previousVersion, version }) =>
334
+ `- ${packageId} ${previousVersion} -> ${version}`).join("\n")}\n`
335
+ );
336
+ }
329
337
  if (!options.install) {
330
338
  process.stdout.write(
331
339
  "Skipped npm install; run it before jskit check. If it installs new package migrations, run npm run db:migrate " +
@@ -0,0 +1,67 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileExists, toPosixPath } from "./files.mjs";
4
+ import { readJsonRecord } from "./project-manifests.mjs";
5
+
6
+ // The package migrations a JSKIT update installs, which the app must run before the new packages serve requests.
7
+
8
+ const JSKIT_SCOPE_PREFIX = "@jskit-ai/";
9
+
10
+ // The @jskit-ai packages installed in node_modules, each with its version and the migration files it ships
11
+ // (jskit.migrations.directories and their constraints/), each by its path in the package, as the app's migrations
12
+ // read them from node_modules.
13
+ async function installedPackageMigrations(root) {
14
+ const scope = path.join(root, "node_modules", JSKIT_SCOPE_PREFIX);
15
+ const names = await readdir(scope).catch((error) => {
16
+ if (error?.code === "ENOENT") return [];
17
+ throw error;
18
+ });
19
+ const installed = new Map();
20
+ for (const name of names) {
21
+ const packageRoot = path.join(scope, name);
22
+ const manifestPath = path.join(packageRoot, "package.json");
23
+ if (!(await fileExists(manifestPath))) continue;
24
+ const manifest = (await readJsonRecord(manifestPath)).value;
25
+ const directories = manifest.jskit?.migrations?.directories;
26
+ const migrations = new Set();
27
+ for (const directory of Array.isArray(directories) ? directories : []) {
28
+ for (const folder of [directory, path.join(directory, "constraints")]) {
29
+ const files = await readdir(path.join(packageRoot, folder)).catch(() => []);
30
+ for (const file of files.filter((entry) => entry.endsWith(".cjs"))) {
31
+ migrations.add(toPosixPath(path.join(folder, file)));
32
+ }
33
+ }
34
+ }
35
+ installed.set(`${JSKIT_SCOPE_PREFIX}${name}`, { version: String(manifest.version || ""), migrations });
36
+ }
37
+ return installed;
38
+ }
39
+
40
+ // The package migrations an update added: the files its installed packages ship that the app's previous packages did
41
+ // not. A package node_modules held before is compared file by file. One it did not hold (a fresh checkout or worktree,
42
+ // never installed) is compared through its version in the previous package-lock.json (previousVersions, by package
43
+ // id): at the same version it ships the same files, and one the lock lacks is new to the app, with all its migrations.
44
+ // One whose version moved has earlier files that are nowhere on disk, so it is uncompared: none of its migrations are
45
+ // counted as new.
46
+ function packageMigrationChanges(before, after, previousVersions) {
47
+ const addedMigrations = [];
48
+ const uncomparedPackages = [];
49
+ for (const [packageId, { version, migrations }] of after) {
50
+ const previous = before.get(packageId);
51
+ const previousVersion = previousVersions.get(packageId);
52
+ if (previous) {
53
+ addedMigrations.push(...[...migrations].filter((file) => !previous.migrations.has(file))
54
+ .map((file) => `${packageId}: ${file}`));
55
+ } else if (previousVersion === undefined) {
56
+ addedMigrations.push(...[...migrations].map((file) => `${packageId}: ${file}`));
57
+ } else if (previousVersion !== version && migrations.size > 0) {
58
+ uncomparedPackages.push(Object.freeze({ packageId, previousVersion, version }));
59
+ }
60
+ }
61
+ return {
62
+ addedMigrations: addedMigrations.sort(),
63
+ uncomparedPackages: uncomparedPackages.sort((left, right) => left.packageId.localeCompare(right.packageId))
64
+ };
65
+ }
66
+
67
+ export { installedPackageMigrations, packageMigrationChanges };
@@ -2,6 +2,7 @@ import { readdir, readFile, realpath, rename, rm, writeFile } from "node:fs/prom
2
2
  import path from "node:path";
3
3
  import { fileExists, toPosixPath } from "./files.mjs";
4
4
  import { readOptionalFile, restoreProjectFiles, runNpmInstall, writeManifestUpdates } from "./project-install.mjs";
5
+ import { installedPackageMigrations, packageMigrationChanges } from "./project-migrations.mjs";
5
6
  import { discoverProjectManifests, readJsonRecord, serializePackageJson } from "./project-manifests.mjs";
6
7
 
7
8
  const JSKIT_SCOPE_PREFIX = "@jskit-ai/";
@@ -517,32 +518,6 @@ async function findImports(root, packageIds) {
517
518
  return imports;
518
519
  }
519
520
 
520
- // The migration files the installed @jskit-ai packages ship (jskit.migrations.directories and their constraints/),
521
- // each "<package>: <path in the package>", as the app's migrations read them from node_modules.
522
- async function installedPackageMigrations(root) {
523
- const scope = path.join(root, "node_modules", JSKIT_SCOPE_PREFIX);
524
- const names = await readdir(scope).catch((error) => {
525
- if (error?.code === "ENOENT") return [];
526
- throw error;
527
- });
528
- const migrations = new Set();
529
- for (const name of names) {
530
- const packageRoot = path.join(scope, name);
531
- const manifestPath = path.join(packageRoot, "package.json");
532
- if (!(await fileExists(manifestPath))) continue;
533
- const directories = (await readJsonRecord(manifestPath)).value.jskit?.migrations?.directories;
534
- for (const directory of Array.isArray(directories) ? directories : []) {
535
- for (const folder of [directory, path.join(directory, "constraints")]) {
536
- const files = await readdir(path.join(packageRoot, folder)).catch(() => []);
537
- for (const file of files.filter((entry) => entry.endsWith(".cjs"))) {
538
- migrations.add(`${JSKIT_SCOPE_PREFIX}${name}: ${toPosixPath(path.join(folder, file))}`);
539
- }
540
- }
541
- }
542
- }
543
- return migrations;
544
- }
545
-
546
521
  /**
547
522
  * Approves, in the root manifest's allowScripts, the install script of each JSKIT package in `declared` that has one,
548
523
  * unless the app already allows it by name or denies it in any entry.
@@ -682,10 +657,10 @@ async function updateProject({
682
657
  const packageLockPath = path.join(root, "package-lock.json");
683
658
  const packageLockSnapshot = install ? await readOptionalFile(packageLockPath) : null;
684
659
  // npm install replaces node_modules, so the migrations the packages shipped are read before it.
685
- const migrationsBefore = install ? await installedPackageMigrations(root) : new Set();
660
+ const migrationsBefore = install ? await installedPackageMigrations(root) : new Map();
686
661
  await writeManifestUpdates(updates);
687
662
  let installTransaction = null;
688
- let addedMigrations = [];
663
+ let migrationChanges = { addedMigrations: [], uncomparedPackages: [] };
689
664
  try {
690
665
  if (install) {
691
666
  const updatedManifests = await discoverProjectManifests(root, additionalManifests);
@@ -695,7 +670,12 @@ async function updateProject({
695
670
  if (!result.ok) {
696
671
  throw new Error(`JSKIT graph remains inconsistent after npm install:\n- ${result.issues.join("\n- ")}`);
697
672
  }
698
- addedMigrations = [...await installedPackageMigrations(root)].filter((entry) => !migrationsBefore.has(entry)).sort();
673
+ // The previous lock's top-level JSKIT versions, for packages node_modules did not hold before.
674
+ const previousLock = packageLockSnapshot.exists ? JSON.parse(packageLockSnapshot.contents) : {};
675
+ const previousVersions = new Map(collectLockInstallations(previousLock)
676
+ .filter((entry) => entry.path === `node_modules/${entry.packageId}`)
677
+ .map((entry) => [entry.packageId, entry.version]));
678
+ migrationChanges = packageMigrationChanges(migrationsBefore, await installedPackageMigrations(root), previousVersions);
699
679
  await installTransaction.commit();
700
680
  }
701
681
  } catch (error) {
@@ -727,7 +707,8 @@ async function updateProject({
727
707
  updates.map((update) => toPosixPath(path.relative(root, update.manifest.absolutePath)))
728
708
  ),
729
709
  catalogVersion,
730
- addedMigrations: Object.freeze(addedMigrations),
710
+ addedMigrations: Object.freeze(migrationChanges.addedMigrations),
711
+ uncomparedPackages: Object.freeze(migrationChanges.uncomparedPackages),
731
712
  retiredPackages: Object.freeze(retiredPackageIds.map((packageId) => Object.freeze({
732
713
  packageId,
733
714
  replacedBy: RETIRED_PACKAGES[packageId].packageId
@@ -31,6 +31,8 @@ const OTHER_RUNNER_IMPORT = /\b(?:from|import|require)\s*\(?\s*["'](?:vitest|@pl
31
31
  const MARKER = /^\s*\/\/\s*jskit-test:(.*)$/u;
32
32
  const ALONE = /^\s*alone\s+-\s+(\S.*)$/u;
33
33
  const SHARD = "--test-shard";
34
+ // A run of only some of its files' tests, by name or `only`, says nothing about how long a whole file takes.
35
+ const TEST_FILTER = /^--test-(?:name-pattern|skip-pattern|only)(?:=|$)/u;
34
36
  const REPORTER = "--test-reporter";
35
37
  const DESTINATION = "--test-reporter-destination";
36
38
  const TIME_REPORTER = new URL("./test-time-report.mjs", import.meta.url).href;
@@ -235,7 +237,8 @@ async function runTests(args) {
235
237
  }
236
238
  const times = interrupted
237
239
  ? null
238
- : reportTestTimes({ cwd: process.cwd(), collected, directory: timesDirectory, wallMs: performance.now() - started });
240
+ : reportTestTimes({ cwd: process.cwd(), collected, directory: timesDirectory, wallMs: performance.now() - started,
241
+ filtered: nodeArgs.some((argument) => TEST_FILTER.test(argument)) });
239
242
  if (times) process.stderr.write(times.report);
240
243
  if (times?.overruns.length > 0 && exitCode === 0) exitCode = 1;
241
244
  } finally {
@@ -122,14 +122,16 @@ function checkTestTimes({ bounds, files, tests, wallMs, stopped = [] }) {
122
122
 
123
123
  /**
124
124
  * Reads what the runs' reporters wrote and which files test-file-stop.mjs stopped, records each finished file's time
125
- * for the next command (a stopped file, or one that skipped a test, keeps the time it last finished all its tests in,
126
- * since the next stop is reckoned from it), and checks the times. A run whose
127
- * reporters were replaced (inside another node --test run) wrote nothing, and has no report unless a file was stopped.
128
- * @param {{ cwd: string, collected: string[], directory: string, wallMs: number }} options `collected`: the reporters'
129
- * destination files; `directory`: where the stopped files are written
125
+ * for the next command (a stopped file, one that skipped a test, and every file of a run filtered to some of its tests
126
+ * keep the time they last finished all their tests in, since the next stop is reckoned from it), and checks the times.
127
+ * A run whose reporters were replaced (inside another node --test run) wrote nothing, and has no report unless a file
128
+ * was stopped.
129
+ * @param {{ cwd: string, collected: string[], directory: string, wallMs: number, filtered?: boolean }} options
130
+ * `collected`: the reporters' destination files; `directory`: where the stopped files are written; `filtered`: the run
131
+ * ran only the tests a name pattern or `only` picked
130
132
  * @returns {{ overruns: string[], report: string } | null}
131
133
  */
132
- function reportTestTimes({ cwd, collected, directory, wallMs }) {
134
+ function reportTestTimes({ cwd, collected, directory, wallMs, filtered = false }) {
133
135
  const runs = collected.filter((file) => existsSync(file) && readFileSync(file, "utf8").trim())
134
136
  .map((file) => JSON.parse(readFileSync(file, "utf8")));
135
137
  const stopped = readdirSync(directory).filter((name) => name.startsWith(STOPPED_PREFIX)).sort()
@@ -137,7 +139,7 @@ function reportTestTimes({ cwd, collected, directory, wallMs }) {
137
139
  const files = Object.assign({}, ...runs.map((run) => run.files));
138
140
  if (Object.keys(files).length === 0 && stopped.length === 0) return null;
139
141
  const unrepresentative = new Set([...stopped.map((stop) => stop.file), ...runs.flatMap((run) => run.skipped ?? [])]);
140
- const finished = Object.fromEntries(Object.entries(files).filter(([name]) => !unrepresentative.has(name)));
142
+ const finished = filtered ? {} : Object.fromEntries(Object.entries(files).filter(([name]) => !unrepresentative.has(name)));
141
143
  const record = path.join(cwd, FILE_TIMES);
142
144
  const recorded = existsSync(record) ? JSON.parse(readFileSync(record, "utf8")) : {};
143
145
  mkdirSync(path.dirname(record), { recursive: true });