@hughescr/stryker-bun-runner 1.7.1 → 1.7.2

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/dist/index.js CHANGED
@@ -1910,6 +1910,185 @@ function mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger
1910
1910
  orphanedKeyCount: counterIds.length - creditedKeyCount
1911
1911
  };
1912
1912
  }
1913
+ // src/drain-handshake.ts
1914
+ var DRAIN_ACK_SILENCE_TIMEOUT_MS = 4000;
1915
+ var DRAIN_ACK_ABSOLUTE_CEILING_MS = 30000;
1916
+ var DRAIN_SILENCE_POLL_INTERVAL_MS = 250;
1917
+ var MAX_GAP_IDS_LISTED = 20;
1918
+
1919
+ class DrainWaitTimeoutError extends Error {
1920
+ reason;
1921
+ constructor(message, reason) {
1922
+ super(message);
1923
+ this.name = "DrainWaitTimeoutError";
1924
+ this.reason = reason;
1925
+ }
1926
+ }
1927
+
1928
+ class InspectorClosedError extends Error {
1929
+ }
1930
+ function raceAgainstSilence(inspector, silenceMs, absoluteCeilingMs) {
1931
+ const startedAt = Date.now();
1932
+ let timer;
1933
+ const promise = new Promise((_resolve, reject) => {
1934
+ timer = setInterval(() => {
1935
+ const sinceLastFrame = inspector.getMsSinceLastFrame();
1936
+ const totalElapsed = Date.now() - startedAt;
1937
+ if (totalElapsed >= absoluteCeilingMs) {
1938
+ reject(new DrainWaitTimeoutError(`${absoluteCeilingMs}ms absolute ceiling reached`, "ceiling"));
1939
+ } else if (totalElapsed >= silenceMs && sinceLastFrame >= silenceMs) {
1940
+ reject(new DrainWaitTimeoutError(`${sinceLastFrame}ms of inspector silence (limit ${silenceMs}ms)`, "silence"));
1941
+ }
1942
+ }, DRAIN_SILENCE_POLL_INTERVAL_MS);
1943
+ });
1944
+ return { promise, cancel: () => clearInterval(timer) };
1945
+ }
1946
+ function formatGapIdList(gaps) {
1947
+ if (gaps.length === 0) {
1948
+ return "";
1949
+ }
1950
+ const shown = gaps.slice(0, MAX_GAP_IDS_LISTED).join(",");
1951
+ return gaps.length > MAX_GAP_IDS_LISTED ? ` [${shown},…]` : ` [${shown}]`;
1952
+ }
1953
+ function isProof(reason) {
1954
+ return reason === "ack" || reason === "events";
1955
+ }
1956
+ var nothingToStop = () => {
1957
+ return;
1958
+ };
1959
+
1960
+ class DrainHandshake {
1961
+ inspector;
1962
+ logger;
1963
+ profile;
1964
+ silenceMs;
1965
+ settlements = [];
1966
+ rejection;
1967
+ requests = 0;
1968
+ dropped = 0;
1969
+ expectedStarts = 0;
1970
+ unprovenSince;
1971
+ constructor(inspector, logger, profile, silenceMs = DRAIN_ACK_SILENCE_TIMEOUT_MS) {
1972
+ this.inspector = inspector;
1973
+ this.logger = logger;
1974
+ this.profile = profile;
1975
+ this.silenceMs = silenceMs;
1976
+ }
1977
+ get proven() {
1978
+ return this.requests > 0 && this.dropped === 0 && this.settlements.length === this.requests && this.settlements.every((reason) => isProof(reason));
1979
+ }
1980
+ describe() {
1981
+ const served = this.describeServed();
1982
+ return this.dropped === 0 ? served : `${served}; ${this.dropped} dropped unserved`;
1983
+ }
1984
+ describeServed() {
1985
+ if (this.requests === 0) {
1986
+ return "never requested";
1987
+ }
1988
+ if (this.requests === 1) {
1989
+ return this.settlements.length === 1 ? `settled via ${this.settlements[0]}` : "requested, not settled";
1990
+ }
1991
+ const counts = new Map;
1992
+ for (const reason of this.settlements) {
1993
+ counts.set(reason, (counts.get(reason) ?? 0) + 1);
1994
+ }
1995
+ const unsettled = this.requests - this.settlements.length;
1996
+ if (unsettled > 0) {
1997
+ counts.set("not settled", unsettled);
1998
+ }
1999
+ const byReason = [...counts].map(([how, count]) => `${how} (${count})`);
2000
+ return `${this.requests} requests: ${byReason.join(", ")}`;
2001
+ }
2002
+ requestDropped(request) {
2003
+ this.dropped++;
2004
+ this.unprovenSince ??= "a drain request was dropped unserved";
2005
+ this.logger.debug("Drain request dropped unserved (its client went away first), with a count of %s: no later request of this launch can be proven from the test events", String(request.startedTests));
2006
+ }
2007
+ async handle(request) {
2008
+ const receivedAt = Date.now();
2009
+ this.profile?.at("drainRequest");
2010
+ this.requests++;
2011
+ const startedTests = request?.startedTests;
2012
+ this.expectedStarts = this.expectedStarts === undefined || startedTests === undefined ? undefined : this.expectedStarts + startedTests;
2013
+ const countsAtRequest = this.inspector.getEventCounts();
2014
+ const gapsAtRequest = this.inspector.getFoundIdGaps();
2015
+ this.logger.debug("Drain-request received: %d/%d/%d found/start/end events received so far; %d found-id gap(s)%s", countsAtRequest.found, countsAtRequest.start, countsAtRequest.end, gapsAtRequest.length, formatGapIdList(gapsAtRequest));
2016
+ const reason = await this.prove();
2017
+ this.profile?.at("drainSettled");
2018
+ this.settlements.push(reason);
2019
+ if (!isProof(reason)) {
2020
+ this.unprovenSince ??= `drain-request ${this.requests} settled via ${reason}`;
2021
+ }
2022
+ this.inspector.startProgressWindow();
2023
+ const countsAtSettle = this.inspector.getEventCounts();
2024
+ const gapsAtSettle = this.inspector.getFoundIdGaps();
2025
+ this.logger.debug("Drain handler settled via %s after %dms; events during wait +%d/+%d/+%d found/start/end; found-id gaps %d -> %d%s", reason, Date.now() - receivedAt, countsAtSettle.found - countsAtRequest.found, countsAtSettle.start - countsAtRequest.start, countsAtSettle.end - countsAtRequest.end, gapsAtRequest.length, gapsAtSettle.length, isProof(reason) && gapsAtSettle.length > 0 ? ` — ${reason} resolved but gaps remain: the ${reason} may under-prove drain` : "");
2026
+ }
2027
+ async prove() {
2028
+ const first = this.requests === 1;
2029
+ const provable = this.unprovenSince === undefined;
2030
+ if (!first) {
2031
+ const progress = this.inspector.getTestProgress();
2032
+ this.logger.debug("Drain-request %d of this launch (bun evaluated the preload again, as --isolate does for each test file, and answers no inspector command after the first file): " + "%s: %s test start(s) expected, %d received, %d test(s) running, %d of %d test(s) found since the previous request without an end", this.requests, provable ? "proving it from the test events" : `not proving it from the test events, since ${this.unprovenSince}; waiting for the silence bound instead`, String(this.expectedStarts), progress.testStarts, progress.testsRunning, progress.unendedTests, progress.foundTests);
2033
+ if (provable && this.eventsProveDrain()) {
2034
+ return "events";
2035
+ }
2036
+ }
2037
+ const { promise: silence, cancel } = raceAgainstSilence(this.inspector, this.silenceMs, DRAIN_ACK_ABSOLUTE_CEILING_MS);
2038
+ const proof = first ? this.roundTrip() : this.waitForEvents(provable);
2039
+ try {
2040
+ return await Promise.race([proof.promise, silence]);
2041
+ } catch (error) {
2042
+ return this.giveUpReason(error);
2043
+ } finally {
2044
+ cancel();
2045
+ proof.stop();
2046
+ }
2047
+ }
2048
+ giveUpReason(error) {
2049
+ if (error instanceof DrainWaitTimeoutError) {
2050
+ this.logger.debug("Inspector drain wait gave up: %s", error.message);
2051
+ return error.reason;
2052
+ }
2053
+ if (error instanceof InspectorClosedError) {
2054
+ this.logger.debug("Inspector connection closed before the test events proved drain-request %d", this.requests);
2055
+ return "closed";
2056
+ }
2057
+ this.rejection = error instanceof Error ? error.message : String(error);
2058
+ this.logger.debug("Inspector drain round-trip rejected before any wait bound was hit: %s", this.rejection);
2059
+ return "send-rejected";
2060
+ }
2061
+ roundTrip() {
2062
+ return {
2063
+ promise: this.inspector.send("TestReporter.enable", {}, DRAIN_ACK_ABSOLUTE_CEILING_MS + 1000).then(() => "ack"),
2064
+ stop: nothingToStop
2065
+ };
2066
+ }
2067
+ waitForEvents(provable) {
2068
+ let stop = nothingToStop;
2069
+ const promise = new Promise((resolve, reject) => {
2070
+ const check = () => {
2071
+ if (provable && this.eventsProveDrain()) {
2072
+ resolve("events");
2073
+ } else if (this.inspector.hasClosed) {
2074
+ reject(new InspectorClosedError);
2075
+ }
2076
+ };
2077
+ stop = this.inspector.onProgress(check);
2078
+ check();
2079
+ });
2080
+ return { promise, stop: () => stop() };
2081
+ }
2082
+ eventsProveDrain() {
2083
+ const expected = this.expectedStarts;
2084
+ if (expected === undefined) {
2085
+ return false;
2086
+ }
2087
+ const progress = this.inspector.getTestProgress();
2088
+ return progress.testStarts >= expected && progress.testsRunning === 0 && progress.foundTests > 0 && progress.unendedTests === 0;
2089
+ }
2090
+ }
2091
+
1913
2092
  // src/inspector/types.ts
1914
2093
  var TEST_STATUSES = ["pass", "fail", "timeout", "skip", "todo", "skipped_because_label"];
