@orkestrel/test 0.0.40 → 0.0.41

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.
@@ -38,6 +38,11 @@ var PROGRESS_VERSION = 1;
38
38
  */
39
39
  var PROGRESS_MESSAGE_LIMIT = 300;
40
40
  /**
41
+ * Keys the brand every `ProgressReporter` carries, registered so that each copy of this package
42
+ * reads the same key.
43
+ */
44
+ var PROGRESS_BRAND = Symbol.for("@orkestrel/test.ProgressReporter");
45
+ /**
41
46
  * Names the label a rendered progress reading prints for each failure relation.
42
47
  */
43
48
  var PROGRESS_LABELS = Object.freeze({
@@ -459,11 +464,11 @@ function readInventory(root, targets, options) {
459
464
  return Object.fromEntries(Array.from(contents).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0));
460
465
  }
461
466
  /**
462
- * Reports whether a process id names a live process.
467
+ * Reports whether a process id names a live process, reading each of its threads on Linux.
463
468
  *
464
469
  * @param pid - The process id to read.
465
- * @returns True if a process holds that id at the moment of the call; false otherwise, including a
466
- * pid the host refuses.
470
+ * @returns True if a process holds that id at the moment of the call and, on Linux, one of its
471
+ * threads has not exited; false otherwise, including a pid the host refuses.
467
472
  * @throws Nothing. Every host refusal reads as false.
468
473
  * @remarks This is an instantaneous observation rather than a claim of ownership. A host reuses a
469
474
  * process id after the process holding it exits, so a true answer says some process holds that id at the time of the check
@@ -472,8 +477,14 @@ function readInventory(root, targets, options) {
472
477
  * false here. A pid of `0` names the caller's own process group on POSIX and the system idle process
473
478
  * on Windows, so it reads as true on both without naming a process anyone started.
474
479
  *
475
- * A Linux zombie — a process that has exited and whose parent has not reaped it — still accepts
476
- * signal `0`, so its `/proc` status is read and a `Z` state reads as false.
480
+ * A signal reaches a Linux process that has exited but whose parent has not reaped it, so on Linux
481
+ * the answer also reads `/proc/<pid>/task`. The process has ended only when two readings taken one
482
+ * after the other list the same threads and every thread in both reads `Z` (exited) or `X` (dead).
483
+ * The leader thread's own state decides nothing: a process whose main thread has exited reads `Z`
484
+ * for its leader while another thread still runs, as a Node process does for milliseconds while its
485
+ * worker threads stop during exit, and it reads as true. A thread whose `stat` cannot be read has
486
+ * gone and counts as exited, and a process whose `task` directory cannot be listed reads as false.
487
+ * The thread table is Linux's layout, so every other host keeps the signal answer.
477
488
  *
478
489
  * @example
479
490
  * ```ts
@@ -489,14 +500,23 @@ function isRunning(pid) {
489
500
  } catch {
490
501
  return false;
491
502
  }
492
- if (process.platform !== "linux") return true;
493
- try {
494
- const status = (0, node_fs.readFileSync)(`/proc/${String(pid)}/stat`, "utf8");
495
- const boundary = status.lastIndexOf(") ");
496
- return boundary < 0 || status.slice(boundary + 2, boundary + 3) !== "Z";
497
- } catch {
498
- return false;
499
- }
503
+ if (process.platform !== "linux" || pid === 0) return true;
504
+ const directory = (0, node_path.join)("/proc", String(pid), "task");
505
+ const [first, second] = Array.from({ length: 2 }, () => {
506
+ const listing = (0, _orkestrel_contract.attempt)(() => (0, node_fs.readdirSync)(directory));
507
+ return listing.success ? listing.value.flatMap((thread) => {
508
+ const status = (0, _orkestrel_contract.attempt)(() => (0, node_fs.readFileSync)((0, node_path.join)(directory, thread, "stat"), "utf8"));
509
+ if (!status.success) return [];
510
+ const boundary = status.value.lastIndexOf(") ");
511
+ return [{
512
+ thread,
513
+ state: boundary < 0 ? "" : status.value.slice(boundary + 2, boundary + 3)
514
+ }];
515
+ }) : void 0;
516
+ });
517
+ if (first === void 0 || second === void 0) return false;
518
+ const [listed, relisted] = [first, second].map((reading) => reading.map(({ thread }) => thread).toSorted().join(" "));
519
+ return listed !== relisted || [...first, ...second].some(({ state }) => state !== "Z" && state !== "X");
500
520
  }
501
521
  /**
502
522
  * Waits for a socket to close, accepting a peer reset as a forced close.
@@ -997,7 +1017,9 @@ async function chooseFiles(context, request) {
997
1017
  * ```
998
1018
  */
999
1019
  function normalizeProgressPath(file, root) {
1000
- const path = (0, node_path.relative)(root, file.replace(/^\/@fs\//u, "")).replaceAll("\\", "/");
1020
+ const named = file.startsWith("/@fs/") ? file.slice(5) : file;
1021
+ const absolute = named === file || named.startsWith("/") || /^[a-z]:/iu.test(named) ? named : `/${named}`;
1022
+ const path = (0, node_path.relative)(root, absolute).replaceAll("\\", "/");
1001
1023
  return path === ".." || path.startsWith("../") || (0, node_path.isAbsolute)(path) ? file : path;
1002
1024
  }
1003
1025
  /**
@@ -1051,6 +1073,28 @@ function matchesPlannedCase(test) {
1051
1073
  return test.options.mode === "run" || test.options.mode === "only";
1052
1074
  }
1053
1075
  /**
1076
+ * Checks whether a value is a progress reporter from any copy of this package, by the brand each
1077
+ * one carries under `PROGRESS_BRAND`.
1078
+ *
1079
+ * @param value - The value to inspect, such as an entry of `vitest.config.reporters`.
1080
+ * @returns True if the value holds an own `PROGRESS_BRAND` property whose value is the value
1081
+ * itself; false otherwise, a value whose inspection throws included.
1082
+ * @remarks A configuration that imports the package by a file path loads a separate copy of the
1083
+ * module for each evaluation, so an `instanceof` check against one copy's class misses the
1084
+ * reporters another copy made, and the brand recognizes them all.
1085
+ *
1086
+ * @example
1087
+ * ```ts
1088
+ * import { matchesProgressReporter, ProgressReporter } from '@orkestrel/test/server'
1089
+ *
1090
+ * matchesProgressReporter(new ProgressReporter()) // true
1091
+ * matchesProgressReporter('dot') // false
1092
+ * ```
1093
+ */
1094
+ function matchesProgressReporter(value) {
1095
+ return (0, _orkestrel_contract.holds)(() => (0, _orkestrel_contract.isObject)(value) && Object.hasOwn(value, PROGRESS_BRAND) && Reflect.get(value, PROGRESS_BRAND) === value);
1096
+ }
1097
+ /**
1054
1098
  * Reads the bytes a file holds when it is opened, leaving out every byte appended during the read.
1055
1099
  *
1056
1100
  * @param path - The file to read.
@@ -1152,6 +1196,7 @@ function computeProgressRun(events, now) {
1152
1196
  const specifications = filterProgressEvents(own, "start").flatMap((start) => start.specifications);
1153
1197
  const collections = filterProgressEvents(own, "collected");
1154
1198
  const cases = filterProgressEvents(own, "case");
1199
+ const settled = cases.filter((entry) => entry.state !== "pending");
1155
1200
  const cancel = filterProgressEvents(own, "cancel").at(0);
1156
1201
  const end = filterProgressEvents(own, "end").at(0);
1157
1202
  const clock = end?.time ?? now - init.wall + init.time;
@@ -1165,19 +1210,20 @@ function computeProgressRun(events, now) {
1165
1210
  return {
1166
1211
  name,
1167
1212
  planned: collected.reduce((total, entry) => total + entry.planned, 0),
1168
- done: results.length,
1213
+ done: results.filter((entry) => entry.state !== "pending").length,
1169
1214
  passed: results.filter((entry) => entry.state === "passed").length,
1170
1215
  failed: results.filter((entry) => entry.state === "failed").length + collected.filter((entry) => entry.errors.length > 0).length,
1171
1216
  skipped: results.filter((entry) => entry.state === "skipped").length,
1217
+ pending: results.filter((entry) => entry.state === "pending").length,
1172
1218
  modules: specifications.filter((entry) => entry.project === name).length,
1173
1219
  collected: collected.length
1174
1220
  };
1175
1221
  });
1176
1222
  const planned = projects.reduce((total, project) => total + project.planned, 0);
1177
1223
  const exact = specifications.length > 0 && projects.every((project) => project.collected >= project.modules);
1178
- const first = cases.at(0);
1224
+ const first = settled.at(0);
1179
1225
  const span = first === void 0 ? 0 : clock - (first.time - (first.duration ?? 0));
1180
- const rate = cases.length > 0 && span > 0 ? cases.length / span * 6e4 : void 0;
1226
+ const rate = settled.length > 0 && span > 0 ? settled.length / span * 6e4 : void 0;
1181
1227
  const finished = new Set(cases.map((entry) => entry.id));
1182
1228
  const position = cancel === void 0 ? -1 : own.indexOf(cancel);
1183
1229
  const trigger = own.find((event) => event.event === "case" && event.state === "failed");
@@ -1201,11 +1247,11 @@ function computeProgressRun(events, now) {
1201
1247
  state: end?.reason ?? "live",
1202
1248
  bail: init.bail,
1203
1249
  elapsed: clock,
1204
- done: cases.length,
1250
+ done: settled.length,
1205
1251
  planned,
1206
1252
  exact,
1207
1253
  rate,
1208
- remaining: end === void 0 && exact && rate !== void 0 ? Math.max(0, (planned - cases.length) / rate * 6e4) : void 0,
1254
+ remaining: end === void 0 && exact && rate !== void 0 ? Math.max(0, (planned - settled.length) / rate * 6e4) : void 0,
1209
1255
  projects,
1210
1256
  running: end === void 0 ? filterProgressEvents(own, "ready").filter((ready) => !finished.has(ready.id)).map((ready) => ({
1211
1257
  project: ready.project,
@@ -1311,7 +1357,7 @@ function renderProgress(runs) {
1311
1357
  const width = Math.max(0, ...run.projects.map((project) => project.name.length));
1312
1358
  return [
1313
1359
  `run ${run.pid} ${run.state} ${run.bail === 0 ? "full" : `bail=${run.bail}`}: ${run.done}/${run.planned}${run.exact ? "" : "+"} cases, elapsed ${renderDuration(run.elapsed)}, rate ${run.rate === void 0 ? "-" : `${run.rate.toFixed(1)}/min`}, ETA ${run.remaining === void 0 ? "-" : renderDuration(run.remaining)}`,
1314
- ...run.projects.map((project) => ` ${project.name.padEnd(width)} ${project.done}/${project.planned} passed ${project.passed} failed ${project.failed} skipped ${project.skipped}${project.collected < project.modules ? ` (${project.collected}/${project.modules} modules collected)` : ""}`),
1360
+ ...run.projects.map((project) => ` ${project.name.padEnd(width)} ${project.done}/${project.planned} passed ${project.passed} failed ${project.failed} skipped ${project.skipped}${project.pending > 0 ? ` pending ${project.pending}` : ""}${project.collected < project.modules ? ` (${project.collected}/${project.modules} modules collected)` : ""}`),
1315
1361
  ...run.running.map((entry) => ` running ${renderDuration(entry.duration)} [${entry.project}] ${entry.name}`),
1316
1362
  ...run.cancel === void 0 ? [] : [` cancelled (${run.cancel.reason}) at ${renderDuration(run.cancel.time)}`],
1317
1363
  ...[...run.failures.map((failure) => ({
@@ -1558,6 +1604,10 @@ function createCookieJar() {
1558
1604
  * Appends one JSON line per Vitest run event to the file `--outputFile.progress` names, so a live
1559
1605
  * run's progress and each failure's first error can be read before the run ends.
1560
1606
  *
1607
+ * @remarks Only the first instance in `vitest.config.reporters` writes; a later instance in the same
1608
+ * Vitest writes nothing, so a run is never counted twice. Each instance carries the
1609
+ * `PROGRESS_BRAND` brand, so an instance from another copy of this package counts as earlier.
1610
+ *
1561
1611
  * @example
1562
1612
  * ```ts
1563
1613
  * import { defineConfig } from 'vitest/config'
@@ -1580,12 +1630,15 @@ var ProgressReporter = class {
1580
1630
  #overhead = 0;
1581
1631
  constructor() {
1582
1632
  this.#listener = this.#cancel.bind(this);
1633
+ Object.defineProperty(this, PROGRESS_BRAND, { value: this });
1583
1634
  }
1584
1635
  onInit(vitest) {
1585
1636
  this.#measure(() => {
1586
1637
  const output = vitest.config.outputFile;
1587
1638
  const named = typeof output === "object" ? output.progress : void 0;
1588
1639
  if (named === void 0) throw new Error("ProgressReporter writes no file: pass --outputFile.progress=<file>, or set outputFile: { progress: <file> } in the test config");
1640
+ const writer = vitest.config.reporters.find((entry) => matchesProgressReporter(entry));
1641
+ if (writer !== void 0 && writer !== this) return;
1589
1642
  this.#vitest = vitest;
1590
1643
  this.#path = (0, node_path.resolve)(vitest.config.root, named);
1591
1644
  (0, node_fs.mkdirSync)((0, node_path.dirname)(this.#path), { recursive: true });
@@ -1717,6 +1770,44 @@ var ProgressReporter = class {
1717
1770
  (0, node_fs.appendFileSync)(this.#path, `${JSON.stringify(event)}\n`);
1718
1771
  }
1719
1772
  };
1773
+ // src/server/plugins.ts
1774
+ /**
1775
+ * Creates a Vitest plugin that adds one `ProgressReporter` to every run naming a progress file, so
1776
+ * the reporter still runs when command-line `--reporter` flags replace the configured reporters.
1777
+ *
1778
+ * @remarks Mount the value in the root `plugins` of a configuration. Vitest calls its hook once per
1779
+ * project that carries it, and the hook adds a reporter only while the run's reporters hold no
1780
+ * `ProgressReporter` from any copy of this package, read by its `PROGRESS_BRAND` brand, so a run
1781
+ * writes one `init` line wherever the plugin is mounted, a configuration that imports the package
1782
+ * by a file path included. The hook adds
1783
+ * a reporter when the resolved `outputFile` names `progress`, from `--outputFile.progress` or from
1784
+ * the configuration's `outputFile`, and adds none otherwise, because `ProgressReporter` refuses to
1785
+ * initialize without that file.
1786
+ *
1787
+ * @example
1788
+ * ```ts
1789
+ * import { defineConfig } from 'vitest/config'
1790
+ * import { createProgressPlugin } from '@orkestrel/test/server'
1791
+ *
1792
+ * export default defineConfig({
1793
+ * plugins: [createProgressPlugin()],
1794
+ * test: { projects: [() => ({ test: { name: 'unit' } })] },
1795
+ * })
1796
+ * // npx vitest run --reporter=dot --outputFile.progress=tmp/runs/progress.jsonl
1797
+ * ```
1798
+ */
1799
+ function createProgressPlugin() {
1800
+ return {
1801
+ name: "orkestrel:progress",
1802
+ configureVitest({ vitest }) {
1803
+ const output = vitest.config.outputFile;
1804
+ if (typeof output !== "object" || output.progress === void 0) return;
1805
+ if (vitest.config.reporters.some((entry) => matchesProgressReporter(entry))) return;
1806
+ vitest.config.reporters.push(new ProgressReporter());
1807
+ }
1808
+ };
1809
+ }
1810
+ exports.PROGRESS_BRAND = PROGRESS_BRAND;
1720
1811
  exports.PROGRESS_LABELS = PROGRESS_LABELS;
1721
1812
  exports.PROGRESS_MESSAGE_LIMIT = PROGRESS_MESSAGE_LIMIT;
1722
1813
  exports.PROGRESS_VERSION = PROGRESS_VERSION;
@@ -1731,6 +1822,7 @@ exports.computeProgressRun = computeProgressRun;
1731
1822
  exports.createCookieJar = createCookieJar;
1732
1823
  exports.createLink = createLink;
1733
1824
  exports.createLoopback = createLoopback;
1825
+ exports.createProgressPlugin = createProgressPlugin;
1734
1826
  exports.createScratch = createScratch;
1735
1827
  exports.destroyScratch = destroyScratch;
1736
1828
  exports.extractProgressError = extractProgressError;
@@ -1743,6 +1835,7 @@ exports.isProgressEvent = isProgressEvent;
1743
1835
  exports.isRunning = isRunning;
1744
1836
  exports.matchesIdentity = matchesIdentity;
1745
1837
  exports.matchesPlannedCase = matchesPlannedCase;
1838
+ exports.matchesProgressReporter = matchesProgressReporter;
1746
1839
  exports.normalizeProgressPath = normalizeProgressPath;
1747
1840
  exports.readCapture = readCapture;
1748
1841
  exports.readErrorCode = readErrorCode;