@hughescr/stryker-bun-runner 1.7.1 → 1.8.0

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
@@ -5,12 +5,12 @@ import { PluginKind, declareClassPlugin } from "@stryker-mutator/api/plugin";
5
5
  import { randomBytes as randomBytes4 } from "node:crypto";
6
6
  import * as fsPromises3 from "node:fs/promises";
7
7
  import { tmpdir as tmpdir2 } from "node:os";
8
- import path15 from "node:path";
8
+ import path16 from "node:path";
9
9
  import { tokens, commonTokens } from "@stryker-mutator/api/plugin";
10
10
  import {
11
- DryRunStatus,
11
+ DryRunStatus as DryRunStatus2,
12
12
  MutantRunStatus,
13
- TestStatus,
13
+ TestStatus as TestStatus2,
14
14
  determineHitLimitReached,
15
15
  toMutantRunResult
16
16
  } from "@stryker-mutator/api/test-runner";
@@ -334,20 +334,23 @@ async function readAbortMarker(dir) {
334
334
  const { generation, message } = value;
335
335
  return typeof generation === "string" && generation !== "" && typeof message === "string" && message !== "" ? { generation, message } : undefined;
336
336
  }
337
+ function isPathSet(value) {
338
+ return Array.isArray(value) && value.every((file) => typeof file === "string" && path2.isAbsolute(file)) && new Set(value).size === value.length;
339
+ }
337
340
  function parseCampaignState(value) {
338
341
  if (typeof value !== "object" || value === null) {
339
342
  return;
340
343
  }
341
- const { generation, watchList, watchListFile, fingerprint } = value;
344
+ const { generation, watchList, watchListFile, fingerprint, handed } = value;
342
345
  const isList = Array.isArray(watchList) && watchList.every((file) => typeof file === "string" && file !== "");
343
346
  if (typeof generation !== "string" || generation === "" || !isList || fingerprint !== null && typeof fingerprint !== "string") {
344
347
  return;
345
348
  }
346
349
  const expectedFile = watchList.length === 0 ? null : watchListFileFor(generation);
347
- if (watchListFile !== expectedFile) {
350
+ if (watchListFile !== expectedFile || !isPathSet(handed)) {
348
351
  return;
349
352
  }
350
- return { generation, watchList, watchListFile: expectedFile, fingerprint };
353
+ return { generation, watchList, watchListFile: expectedFile, handed, fingerprint };
351
354
  }
352
355
  async function readRegistryCampaign(registryFile) {
353
356
  try {
@@ -422,10 +425,38 @@ var INCREMENTAL_ADVICE = " Results saved before the change are reused: run once
422
425
  function incrementalAdvice(incremental) {
423
426
  return incremental ? INCREMENTAL_ADVICE : "";
424
427
  }
428
+ var HANDED_INCREMENTAL_ADVICE = " Results for these files that an earlier run saved are reused: run once with --force after upgrading, and again whenever the tests that drive the worker or the child change.";
425
429
  var UNSEEN_LOAD_ADVICE = "If the tests do load one of those in a way the runner cannot see (through a package, a worker or a child process), add it to bun.alwaysImport.";
430
+ var WORKER_CHILD_ADVICE = "A file that only a worker or a child process runs is not covered by that: it needs the call that starts it written in a form " + "the runner reads (the file's path written out in the call), or coverageAnalysis: 'off'.";
431
+ var UNSEEN_LOAD_ADVICE_OTHERS = `If the tests do load one of the others in a way the runner cannot see (through a package), add it to bun.alwaysImport. ${WORKER_CHILD_ADVICE}`;
432
+ var UNSEEN_LOAD_ADVICE_UNREAD = `If the tests do load one of those in a way the runner cannot see (through a package), add it to bun.alwaysImport. ${WORKER_CHILD_ADVICE}`;
433
+ var HAND_OFFS_UNREAD = "Files handed to a worker or a child process are not read.";
434
+ function startersText(testFiles, one) {
435
+ return `the tests in ${count(testFiles, "test file")} that start ${one ? "it" : "them"}`;
436
+ }
437
+ function handedText(handed, incremental) {
438
+ const { started, every, testFiles } = handed;
439
+ const total = started.length + every.length;
440
+ if (total === 0) {
441
+ return "";
442
+ }
443
+ const advice = incremental ? HANDED_INCREMENTAL_ADVICE : "";
444
+ const head = ` The tests hand ${total} of them to a worker or a child process`;
445
+ if (started.length > 0 && every.length > 0) {
446
+ return `${head}: the mutants of ${started.length} (${listText(started)}) are reported as covered by ${startersText(testFiles, started.length === 1)}, ` + `and those of ${every.length} (${listText(every)}) as covered by every test.${advice}`;
447
+ }
448
+ const one = total === 1;
449
+ const by = every.length === 0 ? startersText(testFiles, one) : "every test";
450
+ return `${head} (${listText(every.length === 0 ? started : every)}), so ${one ? "its" : "their"} mutants are reported as covered by ${by}.${advice}`;
451
+ }
426
452
  function leftOutText(summary, imported) {
427
453
  const verb = imported === 0 ? "It does not import any of them itself" : `It does not import the other ${summary.left.length} itself`;
428
- return `${verb}: ${listText(summary.left)}. ${UNSEEN_LOAD_ADVICE}${incrementalAdvice(summary.incremental)}`;
454
+ const handed = summary.handed ?? { started: [], testFiles: 0, every: [] };
455
+ const named = handed.started.length + handed.every.length;
456
+ const unseen = summary.handOffsUnread === true ? UNSEEN_LOAD_ADVICE_UNREAD : UNSEEN_LOAD_ADVICE;
457
+ const others = named === 0 ? ` ${unseen}` : ` ${UNSEEN_LOAD_ADVICE_OTHERS}`;
458
+ const advice = named === summary.left.length ? "" : others;
459
+ return `${verb}: ${listText(summary.left)}.${handedText(handed, summary.incremental)}${advice}${incrementalAdvice(summary.incremental)}`;
429
460
  }
430
461
  function importListOneRunMessage(summary, sources) {
431
462
  const imported = sources.statically + sources.named + sources.always;
@@ -457,15 +488,17 @@ var SCAN_NEXT = {
457
488
  static: "One run of the tests, with those files imported first and the rest watched.",
458
489
  dynamic: "A plain run of the tests is observed first, then the run that publishes results."
459
490
  };
491
+ var HAND_OFF_NOTE = "hand-offs ";
460
492
  function scanMessage(scan) {
461
- const sets = `${scan.statically.length} imported statically [${scan.statically.join(", ")}], ${scan.named.length} named in import() or require() [${scan.named.join(", ")}], ${scan.always.length} kept by bun.alwaysImport [${scan.always.join(", ")}]`;
493
+ const handed = scan.handed.length > 0 || scan.notes.some((note) => note.startsWith(HAND_OFF_NOTE)) ? `${scan.handed.length} handed to a worker or a child process [${scan.handed.join(", ")}], ` : "";
494
+ const sets = `${scan.statically.length} imported statically [${scan.statically.join(", ")}], ${scan.named.length} named in import() or require() [${scan.named.join(", ")}], ` + `${handed}${scan.always.length} kept by bun.alwaysImport [${scan.always.join(", ")}]`;
462
495
  const reasons = scan.reasons.length === 0 ? "" : `; reasons: ${escapeControlCharacters(scan.reasons.join("; "))}`;
463
496
  const notes = scan.notes.length === 0 ? "" : `; notes: ${escapeControlCharacters(scan.notes.join("; "))}`;
464
497
  return `Import scan: ${scan.answer} in ${Math.round(scan.wallMs)} ms over ${scan.scannedFiles} files; of the ${scan.matched} files matched by mutate, ${sets}${reasons}${notes}. ${SCAN_NEXT[scan.next]}`;
465
498
  }
466
499
  function scanUnusableMessage(reason, started) {
467
500
  const what = started ? "The import scan gave no usable answer" : "The import scan was not started";
468
- return `${what}: ${escapeControlCharacters(reason)}. ${SCAN_NEXT.dynamic}`;
501
+ return `${what}: ${escapeControlCharacters(reason)}. ${SCAN_NEXT.dynamic} ${HAND_OFFS_UNREAD}`;
469
502
  }
470
503
  var MISS_DISCARDED = "The run is discarded, and the dry run starts again with a plain run of the tests that observes what they load; if that run is accepted, the runner attempts a third run to publish the results.";
471
504
  function missMessage(files, testFiles, incremental) {
@@ -1069,45 +1102,179 @@ function budgetWarning(usedMs, budgetMs) {
1069
1102
  return { usedMs, remainingMs: Math.max(0, remainingMs), suggestedMinutes: Math.ceil(2 * usedMs / 60000) };
1070
1103
  }
1071
1104
 
1105
+ // src/coverage/handed-coverage.ts
1106
+ import path5 from "node:path";
1107
+ import { DryRunStatus, TestStatus } from "@stryker-mutator/api/test-runner";
1108
+ function holdsAnyId(files) {
1109
+ return files.some((entry) => entry.ids.length > 0);
1110
+ }
1111
+ function testsByFile(tests, cwd, scanned) {
1112
+ const byFile = new Map;
1113
+ let complete = true;
1114
+ for (const test of tests) {
1115
+ if (test.status !== TestStatus.Skipped) {
1116
+ const file = test.fileName === undefined ? undefined : path5.resolve(cwd, test.fileName);
1117
+ if (file === undefined || !scanned.has(file)) {
1118
+ complete = false;
1119
+ continue;
1120
+ }
1121
+ const ids = byFile.get(file) ?? [];
1122
+ ids.push(test.id);
1123
+ byFile.set(file, ids);
1124
+ }
1125
+ }
1126
+ return { byFile, complete };
1127
+ }
1128
+ function handedCredits(handed, tests) {
1129
+ return handed.map(({ file, ids, launchers, every }) => {
1130
+ const started = tests === undefined || launchers === undefined ? undefined : testsOf(launchers, tests.byFile);
1131
+ if (started === undefined || started.tests.length === 0) {
1132
+ return { file, ids };
1133
+ }
1134
+ const startedBy = { testFiles: launchers, tests: started.tests };
1135
+ return every === true || !started.all || !tests.complete ? { file, ids, startedBy, every: true } : { file, ids, startedBy };
1136
+ });
1137
+ }
1138
+ function testsOf(launchers, byFile) {
1139
+ const tests = [];
1140
+ let all = true;
1141
+ for (const launcher of launchers) {
1142
+ const own = byFile.get(launcher);
1143
+ all &&= own !== undefined;
1144
+ for (const id of own ?? []) {
1145
+ tests.push(id);
1146
+ }
1147
+ }
1148
+ return { tests, all };
1149
+ }
1150
+
1151
+ class CreditedCoverage {
1152
+ coverage;
1153
+ constructor(measured) {
1154
+ this.coverage = { static: { ...measured.static }, perTest: { ...measured.perTest } };
1155
+ }
1156
+ addStatic(ids) {
1157
+ for (const id of ids) {
1158
+ this.coverage.static[id] = 1;
1159
+ }
1160
+ }
1161
+ addToTests(ids, tests) {
1162
+ if (ids.length === 0) {
1163
+ return;
1164
+ }
1165
+ for (const test of tests) {
1166
+ const entry = { ...this.coverage.perTest[test] };
1167
+ for (const id of ids) {
1168
+ entry[id] = Math.max(entry[id] ?? 0, 1);
1169
+ }
1170
+ this.coverage.perTest[test] = entry;
1171
+ }
1172
+ }
1173
+ }
1174
+ var EVERY_TEST_ENTRY_LIMIT = 5000000;
1175
+ var n = (value) => value.toLocaleString("en-US");
1176
+ function overLimitWarning(ids, tests, limit) {
1177
+ return `Dry run: ${n(ids)} mutants of files the tests hand to a worker or a child process are covered by every test, ` + `but crediting each of the ${n(tests)} tests that ran with them would take ${n(ids * tests)} per-test entries, more than the runner adds (${n(limit)}), ` + "so they are reported as static only. With ignoreStatic, Stryker ignores them, or runs only the tests known to start their file or seen to reach them. " + "To test them, run without ignoreStatic, or write the path of the worker's or the child's file literally in the test file that starts it, " + "so that the runner can tell which tests start it.";
1178
+ }
1179
+ function creditHandedCoverage(result, credits, display, perTestForEvery, entryLimit = EVERY_TEST_ENTRY_LIMIT) {
1180
+ if (result.status !== DryRunStatus.Complete || result.mutantCoverage === undefined || credits.length === 0) {
1181
+ return { result, files: [], debug: [] };
1182
+ }
1183
+ const measured = result.mutantCoverage;
1184
+ const counts = new CreditedCoverage(measured);
1185
+ const debug = [];
1186
+ const files = [];
1187
+ const toEvery = [];
1188
+ let toTests = 0;
1189
+ let toStatic = 0;
1190
+ for (const { file, ids, startedBy, every } of credits) {
1191
+ if (ids.length === 0) {
1192
+ debug.push(`Dry run: ${display(file)}, which the tests hand to a worker or a child process, holds no mutant id; none of its mutants is credited`);
1193
+ } else {
1194
+ files.push(file);
1195
+ }
1196
+ if (startedBy !== undefined) {
1197
+ counts.addToTests(ids, startedBy.tests);
1198
+ toTests += ids.length;
1199
+ }
1200
+ if (startedBy === undefined || every === true) {
1201
+ const notStatic = ids.filter((id) => (measured.static[id] ?? 0) <= 0);
1202
+ counts.addStatic(notStatic);
1203
+ toStatic += notStatic.length;
1204
+ for (const id of ids) {
1205
+ toEvery.push(id);
1206
+ }
1207
+ }
1208
+ }
1209
+ const { text, warning } = perTestForEvery ? creditEachTest(counts, result.tests, toEvery, entryLimit) : { text: "" };
1210
+ debug.push(`Dry run: of the mutants of ${credits.length} files the tests hand to a worker or a child process, ${toTests} credited to the tests of the test files that start them and ${toStatic} reported as static (run against every test)${text}`);
1211
+ return { result: { ...result, mutantCoverage: counts.coverage }, files, debug, ...warning === undefined ? {} : { warning } };
1212
+ }
1213
+ function creditEachTest(counts, tests, ids, entryLimit) {
1214
+ const ran = tests.filter((test) => test.status !== TestStatus.Skipped).map((test) => test.id);
1215
+ if (ids.length * ran.length > entryLimit) {
1216
+ return {
1217
+ text: `, and none credited to each of the ${ran.length} tests that ran (${ids.length} would take more than ${entryLimit} per-test entries)`,
1218
+ warning: overLimitWarning(ids.length, ran.length, entryLimit)
1219
+ };
1220
+ }
1221
+ counts.addToTests(ids, ran);
1222
+ return { text: `, and ${ids.length} credited to each of the ${ran.length} tests that ran` };
1223
+ }
1224
+
1072
1225
  // src/coverage/import-scan-runner.ts
1073
1226
  import { spawn } from "node:child_process";
1074
1227
  import { randomBytes as randomBytes2 } from "node:crypto";
1075
1228
  import { rm as rm3 } from "node:fs/promises";
1076
- import path5 from "node:path";
1229
+ import path6 from "node:path";
1077
1230
  import { fileURLToPath } from "node:url";
1078
1231
  var IMPORT_SCAN_TIMEOUT_MS = 5000;
1232
+ var HAND_OFF_BUDGET = { wallMs: 250, files: 1000, ids: 1e5 };
1233
+ var HAND_OFF_GRACE_MS = 250;
1234
+ var MAX_MUTANT_ID_LENGTH = 32;
1235
+ var MAX_LAUNCHERS = 1e5;
1236
+ var LAUNCHERS_KEY_BYTES = 32;
1079
1237
  var STDERR_EXCERPT_CHARS = 2000;
1080
1238
  var IMPORT_SCAN_STDERR_LIMIT_BYTES = 64 * 1024;
1081
1239
  var STDOUT_BASE_BYTES = 1024 * 1024;
1082
1240
  function scanOutputLimits(input) {
1083
1241
  const eagerBytes = input.eager.reduce((sum, file) => sum + Buffer.byteLength(file) + 3, 0);
1084
- return { stdout: STDOUT_BASE_BYTES + 6 * eagerBytes, stderr: IMPORT_SCAN_STDERR_LIMIT_BYTES };
1242
+ const idBytes = (input.handOffBudget ?? HAND_OFF_BUDGET).ids * (6 * MAX_MUTANT_ID_LENGTH + 3);
1243
+ const launcherBytes = MAX_LAUNCHERS * (String(input.tests.length).length + 1) + LAUNCHERS_KEY_BYTES * input.eager.length;
1244
+ return { stdout: 2 * STDOUT_BASE_BYTES + 12 * eagerBytes + idBytes + launcherBytes, stderr: IMPORT_SCAN_STDERR_LIMIT_BYTES };
1085
1245
  }
1086
1246
  function resolveBunExecutable(bunPath, cwd) {
1087
- const hasDirectory = bunPath.includes("/") || path5.sep === "\\" && bunPath.includes("\\");
1088
- return hasDirectory && !path5.isAbsolute(bunPath) ? path5.resolve(cwd, bunPath) : bunPath;
1247
+ const hasDirectory = bunPath.includes("/") || path6.sep === "\\" && bunPath.includes("\\");
1248
+ return hasDirectory && !path6.isAbsolute(bunPath) ? path6.resolve(cwd, bunPath) : bunPath;
1089
1249
  }
1090
1250
  var PRELOADING_ENV = ["BUN_OPTIONS", "NODE_OPTIONS"];
1091
1251
  function resolveImportScanScript(moduleDir) {
1092
1252
  const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
1093
- return isBundled ? path5.join(moduleDir, "templates/import-scan.js") : path5.join(moduleDir, "import-scan.ts");
1253
+ return isBundled ? path6.join(moduleDir, "templates/import-scan.js") : path6.join(moduleDir, "import-scan.ts");
1094
1254
  }
1095
1255
  function failedScanResult(reason) {
1096
- return { answer: "dynamic", mandatory: [], named: [], reasons: [reason], notes: [], scannedFiles: 0, elapsedMs: 0 };
1256
+ return { answer: "dynamic", mandatory: [], named: [], handed: [], reasons: [reason], notes: [], scannedFiles: 0, elapsedMs: 0 };
1097
1257
  }
1098
1258
  var isStringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
1099
- function parseImportScanOutput(stdout, eagerList) {
1259
+ function jsonObject(line, what) {
1100
1260
  let value;
1101
1261
  try {
1102
- value = JSON.parse(stdout);
1262
+ value = JSON.parse(line);
1103
1263
  } catch (error) {
1104
- return { problem: `its output is not JSON (${error.message})` };
1264
+ return { problem: `its ${what} is not JSON (${error.message})` };
1105
1265
  }
1106
1266
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
1107
- return { problem: "its output is not a JSON object" };
1267
+ return { problem: `its ${what} is not a JSON object` };
1108
1268
  }
1109
- const output = value;
1110
- const problem = outputProblem(output, new Set(eagerList));
1269
+ return { value };
1270
+ }
1271
+ function parseScanAnswer(line, eagerList) {
1272
+ const parsed = jsonObject(line, "output");
1273
+ if ("problem" in parsed) {
1274
+ return parsed;
1275
+ }
1276
+ const output = parsed.value;
1277
+ const problem = answerProblem(output, new Set(eagerList));
1111
1278
  if (problem !== undefined) {
1112
1279
  return { problem };
1113
1280
  }
@@ -1115,7 +1282,7 @@ function parseImportScanOutput(stdout, eagerList) {
1115
1282
  const mandatorySet = new Set(mandatory);
1116
1283
  const namedSet = new Set(named);
1117
1284
  return {
1118
- result: {
1285
+ answer: {
1119
1286
  answer,
1120
1287
  mandatory: eagerList.filter((file) => mandatorySet.has(file)),
1121
1288
  named: eagerList.filter((file) => namedSet.has(file)),
@@ -1126,7 +1293,7 @@ function parseImportScanOutput(stdout, eagerList) {
1126
1293
  }
1127
1294
  };
1128
1295
  }
1129
- function outputProblem(output, eager) {
1296
+ function answerProblem(output, eager) {
1130
1297
  if (output.answer !== "full" && output.answer !== "static" && output.answer !== "dynamic") {
1131
1298
  return `its answer ${JSON.stringify(output.answer)} is not full, static or dynamic`;
1132
1299
  }
@@ -1136,12 +1303,18 @@ function outputProblem(output, eager) {
1136
1303
  return `its ${name} list is not a list of files of the eager list`;
1137
1304
  }
1138
1305
  }
1139
- for (const name of ["reasons", "notes"]) {
1306
+ return notesProblem(output, ["reasons", "notes"]) ?? countsProblem(output, ["scannedFiles", "elapsedMs"]);
1307
+ }
1308
+ function notesProblem(output, names) {
1309
+ for (const name of names) {
1140
1310
  if (!isStringArray(output[name])) {
1141
1311
  return `its ${name} are not a list of strings`;
1142
1312
  }
1143
1313
  }
1144
- for (const name of ["scannedFiles", "elapsedMs"]) {
1314
+ return;
1315
+ }
1316
+ function countsProblem(output, names) {
1317
+ for (const name of names) {
1145
1318
  const value = output[name];
1146
1319
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
1147
1320
  return `its ${name} is not a non-negative number`;
@@ -1149,6 +1322,98 @@ function outputProblem(output, eager) {
1149
1322
  }
1150
1323
  return;
1151
1324
  }
1325
+ function isIdList(ids) {
1326
+ return isStringArray(ids) && ids.every((id) => id !== "" && id.length <= MAX_MUTANT_ID_LENGTH) && new Set(ids).size === ids.length;
1327
+ }
1328
+ function launcherFiles(launchers, tests) {
1329
+ if (launchers === undefined) {
1330
+ return {};
1331
+ }
1332
+ if (!Array.isArray(launchers) || launchers.length === 0) {
1333
+ return;
1334
+ }
1335
+ const files = [];
1336
+ let last = -1;
1337
+ for (const index of launchers) {
1338
+ if (!Number.isSafeInteger(index) || index <= last || index >= tests.length) {
1339
+ return;
1340
+ }
1341
+ last = index;
1342
+ files.push(tests[last]);
1343
+ }
1344
+ return { files };
1345
+ }
1346
+ function handedEntry(entry, eager, tests) {
1347
+ const { file, ids, launchers, every } = entry ?? {};
1348
+ const starters = launcherFiles(launchers, tests);
1349
+ if (typeof file !== "string" || !eager.has(file) || !isIdList(ids) || starters === undefined) {
1350
+ return;
1351
+ }
1352
+ if (starters.files === undefined) {
1353
+ return every === undefined ? { file, ids } : undefined;
1354
+ }
1355
+ if (every === undefined) {
1356
+ return { file, ids, launchers: starters.files };
1357
+ }
1358
+ return every === true ? { file, ids, launchers: starters.files, every: true } : undefined;
1359
+ }
1360
+ function parseScanHandOffs(line, eagerList, testList) {
1361
+ const parsed = jsonObject(line, "hand-off line");
1362
+ if ("problem" in parsed) {
1363
+ return parsed;
1364
+ }
1365
+ const output = parsed.value;
1366
+ const eager = new Set(eagerList);
1367
+ const { handed } = output;
1368
+ const notHanded = { problem: "its handed list is not a list of files of the eager list, each once with its mutant ids and the test files that start it" };
1369
+ if (!Array.isArray(handed)) {
1370
+ return notHanded;
1371
+ }
1372
+ const byFile = new Map;
1373
+ for (const entry of handed) {
1374
+ const read = handedEntry(entry, eager, testList);
1375
+ if (read === undefined || byFile.has(read.file)) {
1376
+ return notHanded;
1377
+ }
1378
+ byFile.set(read.file, read);
1379
+ }
1380
+ const problem = notesProblem(output, ["notes"]) ?? countsProblem(output, ["elapsedMs"]);
1381
+ if (problem !== undefined) {
1382
+ return { problem };
1383
+ }
1384
+ return { handOffs: { handed: eagerList.filter((file) => byFile.has(file)).map((file) => byFile.get(file)), notes: output.notes } };
1385
+ }
1386
+ function handOffsNotRead(why) {
1387
+ return `hand-offs not read: ${why}`;
1388
+ }
1389
+ function parseImportScanOutput(stdout, input, handOffFailure) {
1390
+ const lines = stdout.split(`
1391
+ `);
1392
+ const parsed = parseScanAnswer(lines[0], input.eager);
1393
+ if ("problem" in parsed) {
1394
+ return parsed;
1395
+ }
1396
+ const { answer } = parsed;
1397
+ const withoutHandOffs = (why) => ({ result: { ...answer, handed: [], notes: [...answer.notes, handOffsNotRead(why)] } });
1398
+ if (handOffFailure !== undefined) {
1399
+ return withoutHandOffs(handOffFailure);
1400
+ }
1401
+ if (lines.length !== 3 || lines[2] !== "") {
1402
+ return withoutHandOffs("the scan helper did not print them on a line of their own");
1403
+ }
1404
+ const handOffs = parseScanHandOffs(lines[1], input.eager, input.tests);
1405
+ if ("problem" in handOffs) {
1406
+ return withoutHandOffs(`the scan helper's hand-off line cannot be used: ${handOffs.problem}`);
1407
+ }
1408
+ return { result: { ...answer, handed: handOffs.handOffs.handed, notes: [...answer.notes, ...handOffs.handOffs.notes] } };
1409
+ }
1410
+ function lineEnds(chunk) {
1411
+ let count = 0;
1412
+ for (let at = chunk.indexOf(10);at !== -1; at = chunk.indexOf(10, at + 1)) {
1413
+ count++;
1414
+ }
1415
+ return count;
1416
+ }
1152
1417
 
1153
1418
  class BoundedStream {
1154
1419
  limit;
@@ -1158,8 +1423,10 @@ class BoundedStream {
1158
1423
  this.limit = limit;
1159
1424
  }
1160
1425
  add(chunk) {
1426
+ const room = this.limit - this.bytes;
1161
1427
  this.bytes += chunk.length;
1162
1428
  if (this.bytes > this.limit) {
1429
+ this.chunks.push(chunk.subarray(0, room));
1163
1430
  return false;
1164
1431
  }
1165
1432
  this.chunks.push(chunk);
@@ -1169,18 +1436,27 @@ class BoundedStream {
1169
1436
  return Buffer.concat(this.chunks).toString("utf8");
1170
1437
  }
1171
1438
  }
1172
- function runHelper(bunPath, args, cwd, timeoutMs, maxBytes) {
1439
+ function runHelper(bunPath, args, cwd, limits) {
1173
1440
  const env = { ...process.env };
1174
1441
  for (const name of PRELOADING_ENV) {
1175
1442
  delete env[name];
1176
1443
  }
1444
+ const { timeoutMs, handOffMs, maxBytes } = limits;
1177
1445
  return new Promise((resolve) => {
1178
1446
  const streams = { stdout: new BoundedStream(maxBytes.stdout), stderr: new BoundedStream(maxBytes.stderr) };
1179
1447
  let timedOut = false;
1448
+ let cut = false;
1180
1449
  let overflow;
1181
1450
  let error;
1451
+ let answeredAt;
1452
+ let complete = false;
1453
+ let newlines = 0;
1454
+ let handOffTimer;
1455
+ let answered = false;
1182
1456
  const ended = (exitCode, signal) => {
1183
- resolve({ stdout: streams.stdout.text(), stderr: streams.stderr.text(), exitCode, signal, timedOut, overflow, error });
1457
+ answered = true;
1458
+ clearTimeout(handOffTimer);
1459
+ resolve({ stdout: streams.stdout.text(), stderr: streams.stderr.text(), exitCode, signal, timedOut, cut, overflow, error, answeredAt, complete });
1184
1460
  };
1185
1461
  let child;
1186
1462
  try {
@@ -1196,15 +1472,42 @@ function runHelper(bunPath, args, cwd, timeoutMs, maxBytes) {
1196
1472
  child.stderr?.destroy();
1197
1473
  ended(null, null);
1198
1474
  };
1475
+ const release = () => {
1476
+ child.unref();
1477
+ for (const stream of [child.stdout, child.stderr]) {
1478
+ stream?.unref();
1479
+ }
1480
+ ended(null, null);
1481
+ };
1199
1482
  const timer = setTimeout(() => {
1200
1483
  timedOut = true;
1201
1484
  abandon();
1202
1485
  }, timeoutMs);
1486
+ const cutHandOffs = () => {
1487
+ cut = true;
1488
+ clearTimeout(timer);
1489
+ abandon();
1490
+ };
1203
1491
  const collect = (name) => (chunk) => {
1204
- if (!streams[name].add(chunk) && overflow === undefined) {
1492
+ if (answered) {
1493
+ return;
1494
+ }
1495
+ const kept = streams[name].add(chunk);
1496
+ if (name === "stdout") {
1497
+ newlines += lineEnds(chunk);
1498
+ }
1499
+ if (newlines > 0 && answeredAt === undefined) {
1500
+ answeredAt = performance.now();
1501
+ handOffTimer = setTimeout(cutHandOffs, handOffMs);
1502
+ }
1503
+ if (!kept) {
1205
1504
  overflow = name;
1206
1505
  clearTimeout(timer);
1207
1506
  abandon();
1507
+ } else if (newlines >= 2) {
1508
+ complete = true;
1509
+ clearTimeout(timer);
1510
+ release();
1208
1511
  }
1209
1512
  };
1210
1513
  child.stdout?.on("data", collect("stdout"));
@@ -1218,17 +1521,20 @@ function runHelper(bunPath, args, cwd, timeoutMs, maxBytes) {
1218
1521
  });
1219
1522
  });
1220
1523
  }
1221
- function helperFailure(exit, timeoutMs, maxBytes) {
1524
+ function helperFailure(exit, limits) {
1222
1525
  if (exit.error !== undefined) {
1223
1526
  return `the scan helper could not be started (${exit.error.message})`;
1224
1527
  }
1225
1528
  if (exit.overflow !== undefined) {
1226
- return `the scan helper printed more than ${maxBytes[exit.overflow]} bytes on ${exit.overflow}`;
1529
+ return `the scan helper printed more than ${limits.maxBytes[exit.overflow]} bytes on ${exit.overflow}`;
1227
1530
  }
1228
1531
  if (exit.timedOut) {
1229
- return `the scan helper did not finish within ${timeoutMs} ms`;
1532
+ return `the scan helper did not finish within ${limits.timeoutMs} ms`;
1533
+ }
1534
+ if (exit.cut) {
1535
+ return `the scan helper did not finish them within ${limits.handOffMs} ms of its answer`;
1230
1536
  }
1231
- if (exit.exitCode !== 0) {
1537
+ if (!exit.complete && exit.exitCode !== 0) {
1232
1538
  const how = exit.exitCode === null ? `was ended by ${exit.signal}` : `exited with code ${exit.exitCode}`;
1233
1539
  const said = exit.stderr.trim().slice(0, STDERR_EXCERPT_CHARS);
1234
1540
  return said === "" ? `the scan helper ${how}` : `the scan helper ${how}: ${said}`;
@@ -1237,30 +1543,39 @@ function helperFailure(exit, timeoutMs, maxBytes) {
1237
1543
  }
1238
1544
  async function runImportScan(input, launch) {
1239
1545
  const started = performance.now();
1240
- const timeoutMs = launch.timeoutMs ?? IMPORT_SCAN_TIMEOUT_MS;
1241
- const maxBytes = launch.maxBytes ?? scanOutputLimits(input);
1242
- const scriptPath = launch.scriptPath ?? resolveImportScanScript(path5.dirname(fileURLToPath(import.meta.url)));
1243
- const stem = path5.join(launch.workDir, `import-scan-${process.pid}-${randomBytes2(8).toString("hex")}`);
1546
+ const scanInput = { ...input, handOffBudget: input.handOffBudget ?? HAND_OFF_BUDGET };
1547
+ const limits = {
1548
+ timeoutMs: launch.timeoutMs ?? IMPORT_SCAN_TIMEOUT_MS,
1549
+ handOffMs: scanInput.handOffBudget.wallMs + HAND_OFF_GRACE_MS,
1550
+ maxBytes: launch.maxBytes ?? scanOutputLimits(scanInput)
1551
+ };
1552
+ const scriptPath = launch.scriptPath ?? resolveImportScanScript(path6.dirname(fileURLToPath(import.meta.url)));
1553
+ const stem = path6.join(launch.workDir, `import-scan-${process.pid}-${randomBytes2(8).toString("hex")}`);
1244
1554
  const inputFile = `${stem}.json`;
1245
1555
  const configFile = `${stem}.bunfig.toml`;
1246
- const report = (result, failure) => ({ result, failure, wallMs: performance.now() - started });
1556
+ const report = (result, failure, answeredAt) => {
1557
+ const ended = performance.now();
1558
+ return { result, failure, wallMs: ended - started, answerMs: (answeredAt ?? ended) - started };
1559
+ };
1247
1560
  const fail = (failure) => report(failedScanResult(failure), failure);
1248
1561
  try {
1249
1562
  try {
1250
1563
  await ensurePrivateDir(launch.workDir);
1251
- await writePrivateFile(inputFile, JSON.stringify(input));
1564
+ await writePrivateFile(inputFile, JSON.stringify(scanInput));
1252
1565
  await writePrivateFile(configFile, "");
1253
1566
  } catch (error) {
1254
1567
  return fail(`the scan's input could not be written (${error.message})`);
1255
1568
  }
1256
1569
  const bunPath = resolveBunExecutable(launch.bunPath, process.cwd());
1257
- const exit = await runHelper(bunPath, ["--no-macros", "--no-install", `--config=${configFile}`, scriptPath, inputFile], launch.workDir, timeoutMs, maxBytes);
1258
- const failure = helperFailure(exit, timeoutMs, maxBytes);
1259
- if (failure !== undefined) {
1570
+ const exit = await runHelper(bunPath, ["--no-macros", "--no-install", `--config=${configFile}`, scriptPath, inputFile], launch.workDir, limits);
1571
+ const failure = helperFailure(exit, limits);
1572
+ const answered = exit.stdout.includes(`
1573
+ `);
1574
+ if (failure !== undefined && !answered) {
1260
1575
  return fail(failure);
1261
1576
  }
1262
- const parsed = parseImportScanOutput(exit.stdout, input.eager);
1263
- return "problem" in parsed ? fail(`the scan helper's answer cannot be used: ${parsed.problem}`) : report(parsed.result, null);
1577
+ const parsed = parseImportScanOutput(exit.stdout, input, failure);
1578
+ return "problem" in parsed ? fail(`the scan helper's answer cannot be used: ${parsed.problem}`) : report(parsed.result, null, exit.answeredAt);
1264
1579
  } finally {
1265
1580
  await Promise.all([inputFile, configFile].map((file) => rm3(file).catch(() => {
1266
1581
  return;
@@ -1270,7 +1585,7 @@ async function runImportScan(input, launch) {
1270
1585
 
1271
1586
  // src/coverage/preload-generator.ts
1272
1587
  import { unlink, readFile as readFile2, realpath as realpath2 } from "node:fs/promises";
1273
- import path6 from "node:path";
1588
+ import path7 from "node:path";
1274
1589
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1275
1590
  import { glob } from "tinyglobby";
1276
1591
 
@@ -1342,7 +1657,7 @@ async function resolveEagerModulesFromGlobs(mutateGlobs, cwd = process.cwd()) {
1342
1657
  expandDirectories: false
1343
1658
  });
1344
1659
  const filtered = paths.filter((p) => CODE_FILE_RE.test(p) && !DECLARATION_FILE_RE.test(p) && !TEST_FILE_SUFFIX_RE.test(p));
1345
- const resolved = filtered.map((p) => path6.resolve(p));
1660
+ const resolved = filtered.map((p) => path7.resolve(p));
1346
1661
  resolved.sort((a, b) => a.localeCompare(b));
1347
1662
  return resolved;
1348
1663
  }
@@ -1363,21 +1678,21 @@ function resolvePreloadTemplate(moduleDir) {
1363
1678
  const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
1364
1679
  if (isBundled) {
1365
1680
  return {
1366
- templatePath: path6.join(moduleDir, "templates/coverage-preload.js"),
1681
+ templatePath: path7.join(moduleDir, "templates/coverage-preload.js"),
1367
1682
  preloadLogicPath: undefined,
1368
1683
  extension: "js"
1369
1684
  };
1370
1685
  }
1371
1686
  return {
1372
- templatePath: path6.join(moduleDir, "../templates/coverage-preload.ts"),
1373
- preloadLogicPath: path6.join(moduleDir, "preload-logic.ts"),
1687
+ templatePath: path7.join(moduleDir, "../templates/coverage-preload.ts"),
1688
+ preloadLogicPath: path7.join(moduleDir, "preload-logic.ts"),
1374
1689
  extension: "ts"
1375
1690
  };
1376
1691
  }
1377
- async function generatePreloadScript(options, moduleDir = path6.dirname(fileURLToPath2(import.meta.url))) {
1692
+ async function generatePreloadScript(options, moduleDir = path7.dirname(fileURLToPath2(import.meta.url))) {
1378
1693
  await ensurePrivateDir(options.tempDir);
1379
1694
  const { templatePath, preloadLogicPath, extension } = resolvePreloadTemplate(moduleDir);
1380
- const preloadPath = path6.join(options.tempDir, `stryker-coverage-preload-${process.pid}.${extension}`);
1695
+ const preloadPath = path7.join(options.tempDir, `stryker-coverage-preload-${process.pid}.${extension}`);
1381
1696
  const template = await readFile2(templatePath, "utf8");
1382
1697
  const content = preloadLogicPath === undefined ? template : template.replace("__PRELOAD_LOGIC_PATH__", () => preloadLogicPath);
1383
1698
  await writePrivateFile(preloadPath, content);
@@ -1910,6 +2225,185 @@ function mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger
1910
2225
  orphanedKeyCount: counterIds.length - creditedKeyCount
1911
2226
  };
1912
2227
  }
2228
+ // src/drain-handshake.ts
2229
+ var DRAIN_ACK_SILENCE_TIMEOUT_MS = 4000;
2230
+ var DRAIN_ACK_ABSOLUTE_CEILING_MS = 30000;
2231
+ var DRAIN_SILENCE_POLL_INTERVAL_MS = 250;
2232
+ var MAX_GAP_IDS_LISTED = 20;
2233
+
2234
+ class DrainWaitTimeoutError extends Error {
2235
+ reason;
2236
+ constructor(message, reason) {
2237
+ super(message);
2238
+ this.name = "DrainWaitTimeoutError";
2239
+ this.reason = reason;
2240
+ }
2241
+ }
2242
+
2243
+ class InspectorClosedError extends Error {
2244
+ }
2245
+ function raceAgainstSilence(inspector, silenceMs, absoluteCeilingMs) {
2246
+ const startedAt = Date.now();
2247
+ let timer;
2248
+ const promise = new Promise((_resolve, reject) => {
2249
+ timer = setInterval(() => {
2250
+ const sinceLastFrame = inspector.getMsSinceLastFrame();
2251
+ const totalElapsed = Date.now() - startedAt;
2252
+ if (totalElapsed >= absoluteCeilingMs) {
2253
+ reject(new DrainWaitTimeoutError(`${absoluteCeilingMs}ms absolute ceiling reached`, "ceiling"));
2254
+ } else if (totalElapsed >= silenceMs && sinceLastFrame >= silenceMs) {
2255
+ reject(new DrainWaitTimeoutError(`${sinceLastFrame}ms of inspector silence (limit ${silenceMs}ms)`, "silence"));
2256
+ }
2257
+ }, DRAIN_SILENCE_POLL_INTERVAL_MS);
2258
+ });
2259
+ return { promise, cancel: () => clearInterval(timer) };
2260
+ }
2261
+ function formatGapIdList(gaps) {
2262
+ if (gaps.length === 0) {
2263
+ return "";
2264
+ }
2265
+ const shown = gaps.slice(0, MAX_GAP_IDS_LISTED).join(",");
2266
+ return gaps.length > MAX_GAP_IDS_LISTED ? ` [${shown},…]` : ` [${shown}]`;
2267
+ }
2268
+ function isProof(reason) {
2269
+ return reason === "ack" || reason === "events";
2270
+ }
2271
+ var nothingToStop = () => {
2272
+ return;
2273
+ };
2274
+
2275
+ class DrainHandshake {
2276
+ inspector;
2277
+ logger;
2278
+ profile;
2279
+ silenceMs;
2280
+ settlements = [];
2281
+ rejection;
2282
+ requests = 0;
2283
+ dropped = 0;
2284
+ expectedStarts = 0;
2285
+ unprovenSince;
2286
+ constructor(inspector, logger, profile, silenceMs = DRAIN_ACK_SILENCE_TIMEOUT_MS) {
2287
+ this.inspector = inspector;
2288
+ this.logger = logger;
2289
+ this.profile = profile;
2290
+ this.silenceMs = silenceMs;
2291
+ }
2292
+ get proven() {
2293
+ return this.requests > 0 && this.dropped === 0 && this.settlements.length === this.requests && this.settlements.every((reason) => isProof(reason));
2294
+ }
2295
+ describe() {
2296
+ const served = this.describeServed();
2297
+ return this.dropped === 0 ? served : `${served}; ${this.dropped} dropped unserved`;
2298
+ }
2299
+ describeServed() {
2300
+ if (this.requests === 0) {
2301
+ return "never requested";
2302
+ }
2303
+ if (this.requests === 1) {
2304
+ return this.settlements.length === 1 ? `settled via ${this.settlements[0]}` : "requested, not settled";
2305
+ }
2306
+ const counts = new Map;
2307
+ for (const reason of this.settlements) {
2308
+ counts.set(reason, (counts.get(reason) ?? 0) + 1);
2309
+ }
2310
+ const unsettled = this.requests - this.settlements.length;
2311
+ if (unsettled > 0) {
2312
+ counts.set("not settled", unsettled);
2313
+ }
2314
+ const byReason = [...counts].map(([how, count]) => `${how} (${count})`);
2315
+ return `${this.requests} requests: ${byReason.join(", ")}`;
2316
+ }
2317
+ requestDropped(request) {
2318
+ this.dropped++;
2319
+ this.unprovenSince ??= "a drain request was dropped unserved";
2320
+ 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));
2321
+ }
2322
+ async handle(request) {
2323
+ const receivedAt = Date.now();
2324
+ this.profile?.at("drainRequest");
2325
+ this.requests++;
2326
+ const startedTests = request?.startedTests;
2327
+ this.expectedStarts = this.expectedStarts === undefined || startedTests === undefined ? undefined : this.expectedStarts + startedTests;
2328
+ const countsAtRequest = this.inspector.getEventCounts();
2329
+ const gapsAtRequest = this.inspector.getFoundIdGaps();
2330
+ 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));
2331
+ const reason = await this.prove();
2332
+ this.profile?.at("drainSettled");
2333
+ this.settlements.push(reason);
2334
+ if (!isProof(reason)) {
2335
+ this.unprovenSince ??= `drain-request ${this.requests} settled via ${reason}`;
2336
+ }
2337
+ this.inspector.startProgressWindow();
2338
+ const countsAtSettle = this.inspector.getEventCounts();
2339
+ const gapsAtSettle = this.inspector.getFoundIdGaps();
2340
+ 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` : "");
2341
+ }
2342
+ async prove() {
2343
+ const first = this.requests === 1;
2344
+ const provable = this.unprovenSince === undefined;
2345
+ if (!first) {
2346
+ const progress = this.inspector.getTestProgress();
2347
+ 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);
2348
+ if (provable && this.eventsProveDrain()) {
2349
+ return "events";
2350
+ }
2351
+ }
2352
+ const { promise: silence, cancel } = raceAgainstSilence(this.inspector, this.silenceMs, DRAIN_ACK_ABSOLUTE_CEILING_MS);
2353
+ const proof = first ? this.roundTrip() : this.waitForEvents(provable);
2354
+ try {
2355
+ return await Promise.race([proof.promise, silence]);
2356
+ } catch (error) {
2357
+ return this.giveUpReason(error);
2358
+ } finally {
2359
+ cancel();
2360
+ proof.stop();
2361
+ }
2362
+ }
2363
+ giveUpReason(error) {
2364
+ if (error instanceof DrainWaitTimeoutError) {
2365
+ this.logger.debug("Inspector drain wait gave up: %s", error.message);
2366
+ return error.reason;
2367
+ }
2368
+ if (error instanceof InspectorClosedError) {
2369
+ this.logger.debug("Inspector connection closed before the test events proved drain-request %d", this.requests);
2370
+ return "closed";
2371
+ }
2372
+ this.rejection = error instanceof Error ? error.message : String(error);
2373
+ this.logger.debug("Inspector drain round-trip rejected before any wait bound was hit: %s", this.rejection);
2374
+ return "send-rejected";
2375
+ }
2376
+ roundTrip() {
2377
+ return {
2378
+ promise: this.inspector.send("TestReporter.enable", {}, DRAIN_ACK_ABSOLUTE_CEILING_MS + 1000).then(() => "ack"),
2379
+ stop: nothingToStop
2380
+ };
2381
+ }
2382
+ waitForEvents(provable) {
2383
+ let stop = nothingToStop;
2384
+ const promise = new Promise((resolve, reject) => {
2385
+ const check = () => {
2386
+ if (provable && this.eventsProveDrain()) {
2387
+ resolve("events");
2388
+ } else if (this.inspector.hasClosed) {
2389
+ reject(new InspectorClosedError);
2390
+ }
2391
+ };
2392
+ stop = this.inspector.onProgress(check);
2393
+ check();
2394
+ });
2395
+ return { promise, stop: () => stop() };
2396
+ }
2397
+ eventsProveDrain() {
2398
+ const expected = this.expectedStarts;
2399
+ if (expected === undefined) {
2400
+ return false;
2401
+ }
2402
+ const progress = this.inspector.getTestProgress();
2403
+ return progress.testStarts >= expected && progress.testsRunning === 0 && progress.foundTests > 0 && progress.unendedTests === 0;
2404
+ }
2405
+ }
2406
+
1913
2407
  // src/inspector/types.ts
1914
2408
  var TEST_STATUSES = ["pass", "fail", "timeout", "skip", "todo", "skipped_because_label"];
1915
2409
  function isTestReporterFoundEvent(message) {
@@ -2050,6 +2544,10 @@ class InspectorClient {
2050
2544
  foundCount = 0;
2051
2545
  startCount = 0;
2052
2546
  endCount = 0;
2547
+ windowTests = 0;
2548
+ windowUnended = new Set;
2549
+ runningTests = new Set;
2550
+ progressListeners = new Set;
2053
2551
  closeCode = undefined;
2054
2552
  closeReason = undefined;
2055
2553
  closeWasClean = undefined;
@@ -2145,6 +2643,21 @@ class InspectorClient {
2145
2643
  this.ws.close();
2146
2644
  }
2147
2645
  this.ws = null;
2646
+ this.notifyProgress();
2647
+ }
2648
+ get hasClosed() {
2649
+ return this.wsClosed || this.isClosing;
2650
+ }
2651
+ onProgress(listener) {
2652
+ this.progressListeners.add(listener);
2653
+ return () => {
2654
+ this.progressListeners.delete(listener);
2655
+ };
2656
+ }
2657
+ notifyProgress() {
2658
+ for (const listener of this.progressListeners) {
2659
+ listener();
2660
+ }
2148
2661
  }
2149
2662
  expectClose() {
2150
2663
  this.closeExpected = true;
@@ -2192,6 +2705,18 @@ class InspectorClient {
2192
2705
  getEventCounts() {
2193
2706
  return { found: this.foundCount, start: this.startCount, end: this.endCount };
2194
2707
  }
2708
+ getTestProgress() {
2709
+ return {
2710
+ testStarts: this.executionOrder.length,
2711
+ testsRunning: this.runningTests.size,
2712
+ foundTests: this.windowTests,
2713
+ unendedTests: this.windowUnended.size
2714
+ };
2715
+ }
2716
+ startProgressWindow() {
2717
+ this.windowTests = 0;
2718
+ this.windowUnended.clear();
2719
+ }
2195
2720
  getCloseInfo() {
2196
2721
  return {
2197
2722
  code: this.closeCode,
@@ -2244,6 +2769,7 @@ class InspectorClient {
2244
2769
  } else if (isTestReporterEndEvent(message)) {
2245
2770
  this.handleTestEnd(message.params);
2246
2771
  }
2772
+ this.notifyProgress();
2247
2773
  } catch (error) {
2248
2774
  this.handleError(error instanceof Error ? error : new Error(String(error)));
2249
2775
  }
@@ -2262,6 +2788,10 @@ class InspectorClient {
2262
2788
  line: params.line
2263
2789
  };
2264
2790
  this.testHierarchy.set(params.id, testInfo);
2791
+ if (testInfo.type === "test") {
2792
+ this.windowTests++;
2793
+ this.windowUnended.add(testInfo);
2794
+ }
2265
2795
  if (this.handlers.onTestFound) {
2266
2796
  this.handlers.onTestFound(testInfo);
2267
2797
  }
@@ -2275,6 +2805,7 @@ class InspectorClient {
2275
2805
  }
2276
2806
  if (testInfo.type === "test") {
2277
2807
  this.executionOrder.push(params.id);
2808
+ this.runningTests.add(params.id);
2278
2809
  }
2279
2810
  if (this.handlers.onTestStart) {
2280
2811
  this.handlers.onTestStart(testInfo);
@@ -2287,6 +2818,8 @@ class InspectorClient {
2287
2818
  this.handleError(new Error(`Test end event for unknown test ID: ${params.id}`));
2288
2819
  return;
2289
2820
  }
2821
+ this.runningTests.delete(params.id);
2822
+ this.windowUnended.delete(testInfo);
2290
2823
  testInfo.status = params.status;
2291
2824
  testInfo.elapsed = params.elapsed;
2292
2825
  if (params.error) {
@@ -2329,6 +2862,7 @@ class InspectorClient {
2329
2862
  for (const finish of waiters) {
2330
2863
  finish();
2331
2864
  }
2865
+ this.notifyProgress();
2332
2866
  if (this.isClosing || this.closeExpected) {
2333
2867
  return;
2334
2868
  }
@@ -2359,1005 +2893,1007 @@ class InspectorClient {
2359
2893
  }
2360
2894
  }
2361
2895
  // 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";
2896
+ import path8 from "node:path";
2366
2897
 
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
- }
2898
+ // src/utils/strip-ansi.ts
2899
+ function stripAnsi(text) {
2900
+ return text.replaceAll(/\u001B\[[0-9;?]*[\u0020-\u002F]*[\u0040-\u007E]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g, "");
2375
2901
  }
2376
2902
 
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;
2903
+ // src/parsers/console-parser.ts
2904
+ var fileHeaderRe = new RegExp(String.raw`^(?:::group::)?([^:]+${TEST_FILE_SUFFIX_PATTERN}):$`, "i");
2905
+ var workflowCommandRe = /^::(?:group|endgroup|error|warning|notice|debug|add-mask|add-matcher|remove-matcher)(?:::|\s|$)/;
2906
+ function parseFilePath(line) {
2907
+ const fileMatch = fileHeaderRe.exec(line);
2908
+ return fileMatch ? fileMatch[1] : null;
2386
2909
  }
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;
2910
+ function headerFilter(lines, testFiles) {
2911
+ if (testFiles === undefined) {
2912
+ return () => true;
2393
2913
  }
2914
+ const roots = new Set(testFiles.map((file) => path8.resolve(file)));
2915
+ const isRunFile = (file) => {
2916
+ let candidate = path8.resolve(file);
2917
+ while (!roots.has(candidate)) {
2918
+ const parent = path8.dirname(candidate);
2919
+ if (parent === candidate) {
2920
+ return false;
2921
+ }
2922
+ candidate = parent;
2923
+ }
2924
+ return true;
2925
+ };
2926
+ const namesRunFile = lines.some((line) => {
2927
+ const file = parseFilePath(line);
2928
+ return file !== null && isRunFile(file);
2929
+ });
2930
+ return namesRunFile ? isRunFile : () => true;
2394
2931
  }
2395
- function parsePsRssOutput(output) {
2396
- const trimmed = output.trim();
2397
- if (trimmed === "") {
2398
- return null;
2399
- }
2400
- const kb = Number(trimmed);
2401
- return Number.isFinite(kb) ? kb * 1024 : null;
2932
+ function isWorkflowCommandLine(line) {
2933
+ return workflowCommandRe.test(line);
2402
2934
  }
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;
2411
- }
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
- });
2422
- });
2423
- }
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;
2438
- }
2439
- var projectDirectory = recordProjectDirectory();
2440
- function resolveAgainstProject(file) {
2441
- return path7.resolve(projectDirectory, file);
2935
+ var MAX_FAILURE_MESSAGE_LENGTH = 4000;
2936
+ function buildTestName(testName, currentFile) {
2937
+ return currentFile ? `${currentFile} > ${testName}` : testName;
2442
2938
  }
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;
2939
+ function parseTestLine(line, currentFile) {
2940
+ const passMatch = /^✓ +(\S.*?) \[([0-9.]+)ms\]$/.exec(line);
2941
+ if (passMatch) {
2942
+ return {
2943
+ test: {
2944
+ name: buildTestName(passMatch[1].trim(), currentFile),
2945
+ file: currentFile,
2946
+ status: "passed",
2947
+ duration: Number.parseFloat(passMatch[2])
2948
+ }
2949
+ };
2453
2950
  }
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 };
2951
+ const failMatch = /^✗ +(\S.*?)(?: \[([0-9.]+)ms\])?$/.exec(line);
2952
+ if (failMatch) {
2953
+ return {
2954
+ test: {
2955
+ name: buildTestName(failMatch[1].trim(), currentFile),
2956
+ file: currentFile,
2957
+ status: "failed",
2958
+ duration: failMatch[2] ? Number.parseFloat(failMatch[2]) : undefined
2959
+ }
2960
+ };
2462
2961
  }
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);
2962
+ const bailFailMatch = /^\(fail\) +(\S.*?)(?: \[([0-9.]+)ms\])?$/.exec(line);
2963
+ if (bailFailMatch) {
2964
+ return {
2965
+ test: {
2966
+ name: buildTestName(bailFailMatch[1].trim(), currentFile),
2967
+ file: currentFile,
2968
+ status: "failed",
2969
+ duration: bailFailMatch[2] ? Number.parseFloat(bailFailMatch[2]) : undefined
2970
+ }
2971
+ };
2474
2972
  }
2475
- const cached = lastBuild;
2476
- if (cached?.cwd === cwd && cached.budget === budget && sameEntries(cached.files, files)) {
2477
- return { ...cached.result, args: [...cached.result.args] };
2973
+ const skipMatch = /^⏭ +(\S.*)$/.exec(line);
2974
+ if (skipMatch) {
2975
+ return {
2976
+ test: {
2977
+ name: buildTestName(skipMatch[1].trim(), currentFile),
2978
+ file: currentFile,
2979
+ status: "skipped"
2980
+ }
2981
+ };
2478
2982
  }
2479
- const result = computeTestFileArgs(files, cwd, budget);
2480
- lastBuild = { files: [...files], cwd, budget, result: { ...result, args: [...result.args] } };
2481
- return result;
2983
+ return {};
2482
2984
  }
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, "");
2985
+ var NON_FAILING_RESULT_LINE = /^(?:\((?:pass|skip|todo)\)|[✓»✎⏭]) +\S/;
2986
+ var CODE_FRAME_LINE = /^\s*\d+ \|(?: |$)/;
2987
+ var ERROR_HEADING_LINE = /^(?:error|\w*Error)(?: \[[^\]]*\])?: /;
2988
+ var AFTER_FAIL_NOTE_LINE = /^\s+\^ \S/;
2989
+ function capFailureMessage(message) {
2990
+ return message.length > MAX_FAILURE_MESSAGE_LENGTH ? `${message.slice(0, MAX_FAILURE_MESSAGE_LENGTH)}
2991
+ … (${message.length - MAX_FAILURE_MESSAGE_LENGTH} more characters)` : message;
2493
2992
  }
2494
- function readSpawnDepth(raw) {
2495
- const parsed = Number(raw);
2496
- return Number.isInteger(parsed) ? Math.max(parsed, 0) : 0;
2993
+ function readFailureBlock(block) {
2994
+ const lines = block.filter((line) => !isWorkflowCommandLine(line));
2995
+ const frameStart = lines.findIndex((line) => CODE_FRAME_LINE.test(line));
2996
+ const start = frameStart === -1 ? lines.findIndex((line) => ERROR_HEADING_LINE.test(line)) : frameStart;
2997
+ const text = lines.slice(Math.max(start, 0)).join(`
2998
+ `).trim();
2999
+ return { text: text === "" ? undefined : text, reported: start !== -1 };
2497
3000
  }
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);
3001
+ function failureMessageFrom(block, notes) {
3002
+ const report = block.text !== undefined && (block.reported || notes.length === 0) ? capFailureMessage(block.text) : undefined;
3003
+ const parts = report === undefined ? notes : [report, ...notes];
3004
+ return parts.length === 0 ? undefined : parts.join(`
3005
+ `);
3006
+ }
3007
+ function setFailureMessage(test, block, notes) {
3008
+ const failureMessage = failureMessageFrom(block, notes);
3009
+ if (failureMessage !== undefined) {
3010
+ test.failureMessage = failureMessage;
2509
3011
  }
2510
- return sanitized;
2511
3012
  }
2512
- var liveChildren = new Set;
2513
- function killAllLiveChildren() {
2514
- for (const child of liveChildren) {
2515
- killProcessTree(child, "SIGKILL");
3013
+ function recordTest(reader, test, index) {
3014
+ if (test.status === "failed") {
3015
+ const block = readFailureBlock(reader.lines.slice(reader.blockStart, index));
3016
+ setFailureMessage(test, block, []);
3017
+ reader.lastFailed = { test, block, notes: [] };
2516
3018
  }
2517
- liveChildren.clear();
3019
+ reader.tests.push(test);
3020
+ reader.counters[test.status]++;
3021
+ reader.blockStart = index + 1;
2518
3022
  }
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;
3023
+ function readLine(reader, index) {
3024
+ const line = reader.lines[index];
3025
+ const filePath = parseFilePath(line);
3026
+ if (filePath && reader.isHeaderFile(filePath)) {
3027
+ reader.currentFile = filePath;
3028
+ reader.blockStart = index + 1;
3029
+ reader.lastFailed = undefined;
3030
+ return;
2528
3031
  }
2529
- for (const s of CLEANUP_SIGNALS) {
2530
- process.on(s, onCleanupSignal);
3032
+ if (isWorkflowCommandLine(line)) {
3033
+ return;
2531
3034
  }
2532
- return true;
2533
- }
2534
- function removeSignalCleanup() {
2535
- for (const s of CLEANUP_SIGNALS) {
2536
- process.off(s, onCleanupSignal);
3035
+ if (reader.lastFailed && AFTER_FAIL_NOTE_LINE.test(line)) {
3036
+ const { test, block, notes } = reader.lastFailed;
3037
+ notes.push(line.trim());
3038
+ setFailureMessage(test, block, notes);
3039
+ reader.blockStart = index + 1;
3040
+ return;
2537
3041
  }
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;
3042
+ reader.lastFailed = undefined;
3043
+ const { test } = parseTestLine(line, reader.currentFile);
3044
+ if (test) {
3045
+ recordTest(reader, test, index);
3046
+ } else if (NON_FAILING_RESULT_LINE.test(line)) {
3047
+ reader.blockStart = index + 1;
2544
3048
  }
2545
- return true;
2546
3049
  }
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");
3050
+ var RAN_LINE = /^\s*Ran\s+(\d+)\s+tests?\b/;
3051
+ var PASS_LINE = /^\s*\d+\s+pass\s*$/;
3052
+ var COUNT_LINE = /^\s*(\d+)\s+(pass|skip|todo|fail|errors?)\s*$/;
3053
+ var BAIL_LINE = /^\s*Bailed out after (\d+) failures?\s*$/;
3054
+ function lastLineMatching(lines, from, pattern, stopAtBlank) {
3055
+ for (let index = from;index >= 0; index--) {
3056
+ const match = pattern.exec(lines[index]);
3057
+ if (match) {
3058
+ return { index, match };
2555
3059
  }
2556
- }, gracePeriodMs);
2557
- return () => {
2558
- clearTimeout(escalationHandle);
2559
- if (!hasEscalated && signalledGroup && pid !== undefined) {
2560
- hasEscalated = true;
2561
- killProcessGroup(pid, "SIGKILL");
3060
+ if (stopAtBlank && !lines[index].trim()) {
3061
+ return;
2562
3062
  }
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
3063
  }
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
- }
2588
- return spawnBunTests(options, spawnDepth);
3064
+ return;
2589
3065
  }
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)
3066
+ function readBunSummary(output) {
3067
+ const lines = stripAnsi(output).split(`
3068
+ `);
3069
+ const lastIndex = lines.length - 1;
3070
+ const ran = lastLineMatching(lines, lastIndex, RAN_LINE, false);
3071
+ const pass = ran ? lastLineMatching(lines, ran.index - 1, PASS_LINE, true) : lastLineMatching(lines, lastIndex, PASS_LINE, false);
3072
+ const summary = {
3073
+ pass: 0,
3074
+ skip: 0,
3075
+ todo: 0,
3076
+ fail: 0,
3077
+ error: 0,
3078
+ ran: ran && Number.parseInt(ran.match[1], 10),
3079
+ bailed: undefined,
3080
+ printed: ran !== undefined || pass !== undefined
2606
3081
  };
2607
- for (const [name, value] of Object.entries(preloadVars)) {
2608
- if (value === undefined) {
2609
- delete env[name];
2610
- } else {
2611
- env[name] = value;
3082
+ if (pass) {
3083
+ for (const line of lines.slice(pass.index, ran?.index ?? lines.length)) {
3084
+ const match = COUNT_LINE.exec(line);
3085
+ if (match) {
3086
+ summary[match[2] === "errors" ? "error" : match[2]] = Number.parseInt(match[1], 10);
3087
+ }
2612
3088
  }
2613
3089
  }
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];
3090
+ for (const line of lines.slice(ran?.index ?? 0)) {
3091
+ const match = BAIL_LINE.exec(line);
3092
+ if (match) {
3093
+ summary.bailed = Number.parseInt(match[1], 10);
3094
+ }
2623
3095
  }
2624
- return env;
3096
+ return summary;
2625
3097
  }
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");
2632
- }
2633
- if (options.bunfigPath) {
2634
- args.push(`--config=${options.bunfigPath}`);
2635
- }
2636
- if (options.preloadScript) {
2637
- args.push("--preload", options.preloadScript);
3098
+ function parseSummaryLines(output) {
3099
+ const bun = readBunSummary(output);
3100
+ const counts = { passed: bun.pass, failed: bun.fail, skipped: bun.skip };
3101
+ if (bun.bailed !== undefined) {
3102
+ counts.failed = Math.max(counts.failed, bun.bailed);
2638
3103
  }
2639
- if (options.testNamePattern) {
2640
- args.push("--test-name-pattern", options.testNamePattern);
3104
+ const genuinePassed = counts.passed;
3105
+ const genuineFailed = counts.failed;
3106
+ if (bun.ran !== undefined) {
3107
+ const totalParsed = counts.passed + counts.failed + counts.skipped;
3108
+ if (totalParsed !== bun.ran && counts.passed === 0 && counts.failed === 0) {
3109
+ counts.passed = bun.ran;
3110
+ }
2641
3111
  }
2642
- if (options.bail) {
2643
- args.push("--bail");
3112
+ return { ...counts, todo: bun.todo, errors: bun.error, printed: bun.printed, genuinePassed, genuineFailed };
3113
+ }
3114
+ function parseBunTestOutput(stdout, stderr, testFiles) {
3115
+ const tests = [];
3116
+ const counters = { passed: 0, failed: 0, skipped: 0 };
3117
+ const output = `${stdout}
3118
+ ${stderr}`;
3119
+ const lines = output.split(`
3120
+ `).map((line) => stripAnsi(line));
3121
+ const reader = {
3122
+ lines,
3123
+ isHeaderFile: headerFilter(lines, testFiles),
3124
+ tests,
3125
+ counters,
3126
+ currentFile: undefined,
3127
+ blockStart: 0,
3128
+ lastFailed: undefined
3129
+ };
3130
+ for (const index of lines.keys()) {
3131
+ readLine(reader, index);
2644
3132
  }
2645
- if (options.sequentialMode) {
2646
- args.push("--max-concurrency=1");
3133
+ const summaryCounts = parseSummaryLines(output);
3134
+ counters.passed = Math.max(counters.passed, summaryCounts.passed);
3135
+ counters.failed = Math.max(counters.failed, summaryCounts.failed);
3136
+ counters.skipped = Math.max(counters.skipped, summaryCounts.skipped);
3137
+ return {
3138
+ tests,
3139
+ totalTests: counters.passed + counters.failed + counters.skipped,
3140
+ passed: counters.passed,
3141
+ failed: counters.failed,
3142
+ skipped: counters.skipped,
3143
+ summaryPassed: summaryCounts.genuinePassed,
3144
+ summaryFailed: summaryCounts.genuineFailed,
3145
+ summarySkipped: summaryCounts.skipped,
3146
+ summaryTodo: summaryCounts.todo,
3147
+ summaryErrors: summaryCounts.errors,
3148
+ summaryPrinted: summaryCounts.printed
3149
+ };
3150
+ }
3151
+
3152
+ // src/parsers/unhandled-errors.ts
3153
+ var MAX_BLOCKS_SHOWN = 20;
3154
+ var MAX_DIAGNOSTIC_CHARS = 16000;
3155
+ var MAX_SNIPPET_LINE_CHARS = 300;
3156
+ var MAX_NAMED = 3;
3157
+ var MAX_NAME_CHARS = 200;
3158
+ var BLOCK_MARKER = "# Unhandled error between tests";
3159
+ var BLOCK_RULE = "-".repeat(31);
3160
+ var LATE_CALL_RE = /^error: Cannot call ([\w$.]+)\(\) after the test run has completed\.?$/;
3161
+ var FILE_HEADER_RE = new RegExp(String.raw`^(?:::group::)?((?:[a-z]:)?[^:]+${TEST_FILE_SUFFIX_PATTERN}):$`, "i");
3162
+ var FRAME_LOCATION_RE = /^(.+):\d+:\d+$/;
3163
+ var SNIPPET_LINE_RE = /^\s*\d+ \|/;
3164
+ var SNIPPET_CARET_RE = /^\s*\^+$/;
3165
+ var isDrivePath = (path) => /^[a-z]:[\\/]/i.test(path);
3166
+ function pathKey(path) {
3167
+ return isDrivePath(path) ? `${path.charAt(0).toLowerCase()}${path.slice(1).replaceAll("\\", "/")}` : path;
3168
+ }
3169
+ function percentDecode(text) {
3170
+ try {
3171
+ return decodeURIComponent(text);
3172
+ } catch {
3173
+ return text;
2647
3174
  }
2648
- if (options.smol) {
2649
- args.push("--smol");
3175
+ }
3176
+ function locationPath(location) {
3177
+ if (/^file:\/\//i.test(location)) {
3178
+ const path = percentDecode(location.slice("file://".length).replace(/^localhost(?=\/)/i, "").replace(/\?.*/s, ""));
3179
+ return /^\/[a-z]:[\\/]/i.test(path) ? path.slice(1) : path;
2650
3180
  }
2651
- if (options.bunArgs && options.bunArgs.length > 0) {
2652
- args.push(...stripBailArgs(options.bunArgs));
3181
+ return /^[a-z][\w+.-]+:/i.test(location) && !isDrivePath(location) ? undefined : location;
3182
+ }
3183
+ function frameFile(line) {
3184
+ const trimmed = line.trim();
3185
+ if (!trimmed.startsWith("at ")) {
3186
+ return;
2653
3187
  }
2654
- if (options.testFiles && options.testFiles.length > 0) {
2655
- args.push(...buildTestFileArgs(options.testFiles).args);
3188
+ let location = trimmed.slice(3).trim();
3189
+ const open = location.lastIndexOf(" (");
3190
+ if (open !== -1 && location.endsWith(")")) {
3191
+ location = location.slice(open + 2, -1);
2656
3192
  }
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
- });
3193
+ const file = FRAME_LOCATION_RE.exec(location)?.[1];
3194
+ return file === undefined ? undefined : locationPath(file);
2813
3195
  }
2814
-
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;
3196
+ function buildBlock(printed, headerFile) {
3197
+ const body = printed.slice(printed.findIndex((line) => line !== ""), printed.findLastIndex((line) => line !== "") + 1);
3198
+ const errorLine = body.find((line) => line.startsWith("error: "));
3199
+ return {
3200
+ headerFile,
3201
+ lines: body,
3202
+ frames: body.flatMap((line) => {
3203
+ const path = frameFile(line);
3204
+ return path === undefined ? [] : [{ path, line }];
3205
+ }),
3206
+ lateCall: errorLine === undefined ? undefined : LATE_CALL_RE.exec(errorLine)?.[1]
3207
+ };
2821
3208
  }
2822
- function headerFilter(lines, testFiles) {
2823
- if (testFiles === undefined) {
2824
- return () => true;
3209
+ function parseUnhandledErrorBlocks(stderr, secrets = []) {
3210
+ const lines = cleanDiagnosticText(stderr, secrets).split(/\r?\n/).map((line) => line.trimEnd());
3211
+ const starts = lines.flatMap((line, i) => line === BLOCK_MARKER && lines[i + 1] === BLOCK_RULE ? [i] : []);
3212
+ const blocks = [];
3213
+ let headerFile;
3214
+ let scanned = 0;
3215
+ for (const [n, start] of starts.entries()) {
3216
+ for (const line of lines.slice(scanned, start)) {
3217
+ headerFile = FILE_HEADER_RE.exec(line)?.[1] ?? headerFile;
3218
+ }
3219
+ const following = lines.slice(start + 2, starts[n + 1] ?? lines.length);
3220
+ const closingRule = following.indexOf(BLOCK_RULE);
3221
+ blocks.push(buildBlock(closingRule === -1 ? following : following.slice(0, closingRule), headerFile));
3222
+ scanned = closingRule === -1 ? start + 2 + following.length : start + 2 + closingRule + 1;
2825
3223
  }
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;
3224
+ return blocks;
3225
+ }
3226
+ var isSnippetLine = (line) => SNIPPET_LINE_RE.test(line) || SNIPPET_CARET_RE.test(line);
3227
+ function renderBlock(block, index, total) {
3228
+ const heading = ` Unhandled error block ${index + 1} of ${total}:`;
3229
+ if (block.lines.length === 0) {
3230
+ const empty = `${heading}
3231
+ (empty)`;
3232
+ return { full: empty, bare: empty };
3233
+ }
3234
+ const full = [];
3235
+ const bare = [];
3236
+ let omittedRun = 0;
3237
+ const endRun = () => {
3238
+ if (omittedRun > 0) {
3239
+ bare.push(` ... [${omittedRun} source line(s) omitted]`);
3240
+ omittedRun = 0;
2835
3241
  }
2836
- return true;
2837
3242
  };
2838
- const namesRunFile = lines.some((line) => {
2839
- const file = parseFilePath(line);
2840
- return file !== null && isRunFile(file);
2841
- });
2842
- return namesRunFile ? isRunFile : () => true;
3243
+ for (const line of block.lines) {
3244
+ if (isSnippetLine(line)) {
3245
+ omittedRun++;
3246
+ 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}`);
3247
+ } else {
3248
+ endRun();
3249
+ full.push(` ${line}`);
3250
+ bare.push(` ${line}`);
3251
+ }
3252
+ }
3253
+ endRun();
3254
+ return { full: [heading, ...full].join(`
3255
+ `), bare: [heading, ...bare].join(`
3256
+ `) };
2843
3257
  }
2844
- function isWorkflowCommandLine(line) {
2845
- return workflowCommandRe.test(line);
3258
+ function nameOf(text, secrets) {
3259
+ const redacted = redactSecrets(text, secrets);
3260
+ return redacted.length > MAX_NAME_CHARS ? `${redacted.slice(0, MAX_NAME_CHARS)}... [${redacted.length - MAX_NAME_CHARS} more character(s) omitted]` : redacted;
2846
3261
  }
2847
- var MAX_FAILURE_MESSAGE_LENGTH = 4000;
2848
- function buildTestName(testName, currentFile) {
2849
- return currentFile ? `${currentFile} > ${testName}` : testName;
3262
+ function nameList(names) {
3263
+ const shown = names.slice(0, MAX_NAMED).join(", ");
3264
+ return names.length > MAX_NAMED ? `${shown} and ${names.length - MAX_NAMED} more` : shown;
2850
3265
  }
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
- };
2862
- }
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
- }
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
- };
2884
- }
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
- };
2894
- }
2895
- return {};
3266
+ function matchesHeader(framePath, header) {
3267
+ const frame = pathKey(framePath);
3268
+ const wanted = pathKey(header).replace(/^\.\//, "");
3269
+ return frame === wanted || frame.endsWith(`/${wanted}`);
2896
3270
  }
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;
3271
+ function testFileFrame(block) {
3272
+ const { headerFile, frames } = block;
3273
+ const inEffect = headerFile === undefined ? undefined : frames.find((frame) => matchesHeader(frame.path, headerFile));
3274
+ return inEffect ?? frames.find((frame) => TEST_FILE_SUFFIX_RE.test(frame.path));
2904
3275
  }
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 };
3276
+ function lateCalls(blocks, secrets) {
3277
+ const seen = new Set;
3278
+ return blocks.flatMap((block, index) => {
3279
+ if (block.lateCall === undefined) {
3280
+ return [];
3281
+ }
3282
+ const frame = testFileFrame(block);
3283
+ const header = block.headerFile === undefined ? undefined : nameOf(block.headerFile, secrets);
3284
+ const call = nameOf(block.lateCall, secrets);
3285
+ const key = `${call}\x00${frame?.path ?? ""}\x00${frame === undefined ? header ?? "" : ""}`;
3286
+ if (seen.has(key)) {
3287
+ return [];
3288
+ }
3289
+ seen.add(key);
3290
+ return [{ call, block: index, header, frame: frame === undefined ? undefined : { block: index, name: nameOf(frame.path, secrets), line: frame.line } }];
3291
+ });
2912
3292
  }
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
- `);
3293
+ function eagerClaims(blocks, eagerModules, secrets) {
3294
+ const eagerByKey = new Map(eagerModules.map((module) => [pathKey(module), module]));
3295
+ const seen = new Set;
3296
+ return blocks.flatMap((block, index) => block.lateCall === undefined ? block.frames.flatMap((frame) => {
3297
+ const module = eagerByKey.get(pathKey(frame.path));
3298
+ if (module === undefined || seen.has(module)) {
3299
+ return [];
3300
+ }
3301
+ seen.add(module);
3302
+ return [{ block: index, name: nameOf(module, secrets), line: frame.line }];
3303
+ }) : []);
2918
3304
  }
2919
- function setFailureMessage(test, block, notes) {
2920
- const failureMessage = failureMessageFrom(block, notes);
2921
- if (failureMessage !== undefined) {
2922
- test.failureMessage = failureMessage;
3305
+ function describeLateCall(late) {
3306
+ const error = `\`Cannot call ${late.call}() after the test run has completed\``;
3307
+ if (late.frame !== undefined) {
3308
+ return `${error} for test file ${late.frame.name} (block ${late.block + 1})`;
2923
3309
  }
2924
- }
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: [] };
3310
+ if (late.header !== undefined) {
3311
+ return `${error} printed under the header of ${late.header} (block ${late.block + 1})`;
2930
3312
  }
2931
- reader.tests.push(test);
2932
- reader.counters[test.status]++;
2933
- reader.blockStart = index + 1;
3313
+ return `${error} (block ${late.block + 1})`;
2934
3314
  }
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;
3315
+ var keyOf = (claim) => `${claim.block}\x00${claim.line}`;
3316
+ function lateCallSentences(lates, blocks) {
3317
+ if (lates.length === 0) {
3318
+ return [];
2943
3319
  }
2944
- if (isWorkflowCommandLine(line)) {
2945
- return;
3320
+ const named = lates.slice(0, MAX_NAMED);
3321
+ const fileKnown = named.every((late) => late.frame !== undefined);
3322
+ 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.";
3323
+ const precededByOtherBlock = blocks.findIndex((block) => block.lateCall !== undefined) > 0;
3324
+ return [
3325
+ [
3326
+ `bun reported ${nameList(lates.map((late) => describeLateCall(late)))}.`,
3327
+ consequence,
3328
+ ...precededByOtherBlock ? ["An error raised outside any test, such as those in the blocks shown, is what makes bun end a run early."] : []
3329
+ ].join(" ")
3330
+ ];
3331
+ }
3332
+ function eagerSentences(modules) {
3333
+ if (modules.length === 0) {
3334
+ return [];
2946
3335
  }
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;
3336
+ const named = nameList(modules.map((claim) => `${claim.name} (block ${claim.block + 1})`));
3337
+ return [
3338
+ `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."
3339
+ ];
3340
+ }
3341
+ var CUT_NOTE_RESERVE = 200;
3342
+ var joinedLength = (parts) => parts.reduce((sum, part) => sum + part.length, 0) + Math.max(0, parts.length - 1);
3343
+ function describeUnhandledErrors(stderr, eagerModules, secrets = []) {
3344
+ const blocks = parseUnhandledErrorBlocks(stderr, secrets);
3345
+ if (blocks.length === 0) {
2952
3346
  return;
2953
3347
  }
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;
2960
- }
2961
- }
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 };
3348
+ const lates = lateCalls(blocks, secrets);
3349
+ const modules = eagerClaims(blocks, eagerModules, secrets);
3350
+ const dropped = new Set;
3351
+ for (let attempt = 0;attempt < 8; attempt++) {
3352
+ const claims = {
3353
+ lates: lates.map((late) => late.frame !== undefined && dropped.has(keyOf(late.frame)) ? { ...late, frame: undefined } : late),
3354
+ modules: modules.filter((claim) => !dropped.has(keyOf(claim)))
3355
+ };
3356
+ const result = layOut(blocks, claims);
3357
+ const lost = [...claims.lates.slice(0, MAX_NAMED).flatMap((late) => late.frame ?? []), ...claims.modules.slice(0, MAX_NAMED)].filter((claim) => !result.shown(claim));
3358
+ if (lost.length === 0) {
3359
+ return result.text;
2971
3360
  }
2972
- if (stopAtBlank && !lines[index].trim()) {
2973
- return;
3361
+ for (const claim of lost) {
3362
+ dropped.add(keyOf(claim));
2974
3363
  }
2975
3364
  }
2976
- return;
3365
+ return layOut(blocks, { lates: lates.map((late) => ({ ...late, frame: undefined })), modules: [] }).text;
2977
3366
  }
2978
- function readBunSummary(output) {
2979
- const lines = stripAnsi(output).split(`
3367
+ function selectBlocks(blockCount, required) {
3368
+ const shown = new Set(required);
3369
+ for (let i = 0;i < blockCount && shown.size < MAX_BLOCKS_SHOWN; i++) {
3370
+ shown.add(i);
3371
+ }
3372
+ return [...shown].toSorted((a, b) => a - b);
3373
+ }
3374
+ function cutBlock(text, share) {
3375
+ const [heading, ...body] = text.split(`
2980
3376
  `);
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);
3377
+ const kept = [heading];
3378
+ let used = heading.length;
3379
+ for (const line of body) {
3380
+ if (used + 1 + line.length > share) {
3381
+ if (kept.length === 1) {
3382
+ const head = Math.max(0, share - used - 1);
3383
+ kept.push(`${line.slice(0, head)}... [${line.length - head} more character(s) of this line omitted]`);
2999
3384
  }
3385
+ break;
3000
3386
  }
3387
+ used += 1 + line.length;
3388
+ kept.push(line);
3001
3389
  }
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;
3390
+ const left = body.length - (kept.length - 1);
3391
+ return left > 0 ? [...kept, ` ... [${left} more line(s) of this block omitted]`].join(`
3392
+ `) : kept.join(`
3393
+ `);
3009
3394
  }
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);
3015
- }
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;
3395
+ function layOut(blocks, claims) {
3396
+ const named = [...claims.lates.slice(0, MAX_NAMED).map((late) => late.block), ...claims.modules.slice(0, MAX_NAMED).map((claim) => claim.block)];
3397
+ const required = new Set([0, ...named]);
3398
+ const intro = `bun's stderr holds ${blocks.length} "Unhandled error between tests" block(s), errors raised outside any individual test:`;
3399
+ let selected = selectBlocks(blocks.length, required);
3400
+ const texts = new Map(selected.map((index) => [index, renderBlock(blocks[index], index, blocks.length)]));
3401
+ const noSnippets = new Set;
3402
+ const shownText = (index) => noSnippets.has(index) ? texts.get(index).bare : texts.get(index).full;
3403
+ const summary = [
3404
+ ...lateCallSentences(claims.lates, blocks),
3405
+ ...eagerSentences(claims.modules)
3406
+ ];
3407
+ const parts = () => {
3408
+ const omitted = blocks.length - selected.length;
3409
+ return [
3410
+ intro,
3411
+ ...selected.map((index) => shownText(index)),
3412
+ ...omitted > 0 ? [` ... [${omitted} more block(s) omitted]`] : [],
3413
+ ...summary
3414
+ ];
3415
+ };
3416
+ const fits = () => joinedLength(parts()) <= MAX_DIAGNOSTIC_CHARS;
3417
+ for (const index of selected.toReversed()) {
3418
+ if (fits()) {
3419
+ break;
3022
3420
  }
3421
+ noSnippets.add(index);
3023
3422
  }
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);
3423
+ for (const dropped of selected.filter((index) => !required.has(index)).toReversed()) {
3424
+ if (fits()) {
3425
+ break;
3426
+ }
3427
+ selected = selected.filter((index) => index !== dropped);
3044
3428
  }
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);
3049
- 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
3429
+ if (!fits()) {
3430
+ const outside = parts().filter((_, position) => position === 0 || position > selected.length);
3431
+ const share = Math.max(0, Math.floor((MAX_DIAGNOSTIC_CHARS - joinedLength(outside) - selected.length) / selected.length) - CUT_NOTE_RESERVE);
3432
+ for (const index of selected) {
3433
+ const text = texts.get(index).bare;
3434
+ texts.set(index, { full: text, bare: cutBlock(text, share) });
3435
+ }
3436
+ }
3437
+ const shownLines = new Map(selected.map((index) => [index, new Set(shownText(index).split(`
3438
+ `))]));
3439
+ return {
3440
+ text: parts().join(`
3441
+ `),
3442
+ shown: (claim) => shownLines.get(claim.block).has(` ${claim.line}`)
3061
3443
  };
3062
3444
  }
3063
3445
 
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) {
3446
+ // src/process-runner.ts
3447
+ import { spawn as spawn3 } from "node:child_process";
3448
+
3449
+ // src/utils/process-group.ts
3450
+ function killProcessGroup(pid, signal) {
3082
3451
  try {
3083
- return decodeURIComponent(text);
3452
+ process.kill(-pid, signal);
3453
+ return true;
3084
3454
  } catch {
3085
- return text;
3086
- }
3087
- }
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;
3455
+ return false;
3092
3456
  }
3093
- return /^[a-z][\w+.-]+:/i.test(location) && !isDrivePath(location) ? undefined : location;
3094
3457
  }
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);
3104
- }
3105
- const file = FRAME_LOCATION_RE.exec(location)?.[1];
3106
- return file === undefined ? undefined : locationPath(file);
3458
+
3459
+ // src/utils/process-rss.ts
3460
+ import { spawn as spawn2 } from "node:child_process";
3461
+ import { readFile as readFile4 } from "node:fs/promises";
3462
+ async function getProcessRssBytes(pid) {
3463
+ return process.platform === "linux" ? getLinuxRss(pid) : getPsRss(pid);
3107
3464
  }
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
- };
3465
+ function parseVmRss(statusContent) {
3466
+ const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(statusContent);
3467
+ return match ? Number(match[1]) * 1024 : null;
3120
3468
  }
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;
3130
- }
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;
3469
+ async function getLinuxRss(pid) {
3470
+ try {
3471
+ const status = await readFile4(`/proc/${pid}/status`, "utf8");
3472
+ return parseVmRss(status);
3473
+ } catch {
3474
+ return null;
3135
3475
  }
3136
- return blocks;
3137
3476
  }
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 };
3477
+ function parsePsRssOutput(output) {
3478
+ const trimmed = output.trim();
3479
+ if (trimmed === "") {
3480
+ return null;
3145
3481
  }
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}`);
3482
+ const kb = Number(trimmed);
3483
+ return Number.isFinite(kb) ? kb * 1024 : null;
3484
+ }
3485
+ async function getPsRss(pid) {
3486
+ return new Promise((resolve) => {
3487
+ let child;
3488
+ try {
3489
+ child = spawn2("ps", ["-o", "rss=", "-p", String(pid)], { stdio: ["ignore", "pipe", "ignore"] });
3490
+ } catch {
3491
+ resolve(null);
3492
+ return;
3163
3493
  }
3494
+ let output = "";
3495
+ child.stdout.on("data", (data) => {
3496
+ output += data.toString();
3497
+ });
3498
+ child.on("close", (code) => {
3499
+ resolve(code === 0 ? parsePsRssOutput(output) : null);
3500
+ });
3501
+ child.on("error", () => {
3502
+ resolve(null);
3503
+ });
3504
+ });
3505
+ }
3506
+
3507
+ // src/utils/project-dir.ts
3508
+ import path9 from "node:path";
3509
+ var PROJECT_DIR_ENV = "STRYKER_BUN_RUNNER_PROJECT_DIR";
3510
+ var STRYKER_WORKER_ENV = "STRYKER_MUTATOR_WORKER";
3511
+ function recordProjectDirectory() {
3512
+ const inherited = process.env[PROJECT_DIR_ENV];
3513
+ const isWorker = process.env[STRYKER_WORKER_ENV] !== undefined;
3514
+ if (isWorker && inherited !== undefined && path9.isAbsolute(inherited)) {
3515
+ return inherited;
3164
3516
  }
3165
- endRun();
3166
- return { full: [heading, ...full].join(`
3167
- `), bare: [heading, ...bare].join(`
3168
- `) };
3517
+ const here = process.cwd();
3518
+ process.env[PROJECT_DIR_ENV] = here;
3519
+ return here;
3169
3520
  }
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;
3521
+ var projectDirectory = recordProjectDirectory();
3522
+ function resolveAgainstProject(file) {
3523
+ return path9.resolve(projectDirectory, file);
3173
3524
  }
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;
3525
+
3526
+ // src/utils/test-file-args.ts
3527
+ import path10 from "node:path";
3528
+ var MAX_TEST_FILE_ARGS_BYTES = 131072;
3529
+ var ENTRY_OVERHEAD_BYTES = 1 + 8;
3530
+ var bytesOf = (args) => args.reduce((sum, arg) => sum + Buffer.byteLength(arg) + ENTRY_OVERHEAD_BYTES, 0);
3531
+ function shortestSpelling(absolute, cwd) {
3532
+ const relative = path10.relative(cwd, absolute);
3533
+ if (relative === "" || relative === "..") {
3534
+ return absolute;
3535
+ }
3536
+ const spelled = relative.startsWith(`..${path10.sep}`) ? relative : `.${path10.sep}${relative}`;
3537
+ return spelled.length < absolute.length ? spelled : absolute;
3177
3538
  }
3178
- function matchesHeader(framePath, header) {
3179
- const frame = pathKey(framePath);
3180
- const wanted = pathKey(header).replace(/^\.\//, "");
3181
- return frame === wanted || frame.endsWith(`/${wanted}`);
3539
+ function computeTestFileArgs(files, cwd, budget) {
3540
+ const absolute = files.map((file) => path10.resolve(cwd, file));
3541
+ const absoluteBytes = bytesOf(absolute);
3542
+ if (absoluteBytes <= budget) {
3543
+ return { args: absolute, form: "absolute", bytes: absoluteBytes, fits: true };
3544
+ }
3545
+ const relative = absolute.map((file) => shortestSpelling(file, cwd));
3546
+ const relativeBytes = bytesOf(relative);
3547
+ return { args: relative, form: "relative", bytes: relativeBytes, fits: relativeBytes <= budget };
3182
3548
  }
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));
3549
+ function sameEntries(a, b) {
3550
+ return a.length === b.length && a.every((entry, index) => entry === b[index]);
3187
3551
  }
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 [];
3200
- }
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
- });
3552
+ var lastBuild;
3553
+ function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
3554
+ if (!path10.isAbsolute(cwd)) {
3555
+ return computeTestFileArgs(files, cwd, budget);
3556
+ }
3557
+ const cached = lastBuild;
3558
+ if (cached?.cwd === cwd && cached.budget === budget && sameEntries(cached.files, files)) {
3559
+ return { ...cached.result, args: [...cached.result.args] };
3560
+ }
3561
+ const result = computeTestFileArgs(files, cwd, budget);
3562
+ lastBuild = { files: [...files], cwd, budget, result: { ...result, args: [...result.args] } };
3563
+ return result;
3204
3564
  }
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 [];
3565
+
3566
+ // src/process-runner.ts
3567
+ var KILL_GRACE_PERIOD_MS = 500;
3568
+ var STDIO_CLOSE_GRACE_MS = 4 * KILL_GRACE_PERIOD_MS;
3569
+ var LIFELINE_FD = 3;
3570
+ var SPAWN_DEPTH_ENV = "__STRYKER_BUN_RUNNER_DEPTH__";
3571
+ var DEFAULT_MAX_SPAWN_DEPTH = 1;
3572
+ var PROFILE_ENV = "STRYKER_BUN_PROFILE";
3573
+ function readSpawnDepth(raw) {
3574
+ const parsed = Number(raw);
3575
+ return Number.isInteger(parsed) ? Math.max(parsed, 0) : 0;
3576
+ }
3577
+ function stripBailArgs(bunArgs) {
3578
+ const sanitized = [];
3579
+ for (let i = 0;i < bunArgs.length; i++) {
3580
+ const arg = bunArgs[i];
3581
+ if (arg === "--bail" || arg.startsWith("--bail=")) {
3582
+ if (arg === "--bail" && /^\d+$/.test(bunArgs[i + 1])) {
3583
+ i += 1;
3584
+ }
3585
+ continue;
3212
3586
  }
3213
- seen.add(module);
3214
- return [{ block: index, name: nameOf(module, secrets), line: frame.line }];
3215
- }) : []);
3216
- }
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})`;
3587
+ sanitized.push(arg);
3221
3588
  }
