@hughescr/stryker-bun-runner 1.3.1 → 1.3.3

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
@@ -5540,7 +5540,7 @@ function mergeCoverageData(dataList) {
5540
5540
  merged.static = [...staticSet];
5541
5541
  return merged;
5542
5542
  }
5543
- async function collectCoverage(coverageFile, logger) {
5543
+ async function readCoverageFileData(coverageFile, logger) {
5544
5544
  try {
5545
5545
  const content = await readFile2(coverageFile, "utf8");
5546
5546
  const trimmed = content.trim();
@@ -5556,6 +5556,14 @@ async function collectCoverage(coverageFile, logger) {
5556
5556
  logger?.warn("[Stryker Coverage] Failed to parse coverage line: %s", errorMsg);
5557
5557
  }
5558
5558
  }
5559
+ return dataList;
5560
+ } catch {
5561
+ return [];
5562
+ }
5563
+ }
5564
+ async function collectCoverage(coverageFile, logger) {
5565
+ try {
5566
+ const dataList = await readCoverageFileData(coverageFile, logger);
5559
5567
  if (dataList.length === 0) {
5560
5568
  return;
5561
5569
  }
@@ -5573,12 +5581,41 @@ async function collectCoverage(coverageFile, logger) {
5573
5581
  return;
5574
5582
  }
5575
5583
  }
5584
+ async function collectLateHits(coverageFile, logger) {
5585
+ const dataList = await readCoverageFileData(coverageFile, logger);
5586
+ return dataList.flatMap((data) => data.lateHits ?? []);
5587
+ }
5576
5588
  async function cleanupCoverageFile(coverageFile) {
5577
5589
  try {
5578
5590
  await unlink2(coverageFile);
5579
5591
  } catch {}
5580
5592
  }
5581
5593
 
5594
+ // src/utils/duplicate-suffix.ts
5595
+ function buildDiscoveryOrderIndex(discoveryOrderedIds) {
5596
+ const index = new Map;
5597
+ let i = 0;
5598
+ for (const id of discoveryOrderedIds) {
5599
+ index.set(id, i);
5600
+ i++;
5601
+ }
5602
+ return index;
5603
+ }
5604
+ function sortDuplicateGroupByLineThenDiscovery(group, getLine, getInspectorId, discoveryOrderIndex) {
5605
+ return group.toSorted((a, b) => {
5606
+ const lineA = getLine(a) ?? Infinity;
5607
+ const lineB = getLine(b) ?? Infinity;
5608
+ if (lineA !== lineB) {
5609
+ return lineA - lineB;
5610
+ }
5611
+ const idA = getInspectorId(a);
5612
+ const idB = getInspectorId(b);
5613
+ const discA = idA === undefined ? Infinity : discoveryOrderIndex.get(idA) ?? Infinity;
5614
+ const discB = idB === undefined ? Infinity : discoveryOrderIndex.get(idB) ?? Infinity;
5615
+ return discA - discB;
5616
+ });
5617
+ }
5618
+
5582
5619
  // src/utils/test-name.ts
5583
5620
  function normalizeTestFilePath(url) {
5584
5621
  if (!url) {
@@ -5607,16 +5644,34 @@ function buildUniqueTestName(fullName, url) {
5607
5644
  // src/coverage/coverage-mapper.ts
5608
5645
  function mapCoverageToInspectorIds(rawCoverage, executionOrder, testHierarchy, logger) {
5609
5646
  if (!rawCoverage?.perTest || Object.keys(rawCoverage.perTest).length === 0) {
5610
- return { coverage: rawCoverage ?? undefined, inspectorIdToProjectFile: new Map };
5647
+ return {
5648
+ coverage: rawCoverage ?? undefined,
5649
+ inspectorIdToProjectFile: new Map,
5650
+ counterKeyToTestName: new Map,
5651
+ rawKeyCount: 0,
5652
+ orphanedKeyCount: 0
5653
+ };
5611
5654
  }
5612
5655
  const firstKey = Object.keys(rawCoverage.perTest)[0];
5613
5656
  if (/@@test-\d+$/.test(firstKey)) {
5614
5657
  return mapFilePrefixedCounterKeys(rawCoverage, executionOrder, testHierarchy, logger);
5615
5658
  }
5616
5659
  if (/^test-\d+$/.test(firstKey)) {
5617
- return { coverage: mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger), inspectorIdToProjectFile: new Map };
5660
+ return {
5661
+ coverage: mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger),
5662
+ inspectorIdToProjectFile: new Map,
5663
+ counterKeyToTestName: new Map,
5664
+ rawKeyCount: Object.keys(rawCoverage.perTest).length,
5665
+ orphanedKeyCount: 0
5666
+ };
5618
5667
  }
5619
- return { coverage: rawCoverage, inspectorIdToProjectFile: new Map };
5668
+ return {
5669
+ coverage: rawCoverage,
5670
+ inspectorIdToProjectFile: new Map,
5671
+ counterKeyToTestName: new Map,
5672
+ rawKeyCount: Object.keys(rawCoverage.perTest).length,
5673
+ orphanedKeyCount: 0
5674
+ };
5620
5675
  }
5621
5676
  function buildFilteredPerTest(perTestEntries, staticIds) {
5622
5677
  const newPerTest = {};
@@ -5672,7 +5727,7 @@ function resolveCounterKeys(counterIds, fileToInspectorIds, testHierarchy, logge
5672
5727
  const testName = buildProjectFileTestName(filePrefix, testInfo.fullName);
5673
5728
  return { name: testName, testInfo, inspectorId };
5674
5729
  }
5675
- logger?.warn('Coverage key %s: no inspector test found for file "%s" at position %s ' + "(file has %s tests in execution order). Skipping this test in coverage mapping.", key, filePrefix, n, fileToInspectorIds.get(filePrefix)?.length ?? 0);
5730
+ logger?.debug('Coverage key %s: no inspector test found for file "%s" at position %s ' + "(file has %s tests in execution order). Skipping this test in coverage mapping.", key, filePrefix, n, fileToInspectorIds.get(filePrefix)?.length ?? 0);
5676
5731
  return { name: `unknown-${key}`, testInfo: null, inspectorId: undefined };
5677
5732
  });
5678
5733
  }