1915
2094
  function isTestReporterFoundEvent(message) {
@@ -2050,6 +2229,10 @@ class InspectorClient {
2050
2229
  foundCount = 0;
2051
2230
  startCount = 0;
2052
2231
  endCount = 0;
2232
+ windowTests = 0;
2233
+ windowUnended = new Set;
2234
+ runningTests = new Set;
2235
+ progressListeners = new Set;
2053
2236
  closeCode = undefined;
2054
2237
  closeReason = undefined;
2055
2238
  closeWasClean = undefined;
@@ -2145,6 +2328,21 @@ class InspectorClient {
2145
2328
  this.ws.close();
2146
2329
  }
2147
2330
  this.ws = null;
2331
+ this.notifyProgress();
2332
+ }
2333
+ get hasClosed() {
2334
+ return this.wsClosed || this.isClosing;
2335
+ }
2336
+ onProgress(listener) {
2337
+ this.progressListeners.add(listener);
2338
+ return () => {
2339
+ this.progressListeners.delete(listener);
2340
+ };
2341
+ }
2342
+ notifyProgress() {
2343
+ for (const listener of this.progressListeners) {
2344
+ listener();
2345
+ }
2148
2346
  }
2149
2347
  expectClose() {
2150
2348
  this.closeExpected = true;
@@ -2192,6 +2390,18 @@ class InspectorClient {
2192
2390
  getEventCounts() {
2193
2391
  return { found: this.foundCount, start: this.startCount, end: this.endCount };
2194
2392
  }
2393
+ getTestProgress() {
2394
+ return {
2395
+ testStarts: this.executionOrder.length,
2396
+ testsRunning: this.runningTests.size,
2397
+ foundTests: this.windowTests,
2398
+ unendedTests: this.windowUnended.size
2399
+ };
2400
+ }
2401
+ startProgressWindow() {
2402
+ this.windowTests = 0;
2403
+ this.windowUnended.clear();
2404
+ }
2195
2405
  getCloseInfo() {
2196
2406
  return {
2197
2407
  code: this.closeCode,
@@ -2244,6 +2454,7 @@ class InspectorClient {
2244
2454
  } else if (isTestReporterEndEvent(message)) {
2245
2455
  this.handleTestEnd(message.params);
2246
2456
  }
2457
+ this.notifyProgress();
2247
2458
  } catch (error) {
2248
2459
  this.handleError(error instanceof Error ? error : new Error(String(error)));
2249
2460
  }
@@ -2262,6 +2473,10 @@ class InspectorClient {
2262
2473
  line: params.line
2263
2474
  };
2264
2475
  this.testHierarchy.set(params.id, testInfo);
2476
+ if (testInfo.type === "test") {
2477
+ this.windowTests++;
2478
+ this.windowUnended.add(testInfo);
2479
+ }
2265
2480
  if (this.handlers.onTestFound) {
2266
2481
  this.handlers.onTestFound(testInfo);
2267
2482
  }
@@ -2275,6 +2490,7 @@ class InspectorClient {
2275
2490
  }
2276
2491
  if (testInfo.type === "test") {
2277
2492
  this.executionOrder.push(params.id);
2493
+ this.runningTests.add(params.id);
2278
2494
  }
2279
2495
  if (this.handlers.onTestStart) {
2280
2496
  this.handlers.onTestStart(testInfo);
@@ -2287,6 +2503,8 @@ class InspectorClient {
2287
2503
  this.handleError(new Error(`Test end event for unknown test ID: ${params.id}`));
2288
2504
  return;
2289
2505
  }
2506
+ this.runningTests.delete(params.id);
2507
+ this.windowUnended.delete(testInfo);
2290
2508
  testInfo.status = params.status;
2291
2509
  testInfo.elapsed = params.elapsed;
2292
2510
  if (params.error) {
@@ -2329,6 +2547,7 @@ class InspectorClient {
2329
2547
  for (const finish of waiters) {
2330
2548
  finish();
2331
2549
  }
2550
+ this.notifyProgress();
2332
2551
  if (this.isClosing || this.closeExpected) {
2333
2552
  return;
2334
2553
  }
@@ -2359,1000 +2578,1002 @@ class InspectorClient {
2359
2578
  }
2360
2579
  }
2361
2580
  // src/parsers/console-parser.ts
2362
- import path9 from "node:path";
2363
-
2364
- // src/process-runner.ts
2365
- import { spawn as spawn3 } from "node:child_process";
2581
+ import path7 from "node:path";
2366
2582
 
2367
- // src/utils/process-group.ts
2368
- function killProcessGroup(pid, signal) {
2369
- try {
2370
- process.kill(-pid, signal);
2371
- return true;
2372
- } catch {
2373
- return false;
2374
- }
2583
+ // src/utils/strip-ansi.ts
2584
+ function stripAnsi(text) {
2585
+ return text.replaceAll(/\u001B\[[0-9;?]*[\u0020-\u002F]*[\u0040-\u007E]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g, "");
2375
2586
  }
2376
2587
 
2377
- // src/utils/process-rss.ts
2378
- import { spawn as spawn2 } from "node:child_process";
2379
- import { readFile as readFile4 } from "node:fs/promises";
2380
- async function getProcessRssBytes(pid) {
2381
- return process.platform === "linux" ? getLinuxRss(pid) : getPsRss(pid);
2382
- }
2383
- function parseVmRss(statusContent) {
2384
- const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(statusContent);
2385
- return match ? Number(match[1]) * 1024 : null;
2386
- }
2387
- async function getLinuxRss(pid) {
2388
- try {
2389
- const status = await readFile4(`/proc/${pid}/status`, "utf8");
2390
- return parseVmRss(status);
2391
- } catch {
2392
- return null;
2393
- }
2588
+ // src/parsers/console-parser.ts
2589
+ var fileHeaderRe = new RegExp(String.raw`^(?:::group::)?([^:]+${TEST_FILE_SUFFIX_PATTERN}):$`, "i");
2590
+ var workflowCommandRe = /^::(?:group|endgroup|error|warning|notice|debug|add-mask|add-matcher|remove-matcher)(?:::|\s|$)/;
2591
+ function parseFilePath(line) {
2592
+ const fileMatch = fileHeaderRe.exec(line);
2593
+ return fileMatch ? fileMatch[1] : null;
2394
2594
  }
2395
- function parsePsRssOutput(output) {
2396
- const trimmed = output.trim();
2397
- if (trimmed === "") {
2398
- return null;
2595
+ function headerFilter(lines, testFiles) {
2596
+ if (testFiles === undefined) {
2597
+ return () => true;
2399
2598
  }
2400
- const kb = Number(trimmed);
2401
- return Number.isFinite(kb) ? kb * 1024 : null;
2402
- }
2403
- async function getPsRss(pid) {
2404
- return new Promise((resolve) => {
2405
- let child;
2406
- try {
2407
- child = spawn2("ps", ["-o", "rss=", "-p", String(pid)], { stdio: ["ignore", "pipe", "ignore"] });
2408
- } catch {
2409
- resolve(null);
2410
- return;
2599
+ const roots = new Set(testFiles.map((file) => path7.resolve(file)));
2600
+ const isRunFile = (file) => {
2601
+ let candidate = path7.resolve(file);
2602
+ while (!roots.has(candidate)) {
2603
+ const parent = path7.dirname(candidate);
2604
+ if (parent === candidate) {
2605
+ return false;
2606
+ }
2607
+ candidate = parent;
2411
2608
  }
2412
- let output = "";
2413
- child.stdout.on("data", (data) => {
2414
- output += data.toString();
2415
- });
2416
- child.on("close", (code) => {
2417
- resolve(code === 0 ? parsePsRssOutput(output) : null);
2418
- });
2419
- child.on("error", () => {
2420
- resolve(null);
2421
- });
2609
+ return true;
2610
+ };
2611
+ const namesRunFile = lines.some((line) => {
2612
+ const file = parseFilePath(line);
2613
+ return file !== null && isRunFile(file);
2422
2614
  });
2615
+ return namesRunFile ? isRunFile : () => true;
2423
2616
  }
2424
-
2425
- // src/utils/project-dir.ts
2426
- import path7 from "node:path";
2427
- var PROJECT_DIR_ENV = "STRYKER_BUN_RUNNER_PROJECT_DIR";
2428
- var STRYKER_WORKER_ENV = "STRYKER_MUTATOR_WORKER";
2429
- function recordProjectDirectory() {
2430
- const inherited = process.env[PROJECT_DIR_ENV];
2431
- const isWorker = process.env[STRYKER_WORKER_ENV] !== undefined;
2432
- if (isWorker && inherited !== undefined && path7.isAbsolute(inherited)) {
2433
- return inherited;
2434
- }
2435
- const here = process.cwd();
2436
- process.env[PROJECT_DIR_ENV] = here;
2437
- return here;
2617
+ function isWorkflowCommandLine(line) {
2618
+ return workflowCommandRe.test(line);
2438
2619
  }
2439
- var projectDirectory = recordProjectDirectory();
2440
- function resolveAgainstProject(file) {
2441
- return path7.resolve(projectDirectory, file);
2620
+ var MAX_FAILURE_MESSAGE_LENGTH = 4000;
2621
+ function buildTestName(testName, currentFile) {
2622
+ return currentFile ? `${currentFile} > ${testName}` : testName;
2442
2623
  }
2443
-
2444
- // src/utils/test-file-args.ts
2445
- import path8 from "node:path";
2446
- var MAX_TEST_FILE_ARGS_BYTES = 131072;
2447
- var ENTRY_OVERHEAD_BYTES = 1 + 8;
2448
- var bytesOf = (args) => args.reduce((sum, arg) => sum + Buffer.byteLength(arg) + ENTRY_OVERHEAD_BYTES, 0);
2449
- function shortestSpelling(absolute, cwd) {
2450
- const relative = path8.relative(cwd, absolute);
2451
- if (relative === "" || relative === "..") {
2452
- return absolute;
2624
+ function parseTestLine(line, currentFile) {
2625
+ const passMatch = /^✓ +(\S.*?) \[([0-9.]+)ms\]$/.exec(line);
2626
+ if (passMatch) {
2627
+ return {
2628
+ test: {
2629
+ name: buildTestName(passMatch[1].trim(), currentFile),
2630
+ file: currentFile,
2631
+ status: "passed",
2632
+ duration: Number.parseFloat(passMatch[2])
2633
+ }
2634
+ };
2453
2635
  }
2454
- const spelled = relative.startsWith(`..${path8.sep}`) ? relative : `.${path8.sep}${relative}`;
2455
- return spelled.length < absolute.length ? spelled : absolute;
2456
- }
2457
- function computeTestFileArgs(files, cwd, budget) {
2458
- const absolute = files.map((file) => path8.resolve(cwd, file));
2459
- const absoluteBytes = bytesOf(absolute);
2460
- if (absoluteBytes <= budget) {
2461
- return { args: absolute, form: "absolute", bytes: absoluteBytes, fits: true };
2636
+ const failMatch = /^✗ +(\S.*?)(?: \[([0-9.]+)ms\])?$/.exec(line);
2637
+ if (failMatch) {
2638
+ return {
2639
+ test: {
2640
+ name: buildTestName(failMatch[1].trim(), currentFile),
2641
+ file: currentFile,
2642
+ status: "failed",
2643
+ duration: failMatch[2] ? Number.parseFloat(failMatch[2]) : undefined
2644
+ }
2645
+ };
2462
2646
  }
2463
- const relative = absolute.map((file) => shortestSpelling(file, cwd));
2464
- const relativeBytes = bytesOf(relative);
2465
- return { args: relative, form: "relative", bytes: relativeBytes, fits: relativeBytes <= budget };
2466
- }
2467
- function sameEntries(a, b) {
2468
- return a.length === b.length && a.every((entry, index) => entry === b[index]);
2469
- }
2470
- var lastBuild;
2471
- function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
2472
- if (!path8.isAbsolute(cwd)) {
2473
- return computeTestFileArgs(files, cwd, budget);
2647
+ const bailFailMatch = /^\(fail\) +(\S.*?)(?: \[([0-9.]+)ms\])?$/.exec(line);
2648
+ if (bailFailMatch) {
2649
+ return {
2650
+ test: {
2651
+ name: buildTestName(bailFailMatch[1].trim(), currentFile),
2652
+ file: currentFile,
2653
+ status: "failed",
2654
+ duration: bailFailMatch[2] ? Number.parseFloat(bailFailMatch[2]) : undefined
2655
+ }
2656
+ };
2474
2657
  }
2475
- const cached = lastBuild;
2476
- if (cached?.cwd === cwd && cached.budget === budget && sameEntries(cached.files, files)) {
2477
- return { ...cached.result, args: [...cached.result.args] };
2658
+ const skipMatch = /^⏭ +(\S.*)$/.exec(line);
2659
+ if (skipMatch) {
2660
+ return {
2661
+ test: {
2662
+ name: buildTestName(skipMatch[1].trim(), currentFile),
2663
+ file: currentFile,
2664
+ status: "skipped"
2665
+ }
2666
+ };
2478
2667
  }
2479
- const result = computeTestFileArgs(files, cwd, budget);
2480
- lastBuild = { files: [...files], cwd, budget, result: { ...result, args: [...result.args] } };
2481
- return result;
2668
+ return {};
2482
2669
  }
2483
-
2484
- // src/process-runner.ts
2485
- var KILL_GRACE_PERIOD_MS = 500;
2486
- var STDIO_CLOSE_GRACE_MS = 4 * KILL_GRACE_PERIOD_MS;
2487
- var LIFELINE_FD = 3;
2488
- var SPAWN_DEPTH_ENV = "__STRYKER_BUN_RUNNER_DEPTH__";
2489
- var DEFAULT_MAX_SPAWN_DEPTH = 1;
2490
- var PROFILE_ENV = "STRYKER_BUN_PROFILE";
2491
- function stripAnsi(text) {
2492
- return text.replaceAll(/\u001B\[[0-9;?]*[\u0020-\u002F]*[\u0040-\u007E]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g, "");
2670
+ var NON_FAILING_RESULT_LINE = /^(?:\((?:pass|skip|todo)\)|[✓»✎⏭]) +\S/;
2671
+ var CODE_FRAME_LINE = /^\s*\d+ \|(?: |$)/;
2672
+ var ERROR_HEADING_LINE = /^(?:error|\w*Error)(?: \[[^\]]*\])?: /;
2673
+ var AFTER_FAIL_NOTE_LINE = /^\s+\^ \S/;
2674
+ function capFailureMessage(message) {
2675
+ return message.length > MAX_FAILURE_MESSAGE_LENGTH ? `${message.slice(0, MAX_FAILURE_MESSAGE_LENGTH)}
2676
+ … (${message.length - MAX_FAILURE_MESSAGE_LENGTH} more characters)` : message;
2493
2677
  }
2494
- function readSpawnDepth(raw) {
2495
- const parsed = Number(raw);
2496
- return Number.isInteger(parsed) ? Math.max(parsed, 0) : 0;
2678
+ function readFailureBlock(block) {
2679
+ const lines = block.filter((line) => !isWorkflowCommandLine(line));
2680
+ const frameStart = lines.findIndex((line) => CODE_FRAME_LINE.test(line));
2681
+ const start = frameStart === -1 ? lines.findIndex((line) => ERROR_HEADING_LINE.test(line)) : frameStart;
2682
+ const text = lines.slice(Math.max(start, 0)).join(`
2683
+ `).trim();
2684
+ return { text: text === "" ? undefined : text, reported: start !== -1 };
2497
2685
  }
2498
- function stripBailArgs(bunArgs) {
2499
- const sanitized = [];
2500
- for (let i = 0;i < bunArgs.length; i++) {
2501
- const arg = bunArgs[i];
2502
- if (arg === "--bail" || arg.startsWith("--bail=")) {
2503
- if (arg === "--bail" && /^\d+$/.test(bunArgs[i + 1])) {
2504
- i += 1;
2505
- }
2506
- continue;
2507
- }
2508
- sanitized.push(arg);
2686
+ function failureMessageFrom(block, notes) {
2687
+ const report = block.text !== undefined && (block.reported || notes.length === 0) ? capFailureMessage(block.text) : undefined;
2688
+ const parts = report === undefined ? notes : [report, ...notes];
2689
+ return parts.length === 0 ? undefined : parts.join(`
2690
+ `);
2691
+ }
2692
+ function setFailureMessage(test, block, notes) {
2693
+ const failureMessage = failureMessageFrom(block, notes);
2694
+ if (failureMessage !== undefined) {
2695
+ test.failureMessage = failureMessage;
2509
2696
  }
2510
- return sanitized;
2511
2697
  }
2512
- var liveChildren = new Set;
2513
- function killAllLiveChildren() {
2514
- for (const child of liveChildren) {
2515
- killProcessTree(child, "SIGKILL");
2698
+ function recordTest(reader, test, index) {
2699
+ if (test.status === "failed") {
2700
+ const block = readFailureBlock(reader.lines.slice(reader.blockStart, index));
2701
+ setFailureMessage(test, block, []);
2702
+ reader.lastFailed = { test, block, notes: [] };
2516
2703
  }
2517
- liveChildren.clear();
2704
+ reader.tests.push(test);
2705
+ reader.counters[test.status]++;
2706
+ reader.blockStart = index + 1;
2518
2707
  }
2519
- var CLEANUP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
2520
- var onCleanupSignal = (signal) => {
2521
- killAllLiveChildren();
2522
- removeSignalCleanup();
2523
- process.kill(process.pid, signal);
2524
- };
2525
- function ensureSignalCleanup() {
2526
- if (process.listeners(CLEANUP_SIGNALS[0]).includes(onCleanupSignal)) {
2527
- return false;
2708
+ function readLine(reader, index) {
2709
+ const line = reader.lines[index];
2710
+ const filePath = parseFilePath(line);
2711
+ if (filePath && reader.isHeaderFile(filePath)) {
2712
+ reader.currentFile = filePath;
2713
+ reader.blockStart = index + 1;
2714
+ reader.lastFailed = undefined;
2715
+ return;
2528
2716
  }
2529
- for (const s of CLEANUP_SIGNALS) {
2530
- process.on(s, onCleanupSignal);
2717
+ if (isWorkflowCommandLine(line)) {
2718
+ return;
2531
2719
  }
2532
- return true;
2533
- }
2534
- function removeSignalCleanup() {
2535
- for (const s of CLEANUP_SIGNALS) {
2536
- process.off(s, onCleanupSignal);
2720
+ if (reader.lastFailed && AFTER_FAIL_NOTE_LINE.test(line)) {
2721
+ const { test, block, notes } = reader.lastFailed;
2722
+ notes.push(line.trim());
2723
+ setFailureMessage(test, block, notes);
2724
+ reader.blockStart = index + 1;
2725
+ return;
2537
2726
  }
2538
- }
2539
- function killProcessTree(childProcess, signal) {
2540
- const pid = childProcess.pid;
2541
- if (pid === undefined || !killProcessGroup(pid, signal)) {
2542
- childProcess.kill(signal);
2543
- return false;
2727
+ reader.lastFailed = undefined;
2728
+ const { test } = parseTestLine(line, reader.currentFile);
2729
+ if (test) {
2730
+ recordTest(reader, test, index);
2731
+ } else if (NON_FAILING_RESULT_LINE.test(line)) {
2732
+ reader.blockStart = index + 1;
2544
2733
  }
2545
- return true;
2546
2734
  }
2547
- function killWithEscalation(childProcess, isClosed, gracePeriodMs) {
2548
- const pid = childProcess.pid;
2549
- const signalledGroup = killProcessTree(childProcess, "SIGTERM");
2550
- let hasEscalated = false;
2551
- const escalationHandle = setTimeout(() => {
2552
- if (!isClosed()) {
2553
- hasEscalated = true;
2554
- killProcessTree(childProcess, "SIGKILL");
2735
+ var RAN_LINE = /^\s*Ran\s+(\d+)\s+tests?\b/;
2736
+ var PASS_LINE = /^\s*\d+\s+pass\s*$/;
2737
+ var COUNT_LINE = /^\s*(\d+)\s+(pass|skip|todo|fail|errors?)\s*$/;
2738
+ var BAIL_LINE = /^\s*Bailed out after (\d+) failures?\s*$/;
2739
+ function lastLineMatching(lines, from, pattern, stopAtBlank) {
2740
+ for (let index = from;index >= 0; index--) {
2741
+ const match = pattern.exec(lines[index]);
2742
+ if (match) {
2743
+ return { index, match };
2555
2744
  }
2556
- }, gracePeriodMs);
2557
- return () => {
2558
- clearTimeout(escalationHandle);
2559
- if (!hasEscalated && signalledGroup && pid !== undefined) {
2560
- hasEscalated = true;
2561
- killProcessGroup(pid, "SIGKILL");
2745
+ if (stopAtBlank && !lines[index].trim()) {
2746
+ return;
2562
2747
  }
2563
- };
2564
- }
2565
- async function runBunTests(options) {
2566
- const spawnDepth = readSpawnDepth(process.env[SPAWN_DEPTH_ENV]);
2567
- const maxSpawnDepth = options.maxSpawnDepth ?? DEFAULT_MAX_SPAWN_DEPTH;
2568
- if (!Number.isSafeInteger(maxSpawnDepth) || maxSpawnDepth < 1) {
2569
- return {
2570
- stdout: "",
2571
- stderr: `stryker-bun-runner: invalid maxSpawnDepth=${String(maxSpawnDepth)}; expected a positive integer.`,
2572
- exitCode: 1,
2573
- signal: null,
2574
- timedOut: false,
2575
- memoryLimitExceeded: false
2576
- };
2577
- }
2578
- if (spawnDepth >= maxSpawnDepth) {
2579
- return {
2580
- stdout: "",
2581
- stderr: `stryker-bun-runner: refusing to spawn \`bun test\` at nesting depth ${spawnDepth} (maxSpawnDepth=${maxSpawnDepth}). A test run spawned by this runner tried to spawn another one; this is almost always runaway recursion. See the bun.maxSpawnDepth option.`,
2582
- exitCode: 1,
2583
- signal: null,
2584
- timedOut: false,
2585
- memoryLimitExceeded: false
2586
- };
2587
2748
  }
2588
- return spawnBunTests(options, spawnDepth);
2749
+ return;
2589
2750
  }
2590
- function buildChildEnv(options, spawnDepth) {
2591
- const env = {
2592
- ...process.env,
2593
- ...options.env
2594
- };
2595
- const preloadVars = {
2596
- __STRYKER_ACTIVE_MUTANT__: options.activeMutant === "" ? undefined : options.activeMutant,
2597
- __STRYKER_HIT_LIMIT__: options.hitLimit === undefined ? undefined : String(options.hitLimit),
2598
- __STRYKER_HIT_LIMIT_TOKEN__: options.hitLimitToken,
2599
- __STRYKER_COVERAGE_FILE__: options.coverageFile === "" ? undefined : options.coverageFile,
2600
- [COVERAGE_KEYS_ONLY_ENV]: options.coverageKeysOnly === true ? "1" : undefined,
2601
- __STRYKER_SYNC_PORT__: options.syncPort ? String(options.syncPort) : undefined,
2602
- [SYNC_TOKEN_ENV]: options.syncToken,
2603
- [DRY_RUN_PLAN_ENV]: options.dryRunPlan,
2604
- [WATCH_LIST_ENV]: options.watchList,
2605
- [LIFELINE_FD_ENV]: String(LIFELINE_FD)
2751
+ function readBunSummary(output) {
2752
+ const lines = stripAnsi(output).split(`
2753
+ `);
2754
+ const lastIndex = lines.length - 1;
2755
+ const ran = lastLineMatching(lines, lastIndex, RAN_LINE, false);
2756
+ const pass = ran ? lastLineMatching(lines, ran.index - 1, PASS_LINE, true) : lastLineMatching(lines, lastIndex, PASS_LINE, false);
2757
+ const summary = {
2758
+ pass: 0,
2759
+ skip: 0,
2760
+ todo: 0,
2761
+ fail: 0,
2762
+ error: 0,
2763
+ ran: ran && Number.parseInt(ran.match[1], 10),
2764
+ bailed: undefined,
2765
+ printed: ran !== undefined || pass !== undefined
2606
2766
  };
2607
- for (const [name, value] of Object.entries(preloadVars)) {
2608
- if (value === undefined) {
2609
- delete env[name];
2610
- } else {
2611
- env[name] = value;
2767
+ if (pass) {
2768
+ for (const line of lines.slice(pass.index, ran?.index ?? lines.length)) {
2769
+ const match = COUNT_LINE.exec(line);
2770
+ if (match) {
2771
+ summary[match[2] === "errors" ? "error" : match[2]] = Number.parseInt(match[1], 10);
2772
+ }
2612
2773
  }
2613
2774
  }
2614
- env[SPAWN_DEPTH_ENV] = String(spawnDepth + 1);
2615
- delete env[PROJECT_DIR_ENV];
2616
- if (options.profile) {
2617
- delete env[PROFILE_ENV];
2618
- }
2619
- if (options.profile && options.syncPort) {
2620
- env[PRELOAD_TIMINGS_ENV] = "1";
2621
- } else {
2622
- delete env[PRELOAD_TIMINGS_ENV];
2775
+ for (const line of lines.slice(ran?.index ?? 0)) {
2776
+ const match = BAIL_LINE.exec(line);
2777
+ if (match) {
2778
+ summary.bailed = Number.parseInt(match[1], 10);
2779
+ }
2623
2780
  }
2624
- return env;
2781
+ return summary;
2625
2782
  }
2626
- async function spawnBunTests(options, spawnDepth) {
2627
- const profile = options.profile;
2628
- profile?.beginSpawn(options.bail === true, options.testFiles, options.testNamePattern);
2629
- const args = ["test"];
2630
- if (options.inspect) {
2631
- args.push("--inspect=127.0.0.1:0");
2783
+ function parseSummaryLines(output) {
2784
+ const bun = readBunSummary(output);
2785
+ const counts = { passed: bun.pass, failed: bun.fail, skipped: bun.skip };
2786
+ if (bun.bailed !== undefined) {
2787
+ counts.failed = Math.max(counts.failed, bun.bailed);
2632
2788
  }
2633
- if (options.bunfigPath) {
2634
- args.push(`--config=${options.bunfigPath}`);
2789
+ const genuinePassed = counts.passed;
2790
+ const genuineFailed = counts.failed;
2791
+ if (bun.ran !== undefined) {
2792
+ const totalParsed = counts.passed + counts.failed + counts.skipped;
2793
+ if (totalParsed !== bun.ran && counts.passed === 0 && counts.failed === 0) {
2794
+ counts.passed = bun.ran;
2795
+ }
2635
2796
  }
2636
- if (options.preloadScript) {
2637
- args.push("--preload", options.preloadScript);
2797
+ return { ...counts, todo: bun.todo, errors: bun.error, printed: bun.printed, genuinePassed, genuineFailed };
2798
+ }
2799
+ function parseBunTestOutput(stdout, stderr, testFiles) {
2800
+ const tests = [];
2801
+ const counters = { passed: 0, failed: 0, skipped: 0 };
2802
+ const output = `${stdout}
2803
+ ${stderr}`;
2804
+ const lines = output.split(`
2805
+ `).map((line) => stripAnsi(line));
2806
+ const reader = {
2807
+ lines,
2808
+ isHeaderFile: headerFilter(lines, testFiles),
2809
+ tests,
2810
+ counters,
2811
+ currentFile: undefined,
2812
+ blockStart: 0,
2813
+ lastFailed: undefined
2814
+ };
2815
+ for (const index of lines.keys()) {
2816
+ readLine(reader, index);
2638
2817
  }
2639
- if (options.testNamePattern) {
2640
- args.push("--test-name-pattern", options.testNamePattern);
2641
- }
2642
- if (options.bail) {
2643
- args.push("--bail");
2644
- }
2645
- if (options.sequentialMode) {
2646
- args.push("--max-concurrency=1");
2647
- }
2648
- if (options.smol) {
2649
- args.push("--smol");
2650
- }
2651
- if (options.bunArgs && options.bunArgs.length > 0) {
2652
- args.push(...stripBailArgs(options.bunArgs));
2653
- }
2654
- if (options.testFiles && options.testFiles.length > 0) {
2655
- args.push(...buildTestFileArgs(options.testFiles).args);
2656
- }
2657
- const env = buildChildEnv(options, spawnDepth);
2658
- return new Promise((resolve) => {
2659
- const stdoutChunks = [];
2660
- const stderrChunks = [];
2661
- let timedOut = false;
2662
- let processKilled = false;
2663
- let memoryLimitExceeded = false;
2664
- let hasClosed = false;
2665
- let rssIntervalHandle;
2666
- let stdioCloseHandle;
2667
- let onLeaderExitDuringTermination;
2668
- let onAbort;
2669
- if (options.signal?.aborted) {
2670
- resolve({ stdout: "", stderr: "", exitCode: null, signal: null, timedOut: true, memoryLimitExceeded: false });
2671
- return;
2672
- }
2673
- const spawnOpts = {
2674
- env,
2675
- stdio: ["ignore", "pipe", "pipe", "pipe"],
2676
- cwd: process.cwd(),
2677
- detached: true
2678
- };
2679
- try {
2680
- options.onSpawn?.([options.bunPath, ...args]);
2681
- } catch {}
2682
- const childProcess = spawn3(options.bunPath, args, spawnOpts);
2683
- profile?.mark("spawned");
2684
- liveChildren.add(childProcess);
2685
- ensureSignalCleanup();
2686
- const beginTermination = () => {
2687
- if (processKilled) {
2688
- return false;
2689
- }
2690
- processKilled = true;
2691
- timedOut = true;
2692
- onLeaderExitDuringTermination = killWithEscalation(childProcess, () => hasClosed, KILL_GRACE_PERIOD_MS);
2693
- return true;
2694
- };
2695
- const timeoutHandle = setTimeout(() => {
2696
- beginTermination();
2697
- }, options.timeout);
2698
- if (options.signal) {
2699
- onAbort = () => {
2700
- beginTermination();
2701
- };
2702
- options.signal.addEventListener("abort", onAbort, { once: true });
2703
- }
2704
- if (options.maxChildRss !== undefined) {
2705
- const rssLimit = options.maxChildRss;
2706
- const checkMemoryCeiling = async () => {
2707
- if (hasClosed || processKilled) {
2708
- return;
2709
- }
2710
- const pid = childProcess.pid;
2711
- if (pid === undefined) {
2712
- return;
2713
- }
2714
- const rssBytes = await getProcessRssBytes(pid);
2715
- if (rssBytes === null || hasClosed) {
2716
- return;
2717
- }
2718
- if (rssBytes > rssLimit) {
2719
- if (!beginTermination()) {
2720
- return;
2721
- }
2722
- memoryLimitExceeded = true;
2723
- if (rssIntervalHandle) {
2724
- clearInterval(rssIntervalHandle);
2725
- }
2726
- options.onMemoryLimitExceeded?.(rssBytes);
2727
- }
2728
- };
2729
- rssIntervalHandle = setInterval(() => {
2730
- checkMemoryCeiling();
2731
- }, options.rssCheckIntervalMs ?? 1000);
2732
- rssIntervalHandle.unref();
2733
- }
2734
- if (childProcess.stdout) {
2735
- childProcess.stdout.on("data", (data) => {
2736
- stdoutChunks.push(data);
2737
- });
2738
- }
2739
- let inspectorUrlExtracted = false;
2740
- if (childProcess.stderr) {
2741
- childProcess.stderr.on("data", (data) => {
2742
- stderrChunks.push(data);
2743
- profile?.onStderr(data);
2744
- if (options.inspect && !inspectorUrlExtracted && options.onInspectorReady) {
2745
- const text = Buffer.concat(stderrChunks).toString();
2746
- const match = /Listening:[\t\v\f\r \u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*\n\s*(ws:\/\/\S+)/.exec(stripAnsi(text));
2747
- if (match) {
2748
- inspectorUrlExtracted = true;
2749
- options.onInspectorReady(match[1]);
2750
- }
2751
- }
2752
- });
2753
- }
2754
- const release = () => {
2755
- liveChildren.delete(childProcess);
2756
- clearTimeout(timeoutHandle);
2757
- clearTimeout(stdioCloseHandle);
2758
- if (options.signal && onAbort) {
2759
- options.signal.removeEventListener("abort", onAbort);
2760
- }
2761
- if (rssIntervalHandle) {
2762
- clearInterval(rssIntervalHandle);
2763
- }
2764
- };
2765
- childProcess.on("exit", (code, signal) => {
2766
- profile?.mark("exit");
2767
- onLeaderExitDuringTermination?.();
2768
- stdioCloseHandle = setTimeout(() => {
2769
- release();
2770
- resolve({
2771
- stdout: Buffer.concat(stdoutChunks).toString(),
2772
- stderr: Buffer.concat(stderrChunks).toString(),
2773
- exitCode: processKilled ? null : code,
2774
- signal: signal ?? null,
2775
- timedOut,
2776
- memoryLimitExceeded,
2777
- outputIncomplete: true
2778
- });
2779
- }, STDIO_CLOSE_GRACE_MS);
2780
- });
2781
- childProcess.on("close", (code, signal) => {
2782
- profile?.mark("close");
2783
- hasClosed = true;
2784
- onLeaderExitDuringTermination?.();
2785
- release();
2786
- resolve({
2787
- stdout: Buffer.concat(stdoutChunks).toString(),
2788
- stderr: Buffer.concat(stderrChunks).toString(),
2789
- exitCode: processKilled ? null : code,
2790
- signal: signal ?? null,
2791
- timedOut,
2792
- memoryLimitExceeded
2793
- });
2794
- });
2795
- childProcess.on("error", (error) => {
2796
- profile?.mark("close");
2797
- hasClosed = true;
2798
- onLeaderExitDuringTermination?.();
2799
- release();
2800
- const stderrOutput = Buffer.concat(stderrChunks).toString();
2801
- resolve({
2802
- stdout: Buffer.concat(stdoutChunks).toString(),
2803
- stderr: `${stderrOutput}
2804
- Process error: ${error.message}`,
2805
- exitCode: null,
2806
- signal: null,
2807
- timedOut,
2808
- memoryLimitExceeded,
2809
- spawnError: error.message
2810
- });
2811
- });
2812
- });
2818
+ const summaryCounts = parseSummaryLines(output);
2819
+ counters.passed = Math.max(counters.passed, summaryCounts.passed);
2820
+ counters.failed = Math.max(counters.failed, summaryCounts.failed);
2821
+ counters.skipped = Math.max(counters.skipped, summaryCounts.skipped);
2822
+ return {
2823
+ tests,
2824
+ totalTests: counters.passed + counters.failed + counters.skipped,
2825
+ passed: counters.passed,
2826
+ failed: counters.failed,
2827
+ skipped: counters.skipped,
2828
+ summaryPassed: summaryCounts.genuinePassed,
2829
+ summaryFailed: summaryCounts.genuineFailed,
2830
+ summarySkipped: summaryCounts.skipped,
2831
+ summaryTodo: summaryCounts.todo,
2832
+ summaryErrors: summaryCounts.errors,
2833
+ summaryPrinted: summaryCounts.printed
2834
+ };
2813
2835
  }
2814
2836
 
2815
- // src/parsers/console-parser.ts
2816
- var fileHeaderRe = new RegExp(String.raw`^(?:::group::)?([^:]+${TEST_FILE_SUFFIX_PATTERN}):$`, "i");
2817
- var workflowCommandRe = /^::(?:group|endgroup|error|warning|notice|debug|add-mask|add-matcher|remove-matcher)(?:::|\s|$)/;
2818
- function parseFilePath(line) {
2819
- const fileMatch = fileHeaderRe.exec(line);
2820
- return fileMatch ? fileMatch[1] : null;
2837
+ // src/parsers/unhandled-errors.ts
2838
+ var MAX_BLOCKS_SHOWN = 20;
2839
+ var MAX_DIAGNOSTIC_CHARS = 16000;
2840
+ var MAX_SNIPPET_LINE_CHARS = 300;
2841
+ var MAX_NAMED = 3;
2842
+ var MAX_NAME_CHARS = 200;
2843
+ var BLOCK_MARKER = "# Unhandled error between tests";
2844
+ var BLOCK_RULE = "-".repeat(31);
2845
+ var LATE_CALL_RE = /^error: Cannot call ([\w$.]+)\(\) after the test run has completed\.?$/;
2846
+ var FILE_HEADER_RE = new RegExp(String.raw`^(?:::group::)?((?:[a-z]:)?[^:]+${TEST_FILE_SUFFIX_PATTERN}):$`, "i");
2847
+ var FRAME_LOCATION_RE = /^(.+):\d+:\d+$/;
2848
+ var SNIPPET_LINE_RE = /^\s*\d+ \|/;
2849
+ var SNIPPET_CARET_RE = /^\s*\^+$/;
2850
+ var isDrivePath = (path) => /^[a-z]:[\\/]/i.test(path);
2851
+ function pathKey(path) {
2852
+ return isDrivePath(path) ? `${path.charAt(0).toLowerCase()}${path.slice(1).replaceAll("\\", "/")}` : path;
2821
2853
  }
2822
- function headerFilter(lines, testFiles) {
2823
- if (testFiles === undefined) {
2824
- return () => true;
2854
+ function percentDecode(text) {
2855
+ try {
2856
+ return decodeURIComponent(text);
2857
+ } catch {
2858
+ return text;
2825
2859
  }
2826
- const roots = new Set(testFiles.map((file) => path9.resolve(file)));
2827
- const isRunFile = (file) => {
2828
- let candidate = path9.resolve(file);
2829
- while (!roots.has(candidate)) {
2830
- const parent = path9.dirname(candidate);
2831
- if (parent === candidate) {
2832
- return false;
2833
- }
2834
- candidate = parent;
2835
- }
2836
- return true;
2837
- };
2838
- const namesRunFile = lines.some((line) => {
2839
- const file = parseFilePath(line);
2840
- return file !== null && isRunFile(file);
2841
- });
2842
- return namesRunFile ? isRunFile : () => true;
2843
- }
2844
- function isWorkflowCommandLine(line) {
2845
- return workflowCommandRe.test(line);
2846
2860
  }
2847
- var MAX_FAILURE_MESSAGE_LENGTH = 4000;
2848
- function buildTestName(testName, currentFile) {
2849
- return currentFile ? `${currentFile} > ${testName}` : testName;
2861
+ function locationPath(location) {
2862
+ if (/^file:\/\//i.test(location)) {
2863
+ const path = percentDecode(location.slice("file://".length).replace(/^localhost(?=\/)/i, "").replace(/\?.*/s, ""));
2864
+ return /^\/[a-z]:[\\/]/i.test(path) ? path.slice(1) : path;
2865
+ }
2866
+ return /^[a-z][\w+.-]+:/i.test(location) && !isDrivePath(location) ? undefined : location;
2850
2867
  }
2851
- function parseTestLine(line, currentFile) {
2852
- const passMatch = /^✓ +(\S.*?) \[([0-9.]+)ms\]$/.exec(line);
2853
- if (passMatch) {
2854
- return {
2855
- test: {
2856
- name: buildTestName(passMatch[1].trim(), currentFile),
2857
- file: currentFile,
2858
- status: "passed",
2859
- duration: Number.parseFloat(passMatch[2])
2860
- }
2861
- };
2868
+ function frameFile(line) {
2869
+ const trimmed = line.trim();
2870
+ if (!trimmed.startsWith("at ")) {
2871
+ return;
2862
2872
  }
2863
- const failMatch = /^✗ +(\S.*?)(?: \[([0-9.]+)ms\])?$/.exec(line);
2864
- if (failMatch) {
2865
- return {
2866
- test: {
2867
- name: buildTestName(failMatch[1].trim(), currentFile),
2868
- file: currentFile,
2869
- status: "failed",
2870
- duration: failMatch[2] ? Number.parseFloat(failMatch[2]) : undefined
2871
- }
2872
- };
2873
+ let location = trimmed.slice(3).trim();
2874
+ const open = location.lastIndexOf(" (");
2875
+ if (open !== -1 && location.endsWith(")")) {
2876
+ location = location.slice(open + 2, -1);
2873
2877
  }
2874
- const bailFailMatch = /^\(fail\) +(\S.*?)(?: \[([0-9.]+)ms\])?$/.exec(line);
2875
- if (bailFailMatch) {
2876
- return {
2877
- test: {
2878
- name: buildTestName(bailFailMatch[1].trim(), currentFile),
2879
- file: currentFile,
2880
- status: "failed",
2881
- duration: bailFailMatch[2] ? Number.parseFloat(bailFailMatch[2]) : undefined
2882
- }
2883
- };
2878
+ const file = FRAME_LOCATION_RE.exec(location)?.[1];
2879
+ return file === undefined ? undefined : locationPath(file);
2880
+ }
2881
+ function buildBlock(printed, headerFile) {
2882
+ const body = printed.slice(printed.findIndex((line) => line !== ""), printed.findLastIndex((line) => line !== "") + 1);
2883
+ const errorLine = body.find((line) => line.startsWith("error: "));
2884
+ return {
2885
+ headerFile,
2886
+ lines: body,
2887
+ frames: body.flatMap((line) => {
2888
+ const path = frameFile(line);
2889
+ return path === undefined ? [] : [{ path, line }];
2890
+ }),
2891
+ lateCall: errorLine === undefined ? undefined : LATE_CALL_RE.exec(errorLine)?.[1]
2892
+ };
2893
+ }
2894
+ function parseUnhandledErrorBlocks(stderr, secrets = []) {
2895
+ const lines = cleanDiagnosticText(stderr, secrets).split(/\r?\n/).map((line) => line.trimEnd());
2896
+ const starts = lines.flatMap((line, i) => line === BLOCK_MARKER && lines[i + 1] === BLOCK_RULE ? [i] : []);
2897
+ const blocks = [];
2898
+ let headerFile;
2899
+ let scanned = 0;
2900
+ for (const [n, start] of starts.entries()) {
2901
+ for (const line of lines.slice(scanned, start)) {
2902
+ headerFile = FILE_HEADER_RE.exec(line)?.[1] ?? headerFile;
2903
+ }
2904
+ const following = lines.slice(start + 2, starts[n + 1] ?? lines.length);
2905
+ const closingRule = following.indexOf(BLOCK_RULE);
2906
+ blocks.push(buildBlock(closingRule === -1 ? following : following.slice(0, closingRule), headerFile));
2907
+ scanned = closingRule === -1 ? start + 2 + following.length : start + 2 + closingRule + 1;
2884
2908
  }
2885
- const skipMatch = /^⏭ +(\S.*)$/.exec(line);
2886
- if (skipMatch) {
2887
- return {
2888
- test: {
2889
- name: buildTestName(skipMatch[1].trim(), currentFile),
2890
- file: currentFile,
2891
- status: "skipped"
2892
- }
2893
- };
2909
+ return blocks;
2910
+ }
2911
+ var isSnippetLine = (line) => SNIPPET_LINE_RE.test(line) || SNIPPET_CARET_RE.test(line);
2912
+ function renderBlock(block, index, total) {
2913
+ const heading = ` Unhandled error block ${index + 1} of ${total}:`;
2914
+ if (block.lines.length === 0) {
2915
+ const empty = `${heading}
2916
+ (empty)`;
2917
+ return { full: empty, bare: empty };
2894
2918
  }
2895
- return {};
2919
+ const full = [];
2920
+ const bare = [];
2921
+ let omittedRun = 0;
2922
+ const endRun = () => {
2923
+ if (omittedRun > 0) {
2924
+ bare.push(` ... [${omittedRun} source line(s) omitted]`);
2925
+ omittedRun = 0;
2926
+ }
2927
+ };
2928
+ for (const line of block.lines) {
2929
+ if (isSnippetLine(line)) {
2930
+ omittedRun++;
2931
+ full.push(line.length > MAX_SNIPPET_LINE_CHARS ? ` ${line.slice(0, MAX_SNIPPET_LINE_CHARS)}... [${line.length - MAX_SNIPPET_LINE_CHARS} more character(s) of this line omitted]` : ` ${line}`);
2932
+ } else {
2933
+ endRun();
2934
+ full.push(` ${line}`);
2935
+ bare.push(` ${line}`);
2936
+ }
2937
+ }
2938
+ endRun();
2939
+ return { full: [heading, ...full].join(`
2940
+ `), bare: [heading, ...bare].join(`
2941
+ `) };
2896
2942
  }
2897
- var NON_FAILING_RESULT_LINE = /^(?:\((?:pass|skip|todo)\)|[✓»✎⏭]) +\S/;
2898
- var CODE_FRAME_LINE = /^\s*\d+ \|(?: |$)/;
2899
- var ERROR_HEADING_LINE = /^(?:error|\w*Error)(?: \[[^\]]*\])?: /;
2900
- var AFTER_FAIL_NOTE_LINE = /^\s+\^ \S/;
2901
- function capFailureMessage(message) {
2902
- return message.length > MAX_FAILURE_MESSAGE_LENGTH ? `${message.slice(0, MAX_FAILURE_MESSAGE_LENGTH)}
2903
- … (${message.length - MAX_FAILURE_MESSAGE_LENGTH} more characters)` : message;
2943
+ function nameOf(text, secrets) {
2944
+ const redacted = redactSecrets(text, secrets);
2945
+ return redacted.length > MAX_NAME_CHARS ? `${redacted.slice(0, MAX_NAME_CHARS)}... [${redacted.length - MAX_NAME_CHARS} more character(s) omitted]` : redacted;
2904
2946
  }
2905
- function readFailureBlock(block) {
2906
- const lines = block.filter((line) => !isWorkflowCommandLine(line));
2907
- const frameStart = lines.findIndex((line) => CODE_FRAME_LINE.test(line));
2908
- const start = frameStart === -1 ? lines.findIndex((line) => ERROR_HEADING_LINE.test(line)) : frameStart;
2909
- const text = lines.slice(Math.max(start, 0)).join(`
2910
- `).trim();
2911
- return { text: text === "" ? undefined : text, reported: start !== -1 };
2947
+ function nameList(names) {
2948
+ const shown = names.slice(0, MAX_NAMED).join(", ");
2949
+ return names.length > MAX_NAMED ? `${shown} and ${names.length - MAX_NAMED} more` : shown;
2912
2950
  }
2913
- function failureMessageFrom(block, notes) {
2914
- const report = block.text !== undefined && (block.reported || notes.length === 0) ? capFailureMessage(block.text) : undefined;
2915
- const parts = report === undefined ? notes : [report, ...notes];
2916
- return parts.length === 0 ? undefined : parts.join(`
2917
- `);
2951
+ function matchesHeader(framePath, header) {
2952
+ const frame = pathKey(framePath);
2953
+ const wanted = pathKey(header).replace(/^\.\//, "");
2954
+ return frame === wanted || frame.endsWith(`/${wanted}`);
2918
2955
  }
2919
- function setFailureMessage(test, block, notes) {
2920
- const failureMessage = failureMessageFrom(block, notes);
2921
- if (failureMessage !== undefined) {
2922
- test.failureMessage = failureMessage;
2923
- }
2956
+ function testFileFrame(block) {
2957
+ const { headerFile, frames } = block;
2958
+ const inEffect = headerFile === undefined ? undefined : frames.find((frame) => matchesHeader(frame.path, headerFile));
2959
+ return inEffect ?? frames.find((frame) => TEST_FILE_SUFFIX_RE.test(frame.path));
2924
2960
  }
2925
- function recordTest(reader, test, index) {
2926
- if (test.status === "failed") {
2927
- const block = readFailureBlock(reader.lines.slice(reader.blockStart, index));
2928
- setFailureMessage(test, block, []);
2929
- reader.lastFailed = { test, block, notes: [] };
2930
- }
2931
- reader.tests.push(test);
2932
- reader.counters[test.status]++;
2933
- reader.blockStart = index + 1;
2961
+ function lateCalls(blocks, secrets) {
2962
+ const seen = new Set;
2963
+ return blocks.flatMap((block, index) => {
2964
+ if (block.lateCall === undefined) {
2965
+ return [];
2966
+ }
2967
+ const frame = testFileFrame(block);
2968
+ const header = block.headerFile === undefined ? undefined : nameOf(block.headerFile, secrets);
2969
+ const call = nameOf(block.lateCall, secrets);
2970
+ const key = `${call}\x00${frame?.path ?? ""}\x00${frame === undefined ? header ?? "" : ""}`;
2971
+ if (seen.has(key)) {
2972
+ return [];
2973
+ }
2974
+ seen.add(key);
2975
+ return [{ call, block: index, header, frame: frame === undefined ? undefined : { block: index, name: nameOf(frame.path, secrets), line: frame.line } }];
2976
+ });
2934
2977
  }
2935
- function readLine(reader, index) {
2936
- const line = reader.lines[index];
2937
- const filePath = parseFilePath(line);
2938
- if (filePath && reader.isHeaderFile(filePath)) {
2939
- reader.currentFile = filePath;
2940
- reader.blockStart = index + 1;
2941
- reader.lastFailed = undefined;
2942
- return;
2978
+ function eagerClaims(blocks, eagerModules, secrets) {
2979
+ const eagerByKey = new Map(eagerModules.map((module) => [pathKey(module), module]));
2980
+ const seen = new Set;
2981
+ return blocks.flatMap((block, index) => block.lateCall === undefined ? block.frames.flatMap((frame) => {
2982
+ const module = eagerByKey.get(pathKey(frame.path));
2983
+ if (module === undefined || seen.has(module)) {
2984
+ return [];
2985
+ }
2986
+ seen.add(module);
2987
+ return [{ block: index, name: nameOf(module, secrets), line: frame.line }];
2988
+ }) : []);
2989
+ }
2990
+ function describeLateCall(late) {
2991
+ const error = `\`Cannot call ${late.call}() after the test run has completed\``;
2992
+ if (late.frame !== undefined) {
2993
+ return `${error} for test file ${late.frame.name} (block ${late.block + 1})`;
2943
2994
  }
2944
- if (isWorkflowCommandLine(line)) {
2945
- return;
2995
+ if (late.header !== undefined) {
2996
+ return `${error} printed under the header of ${late.header} (block ${late.block + 1})`;
2946
2997
  }
2947
- if (reader.lastFailed && AFTER_FAIL_NOTE_LINE.test(line)) {
2948
- const { test, block, notes } = reader.lastFailed;
2949
- notes.push(line.trim());
2950
- setFailureMessage(test, block, notes);
2951
- reader.blockStart = index + 1;
2952
- return;
2998
+ return `${error} (block ${late.block + 1})`;
2999
+ }
3000
+ var keyOf = (claim) => `${claim.block}\x00${claim.line}`;
3001
+ function lateCallSentences(lates, blocks) {
3002
+ if (lates.length === 0) {
3003
+ return [];
2953
3004
  }
2954
- reader.lastFailed = undefined;
2955
- const { test } = parseTestLine(line, reader.currentFile);
2956
- if (test) {
2957
- recordTest(reader, test, index);
2958
- } else if (NON_FAILING_RESULT_LINE.test(line)) {
2959
- reader.blockStart = index + 1;
3005
+ const named = lates.slice(0, MAX_NAMED);
3006
+ const fileKnown = named.every((late) => late.frame !== undefined);
3007
+ const consequence = fileKnown ? "bun had already ended that file's run when the call was made, so tests registered from that point were not run." : "bun's message says the call came after the test run had completed, so tests registered from that point were not run.";
3008
+ const precededByOtherBlock = blocks.findIndex((block) => block.lateCall !== undefined) > 0;
3009
+ return [
3010
+ [
3011
+ `bun reported ${nameList(lates.map((late) => describeLateCall(late)))}.`,
3012
+ consequence,
3013
+ ...precededByOtherBlock ? ["An error raised outside any test, such as those in the blocks shown, is what makes bun end a run early."] : []
3014
+ ].join(" ")
3015
+ ];
3016
+ }
3017
+ function eagerSentences(modules) {
3018
+ if (modules.length === 0) {
3019
+ return [];
2960
3020
  }
3021
+ const named = nameList(modules.map((claim) => `${claim.name} (block ${claim.block + 1})`));
3022
+ return [
3023
+ `Stack frames point at ${named}. The module(s) named here are in the list of files this run's coverage preload imports before any test runs: ` + "files matched by your Stryker 'mutate' globs that the tests load or name in import() or require(), and any that bun.alwaysImport keeps. " + "If no test needs one of them imported first (typically an entry point with top-level side effects), take it out of bun.alwaysImport, " + "remove the import() or require() of it that never runs, or exclude it from 'mutate' (add a '!<path>' glob) and re-run."
3024
+ ];
2961
3025
  }
2962
- var RAN_LINE = /^\s*Ran\s+(\d+)\s+tests?\b/;
2963
- var PASS_LINE = /^\s*\d+\s+pass\s*$/;
2964
- var COUNT_LINE = /^\s*(\d+)\s+(pass|skip|todo|fail|errors?)\s*$/;
2965
- var BAIL_LINE = /^\s*Bailed out after (\d+) failures?\s*$/;
2966
- function lastLineMatching(lines, from, pattern, stopAtBlank) {
2967
- for (let index = from;index >= 0; index--) {
2968
- const match = pattern.exec(lines[index]);
2969
- if (match) {
2970
- return { index, match };
3026
+ var CUT_NOTE_RESERVE = 200;
3027
+ var joinedLength = (parts) => parts.reduce((sum, part) => sum + part.length, 0) + Math.max(0, parts.length - 1);
3028
+ function describeUnhandledErrors(stderr, eagerModules, secrets = []) {
3029
+ const blocks = parseUnhandledErrorBlocks(stderr, secrets);
3030
+ if (blocks.length === 0) {
3031
+ return;
3032
+ }
3033
+ const lates = lateCalls(blocks, secrets);
3034
+ const modules = eagerClaims(blocks, eagerModules, secrets);
3035
+ const dropped = new Set;
3036
+ for (let attempt = 0;attempt < 8; attempt++) {
3037
+ const claims = {
3038
+ lates: lates.map((late) => late.frame !== undefined && dropped.has(keyOf(late.frame)) ? { ...late, frame: undefined } : late),
3039
+ modules: modules.filter((claim) => !dropped.has(keyOf(claim)))
3040
+ };
3041
+ const result = layOut(blocks, claims);
3042
+ const lost = [...claims.lates.slice(0, MAX_NAMED).flatMap((late) => late.frame ?? []), ...claims.modules.slice(0, MAX_NAMED)].filter((claim) => !result.shown(claim));
3043
+ if (lost.length === 0) {
3044
+ return result.text;
2971
3045
  }
2972
- if (stopAtBlank && !lines[index].trim()) {
2973
- return;
3046
+ for (const claim of lost) {
3047
+ dropped.add(keyOf(claim));
2974
3048
  }
2975
3049
  }
2976
- return;
3050
+ return layOut(blocks, { lates: lates.map((late) => ({ ...late, frame: undefined })), modules: [] }).text;
2977
3051
  }
2978
- function readBunSummary(output) {
2979
- const lines = stripAnsi(output).split(`
3052
+ function selectBlocks(blockCount, required) {
3053
+ const shown = new Set(required);
3054
+ for (let i = 0;i < blockCount && shown.size < MAX_BLOCKS_SHOWN; i++) {
3055
+ shown.add(i);
3056
+ }
3057
+ return [...shown].toSorted((a, b) => a - b);
3058
+ }
3059
+ function cutBlock(text, share) {
3060
+ const [heading, ...body] = text.split(`
2980
3061
  `);
2981
- const lastIndex = lines.length - 1;
2982
- const ran = lastLineMatching(lines, lastIndex, RAN_LINE, false);
2983
- const pass = ran ? lastLineMatching(lines, ran.index - 1, PASS_LINE, true) : lastLineMatching(lines, lastIndex, PASS_LINE, false);
2984
- const summary = {
2985
- pass: 0,
2986
- skip: 0,
2987
- todo: 0,
2988
- fail: 0,
2989
- error: 0,
2990
- ran: ran && Number.parseInt(ran.match[1], 10),
2991
- bailed: undefined,
2992
- printed: ran !== undefined || pass !== undefined
2993
- };
2994
- if (pass) {
2995
- for (const line of lines.slice(pass.index, ran?.index ?? lines.length)) {
2996
- const match = COUNT_LINE.exec(line);
2997
- if (match) {
2998
- summary[match[2] === "errors" ? "error" : match[2]] = Number.parseInt(match[1], 10);
3062
+ const kept = [heading];
3063
+ let used = heading.length;
3064
+ for (const line of body) {
3065
+ if (used + 1 + line.length > share) {
3066
+ if (kept.length === 1) {
3067
+ const head = Math.max(0, share - used - 1);
3068
+ kept.push(`${line.slice(0, head)}... [${line.length - head} more character(s) of this line omitted]`);
2999
3069
  }
3070
+ break;
3000
3071
  }
3072
+ used += 1 + line.length;
3073
+ kept.push(line);
3001
3074
  }
3002
- for (const line of lines.slice(ran?.index ?? 0)) {
3003
- const match = BAIL_LINE.exec(line);
3004
- if (match) {
3005
- summary.bailed = Number.parseInt(match[1], 10);
3006
- }
3007
- }
3008
- return summary;
3075
+ const left = body.length - (kept.length - 1);
3076
+ return left > 0 ? [...kept, ` ... [${left} more line(s) of this block omitted]`].join(`
3077
+ `) : kept.join(`
3078
+ `);
3009
3079
  }
3010
- function parseSummaryLines(output) {
3011
- const bun = readBunSummary(output);
3012
- const counts = { passed: bun.pass, failed: bun.fail, skipped: bun.skip };
3013
- if (bun.bailed !== undefined) {
3014
- counts.failed = Math.max(counts.failed, bun.bailed);
3080
+ function layOut(blocks, claims) {
3081
+ const named = [...claims.lates.slice(0, MAX_NAMED).map((late) => late.block), ...claims.modules.slice(0, MAX_NAMED).map((claim) => claim.block)];
3082
+ const required = new Set([0, ...named]);
3083
+ const intro = `bun's stderr holds ${blocks.length} "Unhandled error between tests" block(s), errors raised outside any individual test:`;
3084
+ let selected = selectBlocks(blocks.length, required);
3085
+ const texts = new Map(selected.map((index) => [index, renderBlock(blocks[index], index, blocks.length)]));
3086
+ const noSnippets = new Set;
3087
+ const shownText = (index) => noSnippets.has(index) ? texts.get(index).bare : texts.get(index).full;
3088
+ const summary = [
3089
+ ...lateCallSentences(claims.lates, blocks),
3090
+ ...eagerSentences(claims.modules)
3091
+ ];
3092
+ const parts = () => {
3093
+ const omitted = blocks.length - selected.length;
3094
+ return [
3095
+ intro,
3096
+ ...selected.map((index) => shownText(index)),
3097
+ ...omitted > 0 ? [` ... [${omitted} more block(s) omitted]`] : [],
3098
+ ...summary
3099
+ ];
3100
+ };
3101
+ const fits = () => joinedLength(parts()) <= MAX_DIAGNOSTIC_CHARS;
3102
+ for (const index of selected.toReversed()) {
3103
+ if (fits()) {
3104
+ break;
3105
+ }
3106
+ noSnippets.add(index);
3015
3107
  }
3016
- const genuinePassed = counts.passed;
3017
- const genuineFailed = counts.failed;
3018
- if (bun.ran !== undefined) {
3019
- const totalParsed = counts.passed + counts.failed + counts.skipped;
3020
- if (totalParsed !== bun.ran && counts.passed === 0 && counts.failed === 0) {
3021
- counts.passed = bun.ran;
3108
+ for (const dropped of selected.filter((index) => !required.has(index)).toReversed()) {
3109
+ if (fits()) {
3110
+ break;
3022
3111
  }
3112
+ selected = selected.filter((index) => index !== dropped);
3023
3113
  }
3024
- return { ...counts, todo: bun.todo, errors: bun.error, printed: bun.printed, genuinePassed, genuineFailed };
3025
- }
3026
- function parseBunTestOutput(stdout, stderr, testFiles) {
3027
- const tests = [];
3028
- const counters = { passed: 0, failed: 0, skipped: 0 };
3029
- const output = `${stdout}
3030
- ${stderr}`;
3031
- const lines = output.split(`
3032
- `).map((line) => stripAnsi(line));
3033
- const reader = {
3034
- lines,
3035
- isHeaderFile: headerFilter(lines, testFiles),
3036
- tests,
3037
- counters,
3038
- currentFile: undefined,
3039
- blockStart: 0,
3040
- lastFailed: undefined
3041
- };
3042
- for (const index of lines.keys()) {
3043
- readLine(reader, index);
3114
+ if (!fits()) {
3115
+ const outside = parts().filter((_, position) => position === 0 || position > selected.length);
3116
+ const share = Math.max(0, Math.floor((MAX_DIAGNOSTIC_CHARS - joinedLength(outside) - selected.length) / selected.length) - CUT_NOTE_RESERVE);
3117
+ for (const index of selected) {
3118
+ const text = texts.get(index).bare;
3119
+ texts.set(index, { full: text, bare: cutBlock(text, share) });
3120
+ }
3044
3121
  }
3045
- const summaryCounts = parseSummaryLines(output);
3046
- counters.passed = Math.max(counters.passed, summaryCounts.passed);
3047
- counters.failed = Math.max(counters.failed, summaryCounts.failed);
3048
- counters.skipped = Math.max(counters.skipped, summaryCounts.skipped);
3122
+ const shownLines = new Map(selected.map((index) => [index, new Set(shownText(index).split(`
3123
+ `))]));
3049
3124
  return {
3050
- tests,
3051
- totalTests: counters.passed + counters.failed + counters.skipped,
3052
- passed: counters.passed,
3053
- failed: counters.failed,
3054
- skipped: counters.skipped,
3055
- summaryPassed: summaryCounts.genuinePassed,
3056
- summaryFailed: summaryCounts.genuineFailed,
3057
- summarySkipped: summaryCounts.skipped,
3058
- summaryTodo: summaryCounts.todo,
3059
- summaryErrors: summaryCounts.errors,
3060
- summaryPrinted: summaryCounts.printed
3125
+ text: parts().join(`
3126
+ `),
3127
+ shown: (claim) => shownLines.get(claim.block).has(` ${claim.line}`)
3061
3128
  };
3062
3129
  }
3063
3130
 
3064
- // src/parsers/unhandled-errors.ts
3065
- var MAX_BLOCKS_SHOWN = 20;
3066
- var MAX_DIAGNOSTIC_CHARS = 16000;
3067
- var MAX_SNIPPET_LINE_CHARS = 300;
3068
- var MAX_NAMED = 3;
3069
- var MAX_NAME_CHARS = 200;
3070
- var BLOCK_MARKER = "# Unhandled error between tests";
3071
- var BLOCK_RULE = "-".repeat(31);
3072
- var LATE_CALL_RE = /^error: Cannot call ([\w$.]+)\(\) after the test run has completed\.?$/;
3073
- var FILE_HEADER_RE = new RegExp(String.raw`^(?:::group::)?((?:[a-z]:)?[^:]+${TEST_FILE_SUFFIX_PATTERN}):$`, "i");
3074
- var FRAME_LOCATION_RE = /^(.+):\d+:\d+$/;
3075
- var SNIPPET_LINE_RE = /^\s*\d+ \|/;
3076
- var SNIPPET_CARET_RE = /^\s*\^+$/;
3077
- var isDrivePath = (path) => /^[a-z]:[\\/]/i.test(path);
3078
- function pathKey(path) {
3079
- return isDrivePath(path) ? `${path.charAt(0).toLowerCase()}${path.slice(1).replaceAll("\\", "/")}` : path;
3080
- }
3081
- function percentDecode(text) {
3131
+ // src/process-runner.ts
3132
+ import { spawn as spawn3 } from "node:child_process";
3133
+
3134
+ // src/utils/process-group.ts
3135
+ function killProcessGroup(pid, signal) {
3082
3136
  try {
3083
- return decodeURIComponent(text);
3137
+ process.kill(-pid, signal);
3138
+ return true;
3084
3139
  } catch {
3085
- return text;
3140
+ return false;
3086
3141
  }
3087
3142
  }
3088
- function locationPath(location) {
3089
- if (/^file:\/\//i.test(location)) {
3090
- const path = percentDecode(location.slice("file://".length).replace(/^localhost(?=\/)/i, "").replace(/\?.*/s, ""));
3091
- return /^\/[a-z]:[\\/]/i.test(path) ? path.slice(1) : path;
3092
- }
3093
- return /^[a-z][\w+.-]+:/i.test(location) && !isDrivePath(location) ? undefined : location;
3143
+
3144
+ // src/utils/process-rss.ts
3145
+ import { spawn as spawn2 } from "node:child_process";
3146
+ import { readFile as readFile4 } from "node:fs/promises";
3147
+ async function getProcessRssBytes(pid) {
3148
+ return process.platform === "linux" ? getLinuxRss(pid) : getPsRss(pid);
3094
3149
  }
3095
- function frameFile(line) {
3096
- const trimmed = line.trim();
3097
- if (!trimmed.startsWith("at ")) {
3098
- return;
3099
- }
3100
- let location = trimmed.slice(3).trim();
3101
- const open = location.lastIndexOf(" (");
3102
- if (open !== -1 && location.endsWith(")")) {
3103
- location = location.slice(open + 2, -1);
3150
+ function parseVmRss(statusContent) {
3151
+ const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(statusContent);
3152
+ return match ? Number(match[1]) * 1024 : null;
3153
+ }
3154
+ async function getLinuxRss(pid) {
3155
+ try {
3156
+ const status = await readFile4(`/proc/${pid}/status`, "utf8");
3157
+ return parseVmRss(status);
3158
+ } catch {
3159
+ return null;
3104
3160
  }
3105
- const file = FRAME_LOCATION_RE.exec(location)?.[1];
3106
- return file === undefined ? undefined : locationPath(file);
3107
3161
  }
3108
- function buildBlock(printed, headerFile) {
3109
- const body = printed.slice(printed.findIndex((line) => line !== ""), printed.findLastIndex((line) => line !== "") + 1);
3110
- const errorLine = body.find((line) => line.startsWith("error: "));
3111
- return {
3112
- headerFile,
3113
- lines: body,
3114
- frames: body.flatMap((line) => {
3115
- const path = frameFile(line);
3116
- return path === undefined ? [] : [{ path, line }];
3117
- }),
3118
- lateCall: errorLine === undefined ? undefined : LATE_CALL_RE.exec(errorLine)?.[1]
3119
- };
3162
+ function parsePsRssOutput(output) {
3163
+ const trimmed = output.trim();
3164
+ if (trimmed === "") {
3165
+ return null;
3166
+ }
3167
+ const kb = Number(trimmed);
3168
+ return Number.isFinite(kb) ? kb * 1024 : null;
3120
3169
  }
3121
- function parseUnhandledErrorBlocks(stderr, secrets = []) {
3122
- const lines = cleanDiagnosticText(stderr, secrets).split(/\r?\n/).map((line) => line.trimEnd());
3123
- const starts = lines.flatMap((line, i) => line === BLOCK_MARKER && lines[i + 1] === BLOCK_RULE ? [i] : []);
3124
- const blocks = [];
3125
- let headerFile;
3126
- let scanned = 0;
3127
- for (const [n, start] of starts.entries()) {
3128
- for (const line of lines.slice(scanned, start)) {
3129
- headerFile = FILE_HEADER_RE.exec(line)?.[1] ?? headerFile;
3170
+ async function getPsRss(pid) {
3171
+ return new Promise((resolve) => {
3172
+ let child;
3173
+ try {
3174
+ child = spawn2("ps", ["-o", "rss=", "-p", String(pid)], { stdio: ["ignore", "pipe", "ignore"] });
3175
+ } catch {
3176
+ resolve(null);
3177
+ return;
3130
3178
  }
3131
- const following = lines.slice(start + 2, starts[n + 1] ?? lines.length);
3132
- const closingRule = following.indexOf(BLOCK_RULE);
3133
- blocks.push(buildBlock(closingRule === -1 ? following : following.slice(0, closingRule), headerFile));
3134
- scanned = closingRule === -1 ? start + 2 + following.length : start + 2 + closingRule + 1;
3135
- }
3136
- return blocks;
3179
+ let output = "";
3180
+ child.stdout.on("data", (data) => {
3181
+ output += data.toString();
3182
+ });
3183
+ child.on("close", (code) => {
3184
+ resolve(code === 0 ? parsePsRssOutput(output) : null);
3185
+ });
3186
+ child.on("error", () => {
3187
+ resolve(null);
3188
+ });
3189
+ });
3137
3190
  }
3138
- var isSnippetLine = (line) => SNIPPET_LINE_RE.test(line) || SNIPPET_CARET_RE.test(line);
3139
- function renderBlock(block, index, total) {
3140
- const heading = ` Unhandled error block ${index + 1} of ${total}:`;
3141
- if (block.lines.length === 0) {
3142
- const empty = `${heading}
3143
- (empty)`;
3144
- return { full: empty, bare: empty };
3191
+
3192
+ // src/utils/project-dir.ts
3193
+ import path8 from "node:path";
3194
+ var PROJECT_DIR_ENV = "STRYKER_BUN_RUNNER_PROJECT_DIR";
3195
+ var STRYKER_WORKER_ENV = "STRYKER_MUTATOR_WORKER";
3196
+ function recordProjectDirectory() {
3197
+ const inherited = process.env[PROJECT_DIR_ENV];
3198
+ const isWorker = process.env[STRYKER_WORKER_ENV] !== undefined;
3199
+ if (isWorker && inherited !== undefined && path8.isAbsolute(inherited)) {
3200
+ return inherited;
3145
3201
  }
3146
- const full = [];
3147
- const bare = [];
3148
- let omittedRun = 0;
3149
- const endRun = () => {
3150
- if (omittedRun > 0) {
3151
- bare.push(` ... [${omittedRun} source line(s) omitted]`);
3152
- omittedRun = 0;
3153
- }
3154
- };
3155
- for (const line of block.lines) {
3156
- if (isSnippetLine(line)) {
3157
- omittedRun++;
3158
- full.push(line.length > MAX_SNIPPET_LINE_CHARS ? ` ${line.slice(0, MAX_SNIPPET_LINE_CHARS)}... [${line.length - MAX_SNIPPET_LINE_CHARS} more character(s) of this line omitted]` : ` ${line}`);
3159
- } else {
3160
- endRun();
3161
- full.push(` ${line}`);
3162
- bare.push(` ${line}`);
3163
- }
3202
+ const here = process.cwd();
3203
+ process.env[PROJECT_DIR_ENV] = here;
3204
+ return here;
3205
+ }
3206
+ var projectDirectory = recordProjectDirectory();
3207
+ function resolveAgainstProject(file) {
3208
+ return path8.resolve(projectDirectory, file);
3209
+ }
3210
+
3211
+ // src/utils/test-file-args.ts
3212
+ import path9 from "node:path";
3213
+ var MAX_TEST_FILE_ARGS_BYTES = 131072;
3214
+ var ENTRY_OVERHEAD_BYTES = 1 + 8;
3215
+ var bytesOf = (args) => args.reduce((sum, arg) => sum + Buffer.byteLength(arg) + ENTRY_OVERHEAD_BYTES, 0);
3216
+ function shortestSpelling(absolute, cwd) {
3217
+ const relative = path9.relative(cwd, absolute);
3218
+ if (relative === "" || relative === "..") {
3219
+ return absolute;
3164
3220
  }
3165
- endRun();
3166
- return { full: [heading, ...full].join(`
3167
- `), bare: [heading, ...bare].join(`
3168
- `) };
3221
+ const spelled = relative.startsWith(`..${path9.sep}`) ? relative : `.${path9.sep}${relative}`;
3222
+ return spelled.length < absolute.length ? spelled : absolute;
3169
3223
  }
3170
- function nameOf(text, secrets) {
3171
- const redacted = redactSecrets(text, secrets);
3172
- return redacted.length > MAX_NAME_CHARS ? `${redacted.slice(0, MAX_NAME_CHARS)}... [${redacted.length - MAX_NAME_CHARS} more character(s) omitted]` : redacted;
3224
+ function computeTestFileArgs(files, cwd, budget) {
3225
+ const absolute = files.map((file) => path9.resolve(cwd, file));
3226
+ const absoluteBytes = bytesOf(absolute);
3227
+ if (absoluteBytes <= budget) {
3228
+ return { args: absolute, form: "absolute", bytes: absoluteBytes, fits: true };
3229
+ }
3230
+ const relative = absolute.map((file) => shortestSpelling(file, cwd));
3231
+ const relativeBytes = bytesOf(relative);
3232
+ return { args: relative, form: "relative", bytes: relativeBytes, fits: relativeBytes <= budget };
3173
3233
  }
3174
- function nameList(names) {
3175
- const shown = names.slice(0, MAX_NAMED).join(", ");
3176
- return names.length > MAX_NAMED ? `${shown} and ${names.length - MAX_NAMED} more` : shown;
3234
+ function sameEntries(a, b) {
3235
+ return a.length === b.length && a.every((entry, index) => entry === b[index]);
3177
3236
  }
3178
- function matchesHeader(framePath, header) {
3179
- const frame = pathKey(framePath);
3180
- const wanted = pathKey(header).replace(/^\.\//, "");
3181
- return frame === wanted || frame.endsWith(`/${wanted}`);
3237
+ var lastBuild;
3238
+ function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
3239
+ if (!path9.isAbsolute(cwd)) {
3240
+ return computeTestFileArgs(files, cwd, budget);
3241
+ }
3242
+ const cached = lastBuild;
3243
+ if (cached?.cwd === cwd && cached.budget === budget && sameEntries(cached.files, files)) {
3244
+ return { ...cached.result, args: [...cached.result.args] };
3245
+ }
3246
+ const result = computeTestFileArgs(files, cwd, budget);
3247
+ lastBuild = { files: [...files], cwd, budget, result: { ...result, args: [...result.args] } };
3248
+ return result;
3182
3249
  }
3183
- function testFileFrame(block) {
3184
- const { headerFile, frames } = block;
3185
- const inEffect = headerFile === undefined ? undefined : frames.find((frame) => matchesHeader(frame.path, headerFile));
3186
- return inEffect ?? frames.find((frame) => TEST_FILE_SUFFIX_RE.test(frame.path));
3250
+
3251
+ // src/process-runner.ts
3252
+ var KILL_GRACE_PERIOD_MS = 500;
3253
+ var STDIO_CLOSE_GRACE_MS = 4 * KILL_GRACE_PERIOD_MS;
3254
+ var LIFELINE_FD = 3;
3255
+ var SPAWN_DEPTH_ENV = "__STRYKER_BUN_RUNNER_DEPTH__";
3256
+ var DEFAULT_MAX_SPAWN_DEPTH = 1;
3257
+ var PROFILE_ENV = "STRYKER_BUN_PROFILE";
3258
+ function readSpawnDepth(raw) {
3259
+ const parsed = Number(raw);
3260
+ return Number.isInteger(parsed) ? Math.max(parsed, 0) : 0;
3187
3261
  }
3188
- function lateCalls(blocks, secrets) {
3189
- const seen = new Set;
3190
- return blocks.flatMap((block, index) => {
3191
- if (block.lateCall === undefined) {
3192
- return [];
3193
- }
3194
- const frame = testFileFrame(block);
3195
- const header = block.headerFile === undefined ? undefined : nameOf(block.headerFile, secrets);
3196
- const call = nameOf(block.lateCall, secrets);
3197
- const key = `${call}\x00${frame?.path ?? ""}\x00${frame === undefined ? header ?? "" : ""}`;
3198
- if (seen.has(key)) {
3199
- return [];
3262
+ function stripBailArgs(bunArgs) {
3263
+ const sanitized = [];
3264
+ for (let i = 0;i < bunArgs.length; i++) {
3265
+ const arg = bunArgs[i];
3266
+ if (arg === "--bail" || arg.startsWith("--bail=")) {
3267
+ if (arg === "--bail" && /^\d+$/.test(bunArgs[i + 1])) {
3268
+ i += 1;
3269
+ }
3270
+ continue;
3200
3271
  }
3201
- seen.add(key);
3202
- return [{ call, block: index, header, frame: frame === undefined ? undefined : { block: index, name: nameOf(frame.path, secrets), line: frame.line } }];
3203
- });
3272
+ sanitized.push(arg);
3273
+ }
3274
+ return sanitized;
3204
3275
  }
3205
- function eagerClaims(blocks, eagerModules, secrets) {
3206
- const eagerByKey = new Map(eagerModules.map((module) => [pathKey(module), module]));
3207
- const seen = new Set;
3208
- return blocks.flatMap((block, index) => block.lateCall === undefined ? block.frames.flatMap((frame) => {
3209
- const module = eagerByKey.get(pathKey(frame.path));
3210
- if (module === undefined || seen.has(module)) {
3211
- return [];
3212
- }
3213
- seen.add(module);
3214
- return [{ block: index, name: nameOf(module, secrets), line: frame.line }];
3215
- }) : []);
3276
+ var liveChildren = new Set;
3277
+ function killAllLiveChildren() {
3278
+ for (const child of liveChildren) {
3279
+ killProcessTree(child, "SIGKILL");
3280
+ }
3281
+ liveChildren.clear();
3216
3282
  }
3217
- function describeLateCall(late) {
3218
- const error = `\`Cannot call ${late.call}() after the test run has completed\``;
3219
- if (late.frame !== undefined) {
3220
- return `${error} for test file ${late.frame.name} (block ${late.block + 1})`;
3283
+ var CLEANUP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
3284
+ var onCleanupSignal = (signal) => {
3285
+ killAllLiveChildren();
3286
+ removeSignalCleanup();
3287
+ process.kill(process.pid, signal);
3288
+ };
3289
+ function ensureSignalCleanup() {
3290
+ if (process.listeners(CLEANUP_SIGNALS[0]).includes(onCleanupSignal)) {
3291
+ return false;
3221
3292
  }
3222
- if (late.header !== undefined) {
3223
- return `${error} printed under the header of ${late.header} (block ${late.block + 1})`;
3293
+ for (const s of CLEANUP_SIGNALS) {
3294
+ process.on(s, onCleanupSignal);
3224
3295
  }
3225
- return `${error} (block ${late.block + 1})`;
3296
+ return true;
3226
3297
  }
3227
- var keyOf = (claim) => `${claim.block}\x00${claim.line}`;
3228
- function lateCallSentences(lates, blocks) {
3229
- if (lates.length === 0) {
3230
- return [];
3298
+ function removeSignalCleanup() {
3299
+ for (const s of CLEANUP_SIGNALS) {
3300
+ process.off(s, onCleanupSignal);
3231
3301
  }
3232
- const named = lates.slice(0, MAX_NAMED);
3233
- const fileKnown = named.every((late) => late.frame !== undefined);
3234
- const consequence = fileKnown ? "bun had already ended that file's run when the call was made, so tests registered from that point were not run." : "bun's message says the call came after the test run had completed, so tests registered from that point were not run.";
3235
- const precededByOtherBlock = blocks.findIndex((block) => block.lateCall !== undefined) > 0;
3236
- return [
3237
- [
3238
- `bun reported ${nameList(lates.map((late) => describeLateCall(late)))}.`,
3239
- consequence,
3240
- ...precededByOtherBlock ? ["An error raised outside any test, such as those in the blocks shown, is what makes bun end a run early."] : []
3241
- ].join(" ")
3242
- ];
3243
3302
  }
3244
- function eagerSentences(modules) {
3245
- if (modules.length === 0) {
3246
- return [];
3303
+ function killProcessTree(childProcess, signal) {
3304
+ const pid = childProcess.pid;
3305
+ if (pid === undefined || !killProcessGroup(pid, signal)) {
3306
+ childProcess.kill(signal);
3307
+ return false;
3247
3308
  }
3248
- const named = nameList(modules.map((claim) => `${claim.name} (block ${claim.block + 1})`));
3249
- return [
3250
- `Stack frames point at ${named}. The module(s) named here are in the list of files this run's coverage preload imports before any test runs: ` + "files matched by your Stryker 'mutate' globs that the tests load or name in import() or require(), and any that bun.alwaysImport keeps. " + "If no test needs one of them imported first (typically an entry point with top-level side effects), take it out of bun.alwaysImport, " + "remove the import() or require() of it that never runs, or exclude it from 'mutate' (add a '!<path>' glob) and re-run."
3251
- ];
3309
+ return true;
3252
3310
  }
3253
- var CUT_NOTE_RESERVE = 200;
3254
- var joinedLength = (parts) => parts.reduce((sum, part) => sum + part.length, 0) + Math.max(0, parts.length - 1);
3255
- function describeUnhandledErrors(stderr, eagerModules, secrets = []) {
3256
- const blocks = parseUnhandledErrorBlocks(stderr, secrets);
3257
- if (blocks.length === 0) {
3258
- return;
3259
- }
3260
- const lates = lateCalls(blocks, secrets);
3261
- const modules = eagerClaims(blocks, eagerModules, secrets);
3262
- const dropped = new Set;
3263
- for (let attempt = 0;attempt < 8; attempt++) {
3264
- const claims = {
3265
- lates: lates.map((late) => late.frame !== undefined && dropped.has(keyOf(late.frame)) ? { ...late, frame: undefined } : late),
3266
- modules: modules.filter((claim) => !dropped.has(keyOf(claim)))
3267
- };
3268
- const result = layOut(blocks, claims);
3269
- const lost = [...claims.lates.slice(0, MAX_NAMED).flatMap((late) => late.frame ?? []), ...claims.modules.slice(0, MAX_NAMED)].filter((claim) => !result.shown(claim));
3270
- if (lost.length === 0) {
3271
- return result.text;
3311
+ function killWithEscalation(childProcess, isClosed, gracePeriodMs) {
3312
+ const pid = childProcess.pid;
3313
+ const signalledGroup = killProcessTree(childProcess, "SIGTERM");
3314
+ let hasEscalated = false;
3315
+ const escalationHandle = setTimeout(() => {
3316
+ if (!isClosed()) {
3317
+ hasEscalated = true;
3318
+ killProcessTree(childProcess, "SIGKILL");
3272
3319
  }
3273
- for (const claim of lost) {
3274
- dropped.add(keyOf(claim));
3320
+ }, gracePeriodMs);
3321
+ return () => {
3322
+ clearTimeout(escalationHandle);
3323
+ if (!hasEscalated && signalledGroup && pid !== undefined) {
3324
+ hasEscalated = true;
3325
+ killProcessGroup(pid, "SIGKILL");
3275
3326
  }
3327
+ };
3328
+ }
3329
+ async function runBunTests(options) {
3330
+ const spawnDepth = readSpawnDepth(process.env[SPAWN_DEPTH_ENV]);
3331
+ const maxSpawnDepth = options.maxSpawnDepth ?? DEFAULT_MAX_SPAWN_DEPTH;
3332
+ if (!Number.isSafeInteger(maxSpawnDepth) || maxSpawnDepth < 1) {
3333
+ return {
3334
+ stdout: "",
3335
+ stderr: `stryker-bun-runner: invalid maxSpawnDepth=${String(maxSpawnDepth)}; expected a positive integer.`,
3336
+ exitCode: 1,
3337
+ signal: null,
3338
+ timedOut: false,
3339
+ memoryLimitExceeded: false
3340
+ };
3276
3341
  }
3277
- return layOut(blocks, { lates: lates.map((late) => ({ ...late, frame: undefined })), modules: [] }).text;
3342
+ if (spawnDepth >= maxSpawnDepth) {
3343
+ return {
3344
+ stdout: "",
3345
+ stderr: `stryker-bun-runner: refusing to spawn \`bun test\` at nesting depth ${spawnDepth} (maxSpawnDepth=${maxSpawnDepth}). A test run spawned by this runner tried to spawn another one; this is almost always runaway recursion. See the bun.maxSpawnDepth option.`,
3346
+ exitCode: 1,
3347
+ signal: null,
3348
+ timedOut: false,
3349
+ memoryLimitExceeded: false
3350
+ };
3351
+ }
3352
+ return spawnBunTests(options, spawnDepth);
3278
3353
  }
3279
- function selectBlocks(blockCount, required) {
3280
- const shown = new Set(required);
3281
- for (let i = 0;i < blockCount && shown.size < MAX_BLOCKS_SHOWN; i++) {
3282
- shown.add(i);
3354
+ function buildChildEnv(options, spawnDepth) {
3355
+ const env = {
3356
+ ...process.env,
3357
+ ...options.env
3358
+ };
3359
+ const preloadVars = {
3360
+ __STRYKER_ACTIVE_MUTANT__: options.activeMutant === "" ? undefined : options.activeMutant,
3361
+ __STRYKER_HIT_LIMIT__: options.hitLimit === undefined ? undefined : String(options.hitLimit),
3362
+ __STRYKER_HIT_LIMIT_TOKEN__: options.hitLimitToken,
3363
+ __STRYKER_COVERAGE_FILE__: options.coverageFile === "" ? undefined : options.coverageFile,
3364
+ [COVERAGE_KEYS_ONLY_ENV]: options.coverageKeysOnly === true ? "1" : undefined,
3365
+ __STRYKER_SYNC_PORT__: options.syncPort ? String(options.syncPort) : undefined,
3366
+ [SYNC_TOKEN_ENV]: options.syncToken,
3367
+ [DRY_RUN_PLAN_ENV]: options.dryRunPlan,
3368
+ [WATCH_LIST_ENV]: options.watchList,
3369
+ [LIFELINE_FD_ENV]: String(LIFELINE_FD)
3370
+ };
3371
+ for (const [name, value] of Object.entries(preloadVars)) {
3372
+ if (value === undefined) {
3373
+ delete env[name];
3374
+ } else {
3375
+ env[name] = value;
3376
+ }
3283
3377
  }
3284
- return [...shown].toSorted((a, b) => a - b);
3378
+ env[SPAWN_DEPTH_ENV] = String(spawnDepth + 1);
3379
+ delete env[PROJECT_DIR_ENV];
3380
+ if (options.profile) {
3381
+ delete env[PROFILE_ENV];
3382
+ }
3383
+ if (options.profile && options.syncPort) {
3384
+ env[PRELOAD_TIMINGS_ENV] = "1";
3385
+ } else {
3386
+ delete env[PRELOAD_TIMINGS_ENV];
3387
+ }
3388
+ return env;
3285
3389
  }
3286
- function cutBlock(text, share) {
3287
- const [heading, ...body] = text.split(`
3288
- `);
3289
- const kept = [heading];
3290
- let used = heading.length;
3291
- for (const line of body) {
3292
- if (used + 1 + line.length > share) {
3293
- if (kept.length === 1) {
3294
- const head = Math.max(0, share - used - 1);
3295
- kept.push(`${line.slice(0, head)}... [${line.length - head} more character(s) of this line omitted]`);
3390
+ async function spawnBunTests(options, spawnDepth) {
3391
+ const profile = options.profile;
3392
+ profile?.beginSpawn(options.bail === true, options.testFiles, options.testNamePattern);
3393
+ const args = ["test"];
3394
+ if (options.inspect) {
3395
+ args.push("--inspect=127.0.0.1:0");
3396
+ }
3397
+ if (options.bunfigPath) {
3398
+ args.push(`--config=${options.bunfigPath}`);
3399
+ }
3400
+ if (options.preloadScript) {
3401
+ args.push("--preload", options.preloadScript);
3402
+ }
3403
+ if (options.testNamePattern) {
3404
+ args.push("--test-name-pattern", options.testNamePattern);
3405
+ }
3406
+ if (options.bail) {
3407
+ args.push("--bail");
3408
+ }
3409
+ if (options.sequentialMode) {
3410
+ args.push("--max-concurrency=1");
3411
+ }
3412
+ if (options.smol) {
3413
+ args.push("--smol");
3414
+ }
3415
+ if (options.bunArgs && options.bunArgs.length > 0) {
3416
+ args.push(...stripBailArgs(options.bunArgs));
3417
+ }
3418
+ if (options.testFiles && options.testFiles.length > 0) {
3419
+ args.push(...buildTestFileArgs(options.testFiles).args);
3420
+ }
3421
+ const env = buildChildEnv(options, spawnDepth);
3422
+ return new Promise((resolve) => {
3423
+ const stdoutChunks = [];
3424
+ const stderrChunks = [];
3425
+ let timedOut = false;
3426
+ let processKilled = false;
3427
+ let memoryLimitExceeded = false;
3428
+ let hasClosed = false;
3429
+ let rssIntervalHandle;
3430
+ let stdioCloseHandle;
3431
+ let onLeaderExitDuringTermination;
3432
+ let onAbort;
3433
+ if (options.signal?.aborted) {
3434
+ resolve({ stdout: "", stderr: "", exitCode: null, signal: null, timedOut: true, memoryLimitExceeded: false });
3435
+ return;
3436
+ }
3437
+ const spawnOpts = {
3438
+ env,
3439
+ stdio: ["ignore", "pipe", "pipe", "pipe"],
3440
+ cwd: process.cwd(),
3441
+ detached: true
3442
+ };
3443
+ try {
3444
+ options.onSpawn?.([options.bunPath, ...args]);
3445
+ } catch {}
3446
+ const childProcess = spawn3(options.bunPath, args, spawnOpts);
3447
+ profile?.mark("spawned");
3448
+ liveChildren.add(childProcess);
3449
+ ensureSignalCleanup();
3450
+ const beginTermination = () => {
3451
+ if (processKilled) {
3452
+ return false;
3296
3453
  }
3297
- break;
3454
+ processKilled = true;
3455
+ timedOut = true;
3456
+ onLeaderExitDuringTermination = killWithEscalation(childProcess, () => hasClosed, KILL_GRACE_PERIOD_MS);
3457
+ return true;
3458
+ };
3459
+ const timeoutHandle = setTimeout(() => {
3460
+ beginTermination();
3461
+ }, options.timeout);
3462
+ if (options.signal) {
3463
+ onAbort = () => {
3464
+ beginTermination();
3465
+ };
3466
+ options.signal.addEventListener("abort", onAbort, { once: true });
3298
3467
  }
3299
- used += 1 + line.length;
3300
- kept.push(line);
3301
- }
3302
- const left = body.length - (kept.length - 1);
3303
- return left > 0 ? [...kept, ` ... [${left} more line(s) of this block omitted]`].join(`
3304
- `) : kept.join(`
3305
- `);
3306
- }
3307
- function layOut(blocks, claims) {
3308
- const named = [...claims.lates.slice(0, MAX_NAMED).map((late) => late.block), ...claims.modules.slice(0, MAX_NAMED).map((claim) => claim.block)];
3309
- const required = new Set([0, ...named]);
3310
- const intro = `bun's stderr holds ${blocks.length} "Unhandled error between tests" block(s), errors raised outside any individual test:`;
3311
- let selected = selectBlocks(blocks.length, required);
3312
- const texts = new Map(selected.map((index) => [index, renderBlock(blocks[index], index, blocks.length)]));
3313
- const noSnippets = new Set;
3314
- const shownText = (index) => noSnippets.has(index) ? texts.get(index).bare : texts.get(index).full;
3315
- const summary = [
3316
- ...lateCallSentences(claims.lates, blocks),
3317
- ...eagerSentences(claims.modules)
3318
- ];
3319
- const parts = () => {
3320
- const omitted = blocks.length - selected.length;
3321
- return [
3322
- intro,
3323
- ...selected.map((index) => shownText(index)),
3324
- ...omitted > 0 ? [` ... [${omitted} more block(s) omitted]`] : [],
3325
- ...summary
3326
- ];
3327
- };
3328
- const fits = () => joinedLength(parts()) <= MAX_DIAGNOSTIC_CHARS;
3329
- for (const index of selected.toReversed()) {
3330
- if (fits()) {
3331
- break;
3468
+ if (options.maxChildRss !== undefined) {
3469
+ const rssLimit = options.maxChildRss;
3470
+ const checkMemoryCeiling = async () => {
3471
+ if (hasClosed || processKilled) {
3472
+ return;
3473
+ }
3474
+ const pid = childProcess.pid;
3475
+ if (pid === undefined) {
3476
+ return;
3477
+ }
3478
+ const rssBytes = await getProcessRssBytes(pid);
3479
+ if (rssBytes === null || hasClosed) {
3480
+ return;
3481
+ }
3482
+ if (rssBytes > rssLimit) {
3483
+ if (!beginTermination()) {
3484
+ return;
3485
+ }
3486
+ memoryLimitExceeded = true;
3487
+ if (rssIntervalHandle) {
3488
+ clearInterval(rssIntervalHandle);
3489
+ }
3490
+ options.onMemoryLimitExceeded?.(rssBytes);
3491
+ }
3492
+ };
3493
+ rssIntervalHandle = setInterval(() => {
3494
+ checkMemoryCeiling();
3495
+ }, options.rssCheckIntervalMs ?? 1000);
3496
+ rssIntervalHandle.unref();
3332
3497
  }
3333
- noSnippets.add(index);
3334
- }
3335
- for (const dropped of selected.filter((index) => !required.has(index)).toReversed()) {
3336
- if (fits()) {
3337
- break;
3498
+ if (childProcess.stdout) {
3499
+ childProcess.stdout.on("data", (data) => {
3500
+ stdoutChunks.push(data);
3501
+ });
3338
3502
  }
3339
- selected = selected.filter((index) => index !== dropped);
3340
- }
3341
- if (!fits()) {
3342
- const outside = parts().filter((_, position) => position === 0 || position > selected.length);
3343
- const share = Math.max(0, Math.floor((MAX_DIAGNOSTIC_CHARS - joinedLength(outside) - selected.length) / selected.length) - CUT_NOTE_RESERVE);
3344
- for (const index of selected) {
3345
- const text = texts.get(index).bare;
3346
- texts.set(index, { full: text, bare: cutBlock(text, share) });
3503
+ let inspectorUrlExtracted = false;
3504
+ if (childProcess.stderr) {
3505
+ childProcess.stderr.on("data", (data) => {
3506
+ stderrChunks.push(data);
3507
+ profile?.onStderr(data);
3508
+ if (options.inspect && !inspectorUrlExtracted && options.onInspectorReady) {
3509
+ const text = Buffer.concat(stderrChunks).toString();
3510
+ const match = /Listening:[\t\v\f\r \u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*\n\s*(ws:\/\/\S+)/.exec(stripAnsi(text));
3511
+ if (match) {
3512
+ inspectorUrlExtracted = true;
3513
+ options.onInspectorReady(match[1]);
3514
+ }
3515
+ }
3516
+ });
3347
3517
  }
3348
- }
3349
- const shownLines = new Map(selected.map((index) => [index, new Set(shownText(index).split(`
3350
- `))]));
3351
- return {
3352
- text: parts().join(`
3353
- `),
3354
- shown: (claim) => shownLines.get(claim.block).has(` ${claim.line}`)
3355
- };
3518
+ const release = () => {
3519
+ liveChildren.delete(childProcess);
3520
+ clearTimeout(timeoutHandle);
3521
+ clearTimeout(stdioCloseHandle);
3522
+ if (options.signal && onAbort) {
3523
+ options.signal.removeEventListener("abort", onAbort);
3524
+ }
3525
+ if (rssIntervalHandle) {
3526
+ clearInterval(rssIntervalHandle);
3527
+ }
3528
+ };
3529
+ childProcess.on("exit", (code, signal) => {
3530
+ profile?.mark("exit");
3531
+ onLeaderExitDuringTermination?.();
3532
+ stdioCloseHandle = setTimeout(() => {
3533
+ release();
3534
+ resolve({
3535
+ stdout: Buffer.concat(stdoutChunks).toString(),
3536
+ stderr: Buffer.concat(stderrChunks).toString(),
3537
+ exitCode: processKilled ? null : code,
3538
+ signal: signal ?? null,
3539
+ timedOut,
3540
+ memoryLimitExceeded,
3541
+ outputIncomplete: true
3542
+ });
3543
+ }, STDIO_CLOSE_GRACE_MS);
3544
+ });
3545
+ childProcess.on("close", (code, signal) => {
3546
+ profile?.mark("close");
3547
+ hasClosed = true;
3548
+ onLeaderExitDuringTermination?.();
3549
+ release();
3550
+ resolve({
3551
+ stdout: Buffer.concat(stdoutChunks).toString(),
3552
+ stderr: Buffer.concat(stderrChunks).toString(),
3553
+ exitCode: processKilled ? null : code,
3554
+ signal: signal ?? null,
3555
+ timedOut,
3556
+ memoryLimitExceeded
3557
+ });
3558
+ });
3559
+ childProcess.on("error", (error) => {
3560
+ profile?.mark("close");
3561
+ hasClosed = true;
3562
+ onLeaderExitDuringTermination?.();
3563
+ release();
3564
+ const stderrOutput = Buffer.concat(stderrChunks).toString();
3565
+ resolve({
3566
+ stdout: Buffer.concat(stdoutChunks).toString(),
3567
+ stderr: `${stderrOutput}
3568
+ Process error: ${error.message}`,
3569
+ exitCode: null,
3570
+ signal: null,
3571
+ timedOut,
3572
+ memoryLimitExceeded,
3573
+ spawnError: error.message
3574
+ });
3575
+ });
3576
+ });
3356
3577
  }
3357
3578
 
3358
3579
  // src/run-profile.ts
@@ -3897,6 +4118,28 @@ function rawDataToString(data) {
3897
4118
  }
3898
4119
  return Buffer.isBuffer(data) ? data.toString("utf8") : Buffer.from(data).toString("utf8");
3899
4120
  }
4121
+ var DRAIN_REQUEST = "drain-request";
4122
+ function parseDrainRequest(text) {
4123
+ if (text === DRAIN_REQUEST) {
4124
+ return { startedTests: undefined };
4125
+ }
4126
+ if (!text.startsWith(`${DRAIN_REQUEST} `)) {
4127
+ return null;
4128
+ }
4129
+ const count = text.slice(DRAIN_REQUEST.length + 1);
4130
+ const startedTests = Number(count);
4131
+ return { startedTests: /^\d+$/.test(count) && Number.isSafeInteger(startedTests) ? startedTests : undefined };
4132
+ }
4133
+ function newDrainState() {
4134
+ return { handler: null, onDropped: null, dropped: [], queue: [], pending: new Set, busy: false, closed: false };
4135
+ }
4136
+ function reportDropped(drain, request) {
4137
+ if (drain.onDropped === null) {
4138
+ drain.dropped.push(request);
4139
+ } else {
4140
+ drain.onDropped(request);
4141
+ }
4142
+ }
3900
4143
 
3901
4144
  class SyncServer {
3902
4145
  token = randomBytes3(16).toString("hex");
@@ -3908,9 +4151,7 @@ class SyncServer {
3908
4151
  createHttpServer;
3909
4152
  WebSocketServerClass;
3910
4153
  webSocketOpenState;
3911
- drainHandler = null;
3912
- drainInFlight = null;
3913
- pendingDrainClients = new Set;
4154
+ drain = newDrainState();
3914
4155
  constructor(options = {}) {
3915
4156
  this.createHttpServer = options.createHttpServer ?? createServer;
3916
4157
  this.WebSocketServerClass = options.WebSocketServerClass ?? WebSocketServer;
@@ -3948,11 +4189,12 @@ class SyncServer {
3948
4189
  }
3949
4190
  ws.on("close", () => {
3950
4191
  this.clients.delete(ws);
3951
- this.pendingDrainClients.delete(ws);
4192
+ this.forgetQueuedDrainRequest(ws);
3952
4193
  });
3953
4194
  ws.on("message", (data) => {
3954
- if (rawDataToString(data) === "drain-request") {
3955
- this.handleDrainRequest(ws);
4195
+ const request = parseDrainRequest(rawDataToString(data));
4196
+ if (request) {
4197
+ this.handleDrainRequest(ws, request);
3956
4198
  }
3957
4199
  });
3958
4200
  });
@@ -3977,46 +4219,69 @@ class SyncServer {
3977
4219
  } catch {}
3978
4220
  }
3979
4221
  }
3980
- setDrainHandler(handler) {
3981
- this.drainHandler = handler;
3982
- const pending = this.pendingDrainClients;
3983
- this.pendingDrainClients = new Set;
3984
- for (const ws of pending) {
3985
- this.handleDrainRequest(ws);
4222
+ setDrainHandler(handler, onDropped) {
4223
+ const drain = this.drain;
4224
+ drain.handler = handler;
4225
+ if (onDropped !== undefined) {
4226
+ drain.onDropped = onDropped;
4227
+ for (const request of drain.dropped.splice(0)) {
4228
+ onDropped(request);
4229
+ }
3986
4230
  }
4231
+ this.serveNextDrainRequest(drain);
3987
4232
  }
3988
- handleDrainRequest(ws) {
3989
- if (!this.drainHandler) {
3990
- this.pendingDrainClients.add(ws);
4233
+ handleDrainRequest(ws, request) {
4234
+ const drain = this.drain;
4235
+ if (drain.pending.has(ws)) {
3991
4236
  return;
3992
4237
  }
3993
- if (this.drainInFlight === null) {
3994
- const started = this.drainHandler();
3995
- this.drainInFlight = started;
3996
- const settled = () => {
3997
- this.drainInFlight = null;
3998
- };
3999
- started.then(settled).catch(settled);
4238
+ drain.pending.add(ws);
4239
+ drain.queue.push({ ws, request });
4240
+ this.serveNextDrainRequest(drain);
4241
+ }
4242
+ forgetQueuedDrainRequest(ws) {
4243
+ const drain = this.drain;
4244
+ const index = drain.queue.findIndex((queued) => queued.ws === ws);
4245
+ if (index !== -1) {
4246
+ const [queued] = drain.queue.splice(index, 1);
4247
+ drain.pending.delete(ws);
4248
+ reportDropped(drain, queued.request);
4000
4249
  }
4001
- const inFlight = this.drainInFlight;
4002
- (async () => {
4003
- try {
4004
- await inFlight;
4005
- } catch {
4006
- return;
4007
- }
4250
+ }
4251
+ serveNextDrainRequest(drain) {
4252
+ const handler = drain.handler;
4253
+ if (handler === null || drain.busy || drain.closed) {
4254
+ return;
4255
+ }
4256
+ const next = drain.queue.shift();
4257
+ if (next === undefined) {
4258
+ return;
4259
+ }
4260
+ drain.busy = true;
4261
+ const answer = () => {
4008
4262
  try {
4009
- if (ws.readyState === this.webSocketOpenState) {
4010
- ws.send("drained");
4263
+ if (next.ws.readyState === this.webSocketOpenState) {
4264
+ next.ws.send("drained");
4011
4265
  }
4012
4266
  } catch {}
4013
- })();
4267
+ };
4268
+ const done = () => {
4269
+ drain.pending.delete(next.ws);
4270
+ drain.busy = false;
4271
+ this.serveNextDrainRequest(drain);
4272
+ };
4273
+ handler(next.request).then(answer).catch(() => {
4274
+ return;
4275
+ }).finally(done);
4014
4276
  }
4015
4277
  async close() {
4016
4278
  this.readyLatched = false;
4017
- this.drainHandler = null;
4018
- this.drainInFlight = null;
4019
- this.pendingDrainClients = new Set;
4279
+ const drain = this.drain;
4280
+ drain.closed = true;
4281
+ for (const queued of drain.queue) {
4282
+ reportDropped(drain, queued.request);
4283
+ }
4284
+ this.drain = newDrainState();
4020
4285
  for (const client of this.clients) {
4021
4286
  try {
4022
4287
  client.close();
@@ -4616,45 +4881,6 @@ function createInspectorUrlWaiter() {
4616
4881
  }
4617
4882
  };
4618
4883
  }
4619
- var DRAIN_ACK_SILENCE_TIMEOUT_MS = 4000;
4620
- var DRAIN_ACK_ABSOLUTE_CEILING_MS = 30000;
4621
- var DRAIN_SILENCE_POLL_INTERVAL_MS = 250;
4622
- var MAX_GAP_IDS_LISTED = 20;
4623
-
4624
- class DrainWaitTimeoutError extends Error {
4625
- reason;
4626
- constructor(message, reason) {
4627
- super(message);
4628
- this.name = "DrainWaitTimeoutError";
4629
- this.reason = reason;
4630
- }
4631
- }
4632
- function raceAgainstSilence(inspector, silenceMs, absoluteCeilingMs) {
4633
- const startedAt = Date.now();
4634
- let timer;
4635
- const promise = new Promise((_resolve, reject) => {
4636
- timer = setInterval(() => {
4637
- const sinceLastFrame = inspector.getMsSinceLastFrame();
4638
- const totalElapsed = Date.now() - startedAt;
4639
- if (totalElapsed >= absoluteCeilingMs) {
4640
- reject(new DrainWaitTimeoutError(`${absoluteCeilingMs}ms absolute ceiling reached`, "ceiling"));
4641
- } else if (totalElapsed >= silenceMs && sinceLastFrame >= silenceMs) {
4642
- reject(new DrainWaitTimeoutError(`${sinceLastFrame}ms of inspector silence (limit ${silenceMs}ms)`, "silence"));
4643
- }
4644
- }, DRAIN_SILENCE_POLL_INTERVAL_MS);
4645
- });
4646
- return { promise, cancel: () => clearInterval(timer) };
4647
- }
4648
- function formatGapIdList(gaps) {
4649
- if (gaps.length === 0) {
4650
- return "";
4651
- }
4652
- const shown = gaps.slice(0, MAX_GAP_IDS_LISTED).join(",");
4653
- return gaps.length > MAX_GAP_IDS_LISTED ? ` [${shown},…]` : ` [${shown}]`;
4654
- }
4655
- function formatDrainSettleReason(reason) {
4656
- return reason === undefined ? "never requested" : `settled via ${reason}`;
4657
- }
4658
4884
  function formatSpawnErrorMessage(spawnError) {
4659
4885
  return `could not start bun test: ${spawnError}`;
4660
4886
  }
@@ -4685,9 +4911,9 @@ function formatInspectorConnectMessage(error, child, secrets) {
4685
4911
  }
4686
4912
  function collectAbnormalDrainProblems(data) {
4687
4913
  const problems = [];
4688
- if (data.drainSettleReason !== "ack") {
4914
+ if (!data.drainProven) {
4689
4915
  const rejection = data.drainRejection === undefined ? "" : ` (${data.drainRejection})`;
4690
- problems.push(`drain handshake ${formatDrainSettleReason(data.drainSettleReason)}${rejection}`);
4916
+ problems.push(`drain handshake ${data.drainSummary}${rejection}`);
4691
4917
  }
4692
4918
  if (data.finalGaps.length > 0) {
4693
4919
  problems.push(`${data.finalGaps.length} found-id gap(s) remaining${formatGapIdList(data.finalGaps)}`);
@@ -4899,6 +5125,7 @@ class BunTestRunner {
4899
5125
  campaign;
4900
5126
  warnedWatchListProblem = false;
4901
5127
  currentAbortController;
5128
+ drainSilenceMs = DRAIN_ACK_SILENCE_TIMEOUT_MS;
4902
5129
  constructor(logger, options) {
4903
5130
  this.logger = logger;
4904
5131
  const bunOptions = options.bun ?? {};
@@ -6084,38 +6311,9 @@ exit=%s timedOut=%s
6084
6311
  }
6085
6312
  };
6086
6313
  }
6087
- let drainSettleReason;
6088
- let drainRejection;
6089
- syncServer.setDrainHandler(async () => {
6090
- const drainRequestReceivedAt = Date.now();
6091
- profile?.at("drainRequest");
6092
- const countsAtRequest = inspector.getEventCounts();
6093
- const gapsAtRequest = inspector.getFoundIdGaps();
6094
- this.logger.debug("Drain-request received: %d/%d/%d found/start/end events received so far; %d found-id gap(s)%s", countsAtRequest.found, countsAtRequest.start, countsAtRequest.end, gapsAtRequest.length, formatGapIdList(gapsAtRequest));
6095
- const { promise: silencePromise, cancel: cancelSilence } = raceAgainstSilence(inspector, DRAIN_ACK_SILENCE_TIMEOUT_MS, DRAIN_ACK_ABSOLUTE_CEILING_MS);
6096
- try {
6097
- await Promise.race([
6098
- inspector.send("TestReporter.enable", {}, DRAIN_ACK_ABSOLUTE_CEILING_MS + 1000),
6099
- silencePromise
6100
- ]);
6101
- drainSettleReason = "ack";
6102
- } catch (error) {
6103
- if (error instanceof DrainWaitTimeoutError) {
6104
- drainSettleReason = error.reason;
6105
- this.logger.debug("Inspector drain wait gave up: %s", error.message);
6106
- } else {
6107
- drainSettleReason = "send-rejected";
6108
- drainRejection = error instanceof Error ? error.message : String(error);
6109
- this.logger.debug("Inspector drain round-trip rejected before any wait bound was hit: %s", drainRejection);
6110
- }
6111
- } finally {
6112
- profile?.at("drainSettled");
6113
- cancelSilence();
6114
- const elapsedMs = Date.now() - drainRequestReceivedAt;
6115
- const countsAtSettle = inspector.getEventCounts();
6116
- const gapsAtSettle = inspector.getFoundIdGaps();
6117
- this.logger.debug("Drain handler settled via %s after %dms; events during wait +%d/+%d/+%d found/start/end; found-id gaps %d -> %d%s", drainSettleReason, elapsedMs, countsAtSettle.found - countsAtRequest.found, countsAtSettle.start - countsAtRequest.start, countsAtSettle.end - countsAtRequest.end, gapsAtRequest.length, gapsAtSettle.length, drainSettleReason === "ack" && gapsAtSettle.length > 0 ? " — ack resolved but gaps remain: the ack may under-prove drain" : "");
6118
- }
6314
+ const drain = new DrainHandshake(inspector, this.logger, profile, this.drainSilenceMs);
6315
+ syncServer.setDrainHandler(async (request) => drain.handle(request), (request) => {
6316
+ drain.requestDropped(request);
6119
6317
  });
6120
6318
  syncServer.signalReady();
6121
6319
  this.logger.debug("Signaled preload script to proceed");
@@ -6134,13 +6332,14 @@ exit=%s timedOut=%s
6134
6332
  await inspector.close();
6135
6333
  this.logger.debug("Inspector collected %d tests in hierarchy, %d in execution order", testHierarchy.length, executionOrder.length);
6136
6334
  const finalGaps = inspector.getFoundIdGaps();
6137
- this.logger.debug("Post-drain inspector snapshot: %d found-id gap(s) remaining%s; drain handshake %s", finalGaps.length, formatGapIdList(finalGaps), formatDrainSettleReason(drainSettleReason));
6335
+ this.logger.debug("Post-drain inspector snapshot: %d found-id gap(s) remaining%s; drain handshake %s", finalGaps.length, formatGapIdList(finalGaps), drain.describe());
6138
6336
  const closeInfo = inspector.getCloseInfo();
6139
6337
  const collisionStats = inspector.getFoundIdCollisionStats();
6140
6338
  this.logger.debug("Post-drain inspector close/collision diagnostics: WS close code=%s reason=%s wasClean=%s msFromLastFrameToClose=%s; " + "found events %d raw / %d unique id(s) / %d duplicate id event(s) (nonzero duplicates = direct evidence of the Bun " + "TestReporter id-collision bug; the found-id-gap count above is density-only — it does NOT prove losslessness under collisions)", String(closeInfo.code), String(closeInfo.reason), String(closeInfo.wasClean), String(closeInfo.msFromLastFrameToClose), collisionStats.rawFoundCount, collisionStats.uniqueFoundIdCount, collisionStats.duplicateFoundIdCount);
6141
6339
  this.warnOnAbnormalDrainData({
6142
- drainSettleReason,
6143
- drainRejection,
6340
+ drainProven: drain.proven,
6341
+ drainSummary: drain.describe(),
6342
+ drainRejection: drain.rejection,
6144
6343
  finalGaps,
6145
6344
  duplicateFoundIdCount: collisionStats.duplicateFoundIdCount
6146
6345
  });