@hughescr/stryker-bun-runner 1.3.1 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -69,6 +69,8 @@ The plugin uses Bun's Inspector Protocol (WebSocket) to:
69
69
 
70
70
  Oversized covering-test patterns (over 100,000 UTF-8 bytes) fall back to running the full suite, to stay within OS argument-length limits. This approach provides reliable test-to-mutant correlation, even with multiple test files.
71
71
 
72
+ A second full-suite fallback happens at run time: a `--test-name-pattern` that matches zero tests triggers a one-shot full-suite retry (see [Diagnostic warnings worth grepping for in CI](#diagnostic-warnings-worth-grepping-for-in-ci)).
73
+
72
74
  ## Options
73
75
 
74
76
  | Option | Type | Default | Description |
@@ -168,6 +170,37 @@ export default {
168
170
  };
169
171
  ```
170
172
 
173
+ ## Diagnostic warnings worth grepping for in CI
174
+
175
+ The runner logs three warnings that flag when a mutant run's `--test-name-pattern`
176
+ couldn't be built or applied with full fidelity. None of them indicate a wrong
177
+ mutation-testing verdict by themselves, but they're worth grepping your CI logs for
178
+ because they mark where the runner fell back to less-precise behavior:
179
+
180
+ - **`--test-name-pattern matched 0 tests`** — the pattern for a mutant's covering
181
+ tests matched nothing across the whole run (usually because a mutant changed a
182
+ value interpolated into an `it.each` title). The runner retries once with the
183
+ full suite rather than reporting a false kill, so the eventual verdict is still
184
+ genuine — if the retry itself also matches zero tests (or the zero-match came
185
+ from a user-supplied `--test-name-pattern` in `bunArgs`, which is never retried),
186
+ the mutant is classified as an infrastructure `Error`, never a kill. Every
187
+ occurrence is worth spot-checking that it's explained by an interpolated-title
188
+ change, not a real pattern gap.
189
+ - **`no exact-name registry available`** — this worker couldn't load the shared
190
+ dry-run test-name registry, so every alternative in that mutant's pattern used
191
+ the lossy `' > '`-collapsing reconstruction instead of Bun's exact matching
192
+ names. Tests whose titles legitimately contain `" > "` may have been silently
193
+ excluded from that run.
194
+ - **`missing from exact-name registry`** — the registry loaded, but one or more
195
+ `testFilter` ids for this mutant weren't in it (falls back to the same lossy
196
+ reconstruction for just those ids, listing up to 5 of the missing ids).
197
+
198
+ The last two matter because Bun only errors when a pattern matches **zero** tests
199
+ across the whole run; a *partial* miss — some alternatives hit, others silently
200
+ don't — exits 0 with no error text at all. These two warns are the only signal
201
+ that a partial silent drop was possible for a given mutant run, so seeing either
202
+ of them in a clean run's logs is worth investigating before trusting the score.
203
+
171
204
  ## Known Limitations
172
205
 
173
206
  - **Sequential execution required** - Tests run with `--concurrency=1` to ensure accurate coverage tracking. This is slower than parallel execution but necessary for correct test-to-mutant correlation.
package/dist/index.d.ts CHANGED
@@ -31,6 +31,7 @@ export declare class BunTestRunner implements TestRunner {
31
31
  private tempDir?;
32
32
  private cachedTestNames?;
33
33
  private baseNameIndex?;
34
+ private testNameIndex?;
34
35
  private cachedTestFiles?;
35
36
  private cachedTestFilesCwd?;
36
37
  private cachedEagerModules?;
@@ -84,17 +85,26 @@ export declare class BunTestRunner implements TestRunner {
84
85
  private ensureSanitizedBunfig;
85
86
  /**
86
87
  * Load the shared dryRun registry written by the one worker that ran dryRun.
87
- * Populates this.cachedTestNames and this.baseNameIndex so that subsequent
88
- * mutantRun calls on this worker can resolve killedBy names correctly, even
89
- * for static-coverage mutants where testFilter is empty.
88
+ * Populates this.cachedTestNames, this.baseNameIndex, and this.testNameIndex
89
+ * so that subsequent mutantRun calls on this worker can resolve killedBy names
90
+ * and build exact --test-name-pattern alternatives, even for static-coverage
91
+ * mutants where testFilter is empty.
90
92
  *
91
- * Failures are non-fatal — the worker falls back to raw console names (current
92
- * behaviour before this fix), and a warning is logged so the issue is visible.
93
+ * Loading is all-or-nothing: a wrong version or a malformed field rejects the
94
+ * whole file (never a half-initialised registry). Failures are non-fatal — the
95
+ * worker falls back to raw console names and the lossy pattern reconstruction,
96
+ * and a warning is logged so the issue is visible.
93
97
  */
94
98
  private loadRegistryFile;
95
99
  /**
96
100
  * Build test results from inspector data.
97
101
  *
102
+ * Also returns a testNameIndex mapping each FINAL test id (dedup ' [N]'
103
+ * suffix included) to Bun's exact internal matching name (TestInfo.bunName)
104
+ * for --test-name-pattern generation. Tests without a bunName — console-
105
+ * fallback results and unknown-inspectorId placeholders — get no index entry
106
+ * and stay on the lossy pattern reconstruction path (never worse than before).
107
+ *
98
108
  * @param inspectorIdToProjectFile - Optional mapping from inspector ID to project file path.
99
109
  * When provided, the project file is used for TestResult.id, name, and fileName instead of
100
110
  * testInfo.url. This is important for tests defined via helpers (e.g. RuleTester.run()) where
@@ -107,18 +117,41 @@ export declare class BunTestRunner implements TestRunner {
107
117
  dryRun(): Promise<DryRunResult>;
108
118
  /**
109
119
  * Build the in-memory test name cache and base-name index, then atomically
110
- * persist them to a well-known file so other worker processes can lazy-load
111
- * them when handling static-coverage mutants (testFilter is empty for those).
120
+ * persist them — together with the exact-name testNameIndex from
121
+ * buildTestsFromInspector — to a well-known file so other worker processes
122
+ * can lazy-load them when handling static-coverage mutants (testFilter is
123
+ * empty for those) and build exact --test-name-pattern alternatives.
112
124
  *
113
125
  * Writing to a .tmp path then renaming is atomic on POSIX: readers always see
114
126
  * either the previous complete file or the new one — never a partial write.
115
127
  */
116
128
  private buildAndPersistTestRegistry;
117
129
  /**
130
+ * Lossy-visibility warns for a mutant run's --test-name-pattern.
131
+ *
132
+ * Bun exits 0 on a PARTIAL pattern miss (verified live, bun 1.3.14),
133
+ * silently dropping the missed tests — so these warns are the only signal
134
+ * that some covering-test alternatives were built via the lossy
135
+ * ' > '-collapsing reconstruction instead of exact bun names. Must be called
136
+ * AFTER the registry lazy-load so this.testNameIndex reflects reality.
137
+ */
138
+ private warnLossyPatternAlternatives;
139
+ /**
118
140
  * Run tests with an active mutant
119
141
  */
120
142
  mutantRun(options: MutantRunOptions): Promise<MutantRunResult>;
121
143
  /**
144
+ * Spawn bun for a mutant run and interpret the result. Extracted from
145
+ * mutantRun so that a --test-name-pattern which matched 0 tests can retry
146
+ * once with the full suite (testNamePattern undefined) while reusing the
147
+ * SAME localRegistry/localBaseIndex built from the original testFilter for
148
+ * killedBy resolution — avoiding both a false Killed and redundant setup.
149
+ * The retry always recurses with testNamePattern undefined, so the retry
150
+ * gate's first conjunct is false on that call: recursion is bounded to
151
+ * depth 1 by construction, never a retry-of-a-retry.
152
+ */
153
+ private executeMutantRun;
154
+ /**
122
155
  * Build the MutantRunResult for a killed mutant (non-zero exit code).
123
156
  * Handles runtime error detection and killedBy resolution.
124
157
  */
package/dist/index.js CHANGED
@@ -5983,11 +5983,12 @@ class InspectorClient {
5983
5983
  }
5984
5984
  }
5985
5985
  handleTestFound(params) {
5986
- const fullName = this.buildFullName(params.id, params.name, params.parentId);
5986
+ const { fullName, bunName } = this.buildFullName(params.id, params.name, params.parentId);
5987
5987
  const testInfo = {
5988
5988
  id: params.id,
5989
5989
  name: params.name,
5990
5990
  fullName,
5991
+ bunName,
5991
5992
  type: params.type,
5992
5993
  parentId: params.parentId,
5993
5994
  url: params.url,
@@ -6028,7 +6029,7 @@ class InspectorClient {
6028
6029
  }
6029
6030
  buildFullName(id, name, parentId) {
6030
6031
  if (parentId === undefined) {
6031
- return name;
6032
+ return { fullName: name, bunName: name };
6032
6033
  }
6033
6034
  const parts = [name];
6034
6035
  const visited = new Set([id]);
@@ -6046,7 +6047,7 @@ class InspectorClient {
6046
6047
  parts.unshift(parent.name);
6047
6048
  currentId = parent.parentId;
6048
6049
  }
6049
- return parts.join(" > ");
6050
+ return { fullName: parts.join(" > "), bunName: parts.join(" ") };
6050
6051
  }
6051
6052
  handleClose() {
6052
6053
  if (this.isClosing) {
@@ -7732,20 +7733,28 @@ async function cleanupSanitizedBunfig(filePath) {
7732
7733
  }
7733
7734
  // src/utils/test-name-pattern.ts
7734
7735
  var MAX_TEST_NAME_PATTERN_LENGTH = 1e5;
7735
- function buildTestNamePattern(testFilter) {
7736
+ var fileExtRe = /\.(?:test|spec)\.(?:[jt]sx?|m[jt]s)$/;
7737
+ var dedupSuffixRe = / \[\d+\]$/;
7738
+ var metaRe = /[.*+?^${}()|[\]\\/]/g;
7739
+ function escapeRegex(str) {
7740
+ return str.replaceAll(metaRe, String.raw`\$&`);
7741
+ }
7742
+ function buildTestNamePattern(testFilter, testNameIndex) {
7736
7743
  if (testFilter.length === 0) {
7737
7744
  return;
7738
7745
  }
7739
- const fileExtRe = /\.(?:test|spec)\.(?:[jt]sx?|m[jt]s)$/;
7740
- const dedupSuffixRe = / \[\d+\]$/;
7741
- const metaRe = /[.*+?^${}()|[\]\\/]/g;
7742
7746
  const alternatives = new Set;
7743
7747
  for (const id of testFilter) {
7748
+ const exact = testNameIndex?.get(id);
7749
+ if (exact !== undefined && exact.length > 0 && !exact.includes("\x00")) {
7750
+ alternatives.add(escapeRegex(exact));
7751
+ continue;
7752
+ }
7744
7753
  const firstSepIdx = id.indexOf(" > ");
7745
7754
  let name = firstSepIdx !== -1 && fileExtRe.test(id.slice(0, firstSepIdx)) ? id.slice(firstSepIdx + 3) : id;
7746
7755
  name = name.replace(dedupSuffixRe, "");
7747
7756
  name = name.replaceAll(" > ", " ");
7748
- name = name.replaceAll(metaRe, String.raw`\$&`);
7757
+ name = escapeRegex(name);
7749
7758
  if (name.length > 0) {
7750
7759
  alternatives.add(name);
7751
7760
  }
@@ -7868,6 +7877,17 @@ function sleep(ms) {
7868
7877
  setTimeout(resolve3, ms);
7869
7878
  });
7870
7879
  }
7880
+ function buildTestNameIndex(tests, bunNames) {
7881
+ const testNameIndex = new Map;
7882
+ for (const [i, test] of tests.entries()) {
7883
+ const bunName = bunNames[i];
7884
+ if (bunName !== undefined) {
7885
+ testNameIndex.set(test.id, bunName);
7886
+ }
7887
+ }
7888
+ return testNameIndex;
7889
+ }
7890
+ var ZERO_MATCH_TEST_PATTERN_RE = /matched 0 tests\./;
7871
7891
 
7872
7892
  class BunTestRunner {
7873
7893
  logger;
@@ -7889,6 +7909,7 @@ class BunTestRunner {
7889
7909
  tempDir;
7890
7910
  cachedTestNames;
7891
7911
  baseNameIndex;
7912
+ testNameIndex;
7892
7913
  cachedTestFiles;
7893
7914
  cachedTestFilesCwd;
7894
7915
  cachedEagerModules;
@@ -8015,16 +8036,21 @@ class BunTestRunner {
8015
8036
  try {
8016
8037
  const raw = await fsPromises2.readFile(registryPath, "utf8");
8017
8038
  const parsed = JSON.parse(raw);
8018
- if (parsed.version !== 1) {
8039
+ if (parsed.version !== 2) {
8019
8040
  this.logger.warn("dryRun registry file has unexpected version %s; skipping", String(parsed.version));
8020
8041
  return;
8021
8042
  }
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");
8043
+ if (!Array.isArray(parsed.cachedTestNames) || !Array.isArray(parsed.baseNameIndex) || !Array.isArray(parsed.testNameIndex)) {
8044
+ this.logger.warn("dryRun registry file is malformed (cachedTestNames, baseNameIndex, or testNameIndex missing or not an array); treating as absent");
8045
+ return;
8046
+ }
8047
+ if (!parsed.testNameIndex.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && typeof entry[1] === "string")) {
8048
+ this.logger.warn("dryRun registry file is malformed (testNameIndex entry is not a [string, string] pair); treating as absent");
8024
8049
  return;
8025
8050
  }
8026
8051
  this.cachedTestNames = new Set(parsed.cachedTestNames);
8027
8052
  this.baseNameIndex = new Map(parsed.baseNameIndex);
8053
+ this.testNameIndex = new Map(parsed.testNameIndex);
8028
8054
  this.logger.debug("Loaded dryRun registry from %s (%d entries)", registryPath, this.cachedTestNames.size);
8029
8055
  } catch (err) {
8030
8056
  const code = err.code;
@@ -8037,7 +8063,7 @@ class BunTestRunner {
8037
8063
  }
8038
8064
  buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile) {
8039
8065
  if (executionOrder.length === 0) {
8040
- return parsed.tests.map((t) => {
8066
+ const fallbackTests = parsed.tests.map((t) => {
8041
8067
  const normalizedName = normalizeTestName(t.name);
8042
8068
  if (t.status === "failed") {
8043
8069
  return {
@@ -8063,12 +8089,14 @@ class BunTestRunner {
8063
8089
  timeSpentMs: Math.round(t.duration ?? 1)
8064
8090
  };
8065
8091
  });
8092
+ return { tests: fallbackTests, testNameIndex: new Map };
8066
8093
  }
8067
8094
  const timePerTest = executionOrder.length > 0 ? Math.max(1, Math.round(totalElapsedMs / executionOrder.length)) : 1;
8068
8095
  const testMap = new Map;
8069
8096
  for (const test of testHierarchy) {
8070
8097
  testMap.set(test.id, test);
8071
8098
  }
8099
+ const bunNames = executionOrder.map((inspectorId) => testMap.get(inspectorId)?.bunName);
8072
8100
  const tests = executionOrder.map((inspectorId) => {
8073
8101
  const testInfo = testMap.get(inspectorId);
8074
8102
  if (!testInfo) {
@@ -8143,7 +8171,7 @@ class BunTestRunner {
8143
8171
  test.name = uniqueName;
8144
8172
  }
8145
8173
  }
8146
- return tests;
8174
+ return { tests, testNameIndex: buildTestNameIndex(tests, bunNames) };
8147
8175
  }
8148
8176
  async dryRun() {
8149
8177
  this.logger.debug("Running dry run with inspector-based coverage collection...");
@@ -8248,9 +8276,9 @@ exit=%s timedOut=%s
8248
8276
  return earlyResult;
8249
8277
  }
8250
8278
  const { coverage: mutantCoverage, inspectorIdToProjectFile } = await this.collectAndRemapCoverage(testHierarchy, executionOrder);
8251
- const tests = this.buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile);
8279
+ const { tests, testNameIndex } = this.buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile);
8252
8280
  tests.sort((a, b) => a.name.localeCompare(b.name));
8253
- await this.buildAndPersistTestRegistry(tests);
8281
+ await this.buildAndPersistTestRegistry(tests, testNameIndex);
8254
8282
  return {
8255
8283
  status: DryRunStatus.Complete,
8256
8284
  tests,
@@ -8264,7 +8292,7 @@ exit=%s timedOut=%s
8264
8292
  await syncServer.close();
8265
8293
  }
8266
8294
  }
8267
- async buildAndPersistTestRegistry(tests) {
8295
+ async buildAndPersistTestRegistry(tests, testNameIndex) {
8268
8296
  this.cachedTestNames = new Set(tests.map((t) => t.name));
8269
8297
  if (tests.length !== this.cachedTestNames.size) {
8270
8298
  const nameCount = new Map;
@@ -8289,14 +8317,16 @@ exit=%s timedOut=%s
8289
8317
  }
8290
8318
  }
8291
8319
  this.logger.debug("Cached %d test names from dry run for killedBy resolution", this.cachedTestNames.size);
8320
+ this.testNameIndex = testNameIndex;
8292
8321
  try {
8293
8322
  const registryPath = this.registryPath;
8294
8323
  const tmpPath = this.registryTmpPath;
8295
8324
  const registryData = JSON.stringify({
8296
- version: 1,
8325
+ version: 2,
8297
8326
  writtenAt: Date.now(),
8298
8327
  cachedTestNames: [...this.cachedTestNames],
8299
- baseNameIndex: [...this.baseNameIndex.entries()]
8328
+ baseNameIndex: [...this.baseNameIndex.entries()],
8329
+ testNameIndex: [...testNameIndex.entries()]
8300
8330
  });
8301
8331
  await fsPromises2.writeFile(tmpPath, registryData, "utf8");
8302
8332
  this.lastRegistryTmpPath = tmpPath;
@@ -8307,17 +8337,35 @@ exit=%s timedOut=%s
8307
8337
  this.logger.warn("Failed to write dryRun registry file: %s", error instanceof Error ? error.message : String(error));
8308
8338
  }
8309
8339
  }
8340
+ warnLossyPatternAlternatives(filterIds, mutantId) {
8341
+ if (filterIds.length === 0) {
8342
+ return;
8343
+ }
8344
+ const exactNameIndex = this.testNameIndex;
8345
+ if (exactNameIndex === undefined) {
8346
+ 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);
8347
+ return;
8348
+ }
8349
+ const missed = filterIds.filter((id) => !exactNameIndex.has(id));
8350
+ if (missed.length > 0) {
8351
+ 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 ? ", …" : "");
8352
+ }
8353
+ }
8310
8354
  async mutantRun(options) {
8311
8355
  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);
8356
+ const filterIds = options.testFilter ?? [];
8315
8357
  if (!this.cachedTestNames) {
8316
8358
  await this.loadRegistryFile();
8317
8359
  }
8360
+ this.warnLossyPatternAlternatives(filterIds, options.activeMutant.id);
8361
+ const testNamePattern = buildTestNamePattern(filterIds, this.testNameIndex);
8362
+ const { localRegistry, localBaseIndex } = this.buildLocalTestFilterIndex(filterIds);
8318
8363
  const mutantCwd = process.cwd();
8319
8364
  const bunfigPath = this.sanitizedBunfigPath && this.sanitizedBunfigCwd === mutantCwd ? this.sanitizedBunfigPath : await this.ensureSanitizedBunfig();
8320
8365
  this.cachedTestFiles = await this.getOrDiscoverTestFiles();
8366
+ return this.executeMutantRun(options, bunfigPath, testNamePattern, localRegistry, localBaseIndex);
8367
+ }
8368
+ async executeMutantRun(options, bunfigPath, testNamePattern, localRegistry, localBaseIndex) {
8321
8369
  const abortController = new AbortController;
8322
8370
  this.currentAbortController = abortController;
8323
8371
  let result;
@@ -8361,6 +8409,10 @@ exit=%s timedOut=%s
8361
8409
  exitCode: result.exitCode
8362
8410
  });
8363
8411
  if (result.exitCode !== 0) {
8412
+ if (testNamePattern !== undefined && parsed.tests.length === 0 && ZERO_MATCH_TEST_PATTERN_RE.test(result.stderr)) {
8413
+ 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);
8414
+ return this.executeMutantRun(options, bunfigPath, undefined, localRegistry, localBaseIndex);
8415
+ }
8364
8416
  return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, options.activeMutant.id);
8365
8417
  }
8366
8418
  return {
@@ -8397,6 +8449,13 @@ exit=%s timedOut=%s
8397
8449
  }
8398
8450
  checkRuntimeError(result, mutantId) {
8399
8451
  const stderr = result.stderr;
8452
+ if (ZERO_MATCH_TEST_PATTERN_RE.test(stderr)) {
8453
+ 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));
8454
+ return {
8455
+ status: MutantRunStatus.Error,
8456
+ 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)}`
8457
+ };
8458
+ }
8400
8459
  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
8460
  if (isRuntimeError) {
8402
8461
  this.logger.debug("Mutant %s caused runtime error (tests could not run): %s", mutantId, stderr.slice(0, 200));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hughescr/stryker-bun-runner",
3
- "version": "1.3.1",
3
+ "version": "1.3.2",
4
4
  "description": "Stryker test runner plugin for Bun with perTest coverage support",
5
5
  "keywords": [
6
6
  "stryker",