@@ -5691,31 +5746,40 @@ function buildNameInspectorIds(resolved) {
5691
5746
  }
5692
5747
  return nameInspectorIds;
5693
5748
  }
5694
- function resolveEachTestName(baseName, inspectorId, nameInspectorIds, nameIndexes) {
5749
+ function buildDuplicateNameIndex(nameInspectorIds, testHierarchy) {
5750
+ const discoveryOrderIndex = buildDiscoveryOrderIndex(testHierarchy.keys());
5751
+ const indexByKey = new Map;
5752
+ for (const [baseName, ids] of nameInspectorIds) {
5753
+ if (ids.size <= 1) {
5754
+ continue;
5755
+ }
5756
+ const group = [...ids].filter((id) => id !== undefined);
5757
+ const sorted = sortDuplicateGroupByLineThenDiscovery(group, (id) => testHierarchy.get(id)?.line, (id) => id, discoveryOrderIndex);
5758
+ for (const [i, id] of sorted.entries()) {
5759
+ indexByKey.set(`${id}/${baseName}`, i);
5760
+ }
5761
+ }
5762
+ return indexByKey;
5763
+ }
5764
+ function resolveEachTestName(baseName, inspectorId, nameInspectorIds, duplicateNameIndex) {
5695
5765
  const distinctIds = nameInspectorIds.get(baseName);
5696
5766
  if ((distinctIds?.size ?? 1) <= 1) {
5697
5767
  return baseName;
5698
5768
  }
5699
5769
  const key_ = `${inspectorId}/${baseName}`;
5700
- const existingIndex = nameIndexes.get(key_);
5701
- if (existingIndex === undefined) {
5702
- const nextIndex = nameIndexes.get(baseName) ?? 0;
5703
- nameIndexes.set(key_, nextIndex);
5704
- nameIndexes.set(baseName, nextIndex + 1);
5705
- return `${baseName} [${nextIndex}]`;
5706
- }
5707
- return `${baseName} [${existingIndex}]`;
5770
+ const index = duplicateNameIndex.get(key_) ?? 0;
5771
+ return `${baseName} [${index}]`;
5708
5772
  }
5709
- function buildRemappedPerTest(counterIds, resolved, rawPerTest) {
5773
+ function buildRemappedPerTest(counterIds, resolved, rawPerTest, testHierarchy) {
5710
5774
  const nameInspectorIds = buildNameInspectorIds(resolved);
5775
+ const duplicateNameIndex = buildDuplicateNameIndex(nameInspectorIds, testHierarchy);
5711
5776
  const remappedPerTest = {};
5712
- const nameIndexes = new Map;
5713
5777
  for (const [i, key] of counterIds.entries()) {
5714
5778
  const { name: baseName, testInfo, inspectorId } = resolved[i];
5715
5779
  if (!testInfo) {
5716
5780
  continue;
5717
5781
  }
5718
- const finalName = resolveEachTestName(baseName, inspectorId, nameInspectorIds, nameIndexes);
5782
+ const finalName = resolveEachTestName(baseName, inspectorId, nameInspectorIds, duplicateNameIndex);
5719
5783
  const incoming = rawPerTest[key];
5720
5784
  const existing = remappedPerTest[finalName];
5721
5785
  if (existing) {
@@ -5745,6 +5809,25 @@ function warnInteriorGapIfPresent(pairs, testHierarchy, logger) {
5745
5809
  }
5746
5810
  }
5747
5811
  }
5812
+ function reportOrphanedKeys(resolved, counterIds, logger) {
5813
+ const orphanedIndexes = [];
5814
+ for (const [i, r] of resolved.entries()) {
5815
+ if (!r.testInfo) {
5816
+ orphanedIndexes.push(i);
5817
+ }
5818
+ }
5819
+ const orphanedKeyCount = orphanedIndexes.length;
5820
+ if (orphanedKeyCount > 0) {
5821
+ const orphanedFiles = new Set;
5822
+ for (const i of orphanedIndexes) {
5823
+ const key = counterIds[i];
5824
+ const sepIdx = key.indexOf("@@");
5825
+ orphanedFiles.add(sepIdx === -1 ? key : key.slice(0, sepIdx));
5826
+ }
5827
+ logger?.warn("%s of %s coverage key(s) across %s file(s) could not be paired with any inspector test " + "(orphaned — see per-key detail at debug level). This can indicate the Bun inspector " + "stream was truncated mid-run.", orphanedKeyCount, counterIds.length, orphanedFiles.size);
5828
+ }
5829
+ return orphanedKeyCount;
5830
+ }
5748
5831
  function mapFilePrefixedCounterKeys(rawCoverage, executionOrder, testHierarchy, logger) {
5749
5832
  const globallyOrderedKeys = Object.keys(rawCoverage.perTest);
5750
5833
  const pairs = pairKeysWithInspectorIds(globallyOrderedKeys, executionOrder, testHierarchy, logger);
@@ -5768,12 +5851,25 @@ function mapFilePrefixedCounterKeys(rawCoverage, executionOrder, testHierarchy,
5768
5851
  return nA - nB;
5769
5852
  });
5770
5853
  const resolved = resolveCounterKeys(counterIds, fileToInspectorIds, testHierarchy, logger);
5771
- const remappedPerTest = buildRemappedPerTest(counterIds, resolved, rawCoverage.perTest);
5854
+ const remappedPerTest = buildRemappedPerTest(counterIds, resolved, rawCoverage.perTest, testHierarchy);
5855
+ const counterKeyToTestName = new Map;
5856
+ for (const [i, key] of counterIds.entries()) {
5857
+ if (resolved[i].testInfo) {
5858
+ counterKeyToTestName.set(key, resolved[i].name);
5859
+ }
5860
+ }
5861
+ const orphanedKeyCount = reportOrphanedKeys(resolved, counterIds, logger);
5772
5862
  const coverage = stabilizeCoverage({
5773
5863
  static: rawCoverage.static,
5774
5864
  perTest: remappedPerTest
5775
5865
  });
5776
- return { coverage, inspectorIdToProjectFile };
5866
+ return {
5867
+ coverage,
5868
+ inspectorIdToProjectFile,
5869
+ counterKeyToTestName,
5870
+ rawKeyCount: counterIds.length,
5871
+ orphanedKeyCount
5872
+ };
5777
5873
  }
5778
5874
  function mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger) {
5779
5875
  const counterIds = Object.keys(rawCoverage.perTest).toSorted((a, b) => Number.parseInt(a.split("-")[1] ?? "0", 10) - Number.parseInt(b.split("-")[1] ?? "0", 10));
@@ -5868,6 +5964,10 @@ class InspectorClient {
5868
5964
  state;
5869
5965
  isClosing = false;
5870
5966
  WebSocketClass;
5967
+ closeExpected = false;
5968
+ wsClosed = false;
5969
+ _wasClosedUnexpectedly = false;
5970
+ closeWaiters = [];
5871
5971
  constructor(options) {
5872
5972
  this.handlers = options.handlers ?? {};
5873
5973
  this.WebSocketClass = options.WebSocketClass ?? wrapper_default;
@@ -5946,6 +6046,37 @@ class InspectorClient {
5946
6046
  }
5947
6047
  this.ws = null;
5948
6048
  }
6049
+ expectClose() {
6050
+ this.closeExpected = true;
6051
+ }
6052
+ get wasClosedUnexpectedly() {
6053
+ return this._wasClosedUnexpectedly;
6054
+ }
6055
+ async waitForClose(timeoutMs) {
6056
+ if (this.wsClosed || !this.ws) {
6057
+ return;
6058
+ }
6059
+ return new Promise((resolve3) => {
6060
+ let settled = false;
6061
+ let timer;
6062
+ const finish = () => {
6063
+ if (settled) {
6064
+ return;
6065
+ }
6066
+ settled = true;
6067
+ clearTimeout(timer);
6068
+ const idx = this.closeWaiters.indexOf(finish);
6069
+ if (idx !== -1) {
6070
+ this.closeWaiters.splice(idx, 1);
6071
+ }
6072
+ resolve3();
6073
+ };
6074
+ timer = setTimeout(() => {
6075
+ finish();
6076
+ }, timeoutMs);
6077
+ this.closeWaiters.push(finish);
6078
+ });
6079
+ }
5949
6080
  getTests() {
5950
6081
  return [...this.testHierarchy.values()];
5951
6082
  }
@@ -5983,11 +6114,12 @@ class InspectorClient {
5983
6114
  }
5984
6115
  }
5985
6116
  handleTestFound(params) {
5986
- const fullName = this.buildFullName(params.id, params.name, params.parentId);
6117
+ const { fullName, bunName } = this.buildFullName(params.id, params.name, params.parentId);
5987
6118
  const testInfo = {
5988
6119
  id: params.id,
5989
6120
  name: params.name,
5990
6121
  fullName,
6122
+ bunName,
5991
6123
  type: params.type,
5992
6124
  parentId: params.parentId,
5993
6125
  url: params.url,
@@ -6028,7 +6160,7 @@ class InspectorClient {
6028
6160
  }
6029
6161
  buildFullName(id, name, parentId) {
6030
6162
  if (parentId === undefined) {
6031
- return name;
6163
+ return { fullName: name, bunName: name };
6032
6164
  }
6033
6165
  const parts = [name];
6034
6166
  const visited = new Set([id]);
@@ -6046,12 +6178,19 @@ class InspectorClient {
6046
6178
  parts.unshift(parent.name);
6047
6179
  currentId = parent.parentId;
6048
6180
  }
6049
- return parts.join(" > ");
6181
+ return { fullName: parts.join(" > "), bunName: parts.join(" ") };
6050
6182
  }
6051
6183
  handleClose() {
6052
- if (this.isClosing) {
6184
+ this.wsClosed = true;
6185
+ const waiters = this.closeWaiters;
6186
+ this.closeWaiters = [];
6187
+ for (const finish of waiters) {
6188
+ finish();
6189
+ }
6190
+ if (this.isClosing || this.closeExpected) {
6053
6191
  return;
6054
6192
  }
6193
+ this._wasClosedUnexpectedly = true;
6055
6194
  const error = new InspectorConnectionError("Connection closed unexpectedly");
6056
6195
  for (const pending of this.pendingRequests.values()) {
6057
6196
  clearTimeout(pending.timer);
@@ -6164,6 +6303,8 @@ function parseSummaryLines(output) {
6164
6303
  if (bailSummary) {
6165
6304
  counts.failed = Math.max(counts.failed, Number.parseInt(bailSummary[1], 10));
6166
6305
  }
6306
+ const genuinePassed = counts.passed;
6307
+ const genuineFailed = counts.failed;
6167
6308
  const ranTestsSummary = /Ran\s+(\d+)\s+tests?/.exec(output);
6168
6309
  if (ranTestsSummary) {
6169
6310
  const totalFromRan = Number.parseInt(ranTestsSummary[1], 10);
@@ -6172,7 +6313,7 @@ function parseSummaryLines(output) {
6172
6313
  counts.passed = totalFromRan;
6173
6314
  }
6174
6315
  }
6175
- return counts;
6316
+ return { ...counts, genuinePassed, genuineFailed };
6176
6317
  }
6177
6318
  function parseBunTestOutput(stdout, stderr) {
6178
6319
  const tests = [];
@@ -6218,7 +6359,10 @@ ${stderr}`;
6218
6359
  totalTests: counters.passed + counters.failed + counters.skipped,
6219
6360
  passed: counters.passed,
6220
6361
  failed: counters.failed,
6221
- skipped: counters.skipped
6362
+ skipped: counters.skipped,
6363
+ summaryPassed: summaryCounts.genuinePassed,
6364
+ summaryFailed: summaryCounts.genuineFailed,
6365
+ summarySkipped: summaryCounts.skipped
6222
6366
  };
6223
6367
  }
6224
6368
 
@@ -6300,7 +6444,7 @@ function killWithEscalation(childProcess, isClosed, gracePeriodMs) {
6300
6444
  async function runBunTests(options) {
6301
6445
  const args = ["test"];
6302
6446
  if (options.inspectWaitPort) {
6303
- args.push(`--inspect=${options.inspectWaitPort}`);
6447
+ args.push(`--inspect=127.0.0.1:${options.inspectWaitPort}`);
6304
6448
  }
6305
6449
  if (options.bunfigPath) {
6306
6450
  args.push(`--config=${options.bunfigPath}`);
@@ -7732,20 +7876,28 @@ async function cleanupSanitizedBunfig(filePath) {
7732
7876
  }
7733
7877
  // src/utils/test-name-pattern.ts
7734
7878
  var MAX_TEST_NAME_PATTERN_LENGTH = 1e5;
7735
- function buildTestNamePattern(testFilter) {
7879
+ var fileExtRe = /\.(?:test|spec)\.(?:[jt]sx?|m[jt]s)$/;
7880
+ var dedupSuffixRe = / \[\d+\]$/;
7881
+ var metaRe = /[.*+?^${}()|[\]\\/]/g;
7882
+ function escapeRegex(str) {
7883
+ return str.replaceAll(metaRe, String.raw`\$&`);
7884
+ }
7885
+ function buildTestNamePattern(testFilter, testNameIndex) {
7736
7886
  if (testFilter.length === 0) {
7737
7887
  return;
7738
7888
  }
7739
- const fileExtRe = /\.(?:test|spec)\.(?:[jt]sx?|m[jt]s)$/;
7740
- const dedupSuffixRe = / \[\d+\]$/;
7741
- const metaRe = /[.*+?^${}()|[\]\\/]/g;
7742
7889
  const alternatives = new Set;
7743
7890
  for (const id of testFilter) {
7891
+ const exact = testNameIndex?.get(id);
7892
+ if (exact !== undefined && exact.length > 0 && !exact.includes("\x00")) {
7893
+ alternatives.add(escapeRegex(exact));
7894
+ continue;
7895
+ }
7744
7896
  const firstSepIdx = id.indexOf(" > ");
7745
7897
  let name = firstSepIdx !== -1 && fileExtRe.test(id.slice(0, firstSepIdx)) ? id.slice(firstSepIdx + 3) : id;
7746
7898
  name = name.replace(dedupSuffixRe, "");
7747
7899
  name = name.replaceAll(" > ", " ");
7748
- name = name.replaceAll(metaRe, String.raw`\$&`);
7900
+ name = escapeRegex(name);
7749
7901
  if (name.length > 0) {
7750
7902
  alternatives.add(name);
7751
7903
  }
@@ -7868,6 +8020,23 @@ function sleep(ms) {
7868
8020
  setTimeout(resolve3, ms);
7869
8021
  });
7870
8022
  }
8023
+ function buildTestNameIndex(tests, bunNames) {
8024
+ const testNameIndex = new Map;
8025
+ for (const [i, test] of tests.entries()) {
8026
+ const bunName = bunNames[i];
8027
+ if (bunName !== undefined) {
8028
+ testNameIndex.set(test.id, bunName);
8029
+ }
8030
+ }
8031
+ return testNameIndex;
8032
+ }
8033
+ var ZERO_MATCH_TEST_PATTERN_RE = /matched 0 tests\./;
8034
+ var MAX_DRY_RUN_FAILURE_TESTS_LISTED = 20;
8035
+ var MAX_COVERAGE_BLEED_WARNINGS = 25;
8036
+ var EXECUTION_SHORTFALL_ABS_FLOOR = 10;
8037
+ var EXECUTION_SHORTFALL_RATIO_THRESHOLD = 0.05;
8038
+ var ORPHANED_KEY_ABS_FLOOR = 5;
8039
+ var INSPECTOR_DRAIN_TIMEOUT_MS = 1000;
7871
8040
 
7872
8041
  class BunTestRunner {
7873
8042
  logger;
@@ -7889,6 +8058,7 @@ class BunTestRunner {
7889
8058
  tempDir;
7890
8059
  cachedTestNames;
7891
8060
  baseNameIndex;
8061
+ testNameIndex;
7892
8062
  cachedTestFiles;
7893
8063
  cachedTestFilesCwd;
7894
8064
  cachedEagerModules;
@@ -8015,16 +8185,21 @@ class BunTestRunner {
8015
8185
  try {
8016
8186
  const raw = await fsPromises2.readFile(registryPath, "utf8");
8017
8187
  const parsed = JSON.parse(raw);
8018
- if (parsed.version !== 1) {
8188
+ if (parsed.version !== 2) {
8019
8189
  this.logger.warn("dryRun registry file has unexpected version %s; skipping", String(parsed.version));
8020
8190
  return;
8021
8191
  }
8022
- if (!Array.isArray(parsed.cachedTestNames) || !Array.isArray(parsed.baseNameIndex)) {
8023
- this.logger.warn("dryRun registry file is malformed (cachedTestNames or baseNameIndex missing or not an array); treating as absent");
8192
+ if (!Array.isArray(parsed.cachedTestNames) || !Array.isArray(parsed.baseNameIndex) || !Array.isArray(parsed.testNameIndex)) {
8193
+ this.logger.warn("dryRun registry file is malformed (cachedTestNames, baseNameIndex, or testNameIndex missing or not an array); treating as absent");
8194
+ return;
8195
+ }
8196
+ if (!parsed.testNameIndex.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && typeof entry[1] === "string")) {
8197
+ this.logger.warn("dryRun registry file is malformed (testNameIndex entry is not a [string, string] pair); treating as absent");
8024
8198
  return;
8025
8199
  }
8026
8200
  this.cachedTestNames = new Set(parsed.cachedTestNames);
8027
8201
  this.baseNameIndex = new Map(parsed.baseNameIndex);
8202
+ this.testNameIndex = new Map(parsed.testNameIndex);
8028
8203
  this.logger.debug("Loaded dryRun registry from %s (%d entries)", registryPath, this.cachedTestNames.size);
8029
8204
  } catch (err) {
8030
8205
  const code = err.code;
@@ -8035,9 +8210,16 @@ class BunTestRunner {
8035
8210
  }
8036
8211
  }
8037
8212
  }
8213
+ buildFailureMessage(testInfo, parsed) {
8214
+ const parsedTest = parsed.tests.find((t) => t.name.includes(testInfo.name));
8215
+ const baseFailureMessage = parsedTest?.failureMessage ?? testInfo.error?.message ?? "Test failed";
8216
+ const stack = testInfo.error?.stack;
8217
+ return stack && !baseFailureMessage.includes(stack) ? `${baseFailureMessage}
8218
+ ${stack}` : baseFailureMessage;
8219
+ }
8038
8220
  buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile) {
8039
8221
  if (executionOrder.length === 0) {
8040
- return parsed.tests.map((t) => {
8222
+ const fallbackTests = parsed.tests.map((t) => {
8041
8223
  const normalizedName = normalizeTestName(t.name);
8042
8224
  if (t.status === "failed") {
8043
8225
  return {
@@ -8063,12 +8245,14 @@ class BunTestRunner {
8063
8245
  timeSpentMs: Math.round(t.duration ?? 1)
8064
8246
  };
8065
8247
  });
8248
+ return { tests: fallbackTests, testNameIndex: new Map };
8066
8249
  }
8067
8250
  const timePerTest = executionOrder.length > 0 ? Math.max(1, Math.round(totalElapsedMs / executionOrder.length)) : 1;
8068
8251
  const testMap = new Map;
8069
8252
  for (const test of testHierarchy) {
8070
8253
  testMap.set(test.id, test);
8071
8254
  }
8255
+ const bunNames = executionOrder.map((inspectorId) => testMap.get(inspectorId)?.bunName);
8072
8256
  const tests = executionOrder.map((inspectorId) => {
8073
8257
  const testInfo = testMap.get(inspectorId);
8074
8258
  if (!testInfo) {
@@ -8086,14 +8270,13 @@ class BunTestRunner {
8086
8270
  const elapsed = testInfo.elapsed === undefined ? timePerTest : Math.round(testInfo.elapsed / 1e6);
8087
8271
  const startPosition = testInfo.line === undefined ? undefined : { line: testInfo.line, column: 0 };
8088
8272
  if (status === "fail") {
8089
- const parsedTest = parsed.tests.find((t) => t.name.includes(testInfo.name));
8090
8273
  return {
8091
8274
  id: uniqueName,
8092
8275
  name: uniqueName,
8093
8276
  fileName,
8094
8277
  startPosition,
8095
8278
  status: TestStatus.Failed,
8096
- failureMessage: parsedTest?.failureMessage ?? testInfo.error?.message ?? "Test failed",
8279
+ failureMessage: this.buildFailureMessage(testInfo, parsed),
8097
8280
  timeSpentMs: elapsed
8098
8281
  };
8099
8282
  }
@@ -8116,34 +8299,32 @@ class BunTestRunner {
8116
8299
  timeSpentMs: elapsed
8117
8300
  };
8118
8301
  });
8302
+ const discoveryOrderIndex = buildDiscoveryOrderIndex(testHierarchy.map((t) => t.id));
8119
8303
  const nameCounts = new Map;
8120
8304
  for (const test of tests) {
8121
8305
  nameCounts.set(test.name, (nameCounts.get(test.name) ?? 0) + 1);
8122
8306
  }
8123
8307
  const nameGroups = new Map;
8124
- for (const test of tests) {
8308
+ for (const [i, test] of tests.entries()) {
8125
8309
  if ((nameCounts.get(test.name) ?? 1) > 1) {
8310
+ const entry = { test, inspectorId: executionOrder[i] };
8126
8311
  const group = nameGroups.get(test.name);
8127
8312
  if (group) {
8128
- group.push(test);
8313
+ group.push(entry);
8129
8314
  } else {
8130
- nameGroups.set(test.name, [test]);
8315
+ nameGroups.set(test.name, [entry]);
8131
8316
  }
8132
8317
  }
8133
8318
  }
8134
8319
  for (const [, group] of nameGroups) {
8135
- group.sort((a, b) => {
8136
- const lineA = "startPosition" in a && a.startPosition ? a.startPosition.line : Infinity;
8137
- const lineB = "startPosition" in b && b.startPosition ? b.startPosition.line : Infinity;
8138
- return lineA - lineB;
8139
- });
8140
- for (const [i, test] of group.entries()) {
8320
+ const sorted = sortDuplicateGroupByLineThenDiscovery(group, (e) => ("startPosition" in e.test) && e.test.startPosition ? e.test.startPosition.line : undefined, (e) => e.inspectorId, discoveryOrderIndex);
8321
+ for (const [i, { test }] of sorted.entries()) {
8141
8322
  const uniqueName = `${test.name} [${i}]`;
8142
8323
  test.id = uniqueName;
8143
8324
  test.name = uniqueName;
8144
8325
  }
8145
8326
  }
8146
- return tests;
8327
+ return { tests, testNameIndex: buildTestNameIndex(tests, bunNames) };
8147
8328
  }
8148
8329
  async dryRun() {
8149
8330
  this.logger.debug("Running dry run with inspector-based coverage collection...");
@@ -8218,7 +8399,11 @@ exit=%s timedOut=%s
8218
8399
  url: inspectorUrl,
8219
8400
  connectionTimeout: this.inspectorTimeout,
8220
8401
  requestTimeout: this.inspectorTimeout,
8221
- handlers: {}
8402
+ handlers: {
8403
+ onError: (error) => {
8404
+ this.logger.warn("Inspector error: %s", error.message);
8405
+ }
8406
+ }
8222
8407
  });
8223
8408
  try {
8224
8409
  await inspector.connect();
@@ -8238,24 +8423,19 @@ exit=%s timedOut=%s
8238
8423
  this.logger.debug("Signaled preload script to proceed");
8239
8424
  const result = await testProcess;
8240
8425
  const totalElapsedMs = Date.now() - startTime;
8426
+ inspector.expectClose();
8427
+ await inspector.waitForClose(INSPECTOR_DRAIN_TIMEOUT_MS);
8241
8428
  const testHierarchy = inspector.getTests();
8242
8429
  const executionOrder = inspector.getExecutionOrder();
8430
+ const wasClosedUnexpectedly = inspector.wasClosedUnexpectedly;
8243
8431
  await inspector.close();
8244
8432
  this.logger.debug("Inspector collected %d tests in hierarchy, %d in execution order", testHierarchy.length, executionOrder.length);
8245
8433
  const parsed = parseBunTestOutput(result.stdout, result.stderr);
8246
- const earlyResult = this.checkDryRunProcessResult(result, parsed);
8434
+ const earlyResult = this.checkDryRunProcessResult(result, parsed, testHierarchy);
8247
8435
  if (earlyResult) {
8248
8436
  return earlyResult;
8249
8437
  }
8250
- const { coverage: mutantCoverage, inspectorIdToProjectFile } = await this.collectAndRemapCoverage(testHierarchy, executionOrder);
8251
- const tests = this.buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile);
8252
- tests.sort((a, b) => a.name.localeCompare(b.name));
8253
- await this.buildAndPersistTestRegistry(tests);
8254
- return {
8255
- status: DryRunStatus.Complete,
8256
- tests,
8257
- mutantCoverage
8258
- };
8438
+ return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, wasClosedUnexpectedly);
8259
8439
  } finally {
8260
8440
  abortController.abort();
8261
8441
  if (this.currentAbortController === abortController) {
@@ -8264,7 +8444,23 @@ exit=%s timedOut=%s
8264
8444
  await syncServer.close();
8265
8445
  }
8266
8446
  }
8267
- async buildAndPersistTestRegistry(tests) {
8447
+ async buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, wasClosedUnexpectedly) {
8448
+ const { coverage: mutantCoverage, inspectorIdToProjectFile, rawKeyCount, orphanedKeyCount } = await this.collectAndRemapCoverage(testHierarchy, executionOrder);
8449
+ const { tests, testNameIndex } = this.buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile);
8450
+ tests.sort((a, b) => a.name.localeCompare(b.name));
8451
+ const gateResult = this.checkCompletenessGate(executionOrder, testHierarchy, parsed, rawKeyCount, orphanedKeyCount, wasClosedUnexpectedly, tests);
8452
+ if (gateResult) {
8453
+ return gateResult;
8454
+ }
8455
+ await this.buildAndPersistTestRegistry(tests, testNameIndex);
8456
+ this.warnOnUnidentifiedDryRunFailure(result, parsed, tests);
8457
+ return {
8458
+ status: DryRunStatus.Complete,
8459
+ tests,
8460
+ mutantCoverage
8461
+ };
8462
+ }
8463
+ async buildAndPersistTestRegistry(tests, testNameIndex) {
8268
8464
  this.cachedTestNames = new Set(tests.map((t) => t.name));
8269
8465
  if (tests.length !== this.cachedTestNames.size) {
8270
8466
  const nameCount = new Map;
@@ -8289,14 +8485,16 @@ exit=%s timedOut=%s
8289
8485
  }
8290
8486
  }
8291
8487
  this.logger.debug("Cached %d test names from dry run for killedBy resolution", this.cachedTestNames.size);
8488
+ this.testNameIndex = testNameIndex;
8292
8489
  try {
8293
8490
  const registryPath = this.registryPath;
8294
8491
  const tmpPath = this.registryTmpPath;
8295
8492
  const registryData = JSON.stringify({
8296
- version: 1,
8493
+ version: 2,
8297
8494
  writtenAt: Date.now(),
8298
8495
  cachedTestNames: [...this.cachedTestNames],
8299
- baseNameIndex: [...this.baseNameIndex.entries()]
8496
+ baseNameIndex: [...this.baseNameIndex.entries()],
8497
+ testNameIndex: [...testNameIndex.entries()]
8300
8498
  });
8301
8499
  await fsPromises2.writeFile(tmpPath, registryData, "utf8");
8302
8500
  this.lastRegistryTmpPath = tmpPath;
@@ -8307,17 +8505,35 @@ exit=%s timedOut=%s
8307
8505
  this.logger.warn("Failed to write dryRun registry file: %s", error instanceof Error ? error.message : String(error));
8308
8506
  }
8309
8507
  }
8508
+ warnLossyPatternAlternatives(filterIds, mutantId) {
8509
+ if (filterIds.length === 0) {
8510
+ return;
8511
+ }
8512
+ const exactNameIndex = this.testNameIndex;
8513
+ if (exactNameIndex === undefined) {
8514
+ this.logger.warn('Mutant %s: no exact-name registry available — all %d covering-test pattern alternatives use lossy reconstruction; tests with " > " in their titles may be silently dropped', mutantId, filterIds.length);
8515
+ return;
8516
+ }
8517
+ const missed = filterIds.filter((id) => !exactNameIndex.has(id));
8518
+ if (missed.length > 0) {
8519
+ this.logger.warn('Mutant %s: %d of %d testFilter ids missing from exact-name registry (lossy fallback; " > " titles among them may be silently dropped): %s%s', mutantId, missed.length, filterIds.length, missed.slice(0, 5).join(", "), missed.length > 5 ? ", …" : "");
8520
+ }
8521
+ }
8310
8522
  async mutantRun(options) {
8311
8523
  this.logger.debug("Running mutant run for mutant %s", options.activeMutant.id);
8312
- const testNamePattern = buildTestNamePattern(options.testFilter ?? []);
8313
- const localTestFilter = options.testFilter ?? [];
8314
- const { localRegistry, localBaseIndex } = this.buildLocalTestFilterIndex(localTestFilter);
8524
+ const filterIds = options.testFilter ?? [];
8315
8525
  if (!this.cachedTestNames) {
8316
8526
  await this.loadRegistryFile();
8317
8527
  }
8528
+ this.warnLossyPatternAlternatives(filterIds, options.activeMutant.id);
8529
+ const testNamePattern = buildTestNamePattern(filterIds, this.testNameIndex);
8530
+ const { localRegistry, localBaseIndex } = this.buildLocalTestFilterIndex(filterIds);
8318
8531
  const mutantCwd = process.cwd();
8319
8532
  const bunfigPath = this.sanitizedBunfigPath && this.sanitizedBunfigCwd === mutantCwd ? this.sanitizedBunfigPath : await this.ensureSanitizedBunfig();
8320
8533
  this.cachedTestFiles = await this.getOrDiscoverTestFiles();
8534
+ return this.executeMutantRun(options, bunfigPath, testNamePattern, localRegistry, localBaseIndex);
8535
+ }
8536
+ async executeMutantRun(options, bunfigPath, testNamePattern, localRegistry, localBaseIndex) {
8321
8537
  const abortController = new AbortController;
8322
8538
  this.currentAbortController = abortController;
8323
8539
  let result;
@@ -8361,6 +8577,10 @@ exit=%s timedOut=%s
8361
8577
  exitCode: result.exitCode
8362
8578
  });
8363
8579
  if (result.exitCode !== 0) {
8580
+ if (testNamePattern !== undefined && parsed.tests.length === 0 && ZERO_MATCH_TEST_PATTERN_RE.test(result.stderr)) {
8581
+ this.logger.warn("Mutant %s: --test-name-pattern matched 0 tests — usually a runner pattern gap or a mutant that changed an interpolated test title (it.each); retrying once with the full suite", options.activeMutant.id);
8582
+ return this.executeMutantRun(options, bunfigPath, undefined, localRegistry, localBaseIndex);
8583
+ }
8364
8584
  return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, options.activeMutant.id);
8365
8585
  }
8366
8586
  return {
@@ -8397,6 +8617,13 @@ exit=%s timedOut=%s
8397
8617
  }
8398
8618
  checkRuntimeError(result, mutantId) {
8399
8619
  const stderr = result.stderr;
8620
+ if (ZERO_MATCH_TEST_PATTERN_RE.test(stderr)) {
8621
+ this.logger.warn("Mutant %s: --test-name-pattern matched 0 tests with no covering tests left to retry — not a kill: %s", mutantId, stderr.slice(0, 200));
8622
+ return {
8623
+ status: MutantRunStatus.Error,
8624
+ errorMessage: `stryker-bun-runner: bun's --test-name-pattern matched 0 tests for this mutant (runner pattern gap or mutant-changed interpolated title — not a kill): ${stderr.slice(0, 500)}`
8625
+ };
8626
+ }
8400
8627
  const isRuntimeError = stderr.includes("Unhandled error") || stderr.includes("Cannot find module") || stderr.includes("SyntaxError") || stderr.includes("TypeError") || stderr.includes("ReferenceError") || stderr.includes("is not defined") || stderr.includes("Unexpected token");
8401
8628
  if (isRuntimeError) {
8402
8629
  this.logger.debug("Mutant %s caused runtime error (tests could not run): %s", mutantId, stderr.slice(0, 200));
@@ -8407,32 +8634,120 @@ exit=%s timedOut=%s
8407
8634
  }
8408
8635
  return null;
8409
8636
  }
8410
- checkDryRunProcessResult(result, parsed) {
8637
+ checkDryRunProcessResult(result, parsed, testHierarchy) {
8411
8638
  if (result.timedOut) {
8412
8639
  this.logger.warn("Dry run timed out");
8413
8640
  return { status: DryRunStatus.Timeout };
8414
8641
  }
8415
8642
  if (result.exitCode !== 0 && parsed.failed === 0) {
8643
+ const failureDetails = this.formatInspectorFailureDetails(testHierarchy);
8644
+ const messageParts = [`Bun test process failed with exit code ${result.exitCode}`];
8645
+ if (failureDetails) {
8646
+ messageParts.push(failureDetails);
8647
+ }
8648
+ messageParts.push(result.stderr);
8416
8649
  return {
8417
8650
  status: DryRunStatus.Error,
8418
- errorMessage: `Bun test process failed with exit code ${result.exitCode}
8419
- ${result.stderr}`
8651
+ errorMessage: messageParts.join(`
8652
+ `)
8420
8653
  };
8421
8654
  }
8422
8655
  return null;
8423
8656
  }
8657
+ formatInspectorFailureDetails(testHierarchy) {
8658
+ const failedTests = testHierarchy.filter((t) => t.type === "test" && t.status === "fail");
8659
+ if (failedTests.length === 0) {
8660
+ return "";
8661
+ }
8662
+ const listed = failedTests.slice(0, MAX_DRY_RUN_FAILURE_TESTS_LISTED);
8663
+ const lines = listed.map((t) => {
8664
+ const message = t.error?.message ?? "no error message captured";
8665
+ let line = ` - ${t.fullName}: ${message}`;
8666
+ if (t.error?.stack) {
8667
+ const indentedStack = t.error.stack.split(`
8668
+ `).map((stackLine) => ` ${stackLine}`).join(`
8669
+ `);
8670
+ line += `
8671
+ ${indentedStack}`;
8672
+ }
8673
+ return line;
8674
+ });
8675
+ const remaining = failedTests.length - listed.length;
8676
+ if (remaining > 0) {
8677
+ lines.push(` ...and ${remaining} more`);
8678
+ }
8679
+ return `${failedTests.length} test(s) reported failed via Bun's inspector (stdout/stderr recap may be truncated or missing):
8680
+ ${lines.join(`
8681
+ `)}`;
8682
+ }
8683
+ warnOnUnidentifiedDryRunFailure(result, parsed, tests) {
8684
+ if ((result.exitCode !== 0 || parsed.failed > 0) && !tests.some((t) => t.status === TestStatus.Failed)) {
8685
+ 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:
8686
+ %s`, String(result.exitCode), parsed.failed, result.stderr.slice(-500));
8687
+ }
8688
+ }
8689
+ checkCompletenessGate(executionOrder, testHierarchy, parsed, rawKeyCount, orphanedKeyCount, wasClosedUnexpectedly, tests) {
8690
+ if (tests.some((t) => t.status === TestStatus.Failed)) {
8691
+ return null;
8692
+ }
8693
+ const testMap = new Map(testHierarchy.map((t) => [t.id, t]));
8694
+ const nonSkippedExecutionCount = executionOrder.filter((id) => {
8695
+ const status = testMap.get(id)?.status;
8696
+ return status !== "skip" && status !== "todo";
8697
+ }).length;
8698
+ const consoleTotal = parsed.summaryPassed + parsed.summaryFailed;
8699
+ const shortfall = consoleTotal - nonSkippedExecutionCount;
8700
+ const signalA = consoleTotal > 0 && shortfall > EXECUTION_SHORTFALL_ABS_FLOOR && shortfall / consoleTotal > EXECUTION_SHORTFALL_RATIO_THRESHOLD;
8701
+ const signalB = orphanedKeyCount > ORPHANED_KEY_ABS_FLOOR;
8702
+ if (!signalA && !signalB) {
8703
+ return null;
8704
+ }
8705
+ const reasons = [];
8706
+ if (signalA) {
8707
+ reasons.push(`console reported ${consoleTotal} test(s) (pass+fail) but the inspector's execution order ` + `contains only ${nonSkippedExecutionCount} non-skipped test(s) (shortfall ${shortfall})`);
8708
+ }
8709
+ if (signalB) {
8710
+ reasons.push(`${orphanedKeyCount} of ${rawKeyCount} coverage key(s) could not be paired with any inspector test (orphaned)`);
8711
+ }
8712
+ if (wasClosedUnexpectedly) {
8713
+ reasons.push("the inspector WebSocket closed unexpectedly before this data could be fully drained");
8714
+ }
8715
+ const errorMessage = "stryker-bun-runner: dry run data-completeness check failed — " + `${reasons.join("; ")}. This indicates the Bun inspector event stream may have been ` + "truncated mid-run; proceeding would risk silently " + "corrupted coverage attribution, so this dry run is being reported as an error instead of " + "Complete, and the test registry has NOT been persisted.";
8716
+ this.logger.error("%s", errorMessage);
8717
+ return {
8718
+ status: DryRunStatus.Error,
8719
+ errorMessage
8720
+ };
8721
+ }
8424
8722
  async collectAndRemapCoverage(testHierarchy, executionOrder) {
8425
8723
  const testMap = new Map(testHierarchy.map((t) => [t.id, t]));
8426
8724
  if (!this.coverageFilePath) {
8427
- return { coverage: undefined, inspectorIdToProjectFile: new Map };
8725
+ return { coverage: undefined, inspectorIdToProjectFile: new Map, rawKeyCount: 0, orphanedKeyCount: 0 };
8428
8726
  }
8429
- const rawCoverage = await collectCoverage(this.coverageFilePath, this.logger);
8727
+ const [rawCoverage, lateHits] = await Promise.all([
8728
+ collectCoverage(this.coverageFilePath, this.logger),
8729
+ collectLateHits(this.coverageFilePath, this.logger)
8730
+ ]);
8430
8731
  await cleanupCoverageFile(this.coverageFilePath);
8431
8732
  if (!rawCoverage) {
8432
- return { coverage: undefined, inspectorIdToProjectFile: new Map };
8733
+ return { coverage: undefined, inspectorIdToProjectFile: new Map, rawKeyCount: 0, orphanedKeyCount: 0 };
8734
+ }
8735
+ const { coverage, inspectorIdToProjectFile, counterKeyToTestName, rawKeyCount, orphanedKeyCount } = mapCoverageToInspectorIds(rawCoverage, executionOrder, testMap, this.logger);
8736
+ if (lateHits.length > 0) {
8737
+ this.emitCoverageBleedWarnings(lateHits, counterKeyToTestName);
8738
+ }
8739
+ return { coverage, inspectorIdToProjectFile, rawKeyCount, orphanedKeyCount };
8740
+ }
8741
+ emitCoverageBleedWarnings(lateHits, counterKeyToTestName) {
8742
+ const listed = lateHits.slice(0, MAX_COVERAGE_BLEED_WARNINGS);
8743
+ for (const { testId, mutantIds } of listed) {
8744
+ const testName = counterKeyToTestName.get(testId) ?? testId;
8745
+ this.logger.warn("mutant coverage was recorded between tests, after '%s' completed — likely fire-and-forget async work " + "leaking past the test boundary (or beforeAll/fixture code running between tests); attribution for %d " + "mutant(s) may be wrong (mutant IDs: %s)", testName, mutantIds.length, mutantIds.join(", "));
8746
+ }
8747
+ const remaining = lateHits.length - listed.length;
8748
+ if (remaining > 0) {
8749
+ this.logger.warn("...and %d more coverage-bleed warning(s) suppressed", remaining);
8433
8750
  }
8434
- const { coverage, inspectorIdToProjectFile } = mapCoverageToInspectorIds(rawCoverage, executionOrder, testMap, this.logger);
8435
- return { coverage, inspectorIdToProjectFile };
8436
8751
  }
8437
8752
  buildLocalTestFilterIndex(testFilter) {
8438
8753
  const localRegistry = new Set(testFilter);