3222
- if (late.header !== undefined) {
3223
- return `${error} printed under the header of ${late.header} (block ${late.block + 1})`;
3589
+ return sanitized;
3590
+ }
3591
+ var liveChildren = new Set;
3592
+ function killAllLiveChildren() {
3593
+ for (const child of liveChildren) {
3594
+ killProcessTree(child, "SIGKILL");
3224
3595
  }
3225
- return `${error} (block ${late.block + 1})`;
3596
+ liveChildren.clear();
3226
3597
  }
3227
- var keyOf = (claim) => `${claim.block}\x00${claim.line}`;
3228
- function lateCallSentences(lates, blocks) {
3229
- if (lates.length === 0) {
3230
- return [];
3598
+ var CLEANUP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
3599
+ var onCleanupSignal = (signal) => {
3600
+ killAllLiveChildren();
3601
+ removeSignalCleanup();
3602
+ process.kill(process.pid, signal);
3603
+ };
3604
+ function ensureSignalCleanup() {
3605
+ if (process.listeners(CLEANUP_SIGNALS[0]).includes(onCleanupSignal)) {
3606
+ return false;
3231
3607
  }
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
- ];
3608
+ for (const s of CLEANUP_SIGNALS) {
3609
+ process.on(s, onCleanupSignal);
3610
+ }
3611
+ return true;
3243
3612
  }
3244
- function eagerSentences(modules) {
3245
- if (modules.length === 0) {
3246
- return [];
3613
+ function removeSignalCleanup() {
3614
+ for (const s of CLEANUP_SIGNALS) {
3615
+ process.off(s, onCleanupSignal);
3247
3616
  }
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
- ];
3252
3617
  }
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;
3618
+ function killProcessTree(childProcess, signal) {
3619
+ const pid = childProcess.pid;
3620
+ if (pid === undefined || !killProcessGroup(pid, signal)) {
3621
+ childProcess.kill(signal);
3622
+ return false;
3259
3623
  }
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;
3624
+ return true;
3625
+ }
3626
+ function killWithEscalation(childProcess, isClosed, gracePeriodMs) {
3627
+ const pid = childProcess.pid;
3628
+ const signalledGroup = killProcessTree(childProcess, "SIGTERM");
3629
+ let hasEscalated = false;
3630
+ const escalationHandle = setTimeout(() => {
3631
+ if (!isClosed()) {
3632
+ hasEscalated = true;
3633
+ killProcessTree(childProcess, "SIGKILL");
3272
3634
  }
3273
- for (const claim of lost) {
3274
- dropped.add(keyOf(claim));
3635
+ }, gracePeriodMs);
3636
+ return () => {
3637
+ clearTimeout(escalationHandle);
3638
+ if (!hasEscalated && signalledGroup && pid !== undefined) {
3639
+ hasEscalated = true;
3640
+ killProcessGroup(pid, "SIGKILL");
3275
3641
  }
3276
- }
3277
- return layOut(blocks, { lates: lates.map((late) => ({ ...late, frame: undefined })), modules: [] }).text;
3642
+ };
3278
3643
  }
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);
3644
+ async function runBunTests(options) {
3645
+ const spawnDepth = readSpawnDepth(process.env[SPAWN_DEPTH_ENV]);
3646
+ const maxSpawnDepth = options.maxSpawnDepth ?? DEFAULT_MAX_SPAWN_DEPTH;
3647
+ if (!Number.isSafeInteger(maxSpawnDepth) || maxSpawnDepth < 1) {
3648
+ return {
3649
+ stdout: "",
3650
+ stderr: `stryker-bun-runner: invalid maxSpawnDepth=${String(maxSpawnDepth)}; expected a positive integer.`,
3651
+ exitCode: 1,
3652
+ signal: null,
3653
+ timedOut: false,
3654
+ memoryLimitExceeded: false
3655
+ };
3283
3656
  }
3284
- return [...shown].toSorted((a, b) => a - b);
3657
+ if (spawnDepth >= maxSpawnDepth) {
3658
+ return {
3659
+ stdout: "",
3660
+ 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.`,
3661
+ exitCode: 1,
3662
+ signal: null,
3663
+ timedOut: false,
3664
+ memoryLimitExceeded: false
3665
+ };
3666
+ }
3667
+ return spawnBunTests(options, spawnDepth);
3285
3668
  }
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]`);
3296
- }
3297
- break;
3669
+ function buildChildEnv(options, spawnDepth) {
3670
+ const env = {
3671
+ ...process.env,
3672
+ ...options.env
3673
+ };
3674
+ const preloadVars = {
3675
+ __STRYKER_ACTIVE_MUTANT__: options.activeMutant === "" ? undefined : options.activeMutant,
3676
+ __STRYKER_HIT_LIMIT__: options.hitLimit === undefined ? undefined : String(options.hitLimit),
3677
+ __STRYKER_HIT_LIMIT_TOKEN__: options.hitLimitToken,
3678
+ __STRYKER_COVERAGE_FILE__: options.coverageFile === "" ? undefined : options.coverageFile,
3679
+ [COVERAGE_KEYS_ONLY_ENV]: options.coverageKeysOnly === true ? "1" : undefined,
3680
+ __STRYKER_SYNC_PORT__: options.syncPort ? String(options.syncPort) : undefined,
3681
+ [SYNC_TOKEN_ENV]: options.syncToken,
3682
+ [DRY_RUN_PLAN_ENV]: options.dryRunPlan,
3683
+ [WATCH_LIST_ENV]: options.watchList,
3684
+ [LIFELINE_FD_ENV]: String(LIFELINE_FD)
3685
+ };
3686
+ for (const [name, value] of Object.entries(preloadVars)) {
3687
+ if (value === undefined) {
3688
+ delete env[name];
3689
+ } else {
3690
+ env[name] = value;
3298
3691
  }
3299
- used += 1 + line.length;
3300
- kept.push(line);
3301
3692
  }
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
- `);
3693
+ env[SPAWN_DEPTH_ENV] = String(spawnDepth + 1);
3694
+ delete env[PROJECT_DIR_ENV];
3695
+ if (options.profile) {
3696
+ delete env[PROFILE_ENV];
3697
+ }
3698
+ if (options.profile && options.syncPort) {
3699
+ env[PRELOAD_TIMINGS_ENV] = "1";
3700
+ } else {
3701
+ delete env[PRELOAD_TIMINGS_ENV];
3702
+ }
3703
+ return env;
3306
3704
  }
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;
3705
+ async function spawnBunTests(options, spawnDepth) {
3706
+ const profile = options.profile;
3707
+ profile?.beginSpawn(options.bail === true, options.testFiles, options.testNamePattern);
3708
+ const args = ["test"];
3709
+ if (options.inspect) {
3710
+ args.push("--inspect=127.0.0.1:0");
3711
+ }
3712
+ if (options.bunfigPath) {
3713
+ args.push(`--config=${options.bunfigPath}`);
3714
+ }
3715
+ if (options.preloadScript) {
3716
+ args.push("--preload", options.preloadScript);
3717
+ }
3718
+ if (options.testNamePattern) {
3719
+ args.push("--test-name-pattern", options.testNamePattern);
3720
+ }
3721
+ if (options.bail) {
3722
+ args.push("--bail");
3723
+ }
3724
+ if (options.sequentialMode) {
3725
+ args.push("--max-concurrency=1");
3726
+ }
3727
+ if (options.smol) {
3728
+ args.push("--smol");
3729
+ }
3730
+ if (options.bunArgs && options.bunArgs.length > 0) {
3731
+ args.push(...stripBailArgs(options.bunArgs));
3732
+ }
3733
+ if (options.testFiles && options.testFiles.length > 0) {
3734
+ args.push(...buildTestFileArgs(options.testFiles).args);
3735
+ }
3736
+ const env = buildChildEnv(options, spawnDepth);
3737
+ return new Promise((resolve) => {
3738
+ const stdoutChunks = [];
3739
+ const stderrChunks = [];
3740
+ let timedOut = false;
3741
+ let processKilled = false;
3742
+ let memoryLimitExceeded = false;
3743
+ let hasClosed = false;
3744
+ let rssIntervalHandle;
3745
+ let stdioCloseHandle;
3746
+ let onLeaderExitDuringTermination;
3747
+ let onAbort;
3748
+ if (options.signal?.aborted) {
3749
+ resolve({ stdout: "", stderr: "", exitCode: null, signal: null, timedOut: true, memoryLimitExceeded: false });
3750
+ return;
3751
+ }
3752
+ const spawnOpts = {
3753
+ env,
3754
+ stdio: ["ignore", "pipe", "pipe", "pipe"],
3755
+ cwd: process.cwd(),
3756
+ detached: true
3757
+ };
3758
+ try {
3759
+ options.onSpawn?.([options.bunPath, ...args]);
3760
+ } catch {}
3761
+ const childProcess = spawn3(options.bunPath, args, spawnOpts);
3762
+ profile?.mark("spawned");
3763
+ liveChildren.add(childProcess);
3764
+ ensureSignalCleanup();
3765
+ const beginTermination = () => {
3766
+ if (processKilled) {
3767
+ return false;
3768
+ }
3769
+ processKilled = true;
3770
+ timedOut = true;
3771
+ onLeaderExitDuringTermination = killWithEscalation(childProcess, () => hasClosed, KILL_GRACE_PERIOD_MS);
3772
+ return true;
3773
+ };
3774
+ const timeoutHandle = setTimeout(() => {
3775
+ beginTermination();
3776
+ }, options.timeout);
3777
+ if (options.signal) {
3778
+ onAbort = () => {
3779
+ beginTermination();
3780
+ };
3781
+ options.signal.addEventListener("abort", onAbort, { once: true });
3332
3782
  }
3333
- noSnippets.add(index);
3334
- }
3335
- for (const dropped of selected.filter((index) => !required.has(index)).toReversed()) {
3336
- if (fits()) {
3337
- break;
3783
+ if (options.maxChildRss !== undefined) {
3784
+ const rssLimit = options.maxChildRss;
3785
+ const checkMemoryCeiling = async () => {
3786
+ if (hasClosed || processKilled) {
3787
+ return;
3788
+ }
3789
+ const pid = childProcess.pid;
3790
+ if (pid === undefined) {
3791
+ return;
3792
+ }
3793
+ const rssBytes = await getProcessRssBytes(pid);
3794
+ if (rssBytes === null || hasClosed) {
3795
+ return;
3796
+ }
3797
+ if (rssBytes > rssLimit) {
3798
+ if (!beginTermination()) {
3799
+ return;
3800
+ }
3801
+ memoryLimitExceeded = true;
3802
+ if (rssIntervalHandle) {
3803
+ clearInterval(rssIntervalHandle);
3804
+ }
3805
+ options.onMemoryLimitExceeded?.(rssBytes);
3806
+ }
3807
+ };
3808
+ rssIntervalHandle = setInterval(() => {
3809
+ checkMemoryCeiling();
3810
+ }, options.rssCheckIntervalMs ?? 1000);
3811
+ rssIntervalHandle.unref();
3338
3812
  }
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) });
3813
+ if (childProcess.stdout) {
3814
+ childProcess.stdout.on("data", (data) => {
3815
+ stdoutChunks.push(data);
3816
+ });
3347
3817
  }
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
- };
3818
+ let inspectorUrlExtracted = false;
3819
+ if (childProcess.stderr) {
3820
+ childProcess.stderr.on("data", (data) => {
3821
+ stderrChunks.push(data);
3822
+ profile?.onStderr(data);
3823
+ if (options.inspect && !inspectorUrlExtracted && options.onInspectorReady) {
3824
+ const text = Buffer.concat(stderrChunks).toString();
3825
+ const match = /Listening:[\t\v\f\r \u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*\n\s*(ws:\/\/\S+)/.exec(stripAnsi(text));
3826
+ if (match) {
3827
+ inspectorUrlExtracted = true;
3828
+ options.onInspectorReady(match[1]);
3829
+ }
3830
+ }
3831
+ });
3832
+ }
3833
+ const release = () => {
3834
+ liveChildren.delete(childProcess);
3835
+ clearTimeout(timeoutHandle);
3836
+ clearTimeout(stdioCloseHandle);
3837
+ if (options.signal && onAbort) {
3838
+ options.signal.removeEventListener("abort", onAbort);
3839
+ }
3840
+ if (rssIntervalHandle) {
3841
+ clearInterval(rssIntervalHandle);
3842
+ }
3843
+ };
3844
+ childProcess.on("exit", (code, signal) => {
3845
+ profile?.mark("exit");
3846
+ onLeaderExitDuringTermination?.();
3847
+ stdioCloseHandle = setTimeout(() => {
3848
+ release();
3849
+ resolve({
3850
+ stdout: Buffer.concat(stdoutChunks).toString(),
3851
+ stderr: Buffer.concat(stderrChunks).toString(),
3852
+ exitCode: processKilled ? null : code,
3853
+ signal: signal ?? null,
3854
+ timedOut,
3855
+ memoryLimitExceeded,
3856
+ outputIncomplete: true
3857
+ });
3858
+ }, STDIO_CLOSE_GRACE_MS);
3859
+ });
3860
+ childProcess.on("close", (code, signal) => {
3861
+ profile?.mark("close");
3862
+ hasClosed = true;
3863
+ onLeaderExitDuringTermination?.();
3864
+ release();
3865
+ resolve({
3866
+ stdout: Buffer.concat(stdoutChunks).toString(),
3867
+ stderr: Buffer.concat(stderrChunks).toString(),
3868
+ exitCode: processKilled ? null : code,
3869
+ signal: signal ?? null,
3870
+ timedOut,
3871
+ memoryLimitExceeded
3872
+ });
3873
+ });
3874
+ childProcess.on("error", (error) => {
3875
+ profile?.mark("close");
3876
+ hasClosed = true;
3877
+ onLeaderExitDuringTermination?.();
3878
+ release();
3879
+ const stderrOutput = Buffer.concat(stderrChunks).toString();
3880
+ resolve({
3881
+ stdout: Buffer.concat(stdoutChunks).toString(),
3882
+ stderr: `${stderrOutput}
3883
+ Process error: ${error.message}`,
3884
+ exitCode: null,
3885
+ signal: null,
3886
+ timedOut,
3887
+ memoryLimitExceeded,
3888
+ spawnError: error.message
3889
+ });
3890
+ });
3891
+ });
3356
3892
  }
3357
3893
 
3358
3894
  // src/run-profile.ts
3359
3895
  import { appendFileSync as appendFileSync2 } from "node:fs";
3360
- import path10 from "node:path";
3896
+ import path11 from "node:path";
3361
3897
  import { StringDecoder } from "node:string_decoder";
3362
3898
  var PROFILE_FORMAT_VERSION = 1;
3363
3899
  var SPAWN_MARKS = ["spawnStart", "spawned", "firstStderr", "inspector", "firstFile", "decisive", "exit", "close"];
@@ -3715,7 +4251,7 @@ function createWorkerProfiler(logger, env = process.env) {
3715
4251
  if (value === undefined || value === "" || value === "0" || value === "false") {
3716
4252
  return;
3717
4253
  }
3718
- if (!path10.isAbsolute(value)) {
4254
+ if (!path11.isAbsolute(value)) {
3719
4255
  logger.warn("%s must be the absolute path of a JSONL file to append to (got %s); profiling is off", PROFILE_ENV, value);
3720
4256
  return;
3721
4257
  }
@@ -3897,6 +4433,28 @@ function rawDataToString(data) {
3897
4433
  }
3898
4434
  return Buffer.isBuffer(data) ? data.toString("utf8") : Buffer.from(data).toString("utf8");
3899
4435
  }
4436
+ var DRAIN_REQUEST = "drain-request";
4437
+ function parseDrainRequest(text) {
4438
+ if (text === DRAIN_REQUEST) {
4439
+ return { startedTests: undefined };
4440
+ }
4441
+ if (!text.startsWith(`${DRAIN_REQUEST} `)) {
4442
+ return null;
4443
+ }
4444
+ const count = text.slice(DRAIN_REQUEST.length + 1);
4445
+ const startedTests = Number(count);
4446
+ return { startedTests: /^\d+$/.test(count) && Number.isSafeInteger(startedTests) ? startedTests : undefined };
4447
+ }
4448
+ function newDrainState() {
4449
+ return { handler: null, onDropped: null, dropped: [], queue: [], pending: new Set, busy: false, closed: false };
4450
+ }
4451
+ function reportDropped(drain, request) {
4452
+ if (drain.onDropped === null) {
4453
+ drain.dropped.push(request);
4454
+ } else {
4455
+ drain.onDropped(request);
4456
+ }
4457
+ }
3900
4458
 
3901
4459
  class SyncServer {
3902
4460
  token = randomBytes3(16).toString("hex");
@@ -3908,9 +4466,7 @@ class SyncServer {
3908
4466
  createHttpServer;
3909
4467
  WebSocketServerClass;
3910
4468
  webSocketOpenState;
3911
- drainHandler = null;
3912
- drainInFlight = null;
3913
- pendingDrainClients = new Set;
4469
+ drain = newDrainState();
3914
4470
  constructor(options = {}) {
3915
4471
  this.createHttpServer = options.createHttpServer ?? createServer;
3916
4472
  this.WebSocketServerClass = options.WebSocketServerClass ?? WebSocketServer;
@@ -3948,11 +4504,12 @@ class SyncServer {
3948
4504
  }
3949
4505
  ws.on("close", () => {
3950
4506
  this.clients.delete(ws);
3951
- this.pendingDrainClients.delete(ws);
4507
+ this.forgetQueuedDrainRequest(ws);
3952
4508
  });
3953
4509
  ws.on("message", (data) => {
3954
- if (rawDataToString(data) === "drain-request") {
3955
- this.handleDrainRequest(ws);
4510
+ const request = parseDrainRequest(rawDataToString(data));
4511
+ if (request) {
4512
+ this.handleDrainRequest(ws, request);
3956
4513
  }
3957
4514
  });
3958
4515
  });
@@ -3977,46 +4534,69 @@ class SyncServer {
3977
4534
  } catch {}
3978
4535
  }
3979
4536
  }
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);
4537
+ setDrainHandler(handler, onDropped) {
4538
+ const drain = this.drain;
4539
+ drain.handler = handler;
4540
+ if (onDropped !== undefined) {
4541
+ drain.onDropped = onDropped;
4542
+ for (const request of drain.dropped.splice(0)) {
4543
+ onDropped(request);
4544
+ }
3986
4545
  }
4546
+ this.serveNextDrainRequest(drain);
3987
4547
  }
3988
- handleDrainRequest(ws) {
3989
- if (!this.drainHandler) {
3990
- this.pendingDrainClients.add(ws);
4548
+ handleDrainRequest(ws, request) {
4549
+ const drain = this.drain;
4550
+ if (drain.pending.has(ws)) {
3991
4551
  return;
3992
4552
  }
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);
4553
+ drain.pending.add(ws);
4554
+ drain.queue.push({ ws, request });
4555
+ this.serveNextDrainRequest(drain);
4556
+ }
4557
+ forgetQueuedDrainRequest(ws) {
4558
+ const drain = this.drain;
4559
+ const index = drain.queue.findIndex((queued) => queued.ws === ws);
4560
+ if (index !== -1) {
4561
+ const [queued] = drain.queue.splice(index, 1);
4562
+ drain.pending.delete(ws);
4563
+ reportDropped(drain, queued.request);
4000
4564
  }
4001
- const inFlight = this.drainInFlight;
4002
- (async () => {
4003
- try {
4004
- await inFlight;
4005
- } catch {
4006
- return;
4007
- }
4565
+ }
4566
+ serveNextDrainRequest(drain) {
4567
+ const handler = drain.handler;
4568
+ if (handler === null || drain.busy || drain.closed) {
4569
+ return;
4570
+ }
4571
+ const next = drain.queue.shift();
4572
+ if (next === undefined) {
4573
+ return;
4574
+ }
4575
+ drain.busy = true;
4576
+ const answer = () => {
4008
4577
  try {
4009
- if (ws.readyState === this.webSocketOpenState) {
4010
- ws.send("drained");
4578
+ if (next.ws.readyState === this.webSocketOpenState) {
4579
+ next.ws.send("drained");
4011
4580
  }
4012
4581
  } catch {}
4013
- })();
4582
+ };
4583
+ const done = () => {
4584
+ drain.pending.delete(next.ws);
4585
+ drain.busy = false;
4586
+ this.serveNextDrainRequest(drain);
4587
+ };
4588
+ handler(next.request).then(answer).catch(() => {
4589
+ return;
4590
+ }).finally(done);
4014
4591
  }
4015
4592
  async close() {
4016
4593
  this.readyLatched = false;
4017
- this.drainHandler = null;
4018
- this.drainInFlight = null;
4019
- this.pendingDrainClients = new Set;
4594
+ const drain = this.drain;
4595
+ drain.closed = true;
4596
+ for (const queued of drain.queue) {
4597
+ reportDropped(drain, queued.request);
4598
+ }
4599
+ this.drain = newDrainState();
4020
4600
  for (const client of this.clients) {
4021
4601
  try {
4022
4602
  client.close();
@@ -4044,7 +4624,7 @@ class SyncServer {
4044
4624
  }
4045
4625
  // src/utils/bunfig-sanitizer.ts
4046
4626
  import { readFile as readFile5, unlink as unlink3 } from "node:fs/promises";
4047
- import path11 from "node:path";
4627
+ import path12 from "node:path";
4048
4628
  import { parse, stringify } from "smol-toml";
4049
4629
  var SAFE_TEST_KEYS = new Set([
4050
4630
  "preload",
@@ -4078,7 +4658,7 @@ function absolutizePath(value, projectCwd) {
4078
4658
  if (typeof value !== "string") {
4079
4659
  return value;
4080
4660
  }
4081
- return path11.isAbsolute(value) ? value : path11.resolve(projectCwd, value);
4661
+ return path12.isAbsolute(value) ? value : path12.resolve(projectCwd, value);
4082
4662
  }
4083
4663
  function absolutizePathValue(value, projectCwd) {
4084
4664
  if (Array.isArray(value)) {
@@ -4087,7 +4667,7 @@ function absolutizePathValue(value, projectCwd) {
4087
4667
  return absolutizePath(value, projectCwd);
4088
4668
  }
4089
4669
  async function readSourceBunfig(projectCwd, sourceBunfig) {
4090
- const bunfigPath = sourceBunfig === undefined ? path11.join(projectCwd, "bunfig.toml") : path11.resolve(projectCwd, sourceBunfig);
4670
+ const bunfigPath = sourceBunfig === undefined ? path12.join(projectCwd, "bunfig.toml") : path12.resolve(projectCwd, sourceBunfig);
4091
4671
  try {
4092
4672
  const content = await readFile5(bunfigPath, "utf8");
4093
4673
  return parse(content);
@@ -4102,14 +4682,14 @@ async function readSourceBunfig(projectCwd, sourceBunfig) {
4102
4682
  async function readBunfigTestRoot(projectCwd, sourceBunfig) {
4103
4683
  const rawConfig = await readSourceBunfig(projectCwd, sourceBunfig);
4104
4684
  const root = rawConfig.test?.root;
4105
- return typeof root === "string" ? path11.resolve(projectCwd, root) : undefined;
4685
+ return typeof root === "string" ? path12.resolve(projectCwd, root) : undefined;
4106
4686
  }
4107
4687
  async function readBunfigTestPreloads(projectCwd, sourceBunfig) {
4108
4688
  return testPreloadsOf(await readSourceBunfig(projectCwd, sourceBunfig), projectCwd);
4109
4689
  }
4110
4690
  function testPreloadsOf(rawConfig, projectCwd) {
4111
4691
  const preload = rawConfig.test?.preload;
4112
- return [preload].flat().filter((entry) => typeof entry === "string").map((entry) => path11.resolve(projectCwd, entry));
4692
+ return [preload].flat().filter((entry) => typeof entry === "string").map((entry) => path12.resolve(projectCwd, entry));
4113
4693
  }
4114
4694
  var SCAN_NEUTRAL_BUNFIG_KEYS = new Set(["preload", "smol", "logLevel", "telemetry", "env", "console", "serve", "install", "run", "conditions", "test"]);
4115
4695
  var JSX_BUNFIG_KEYS = new Set(["jsx", "jsxImportSource", "jsxFactory", "jsxFragment"]);
@@ -4191,7 +4771,7 @@ async function generateSanitizedBunfig(projectCwd, tmpDir, sourceBunfig, onDropp
4191
4771
  dropped.push({ key: `test.${key}`, reason: RANDOM_ORDER_REASON, warn: false, mutantRunsOnly: true });
4192
4772
  }
4193
4773
  onDropped?.(dropped);
4194
- const outPath = path11.join(tmpDir, `stryker-bun-runner-bunfig-${process.pid}-${Date.now()}.toml`);
4774
+ const outPath = path12.join(tmpDir, `stryker-bun-runner-bunfig-${process.pid}-${Date.now()}.toml`);
4195
4775
  await writePrivateFile(outPath, stringify(sanitized));
4196
4776
  const mutantRunTest = { ...sanitizedTest, onlyFailures: true };
4197
4777
  if (randomOrderKeys.length > 0) {
@@ -4216,7 +4796,7 @@ async function cleanupSanitizedBunfig(filePath) {
4216
4796
  }
4217
4797
  // src/utils/test-file-discovery.ts
4218
4798
  import * as fsPromises2 from "node:fs/promises";
4219
- import path12 from "node:path";
4799
+ import path13 from "node:path";
4220
4800
  function isExcludedDirName(name) {
4221
4801
  return name.startsWith(".") || name.toLowerCase() === "node_modules";
4222
4802
  }
@@ -4262,7 +4842,7 @@ async function handleSymlinkFile(fullPath, entryName, ctx) {
4262
4842
  }
4263
4843
  const resolvedTarget = await tryRealpath(fullPath);
4264
4844
  if (resolvedTarget && !hasExcludedAncestor(resolvedTarget)) {
4265
- ctx.results.push(path12.relative(ctx.cwd, fullPath));
4845
+ ctx.results.push(path13.relative(ctx.cwd, fullPath));
4266
4846
  }
4267
4847
  }
4268
4848
  async function handleSymlink(fullPath, entryName, ctx) {
@@ -4278,7 +4858,7 @@ async function handleSymlink(fullPath, entryName, ctx) {
4278
4858
  }
4279
4859
  }
4280
4860
  async function processEntry(entry, dir, ctx) {
4281
- const fullPath = path12.join(dir, entry.name);
4861
+ const fullPath = path13.join(dir, entry.name);
4282
4862
  if (entry.isDirectory()) {
4283
4863
  if (!isExcludedDirName(entry.name)) {
4284
4864
  await ctx.walk(fullPath);
@@ -4286,7 +4866,7 @@ async function processEntry(entry, dir, ctx) {
4286
4866
  } else if (entry.isSymbolicLink()) {
4287
4867
  await handleSymlink(fullPath, entry.name, ctx);
4288
4868
  } else if (entry.isFile() && TEST_FILE_SUFFIX_RE.test(entry.name)) {
4289
- ctx.results.push(path12.relative(ctx.cwd, fullPath));
4869
+ ctx.results.push(path13.relative(ctx.cwd, fullPath));
4290
4870
  }
4291
4871
  }
4292
4872
  async function discoverTestFiles(cwd = process.cwd(), logger, sourceBunfig) {
@@ -4330,14 +4910,14 @@ async function walkTestFiles(walkRoot, cwd, logger) {
4330
4910
  }
4331
4911
  async function expandTestFileEntries(entries, cwd, logger) {
4332
4912
  const expanded = await Promise.all(entries.map(async (entry) => {
4333
- const absolute = path12.resolve(cwd, entry);
4913
+ const absolute = path13.resolve(cwd, entry);
4334
4914
  const stat = await tryStat(absolute);
4335
4915
  if (stat?.isFile()) {
4336
4916
  return [absolute];
4337
4917
  }
4338
4918
  if (stat?.isDirectory()) {
4339
4919
  const found = await walkTestFiles(absolute, cwd, logger);
4340
- return found.map((file) => path12.resolve(cwd, file));
4920
+ return found.map((file) => path13.resolve(cwd, file));
4341
4921
  }
4342
4922
  return entry;
4343
4923
  }));
@@ -4376,10 +4956,25 @@ class MutantWarnAggregator {
4376
4956
  }
4377
4957
  }
4378
4958
  // src/utils/likely-killer-order.ts
4379
- import path13 from "node:path";
4380
- var MUTANT_SWITCH_RE = /stryMutAct_9fa48\("([^"\\]+)"\)/g;
4959
+ import path14 from "node:path";
4960
+ var SWITCH_DECLARATION_RE = /function stryMutAct_([\w$]+)\(/;
4961
+ var HELPER_CALL_RE = /(?<![\w$])(?:stryMutAct|stryCov)_([\w$]+)\(([^()]*)\)/g;
4962
+ var ID_ARGUMENT_RE = /"([^"\\]+)"/g;
4963
+ function instrumenterSuffix(code) {
4964
+ const suffix = SWITCH_DECLARATION_RE.exec(code)?.[1];
4965
+ return code.includes(`function stryCov_${suffix}(`) ? suffix : undefined;
4966
+ }
4381
4967
  function mutantIdsInInstrumentedSource(code) {
4382
- return new Set(Array.from(code.matchAll(MUTANT_SWITCH_RE), (match) => match[1]));
4968
+ const ids = new Set;
4969
+ const suffix = instrumenterSuffix(code);
4970
+ for (const [, callSuffix, args] of code.matchAll(HELPER_CALL_RE)) {
4971
+ if (callSuffix === suffix) {
4972
+ for (const [, id] of args.matchAll(ID_ARGUMENT_RE)) {
4973
+ ids.add(id);
4974
+ }
4975
+ }
4976
+ }
4977
+ return ids;
4383
4978
  }
4384
4979
 
4385
4980
  class TestFileCoverage {
@@ -4451,8 +5046,8 @@ function namedAfter(sourceFile) {
4451
5046
  if (sourceFile === undefined) {
4452
5047
  return () => false;
4453
5048
  }
4454
- const sourceStem = path13.parse(sourceFile).name.toLowerCase();
4455
- return (testFile) => path13.basename(testFile).replace(TEST_FILE_SUFFIX_RE, "").toLowerCase() === sourceStem;
5049
+ const sourceStem = path14.parse(sourceFile).name.toLowerCase();
5050
+ return (testFile) => path14.basename(testFile).replace(TEST_FILE_SUFFIX_RE, "").toLowerCase() === sourceStem;
4456
5051
  }
4457
5052
  function compareKillerRanks(a, b) {
4458
5053
  return a.coverage - b.coverage || b.sourceMutants - a.sourceMutants || Number(b.namedAfter) - Number(a.namedAfter);
@@ -4464,7 +5059,7 @@ function orderLikelyKillersFirst(files, rankOf) {
4464
5059
  // src/utils/dry-run-output-log.ts
4465
5060
  import { randomUUID } from "node:crypto";
4466
5061
  import { lstat as lstat2, mkdir as mkdir2, open, rename as rename2, rm as rm4 } from "node:fs/promises";
4467
- import path14 from "node:path";
5062
+ import path15 from "node:path";
4468
5063
  var MAX_LOG_STREAM_CHARS = 16 * 1024 * 1024;
4469
5064
  var MAX_LOG_COMMAND_CHARS = 4000;
4470
5065
  function capStream(text, max) {
@@ -4559,11 +5154,11 @@ function oneLine(error) {
4559
5154
  async function saveDryRunOutput(file, output, options = {}) {
4560
5155
  try {
4561
5156
  const text = formatDryRunOutputLog(output, new Date(options.now ?? Date.now()), options.maxStreamChars);
4562
- const directory = path14.dirname(file);
5157
+ const directory = path15.dirname(file);
4563
5158
  await mkdir2(directory, { recursive: true });
4564
5159
  throwIfAbandoned(options.signal);
4565
5160
  await checkTarget(file);
4566
- const temporary = path14.join(directory, `.stryker-bun-runner-output-${randomUUID()}.tmp`);
5161
+ const temporary = path15.join(directory, `.stryker-bun-runner-output-${randomUUID()}.tmp`);
4567
5162
  const handle = await open(temporary, "wx", 384);
4568
5163
  try {
4569
5164
  try {
@@ -4616,45 +5211,6 @@ function createInspectorUrlWaiter() {
4616
5211
  }
4617
5212
  };
4618
5213
  }
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
5214
  function formatSpawnErrorMessage(spawnError) {
4659
5215
  return `could not start bun test: ${spawnError}`;
4660
5216
  }
@@ -4685,9 +5241,9 @@ function formatInspectorConnectMessage(error, child, secrets) {
4685
5241
  }
4686
5242
  function collectAbnormalDrainProblems(data) {
4687
5243
  const problems = [];
4688
- if (data.drainSettleReason !== "ack") {
5244
+ if (!data.drainProven) {
4689
5245
  const rejection = data.drainRejection === undefined ? "" : ` (${data.drainRejection})`;
4690
- problems.push(`drain handshake ${formatDrainSettleReason(data.drainSettleReason)}${rejection}`);
5246
+ problems.push(`drain handshake ${data.drainSummary}${rejection}`);
4691
5247
  }
4692
5248
  if (data.finalGaps.length > 0) {
4693
5249
  problems.push(`${data.finalGaps.length} found-id gap(s) remaining${formatGapIdList(data.finalGaps)}`);
@@ -4722,7 +5278,7 @@ async function writingTo(file, write) {
4722
5278
  var MISSING_COVERAGE_FOR_RULE_3_3 = "the run that publishes left no coverage data, so the runner cannot check that it reached every mutant the plain run of the tests reached";
4723
5279
  var RUN_ORDINALS = ["first", "second", "third"];
4724
5280
  function isGreen(result) {
4725
- return result.status === DryRunStatus.Complete && !result.tests.some((test) => test.status === TestStatus.Failed);
5281
+ return result.status === DryRunStatus2.Complete && !result.tests.some((test) => test.status === TestStatus2.Failed);
4726
5282
  }
4727
5283
  function buildTestNameIndex(tests, bunNames) {
4728
5284
  const testNameIndex = new Map;
@@ -4794,6 +5350,9 @@ function coversAnyMutant(coverage) {
4794
5350
  const buckets = [coverage.static, ...Object.values(coverage.perTest)];
4795
5351
  return buckets.some((bucket) => Object.values(bucket).some((count) => count > 0));
4796
5352
  }
5353
+ function campaignOf(campaign, dir) {
5354
+ return { ...campaign, dir, watched: new Set(campaign.watchList), handedFiles: new Set(campaign.handed) };
5355
+ }
4797
5356
  var MUTANT_WARN_KIND = {
4798
5357
  unresolvedKilledBy: "failed test names could not be resolved to dry-run test ids",
4799
5358
  noRegistry: "no exact-name registry available (lossy covering-test patterns)",
@@ -4862,6 +5421,7 @@ class BunTestRunner {
4862
5421
  maxSpawnDepth;
4863
5422
  dryRunOutputFile;
4864
5423
  coverageAnalysis;
5424
+ ignoreStatic;
4865
5425
  preloadScriptPath;
4866
5426
  coverageFilePath;
4867
5427
  sanitizedBunfigPath;
@@ -4899,6 +5459,8 @@ class BunTestRunner {
4899
5459
  campaign;
4900
5460
  warnedWatchListProblem = false;
4901
5461
  currentAbortController;
5462
+ drainSilenceMs = DRAIN_ACK_SILENCE_TIMEOUT_MS;
5463
+ handOffBudget = HAND_OFF_BUDGET;
4902
5464
  constructor(logger, options) {
4903
5465
  this.logger = logger;
4904
5466
  const bunOptions = options.bun ?? {};
@@ -4925,6 +5487,7 @@ class BunTestRunner {
4925
5487
  this.mutateGlobs = options.mutate ?? [];
4926
5488
  this.coverageAnalysis = options.coverageAnalysis;
4927
5489
  this.disableBail = options.disableBail;
5490
+ this.ignoreStatic = options.ignoreStatic === true;
4928
5491
  this.incremental = options.incremental === true;
4929
5492
  this.inPlace = options.inPlace === true;
4930
5493
  this.alwaysImport = bunOptions.alwaysImport;
@@ -4943,7 +5506,7 @@ class BunTestRunner {
4943
5506
  maxSpawnDepth: this.maxSpawnDepth,
4944
5507
  dryRunOutputFile: this.dryRunOutputFile
4945
5508
  });
4946
- if (this.testFilesOverride?.some((p) => path15.isAbsolute(p))) {
5509
+ if (this.testFilesOverride?.some((p) => path16.isAbsolute(p))) {
4947
5510
  const isSandbox = process.cwd().includes(".stryker-tmp/sandbox-");
4948
5511
  if (isSandbox) {
4949
5512
  this.logger.warn("bun.testFiles contains absolute path(s) and the current working directory appears to be a Stryker sandbox (%s). " + "Absolute paths point at the ORIGINAL (unmutated) source files — mutations will be silently bypassed. " + "Use relative paths so that Bun resolves them against the sandbox copy.", process.cwd());
@@ -4952,7 +5515,7 @@ class BunTestRunner {
4952
5515
  }
4953
5516
  async resolveRegistryPath() {
4954
5517
  this.assertRunOwnerIsParent();
4955
- return path15.join(await resolveRunTempDir(), REGISTRY_FILE);
5518
+ return path16.join(await resolveRunTempDir(), REGISTRY_FILE);
4956
5519
  }
4957
5520
  assertRunOwnerIsParent() {
4958
5521
  if (this.runOwnerPid !== undefined && process.ppid !== this.runOwnerPid) {
@@ -5083,7 +5646,7 @@ class BunTestRunner {
5083
5646
  this.logger.debug("Stryker passed an empty testFiles array; ignoring it");
5084
5647
  }
5085
5648
  } else {
5086
- const files = [...new Set(requested.map((file) => path15.resolve(cwd, file)))].toSorted((a, b) => a.localeCompare(b));
5649
+ const files = [...new Set(requested.map((file) => path16.resolve(cwd, file)))].toSorted((a, b) => a.localeCompare(b));
5087
5650
  this.strykerTestFiles = { cwd, files };
5088
5651
  this.warnIfTestFilesOverridden(files, cwd);
5089
5652
  }
@@ -5145,7 +5708,7 @@ class BunTestRunner {
5145
5708
  if (this.warnedTestFilesConflict || this.testFilesOverride === undefined) {
5146
5709
  return;
5147
5710
  }
5148
- const configured = [...new Set(this.testFilesOverride.map((file) => path15.resolve(cwd, file)))];
5711
+ const configured = [...new Set(this.testFilesOverride.map((file) => path16.resolve(cwd, file)))];
5149
5712
  const selectedSet = new Set(selected);
5150
5713
  if (configured.length === selectedSet.size && configured.every((file) => selectedSet.has(file))) {
5151
5714
  return;
@@ -5218,7 +5781,7 @@ class BunTestRunner {
5218
5781
  this.runOwnerPid ??= process.ppid;
5219
5782
  const tempDir = await this.ensureRunTempDir();
5220
5783
  this.tempDirTouchedAt = Date.now();
5221
- this.coverageFilePath = path15.join(tempDir, `coverage-${Date.now()}.json`);
5784
+ this.coverageFilePath = path16.join(tempDir, `coverage-${Date.now()}.json`);
5222
5785
  this.logger.debug("Generating coverage preload script...");
5223
5786
  const eagerCwd = process.cwd();
5224
5787
  const testFilesPending = this.getOrDiscoverTestFiles();
@@ -5247,7 +5810,7 @@ class BunTestRunner {
5247
5810
  if (marker === undefined) {
5248
5811
  return;
5249
5812
  }
5250
- const campaign = await readRegistryCampaign(path15.join(runDir, REGISTRY_FILE));
5813
+ const campaign = await readRegistryCampaign(path16.join(runDir, REGISTRY_FILE));
5251
5814
  if (campaign?.generation !== marker.generation) {
5252
5815
  this.logger.debug("Ignoring the abort marker in %s: it belongs to an earlier campaign", runDir);
5253
5816
  return;
@@ -5326,7 +5889,7 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
5326
5889
  if (this.coverageAnalysis !== "off") {
5327
5890
  this.timeoutCorrectionMs = parsed.timeoutCorrectionMs;
5328
5891
  const campaign = parseCampaignState(parsed.campaign);
5329
- this.campaign = campaign === undefined ? undefined : { ...campaign, dir: path15.dirname(registryPath), watched: new Set(campaign.watchList) };
5892
+ this.campaign = campaign === undefined ? undefined : campaignOf(campaign, path16.dirname(registryPath));
5330
5893
  }
5331
5894
  this.logger.debug("Loaded dryRun registry from %s (%d entries)", registryPath, this.cachedTestNames.size);
5332
5895
  } catch (err) {
@@ -5353,7 +5916,7 @@ ${stack}` : baseFailureMessage;
5353
5916
  return {
5354
5917
  id: normalizedName,
5355
5918
  name: normalizedName,
5356
- status: TestStatus.Failed,
5919
+ status: TestStatus2.Failed,
5357
5920
  failureMessage: t.failureMessage ?? "Test failed",
5358
5921
  timeSpentMs: Math.round(t.duration ?? 1)
5359
5922
  };
@@ -5362,14 +5925,14 @@ ${stack}` : baseFailureMessage;
5362
5925
  return {
5363
5926
  id: normalizedName,
5364
5927
  name: normalizedName,
5365
- status: TestStatus.Skipped,
5928
+ status: TestStatus2.Skipped,
5366
5929
  timeSpentMs: Math.round(t.duration ?? 1)
5367
5930
  };
5368
5931
  }
5369
5932
  return {
5370
5933
  id: normalizedName,
5371
5934
  name: normalizedName,
5372
- status: TestStatus.Success,
5935
+ status: TestStatus2.Success,
5373
5936
  timeSpentMs: Math.round(t.duration ?? 1)
5374
5937
  };
5375
5938
  });
@@ -5387,7 +5950,7 @@ ${stack}` : baseFailureMessage;
5387
5950
  return {
5388
5951
  id: `unknown-${inspectorId}`,
5389
5952
  name: `unknown-${inspectorId}`,
5390
- status: TestStatus.Success,
5953
+ status: TestStatus2.Success,
5391
5954
  timeSpentMs: timePerTest
5392
5955
  };
5393
5956
  }
@@ -5403,7 +5966,7 @@ ${stack}` : baseFailureMessage;
5403
5966
  name: uniqueName,
5404
5967
  fileName,
5405
5968
  startPosition,
5406
- status: TestStatus.Failed,
5969
+ status: TestStatus2.Failed,
5407
5970
  failureMessage: this.buildFailureMessage(testInfo, parsed),
5408
5971
  timeSpentMs: elapsed
5409
5972
  };
@@ -5414,7 +5977,7 @@ ${stack}` : baseFailureMessage;
5414
5977
  name: uniqueName,
5415
5978
  fileName,
5416
5979
  startPosition,
5417
- status: TestStatus.Skipped,
5980
+ status: TestStatus2.Skipped,
5418
5981
  timeSpentMs: elapsed
5419
5982
  };
5420
5983
  }
@@ -5423,7 +5986,7 @@ ${stack}` : baseFailureMessage;
5423
5986
  name: uniqueName,
5424
5987
  fileName,
5425
5988
  startPosition,
5426
- status: TestStatus.Success,
5989
+ status: TestStatus2.Success,
5427
5990
  timeSpentMs: elapsed
5428
5991
  };
5429
5992
  });
@@ -5477,10 +6040,11 @@ ${stack}` : baseFailureMessage;
5477
6040
  startedAt,
5478
6041
  profile,
5479
6042
  extraMs: 0,
5480
- launches: 0
6043
+ launches: 0,
6044
+ handed: []
5481
6045
  };
5482
6046
  if (this.inPlace && this.tempDir !== undefined) {
5483
- await removeQuietly(path15.join(this.tempDir, ABORT_MARKER_FILE));
6047
+ await removeQuietly(path16.join(this.tempDir, ABORT_MARKER_FILE));
5484
6048
  }
5485
6049
  if (coverageAnalysis === "off") {
5486
6050
  return this.runWithoutCoverage(launchContext);
@@ -5530,7 +6094,7 @@ ${stack}` : baseFailureMessage;
5530
6094
  const { expanded } = tests;
5531
6095
  let selected = [];
5532
6096
  if (expanded !== undefined) {
5533
- selected = "files" in expanded ? expanded.files : tests.entries.map((entry) => path15.resolve(ctx.cwd, entry));
6097
+ selected = "files" in expanded ? expanded.files : tests.entries.map((entry) => path16.resolve(ctx.cwd, entry));
5534
6098
  }
5535
6099
  const split = await withoutSelectedTestFiles(ctx.matched, selected);
5536
6100
  if (split.removed.length > 0) {
@@ -5553,6 +6117,22 @@ ${stack}` : baseFailureMessage;
5553
6117
  projectPathsOf(ctx, files) {
5554
6118
  return files.map((file) => shownPath(file, ctx.cwd));
5555
6119
  }
6120
+ handedCreditsOf(ctx, tests) {
6121
+ const started = ctx.handed.some((entry) => entry.launchers !== undefined);
6122
+ const byFile = started && ctx.coverageAnalysis !== "all" ? testsByFile(tests, ctx.cwd, new Set(ctx.handOffTests)) : undefined;
6123
+ return handedCredits(ctx.handed, byFile);
6124
+ }
6125
+ handedSummary(ctx, credits, notLoaded) {
6126
+ const left = new Set(notLoaded);
6127
+ const named = credits.filter((credit) => credit.ids.length > 0 && left.has(credit.file));
6128
+ const started = named.filter((credit) => credit.startedBy !== undefined && credit.every === undefined);
6129
+ const every = named.filter((credit) => credit.startedBy === undefined || credit.every === true);
6130
+ return {
6131
+ started: this.projectPathsOf(ctx, started.map((credit) => credit.file)),
6132
+ testFiles: new Set(started.flatMap((credit) => credit.startedBy.testFiles)).size,
6133
+ every: this.projectPathsOf(ctx, every.map((credit) => credit.file))
6134
+ };
6135
+ }
5556
6136
  logListed(level, message, lists) {
5557
6137
  this.logger[level]("%s", message);
5558
6138
  for (const [what, entries] of lists) {
@@ -5564,6 +6144,7 @@ ${stack}` : baseFailureMessage;
5564
6144
  }
5565
6145
  async decideShape(ctx) {
5566
6146
  const started = performance.now();
6147
+ ctx.handOffsUnread = true;
5567
6148
  try {
5568
6149
  const input = await this.importScanInput(ctx);
5569
6150
  if ("problem" in input) {
@@ -5572,14 +6153,18 @@ ${stack}` : baseFailureMessage;
5572
6153
  }
5573
6154
  const report = await runImportScan(input.input, { bunPath: this.bunPath, workDir: ctx.runDir });
5574
6155
  const decision = decideFromScan(report.result, ctx.eager, ctx.always, this.importDiscovery);
6156
+ ctx.handed = report.result.handed;
6157
+ ctx.handOffTests = input.input.tests;
6158
+ ctx.handOffsUnread = report.failure !== null;
5575
6159
  if (report.failure === null) {
5576
6160
  this.logger.debug("%s", scanMessage({
5577
6161
  answer: report.result.answer,
5578
- wallMs: report.wallMs,
6162
+ wallMs: report.answerMs,
5579
6163
  scannedFiles: report.result.scannedFiles,
5580
6164
  matched: ctx.eager.length,
5581
6165
  statically: this.projectPathsOf(ctx, decision.sources.statically),
5582
6166
  named: this.projectPathsOf(ctx, decision.sources.named),
6167
+ handed: this.projectPathsOf(ctx, report.result.handed.map((entry) => entry.file)),
5583
6168
  always: this.projectPathsOf(ctx, decision.sources.always),
5584
6169
  reasons: decision.kind === "dynamic" ? decision.reasons : report.result.reasons,
5585
6170
  notes: report.result.notes,
@@ -5615,19 +6200,22 @@ ${stack}` : baseFailureMessage;
5615
6200
  return { problem: bunfig.problem };
5616
6201
  }
5617
6202
  const { preloads } = bunfig;
6203
+ const preloaded = new Set([...preloads, ...launch.preloads]);
5618
6204
  return {
5619
6205
  input: {
5620
6206
  eager: ctx.eager,
5621
- roots: [...new Set([...expanded.files, ...preloads, ...launch.preloads])],
6207
+ roots: [...new Set([...expanded.files, ...preloaded])],
6208
+ tests: expanded.files.filter((file) => !preloaded.has(file)),
5622
6209
  always: ctx.always,
5623
6210
  tsconfig: await this.applicableTsconfig(ctx.cwd),
5624
- projectDir: ctx.cwd
6211
+ projectDir: ctx.cwd,
6212
+ handOffBudget: this.handOffBudget
5625
6213
  }
5626
6214
  };
5627
6215
  }
5628
6216
  async applicableTsconfig(cwd) {
5629
6217
  for (const name of ["tsconfig.json", "jsconfig.json"]) {
5630
- const file = path15.join(cwd, name);
6218
+ const file = path16.join(cwd, name);
5631
6219
  const stat = await fsPromises3.stat(file).catch(() => {
5632
6220
  return;
5633
6221
  });
@@ -5671,7 +6259,7 @@ ${stack}` : baseFailureMessage;
5671
6259
  }
5672
6260
  launchFiles(ctx) {
5673
6261
  return {
5674
- planFile: this.preloadScriptPath === undefined ? undefined : newLaunchFile(path15.dirname(this.preloadScriptPath), "dry-run-plan"),
6262
+ planFile: this.preloadScriptPath === undefined ? undefined : newLaunchFile(path16.dirname(this.preloadScriptPath), "dry-run-plan"),
5675
6263
  recordFile: newRecordFile(ctx.runDir)
5676
6264
  };
5677
6265
  }
@@ -5689,7 +6277,7 @@ ${stack}` : baseFailureMessage;
5689
6277
  } catch (error) {
5690
6278
  const errorMessage = `stryker-bun-runner: cannot write the dry-run plan ${planFile} (${errorText(error)})`;
5691
6279
  this.logger.error("%s", errorMessage);
5692
- return { result: { status: DryRunStatus.Error, errorMessage } };
6280
+ return { result: { status: DryRunStatus2.Error, errorMessage } };
5693
6281
  }
5694
6282
  }
5695
6283
  async readRecord(file, parse) {
@@ -5722,7 +6310,7 @@ ${stack}` : baseFailureMessage;
5722
6310
  }
5723
6311
  async runStaticShape(ctx, decision, roots) {
5724
6312
  const launch = await this.runPublished(ctx, decision.list);
5725
- const testFiles = launch.result.status === DryRunStatus.Complete ? launch.result.tests.map((test) => test.fileName) : [];
6313
+ const testFiles = launch.result.status === DryRunStatus2.Complete ? launch.result.tests.map((test) => test.fileName) : [];
5726
6314
  const outcome = oneRunOutcome(this.launchFacts(ctx, launch), unscannedTestFiles(testFiles, roots, ctx.cwd), decision.sources.named);
5727
6315
  if (outcome.kind === "refuse") {
5728
6316
  return this.refuseDryRun(outcome.problems);
@@ -5740,8 +6328,10 @@ ${stack}` : baseFailureMessage;
5740
6328
  }
5741
6329
  this.warnEagerFailures(ctx, launch.record);
5742
6330
  if (outcome.kind === "publish") {
5743
- const left = this.projectPathsOf(ctx, ctx.eager.filter((file) => !decision.list.includes(file)));
5744
- this.logListed("info", importListOneRunMessage({ matched: ctx.eager.length, left, incremental: this.incremental }, { statically: decision.sources.statically.length, named: decision.sources.named.length, always: decision.sources.always.length }), [["the files the runner does not import", left]]);
6331
+ const notImported = ctx.eager.filter((file) => !decision.list.includes(file));
6332
+ const left = this.projectPathsOf(ctx, notImported);
6333
+ const handed = this.handedSummary(ctx, this.handedCreditsOf(ctx, launch.publication.tests), notImported);
6334
+ this.logListed("info", importListOneRunMessage({ matched: ctx.eager.length, left, handed, incremental: this.incremental }, { statically: decision.sources.statically.length, named: decision.sources.named.length, always: decision.sources.always.length }), [["the files the runner does not import", left]]);
5745
6335
  }
5746
6336
  return this.publishDryRun(ctx, launch);
5747
6337
  }
@@ -5805,7 +6395,8 @@ ${stack}` : baseFailureMessage;
5805
6395
  return this.refuseDryRun([MISSING_COVERAGE_FOR_RULE_3_3]);
5806
6396
  }
5807
6397
  const early = outcome.early.map((observation) => observation.file);
5808
- this.reportTwoRunPublication(ctx, { cause, list, observed, early, watched: facts.watched }, publishedOrdinal, discoveryOrdinal);
6398
+ const credits = this.handedCreditsOf(ctx, launch.publication.tests);
6399
+ this.reportTwoRunPublication(ctx, { cause, list, observed, early, watched: facts.watched, credits }, publishedOrdinal, discoveryOrdinal);
5809
6400
  this.warnEagerFailures(ctx, launch.record);
5810
6401
  return this.publishDryRun(ctx, launch, early);
5811
6402
  }
@@ -5816,9 +6407,11 @@ ${stack}` : baseFailureMessage;
5816
6407
  }
5817
6408
  const kept = new Set(run.list);
5818
6409
  if (run.watched) {
5819
- const left = this.projectPathsOf(ctx, ctx.eager.filter((file) => !kept.has(file)));
6410
+ const notImported = ctx.eager.filter((file) => !kept.has(file));
6411
+ const left = this.projectPathsOf(ctx, notImported);
6412
+ const handed = this.handedSummary(ctx, run.credits, notImported);
5820
6413
  const fromObservation = run.list.filter((file) => run.observed.has(file)).length;
5821
- this.logListed("info", importListTwoRunMessage({ matched: ctx.eager.length, left, incremental: this.incremental }, { observed: fromObservation, always: run.list.length - fromObservation }, publishedOrdinal, discoveryOrdinal), [["the files the runner does not import", left]]);
6414
+ this.logListed("info", importListTwoRunMessage({ matched: ctx.eager.length, left, handed, handOffsUnread: ctx.handOffsUnread, incremental: this.incremental }, { observed: fromObservation, always: run.list.length - fromObservation }, publishedOrdinal, discoveryOrdinal), [["the files the runner does not import", left]]);
5822
6415
  }
5823
6416
  if (run.cause.kind === "failed") {
5824
6417
  const unloaded = run.cause.named.filter((file) => !run.observed.has(file));
@@ -5885,7 +6478,7 @@ ${stack}` : baseFailureMessage;
5885
6478
  refuseDryRun(problems) {
5886
6479
  const errorMessage = refuseMessage(problems, this.incremental);
5887
6480
  this.logger.error("%s", errorMessage);
5888
- return { status: DryRunStatus.Error, errorMessage };
6481
+ return { status: DryRunStatus2.Error, errorMessage };
5889
6482
  }
5890
6483
  async discoveryError(ctx, discovery, ordinal, reasons) {
5891
6484
  const { result } = discovery;
@@ -5899,7 +6492,7 @@ ${tail}`;
5899
6492
  ${output}
5900
6493
  ${outputLine}`;
5901
6494
  this.logger.error("%s", errorMessage);
5902
- return { status: DryRunStatus.Error, errorMessage };
6495
+ return { status: DryRunStatus2.Error, errorMessage };
5903
6496
  }
5904
6497
  lateLoadError(ctx, launch, late, published, discovery) {
5905
6498
  const names = launch.publication?.testNames;
@@ -5910,7 +6503,7 @@ ${outputLine}`;
5910
6503
  }));
5911
6504
  const errorMessage = lateLoadMessage(loads, published, discovery, this.incremental);
5912
6505
  this.logListed("error", errorMessage, [["the files loaded late", lateLoadEntries(loads)]]);
5913
- return { status: DryRunStatus.Error, errorMessage };
6506
+ return { status: DryRunStatus2.Error, errorMessage };
5914
6507
  }
5915
6508
  async lostError(ctx, ids, list, always, published) {
5916
6509
  const lost = new Set(ids);
@@ -5931,7 +6524,7 @@ ${outputLine}`;
5931
6524
  };
5932
6525
  const errorMessage = lostMessage(report);
5933
6526
  this.logListed("error", errorMessage, [["the lost mutant ids", ids], ["the files of the lost mutants", report.files], ["the files left out", report.leftOut]]);
5934
- return { status: DryRunStatus.Error, errorMessage };
6527
+ return { status: DryRunStatus2.Error, errorMessage };
5935
6528
  }
5936
6529
  async publishDryRun(ctx, launch, seen = []) {
5937
6530
  const { publication } = launch;
@@ -5942,22 +6535,34 @@ ${outputLine}`;
5942
6535
  const correction = timeoutCorrection(ctx.extraMs, performance.now() - ctx.startedAt, tests.map((test) => test.timeSpentMs));
5943
6536
  ctx.profile?.at("coverageChecked");
5944
6537
  const watched = ctx.coverageAnalysis === "off" ? [] : watchList(ctx.eager, launch.list, seen);
5945
- const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, matched: ctx.matched } : undefined;
6538
+ const handed = creditHandedCoverage(launch.result, this.handedCreditsOf(ctx, tests), (file) => shownPath(file, ctx.cwd), this.ignoreStatic && ctx.coverageAnalysis !== "all");
6539
+ const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, matched: ctx.matched, handed: handed.files } : undefined;
5946
6540
  const unpublished = await this.buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaign);
5947
6541
  ctx.profile?.at("registryWritten");
5948
6542
  if (unpublished !== undefined) {
5949
6543
  this.logger.error("%s", unpublished);
5950
- return { status: DryRunStatus.Error, errorMessage: unpublished };
6544
+ return { status: DryRunStatus2.Error, errorMessage: unpublished };
5951
6545
  }
5952
6546
  this.warnOnUnidentifiedDryRunFailure(processResult, parsed, tests);
5953
6547
  this.warnOnTightDryRunTimeout(totalElapsedMs);
5954
- return launch.result;
6548
+ for (const line of handed.debug) {
6549
+ this.logger.debug("%s", line);
6550
+ }
6551
+ if (handed.warning !== undefined) {
6552
+ this.logger.warn("%s", handed.warning);
6553
+ }
6554
+ return handed.result;
6555
+ }
6556
+ warnIfNoMutantCovered(result, coverageAnalysis) {
6557
+ if (result.mutantCoverage !== undefined && coverageAnalysis !== "off" && !coversAnyMutant(result.mutantCoverage)) {
6558
+ this.logger.warn("The dry run's coverage data shows no mutant covered by any test, per test or statically, so Stryker will report every mutant as NoCoverage. " + "Check that the mutate globs (%s) match the source files your tests import, and that the tests import those files rather than a built copy (e.g. dist/).", this.mutateGlobs.join(", ") || "(none)");
6559
+ }
5955
6560
  }
5956
6561
  async runInspectedPass(ctx, list, planFile) {
5957
6562
  const abortController = new AbortController;
5958
6563
  this.currentAbortController = abortController;
5959
6564
  ctx.profile?.restartLaunch();
5960
- const coverageFile = this.coverageFilePath === undefined ? undefined : newLaunchFile(path15.dirname(this.coverageFilePath), "coverage");
6565
+ const coverageFile = this.coverageFilePath === undefined ? undefined : newLaunchFile(path16.dirname(this.coverageFilePath), "coverage");
5961
6566
  const launched = {};
5962
6567
  try {
5963
6568
  return await this.runInspectedChild(ctx, list, planFile, coverageFile, abortController, launched);
@@ -5983,7 +6588,7 @@ ${outputLine}`;
5983
6588
  this.logger.error("Failed to start sync server: %s", errorMsg);
5984
6589
  return {
5985
6590
  result: {
5986
- status: DryRunStatus.Error,
6591
+ status: DryRunStatus2.Error,
5987
6592
  errorMessage: `Failed to start sync server: ${errorMsg}`
5988
6593
  }
5989
6594
  };
@@ -6043,7 +6648,7 @@ exit=%s timedOut=%s
6043
6648
  %s`, this.inspectorTimeout, String(diagnosticResult.exitCode), String(diagnosticResult.timedOut), stdoutPreview || "(empty)", stderrPreview || "(empty)");
6044
6649
  return {
6045
6650
  result: {
6046
- status: DryRunStatus.Error,
6651
+ status: DryRunStatus2.Error,
6047
6652
  errorMessage: formatInspectorTimeoutMessage(this.inspectorTimeout, diagnosticResult, secrets)
6048
6653
  }
6049
6654
  };
@@ -6079,43 +6684,14 @@ exit=%s timedOut=%s
6079
6684
  const child = await testProcess;
6080
6685
  return {
6081
6686
  result: {
6082
- status: DryRunStatus.Error,
6687
+ status: DryRunStatus2.Error,
6083
6688
  errorMessage: formatInspectorConnectMessage(errorMsg, child, [syncServer.token])
6084
6689
  }
6085
6690
  };
6086
6691
  }
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
- }
6692
+ const drain = new DrainHandshake(inspector, this.logger, profile, this.drainSilenceMs);
6693
+ syncServer.setDrainHandler(async (request) => drain.handle(request), (request) => {
6694
+ drain.requestDropped(request);
6119
6695
  });
6120
6696
  syncServer.signalReady();
6121
6697
  this.logger.debug("Signaled preload script to proceed");
@@ -6134,13 +6710,14 @@ exit=%s timedOut=%s
6134
6710
  await inspector.close();
6135
6711
  this.logger.debug("Inspector collected %d tests in hierarchy, %d in execution order", testHierarchy.length, executionOrder.length);
6136
6712
  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));
6713
+ this.logger.debug("Post-drain inspector snapshot: %d found-id gap(s) remaining%s; drain handshake %s", finalGaps.length, formatGapIdList(finalGaps), drain.describe());
6138
6714
  const closeInfo = inspector.getCloseInfo();
6139
6715
  const collisionStats = inspector.getFoundIdCollisionStats();
6140
6716
  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
6717
  this.warnOnAbnormalDrainData({
6142
- drainSettleReason,
6143
- drainRejection,
6718
+ drainProven: drain.proven,
6719
+ drainSummary: drain.describe(),
6720
+ drainRejection: drain.rejection,
6144
6721
  finalGaps,
6145
6722
  duplicateFoundIdCount: collisionStats.duplicateFoundIdCount
6146
6723
  });
@@ -6150,7 +6727,7 @@ exit=%s timedOut=%s
6150
6727
  if (earlyResult) {
6151
6728
  return { result: earlyResult };
6152
6729
  }
6153
- return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, { wasClosedUnexpectedly, closeInfo, duplicateFoundIdCount: collisionStats.duplicateFoundIdCount }, { coverageAnalysis, imported: list, coverageFile }, { command: spawned.command, cwd, syncToken: syncServer.token }, profile);
6730
+ return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, { wasClosedUnexpectedly, closeInfo, duplicateFoundIdCount: collisionStats.duplicateFoundIdCount }, { coverageAnalysis, imported: list, coverageFile, handedIdsHeld: holdsAnyId(ctx.handed) }, { command: spawned.command, cwd, syncToken: syncServer.token }, profile);
6154
6731
  } finally {
6155
6732
  abortController.abort();
6156
6733
  if (this.currentAbortController === abortController) {
@@ -6189,12 +6766,12 @@ exit=%s timedOut=%s
6189
6766
  const outputLine = await this.saveFailedDryRunOutput(result, spawnInfo);
6190
6767
  return { result: this.completenessError(gateReasons, inspectorState.wasClosedUnexpectedly, inspectorState.closeInfo, outputLine) };
6191
6768
  }
6192
- const coverageResult = this.checkCoverageData(mutantCoverage, tests, run.coverageAnalysis, result.stderr, run.coverageFile);
6769
+ const coverageResult = this.checkCoverageData(mutantCoverage, tests, run, result.stderr);
6193
6770
  if (coverageResult) {
6194
6771
  return { result: coverageResult };
6195
6772
  }
6196
6773
  const off = run.coverageAnalysis === "off";
6197
- const complete = { status: DryRunStatus.Complete, tests };
6774
+ const complete = { status: DryRunStatus2.Complete, tests };
6198
6775
  if (mutantCoverage !== undefined && !off) {
6199
6776
  complete.mutantCoverage = run.coverageAnalysis === "all" ? reachedOnly(mutantCoverage) : mutantCoverage;
6200
6777
  }
@@ -6212,24 +6789,25 @@ exit=%s timedOut=%s
6212
6789
  }
6213
6790
  };
6214
6791
  }
6215
- checkCoverageData(coverage, tests, coverageAnalysis, stderr, coverageFile) {
6792
+ checkCoverageData(coverage, tests, run, stderr) {
6216
6793
  const preloadLines = extractPreloadCoverageDiagnostics(stderr);
6217
- if (coverage !== undefined || tests.some((t) => t.status === TestStatus.Failed)) {
6794
+ if (coverage !== undefined || tests.some((t) => t.status === TestStatus2.Failed)) {
6218
6795
  if (preloadLines.length > 0) {
6219
6796
  this.logger.warn(`The coverage preload reported problems on the dry-run child's stderr:
6220
6797
  %s`, preloadLines.join(`
6221
6798
  `));
6222
6799
  }
6223
- if (coverage !== undefined && coverageAnalysis !== "off" && !coversAnyMutant(coverage)) {
6224
- this.logger.warn("The dry run's coverage data shows no mutant covered by any test, per test or statically, so Stryker will report every mutant as NoCoverage. " + "Check that the mutate globs (%s) match the source files your tests import, and that the tests import those files rather than a built copy (e.g. dist/).", this.mutateGlobs.join(", ") || "(none)");
6800
+ if (!run.handedIdsHeld) {
6801
+ this.warnIfNoMutantCovered({ mutantCoverage: coverage }, run.coverageAnalysis);
6225
6802
  }
6226
6803
  return null;
6227
6804
  }
6805
+ const { coverageAnalysis, coverageFile } = run;
6228
6806
  return this.missingCoverageResult(coverageAnalysis, preloadLines, coverageFile);
6229
6807
  }
6230
6808
  missingCoverageResult(coverageAnalysis, preloadLines, coverageFile) {
6231
6809
  const file = coverageFile ?? "(none configured)";
6232
- const coverageDir = coverageFile === undefined ? tmpdir2() : path15.dirname(coverageFile);
6810
+ const coverageDir = coverageFile === undefined ? tmpdir2() : path16.dirname(coverageFile);
6233
6811
  const causes = "Likely causes: the coverage preload never ran (check for a [test].preload in bunfig.toml or bun.bunArgs that replaces or bypasses it), " + `${coverageDir} is not writable, or the bun test child exited before its final afterAll hook wrote the file (e.g. a test calls process.exit).`;
6234
6812
  const diagnostics = preloadLines.length > 0 ? [`Coverage preload diagnostics from the child's stderr:
6235
6813
  ${preloadLines.join(`
@@ -6249,7 +6827,7 @@ ${preloadLines.join(`
6249
6827
  ].join(" ");
6250
6828
  if (fails) {
6251
6829
  this.logger.error("%s", message);
6252
- return { status: DryRunStatus.Error, errorMessage: message };
6830
+ return { status: DryRunStatus2.Error, errorMessage: message };
6253
6831
  }
6254
6832
  this.logger.warn("%s", message);
6255
6833
  return null;
@@ -6304,7 +6882,7 @@ ${preloadLines.join(`
6304
6882
  return failure instanceof WriteFailure ? unpublishedCampaignMessage(failure.file, failure.message, watched) : unpublishedCampaignMessage("the run's temporary directory", errorText(failure), watched);
6305
6883
  }
6306
6884
  if (campaignInput !== undefined && failure instanceof WriteFailure) {
6307
- const registryPath = path15.join(path15.dirname(failure.file), REGISTRY_FILE);
6885
+ const registryPath = path16.join(path16.dirname(failure.file), REGISTRY_FILE);
6308
6886
  const earlier = await fsPromises3.lstat(registryPath).catch(() => {
6309
6887
  return;
6310
6888
  });
@@ -6317,7 +6895,7 @@ ${preloadLines.join(`
6317
6895
  }
6318
6896
  async writeRegistry(indexes, testFileCoverage, campaignInput) {
6319
6897
  const registryPath = await this.resolveRegistryPath();
6320
- const runDir = path15.dirname(registryPath);
6898
+ const runDir = path16.dirname(registryPath);
6321
6899
  const campaign = campaignInput === undefined ? undefined : await this.writeCampaignFiles(runDir, campaignInput);
6322
6900
  const tmpPath = `${registryPath}.tmp`;
6323
6901
  const registryData = JSON.stringify({
@@ -6338,14 +6916,14 @@ ${preloadLines.join(`
6338
6916
  await writingTo(registryPath, async () => fsPromises3.rename(tmpPath, registryPath));
6339
6917
  } catch (error) {
6340
6918
  if (campaign?.watchListFile) {
6341
- await removeQuietly(path15.join(runDir, campaign.watchListFile));
6919
+ await removeQuietly(path16.join(runDir, campaign.watchListFile));
6342
6920
  }
6343
6921
  throw error;
6344
6922
  }
6345
6923
  this.lastRegistryTmpPath = undefined;
6346
6924
  if (campaign !== undefined) {
6347
- await removeQuietly(path15.join(runDir, ABORT_MARKER_FILE));
6348
- this.campaign = { ...campaign, dir: runDir, watched: new Set(campaign.watchList) };
6925
+ await removeQuietly(path16.join(runDir, ABORT_MARKER_FILE));
6926
+ this.campaign = campaignOf(campaign, runDir);
6349
6927
  }
6350
6928
  this.logger.debug("Wrote dryRun registry to %s (%d entries)", registryPath, indexes.cachedTestNames.size);
6351
6929
  }
@@ -6357,10 +6935,11 @@ ${preloadLines.join(`
6357
6935
  generation,
6358
6936
  watchList: [...watched],
6359
6937
  watchListFile,
6938
+ handed: [...campaignInput.handed],
6360
6939
  fingerprint: watchListFile === null || !this.inPlace ? null : await campaignFingerprint(campaignInput.matched)
6361
6940
  };
6362
6941
  if (watchListFile !== null) {
6363
- const file = path15.join(runDir, watchListFile);
6942
+ const file = path16.join(runDir, watchListFile);
6364
6943
  await writingTo(file, async () => writeWatchList(file, watched));
6365
6944
  }
6366
6945
  return campaign;
@@ -6435,9 +7014,22 @@ ${preloadLines.join(`
6435
7014
  }
6436
7015
  return corrected.timeoutMs;
6437
7016
  }
7017
+ handedFileOf(options) {
7018
+ if (typeof options.sandboxFileName !== "string") {
7019
+ return;
7020
+ }
7021
+ const file = path16.resolve(options.sandboxFileName);
7022
+ return this.campaign?.handedFiles.has(file) === true ? file : undefined;
7023
+ }
7024
+ mutantRunGuards(options) {
7025
+ if (this.handedFileOf(options) !== undefined) {
7026
+ return { hitLimit: undefined, watchList: undefined };
7027
+ }
7028
+ return { hitLimit: options.hitLimit, watchList: this.watchListForMutantRuns() };
7029
+ }
6438
7030
  watchListForMutantRuns() {
6439
7031
  const { campaign } = this;
6440
- return campaign?.watchListFile ? path15.join(campaign.dir, campaign.watchListFile) : undefined;
7032
+ return campaign?.watchListFile ? path16.join(campaign.dir, campaign.watchListFile) : undefined;
6441
7033
  }
6442
7034
  async enforceWitness(stderr, hitLimitToken, ctx, testNamePattern) {
6443
7035
  const { campaign } = this;
@@ -6497,7 +7089,7 @@ ${preloadLines.join(`
6497
7089
  const cwd = process.cwd();
6498
7090
  const exist = await Promise.all(entries.map(async (entry) => {
6499
7091
  try {
6500
- const stat = await fsPromises3.stat(path15.resolve(cwd, entry));
7092
+ const stat = await fsPromises3.stat(path16.resolve(cwd, entry));
6501
7093
  return stat.isFile();
6502
7094
  } catch {
6503
7095
  return false;
@@ -6511,6 +7103,7 @@ ${preloadLines.join(`
6511
7103
  const abortController = new AbortController;
6512
7104
  this.currentAbortController = abortController;
6513
7105
  const hitLimitToken = newHitLimitToken();
7106
+ const guards = this.mutantRunGuards(options);
6514
7107
  const ordered = this.orderForMutantRun(ctx.testFileScope ?? (testNamePattern === undefined ? this.effectiveTestFiles : coveringTestFiles ?? this.effectiveTestFiles), ctx);
6515
7108
  const testFiles = this.fitTestFiles(ordered, ctx.testFileScope === undefined ? this.explicitTestFilesSource(process.cwd()) : "Stryker's testFiles option");
6516
7109
  ctx.profile?.setScope(mutantRunScope(ctx.testFileScope !== undefined, testNamePattern, ctx.coveringTestCount));
@@ -6523,9 +7116,9 @@ ${preloadLines.join(`
6523
7116
  bunArgs: this.mutantBunArgs,
6524
7117
  bunfigPath,
6525
7118
  activeMutant: options.activeMutant.id,
6526
- hitLimit: options.hitLimit,
7119
+ hitLimit: guards.hitLimit,
6527
7120
  hitLimitToken,
6528
- watchList: this.watchListForMutantRuns(),
7121
+ watchList: guards.watchList,
6529
7122
  bail: !options.disableBail,
6530
7123
  sequentialMode: true,
6531
7124
  preloadScript: this.preloadScriptPath,
@@ -6687,11 +7280,11 @@ ${result.stderr}`).trim().slice(-500) || "(no output)";
6687
7280
  if (result.memoryLimitExceeded !== true) {
6688
7281
  this.logger.warn("Dry run timed out: bun.timeout is %dms, and the dry-run child was killed at its %dms limit (bun.timeout plus the drain-handshake allowance) — raise bun.timeout above your full suite's run time", this.timeout, this.timeout + DRAIN_ACK_ABSOLUTE_CEILING_MS);
6689
7282
  }
6690
- return { status: DryRunStatus.Timeout };
7283
+ return { status: DryRunStatus2.Timeout };
6691
7284
  }
6692
7285
  if (result.spawnError !== undefined) {
6693
7286
  return {
6694
- status: DryRunStatus.Error,
7287
+ status: DryRunStatus2.Error,
6695
7288
  errorMessage: `${formatSpawnErrorMessage(result.spawnError)}
6696
7289
  ${cleanDiagnosticText(result.stderr, secrets)}`
6697
7290
  };
@@ -6704,7 +7297,7 @@ ${cleanDiagnosticText(result.stderr, secrets)}`
6704
7297
  }
6705
7298
  messageParts.push(cleanDiagnosticText(result.stderr, secrets));
6706
7299
  return {
6707
- status: DryRunStatus.Error,
7300
+ status: DryRunStatus2.Error,
6708
7301
  errorMessage: messageParts.join(`
6709
7302
  `)
6710
7303
  };
@@ -6738,7 +7331,7 @@ ${lines.join(`
6738
7331
  `)}`;
6739
7332
  }
6740
7333
  warnOnUnidentifiedDryRunFailure(result, parsed, tests) {
6741
- if (parsed.failed > 0 && !tests.some((t) => t.status === TestStatus.Failed)) {
7334
+ if (parsed.failed > 0 && !tests.some((t) => t.status === TestStatus2.Failed)) {
6742
7335
  this.logger.warn("Bun exited with code %s and its console output reported %d failed test(s), " + "but no failing test could be identified from inspector or console data. " + "An unhandled error firing between tests (e.g. a rejected fire-and-forget " + `promise) is a likely cause. Last 500 chars of stderr:
6743
7336
  %s`, String(result.exitCode), parsed.failed, result.stderr.slice(-500));
6744
7337
  }
@@ -6783,7 +7376,7 @@ ${lines.join(`
6783
7376
  }
6784
7377
  }
6785
7378
  findCompletenessProblems(facts, summaryFailed, tests, stderr, eagerModules, secrets = []) {
6786
- if (tests.some((t) => t.status === TestStatus.Failed)) {
7379
+ if (tests.some((t) => t.status === TestStatus2.Failed)) {
6787
7380
  return [];
6788
7381
  }
6789
7382
  const reasons = findDryRunDataLoss(facts);
@@ -6810,7 +7403,7 @@ ${cleanDiagnosticText(stderr, secrets).slice(-500)}`);
6810
7403
  ${outputLine}`;
6811
7404
  this.logger.error("%s", errorMessage);
6812
7405
  return {
6813
- status: DryRunStatus.Error,
7406
+ status: DryRunStatus2.Error,
6814
7407
  errorMessage
6815
7408
  };
6816
7409
  }
@@ -6964,7 +7557,7 @@ ${outputLine}`;
6964
7557
  // src/checker-tsconfig.ts
6965
7558
  import { readFile as readFile7, rename as rename4, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
6966
7559
  import { createRequire as createRequire2 } from "node:module";
6967
- import path16 from "node:path";
7560
+ import path17 from "node:path";
6968
7561
  import { glob as glob2 } from "tinyglobby";
6969
7562
  var DEFAULT_MUTATE_PATTERNS = ["{src,lib}/**"];
6970
7563
  var MUTATION_RANGE_RE = /:\d+(?::\d+)?-\d+(?::\d+)?$/;
@@ -6972,11 +7565,37 @@ var DERIVED_SUFFIX = ".stryker-checker.json";
6972
7565
  var GENERATED_MARKER = "// Generated by withTestFilesExcludedFromTypeCheck()";
6973
7566
  var LOG_PREFIX = "[Stryker] withTestFilesExcludedFromTypeCheck: ";
6974
7567
  var MAX_QUOTED_ERRORS = 3;
7568
+ var COMPILER_API = [
7569
+ "createProgram",
7570
+ "formatDiagnostic",
7571
+ "getParsedCommandLineOfConfigFile",
7572
+ "isExternalModule",
7573
+ "isModuleDeclaration",
7574
+ "isStringLiteral",
7575
+ "parseJsonSourceFileConfigFileContent",
7576
+ "parseJsonText",
7577
+ "preProcessFile",
7578
+ "resolveModuleName"
7579
+ ];
7580
+ function cannotLoad(cwd) {
7581
+ return { problem: `typescript cannot be loaded from ${cwd}; install it there` };
7582
+ }
7583
+ function checkTypeScript(exported, cwd) {
7584
+ const candidate = exported;
7585
+ if (COMPILER_API.every((name) => typeof candidate?.[name] === "function")) {
7586
+ return { ts: exported };
7587
+ }
7588
+ const version = String(candidate?.version);
7589
+ if (Number.parseInt(version, 10) >= 7) {
7590
+ return { problem: `typescript ${version} in ${cwd} is TypeScript 7 or later, which has no compiler API to read the tsconfig with, so the config is left as it is; install typescript 6 or earlier, which Stryker needs too (TypeScript 7 can go beside it as @typescript/native)` };
7591
+ }
7592
+ return cannotLoad(cwd);
7593
+ }
6975
7594
  function loadTypeScript(cwd) {
6976
7595
  try {
6977
- return createRequire2(path16.join(cwd, "package.json"))("typescript");
7596
+ return checkTypeScript(createRequire2(path17.join(cwd, "package.json"))("typescript"), cwd);
6978
7597
  } catch {
6979
- return;
7598
+ return cannotLoad(cwd);
6980
7599
  }
6981
7600
  }
6982
7601
  function readProject(ts, tsconfigPath, shown) {
@@ -7001,7 +7620,7 @@ async function findTestFiles(config, cwd) {
7001
7620
  for (const relativeFiles of [await discoverTestFiles(cwd, undefined, sourceBunfig), bun.testFiles]) {
7002
7621
  if (relativeFiles) {
7003
7622
  for (const file of relativeFiles) {
7004
- testFiles.add(path16.resolve(cwd, file));
7623
+ testFiles.add(path17.resolve(cwd, file));
7005
7624
  }
7006
7625
  }
7007
7626
  }
@@ -7079,12 +7698,12 @@ function derivedHeader(source) {
7079
7698
  `);
7080
7699
  }
7081
7700
  function renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints) {
7082
- const source = path16.basename(sourcePath);
7701
+ const source = path17.basename(sourcePath);
7083
7702
  const body = {
7084
7703
  extends: `./${source}`,
7085
7704
  ...project.options.declarationDir !== undefined && { compilerOptions: { declarationDir: null } },
7086
7705
  include: [],
7087
- files: entryPoints.map((file) => path16.relative(path16.dirname(derivedPath), file))
7706
+ files: entryPoints.map((file) => path17.relative(path17.dirname(derivedPath), file))
7088
7707
  };
7089
7708
  return `${derivedHeader(source)}${JSON.stringify(body, null, 2)}
7090
7709
  `;
@@ -7094,12 +7713,13 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
7094
7713
  console.info(`${LOG_PREFIX}not applied: the config's checkers do not include 'typescript'`);
7095
7714
  return config;
7096
7715
  }
7097
- const ts = loadTypeScript(cwd);
7098
- if (!ts) {
7099
- return leaveUnchanged(config, `typescript cannot be loaded from ${cwd}; install it there`);
7716
+ const loaded = loadTypeScript(cwd);
7717
+ if ("problem" in loaded) {
7718
+ return leaveUnchanged(config, loaded.problem);
7100
7719
  }
7101
- const sourcePath = path16.resolve(cwd, config.tsconfigFile ?? "tsconfig.json");
7102
- const shownSource = path16.relative(cwd, sourcePath);
7720
+ const { ts } = loaded;
7721
+ const sourcePath = path17.resolve(cwd, config.tsconfigFile ?? "tsconfig.json");
7722
+ const shownSource = path17.relative(cwd, sourcePath);
7103
7723
  const read = readProject(ts, sourcePath, shownSource);
7104
7724
  if ("problem" in read) {
7105
7725
  return leaveUnchanged(config, read.problem);
@@ -7116,10 +7736,10 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
7116
7736
  if (entryPoints.length === 0) {
7117
7737
  return leaveUnchanged(config, `${shownSource} would have no files left once test files are excluded`);
7118
7738
  }
7119
- const derivedPath = path16.join(path16.dirname(sourcePath), `${path16.basename(sourcePath, ".json")}${DERIVED_SUFFIX}`);
7120
- const shownDerived = path16.relative(cwd, derivedPath);
7739
+ const derivedPath = path17.join(path17.dirname(sourcePath), `${path17.basename(sourcePath, ".json")}${DERIVED_SUFFIX}`);
7740
+ const shownDerived = path17.relative(cwd, derivedPath);
7121
7741
  const text = renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints);
7122
- const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys, path16.dirname(derivedPath), undefined, derivedPath);
7742
+ const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys, path17.dirname(derivedPath), undefined, derivedPath);
7123
7743
  const derived = createProgram(ts, derivedProject, original);
7124
7744
  const newErrors = findNewErrors(derived, original, testFiles);
7125
7745
  if (newErrors.length > 0) {