@hughescr/stryker-bun-runner 1.6.1 → 1.7.1

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
@@ -30,7 +30,8 @@ coverage so that each mutant runs only the tests that reach it.
30
30
  - [Requirements and compatibility](#requirements-and-compatibility)
31
31
  - [Configuration](#configuration)
32
32
  - [Example with every option](#example-with-every-option) · [bun.bunArgs](#bunbunargs) ·
33
- [Choosing the test files](#choosing-the-test-files) · [Your bunfig.toml](#your-bunfigtoml)
33
+ [Choosing the test files](#choosing-the-test-files) · [Your bunfig.toml](#your-bunfigtoml) ·
34
+ [coverageAnalysis](#coverageanalysis)
34
35
  - [Which mutated files the dry run imports](#which-mutated-files-the-dry-run-imports)
35
36
  - [Tests run twice](#if-the-dry-run-runs-your-tests-twice) ·
36
37
  [A file fails when imported first](#if-a-mutated-file-fails-when-it-is-imported-before-the-tests) ·
@@ -210,6 +211,26 @@ What can change after you upgrade:
210
211
  - **A file that only a package, a worker or a child process loads** is not seen by the runner.
211
212
  List it in `bun.alwaysImport`. If a mutant run later finds that a package loaded such a file, it
212
213
  stops the Stryker run and names the file ([what to do](#if-a-mutant-run-stops-the-campaign)).
214
+ - **`coverageAnalysis: 'all'` and `'off'` now do what Stryker says they do**
215
+ ([coverageAnalysis](#coverageanalysis)). Before, the runner gave Stryker per-test coverage
216
+ whatever the value, so they behaved like `'perTest'`. Now, with `'all'`, each mutant that some
217
+ test reaches runs your whole suite; with `'off'`, every mutant does, and a mutant no test reaches
218
+ is Survived instead of NoCoverage. If you set either one, the mutant runs get slower; to keep the
219
+ earlier speed, set `'perTest'` (or remove the setting: it is Stryker's default). With
220
+ `incremental`, run once with `--force` after upgrading; after that, see
221
+ [coverageAnalysis](#coverageanalysis) for when to use it again.
222
+ - **`.jsx`, `.mts` and `.cts` files are mutated files like the others**
223
+ ([#4](https://github.com/hughescr/stryker-bun-runner/issues/4)). Before, the runner left them out
224
+ of its own list of the files that `mutate` matches, though Stryker mutated them: it never
225
+ imported them before the tests, `bun.alwaysImport` could not name them (and warned that the
226
+ pattern matched none of the files), and nothing named them when no test loaded them. Now the
227
+ module-level code of such a file that your tests load runs before the tests, so results in it
228
+ can change, as for the other files. With `incremental`, run once with `--force` after upgrading.
229
+ - **A file you select as a test is never imported before the tests**, though its name has no test
230
+ suffix and `mutate` matches it (`src/checks.mts` in `bun.testFiles`, say). Before, the runner
231
+ imported it like a source file, and the dry run failed with bun's `Cannot use test during
232
+ preload`. If `bun.alwaysImport` names such a file, it is still not imported, and the runner warns
233
+ about the pattern.
213
234
 
214
235
  ## Upgrading from 1.5
215
236
 
@@ -425,6 +446,52 @@ lists only failing tests. Your `[test].preload` files run before the runner's ow
425
446
  [preload](#terms). Details:
426
447
  [the sanitized config](docs/internals.md#your-bunfigtoml-the-sanitized-config).
427
448
 
449
+ ### coverageAnalysis
450
+
451
+ **Leave it at `'perTest'`, Stryker's default, unless you have a reason not to.** Stryker's
452
+ `coverageAnalysis` option decides how much the dry run tells Stryker about which tests reach which
453
+ mutants, and so how many tests each mutant runs:
454
+
455
+ | Value | What the runner records in the dry run | What each mutant runs |
456
+ |---|---|---|
457
+ | `'perTest'` (default) | which tests reach each mutant | only the tests that reach it ([static mutants](#terms): every test); a mutant no test reaches is NoCoverage |
458
+ | `'all'` | only whether some test reaches each mutant | every test, for each mutant that some test reaches; a mutant no test reaches is NoCoverage |
459
+ | `'off'` | nothing about mutants | every test, for every mutant; no mutant is NoCoverage (one no test reaches is Survived) |
460
+
461
+ What differs between the three values is which tests each mutant runs. With `'all'` and `'off'`
462
+ each mutant that some test reaches runs your whole suite, so the mutant runs take longer, often
463
+ much longer, and `'off'` runs the whole suite for the mutants no test reaches too. Some results
464
+ differ with `'off'` as well:
465
+
466
+ - No mutant is NoCoverage: one that no test reaches is run against every test, and is Survived.
467
+ - Stryker sets no hit limit, so a mutant that loops forever is stopped by its timeout instead of
468
+ after a number of hits. It is still Timeout, but each one takes the whole timeout to find.
469
+
470
+ **With `incremental`, use `--force` whenever you need fresh results.** With `'all'` or `'off'`
471
+ Stryker cannot see that a new or changed test now reaches a mutant, so it keeps the earlier result
472
+ of a mutant that was Survived or NoCoverage. With these values, run with `--force` (or set
473
+ `incremental: false`) each time you need results that reflect your current tests, not only once.
474
+
475
+ With `'all'`, Stryker may warn that static mutants take most of the time and suggest
476
+ `ignoreStatic`. With `'all'` every mutant that some test reaches is a [static mutant](#terms) to
477
+ Stryker, and Stryker itself rejects `ignoreStatic` with any value but `'perTest'`, so the
478
+ suggestion does not apply. Set `warnings: { slow: false }` in your Stryker config to silence it.
479
+
480
+ `'off'` is also the simplest dry run: one run of your tests, with no mutated file imported first and
481
+ no coverage recorded, so `bun.alwaysImport` and `bun.importDiscovery` have no effect with it. Use it
482
+ as the way out if per-test tracking ever gets a result wrong, or the dry run fails one of its
483
+ coverage checks and you cannot fix the cause; please also
484
+ [open an issue](https://github.com/hughescr/stryker-bun-runner/issues). Details:
485
+ [coverageAnalysis](docs/internals.md#coverageanalysis).
486
+
487
+ ```javascript
488
+ export default {
489
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
490
+ testRunner: 'bun',
491
+ coverageAnalysis: 'off', // every mutant runs every test
492
+ };
493
+ ```
494
+
428
495
  ## Which mutated files the dry run imports
429
496
 
430
497
  **In the normal case you need to do nothing.** Before the dry run's tests start, the runner imports
@@ -433,6 +500,13 @@ its mutants are [static mutants](#terms), the same on every run. It does not imp
433
500
  test loads, and a mutant there that no test reaches is NoCoverage. That way a file that fails when
434
501
  it is imported on its own, such as an app's entry point, does not break the dry run.
435
502
 
503
+ The mutated files here are the JavaScript and TypeScript files that `mutate` matches (`.js`,
504
+ `.jsx`, `.mjs`, `.cjs`, `.ts`, `.tsx`, `.mts` and `.cts`), other than declaration files (`.d.ts`,
505
+ `.d.mts`, `.d.cts`) and test files: files whose names end in a test suffix (such as `.test.ts`,
506
+ `_test.mts` or `.spec.jsx`, in any case), and files you select as tests (in `bun.testFiles` or
507
+ Stryker's `testFiles`) whatever their names. A test file is never imported before the tests, even
508
+ when `bun.alwaysImport` names it; the runner warns about a pattern that names only such files.
509
+
436
510
  To find the files, the runner reads the import statements of your test files and preloads
437
511
  (`[test].preload` in your bunfig, and `--preload` in `bun.bunArgs`), with a short `bun` process
438
512
  that runs none of your code. Then:
@@ -992,7 +1066,9 @@ Every log message: [Log output](docs/internals.md#log-output).
992
1066
  | `Dry run timed out: bun.timeout is <N>ms` (and Stryker reports a timeout) | The dry run outgrew `bun.timeout` plus the 30 s drain handshake allowance. | Raise `bun.timeout` above your full suite's run time. |
993
1067
  | `Bun test process failed with exit code <N>` or `Bun test process terminated by signal <SIGNAL>` | Bun exited abnormally with no failing test (a missing module, a crash). The message includes stderr. | Fix what the stderr shows. |
994
1068
  | `stryker-bun-runner: dry run data-completeness check failed — <problems>` | Usually something in your suite: a test or hook that calls `process.exit`, an error raised outside any test (the message then shows bun's `Unhandled error between tests` blocks), or a test file that fails to load (an unresolvable import, say); the problems listed name it. Otherwise test events were lost on a heavily loaded machine. | The message is bounded; its last line says which option to set (`bun.dryRunOutputFile`) to save everything bun printed on the next run, or, if you set it, names the file it was saved to: open that first. Fix the cause in your suite; otherwise re-run, and report it if it recurs. If the message names a module of yours from a stack frame in one of bun's error blocks, the runner imported that module before any test ran: see [If a mutated file fails when it is imported before the tests](#if-a-mutated-file-fails-when-it-is-imported-before-the-tests). A named module alone does not prove that it caused the error: the message names it only because a stack frame points at it. `Cannot call test() after the test run has completed` (or the same for a hook) means bun had already ended that test file's run when the call was made, so tests registered from that point were not run. See [the completeness gate](docs/internals.md#the-completeness-gate). |
995
- | `stryker-bun-runner: the dry run produced no mutant coverage data` | The coverage preload never ran, could not write, or the process exited before its final `afterAll` (a test calls `process.exit`). An error with `coverageAnalysis: 'perTest'`, a warning with `'all'`. | Fix the cause the message names, or set `coverageAnalysis` to `'all'` or `'off'` to run without per-test coverage. |
1069
+ | `stryker-bun-runner: the dry run produced no mutant coverage data` | The coverage preload never ran, could not write, or the process exited before its final `afterAll` (a test calls `process.exit`). An error with `coverageAnalysis: 'perTest'` or `'all'`. | Fix the cause the message names, or set `coverageAnalysis` to `'off'` to run without coverage. |
1070
+ | `stryker-bun-runner: the dry run's record of which test file ran each test, <file>, was missing, unreadable or empty` (a warning, with `coverageAnalysis: 'off'`) | The same causes as the row above. Each test is then named after the file bun reports for it, so a test that a shared helper file defines is credited to that file. | Fix the cause the message names. |
1071
+ | `stryker-bun-runner: cannot write <file> (<error>), so <registry> still holds an earlier dry run's test names, ...` | The dry run could not replace the file that hands its test names to the other workers, and an earlier run's copy is still there. | Check the temporary directory (space, permissions; see [Temporary files](docs/internals.md#temporary-files)), or remove the file it names, and re-run. |
996
1072
  | `stryker-bun-runner: the first run of the dry run (a plain run of the tests, with no mutated file imported first) did not complete cleanly: <reasons>. The second run was not made.` (or the second and third run, after a discarded one), followed by bun's own output | The [plain run](#terms) of your tests failed. A test that passed only because earlier versions imported a file before the tests fails here. | See [If the first, plain run of the tests fails](#if-the-first-plain-run-of-the-tests-fails). |
997
1073
  | `stryker-bun-runner: <file> was loaded during the second run of the dry run (<where>) but not during the first, so the runner had not imported it before the tests. Add it to bun.alwaysImport. No mutant was scored.` | The plain run did not load the file, but the dry run proper loaded it after the runner's imports, so the two runs did not run the same code. | See [If a test loads a mutated file late](#if-a-test-loads-a-mutated-file-late). |
998
1074
  | `stryker-bun-runner: <n> mutants in <files> (ids <ids>) were reached when the tests ran on their own, and not reached when the <m> files the tests load were imported first, in the second run.` (the message goes on to list the files left out) | The plain run reached mutants that the dry run proper, with the tests' files imported first, did not. Either module-level code depends on a file that was left out of the imports, or the tests do not run the same code every time. | Add the left-out file that the message names to `bun.alwaysImport`, or set `bun.alwaysImport: 'all'`. If you use `--randomize`, also give a `--seed`. |
@@ -1048,7 +1124,7 @@ also fails; see [Inspector diagnostics](docs/internals.md#inspector-diagnostics)
1048
1124
  | `A mutant run could not use its watch list (<problem>), so it could not check for files the dry run missed; its result stands.` | The runner could not read the list of mutated files that the dry run left out, so this mutant run could not check whether a test loaded one of them. | Check the temporary directory; re-run if it recurs. |
1049
1125
  | `Could not write the abort marker in <dir> (<error>)` | A mutant run found a file that the dry run missed (the message above it), but the runner could not save the note that stops the rest of the Stryker run, so the run may go on. | Treat the run's results as incomplete; fix the temporary directory and act on the message above it. |
1050
1126
  | Many mutants Timeout | Stryker's timeout is tight for your suite, or many mutants loop forever. Infinite loops stopped by the hit limit carry the reason `Hit limit reached (count/limit)`: open the mutant in the HTML report, or read `statusReason` in Stryker's JSON report. | For the others, raise `timeoutMS` or `timeoutFactor`. |
1051
- | Every mutant runs the whole suite | No per-test coverage: `coverageAnalysis` is not `'perTest'`, or coverage was missing. | Use `'perTest'` and check the dry-run warnings. |
1127
+ | Every mutant runs the whole suite | No per-test coverage: `coverageAnalysis` is `'all'` or `'off'` ([coverageAnalysis](#coverageanalysis)). | Use `'perTest'`. |
1052
1128
  | The score changed after upgrading this plugin | Scoring has changed over time (for example, a crash without a matching failing test is now Error, and a test file that a mutant stops from loading is Killed). | Expected. See [Upgrading: the dry run imports only what your tests load](#upgrading-the-dry-run-imports-only-what-your-tests-load), [Upgrading from 1.5](#upgrading-from-15), [Upgrading from 1.4](#upgrading-from-14), [How results are scored](#how-results-are-scored), and the [commit history](https://github.com/hughescr/stryker-bun-runner/commits/main) for what changed. |
1053
1129
 
1054
1130
  ## Limitations
package/dist/index.d.ts CHANGED
@@ -482,8 +482,8 @@ export declare class BunTestRunner implements TestRunner {
482
482
  private buildTestsFromInspector;
483
483
  /**
484
484
  * Run all tests (dry run). Stryker always passes `options`; its
485
- * `coverageAnalysis` is read (to judge missing coverage, see
486
- * checkCoverageData), falling back to the Stryker options' value, and its
485
+ * `coverageAnalysis` decides what coverage the dry run collects and returns
486
+ * (see executeDryRun), falling back to the Stryker options' value, and its
487
487
  * `timeout` (dryRunTimeoutMinutes) only to warn when another run of the tests
488
488
  * might not fit (M-budget). bun.timeout bounds each child.
489
489
  */
@@ -505,9 +505,40 @@ export declare class BunTestRunner implements TestRunner {
505
505
  *
506
506
  * Every published run is earlier versions' inspected run with its result held back
507
507
  * until the rules pass; nothing is persisted before that ({@link publishDryRun}).
508
+ *
509
+ * With coverageAnalysis 'off' none of that applies: Stryker gets no coverage, so one
510
+ * plain inspected run of the tests ({@link runWithoutCoverage}). 'all' takes the
511
+ * same steps as 'perTest' and hands Stryker only which mutants were reached
512
+ * ({@link reachedOnly}).
508
513
  */
509
514
  private executeDryRun;
510
- /** K: the files of E that bun.alwaysImport keeps, with a warning for each pattern that keeps none. */
515
+ /**
516
+ * The dry run for coverageAnalysis 'off': Stryker then runs every test against every
517
+ * mutant and uses no coverage, so nothing the import list, the scan or the plain run
518
+ * would establish is used. One inspected run of the tests, with nothing imported first
519
+ * (bun.alwaysImport is not evaluated). The preload still records a key per test start,
520
+ * with no hit (coverageKeysOnly): that is how a test is credited to the test file that
521
+ * ran it, as with 'perTest', when bun's inspector reports the file of a shared helper
522
+ * that defined it; the completeness gate compares those keys too. Its campaign
523
+ * watches no file: with every test run for every mutant there is no coverage plan that
524
+ * a file the dry run missed could leave incomplete.
525
+ */
526
+ private runWithoutCoverage;
527
+ /** One info line naming bun.alwaysImport and bun.importDiscovery, when set: with coverageAnalysis 'off' neither has an effect. */
528
+ private noteOptionsWithoutEffect;
529
+ /** The test files this dry run hands bun, and what they expand to: the import scan's roots, and the files E loses. */
530
+ private dryRunTestFiles;
531
+ /**
532
+ * E: the files matched by mutate less the ones this dry run runs as tests (see
533
+ * withoutSelectedTestFiles), which are said at debug. When an entry cannot be expanded
534
+ * (the scan then does not start), the entries themselves are taken: a directory adds only
535
+ * files with a test suffix, which E never holds.
536
+ */
537
+ private withoutTestFilesRun;
538
+ /**
539
+ * K: the files of E that bun.alwaysImport keeps, with a warning for each pattern that keeps
540
+ * none: that it names only test files the dry run runs (`removed`), or that it matches nothing.
541
+ */
511
542
  private selectAlwaysImported;
512
543
  /** `file` relative to the dry run's project directory, as the messages show it (quoted when it must be, see displayName). */
513
544
  private projectPathsOf;
@@ -609,7 +640,7 @@ export declare class BunTestRunner implements TestRunner {
609
640
  /**
610
641
  * Hand Stryker a published run's result: persist the registry (for a green run with the
611
642
  * timeout correction and the campaign: a new generation, the watch list W of the files E
612
- * outside L and `seen`) and give the warnings of a completed run, then return it. Only
643
+ * outside L and `seen`, none with coverageAnalysis 'off') and give the warnings of a completed run, then return it. Only
613
644
  * a Complete result has anything to persist; any other is returned as it is. A run whose
614
645
  * watch list cannot be published with its registry is an Error instead.
615
646
  *
@@ -662,24 +693,30 @@ export declare class BunTestRunner implements TestRunner {
662
693
  * means the preload never ran, could not write (it logs a `[Stryker Coverage]`
663
694
  * line on the child's stderr), or the child exited before that afterAll.
664
695
  *
665
- * - coverageAnalysis 'perTest': the user asked for per-test coverage, and
696
+ * - coverageAnalysis 'perTest' or 'all': the user asked for coverage, and
666
697
  * silently running the full suite per mutant can turn a run of minutes into
667
- * hours — fail the dry run (Error), naming the file and likely causes.
668
- * 'all'/'off' remain available to run without it.
669
- * - 'all' (or unknown): warn with the same explanation; the run is correct, only slower.
670
- * - 'off': Stryker wants no coverage; say nothing.
698
+ * hours (with 'all', Stryker would plan as for 'off') — fail the dry run
699
+ * (Error), naming the file and likely causes. 'off' remains available to run
700
+ * without it. A present but empty coverage is not missing.
701
+ * - unknown: warn with the same explanation; the run is correct, only slower.
702
+ * - 'off': the file holds only the test keys that say which test file ran each
703
+ * test (see runWithoutCoverage); without it a test a shared helper defines is
704
+ * credited to the helper's file, so warn, and go on.
671
705
  * A dry run with failed tests is left alone: Stryker stops on those anyway,
672
706
  * and its failed-test report is the more useful message.
673
707
  *
674
708
  * When coverage exists but covers no mutant at all, every mutant will be
675
709
  * NoCoverage (Stryker's executeNoCoverage) — warn, since that is a legitimate
676
- * outcome only when the tests really never touch the mutated files.
710
+ * outcome only when the tests really never touch the mutated files ('off' records
711
+ * no hit, so it is not judged).
677
712
  *
678
713
  * `[Stryker Coverage]` diagnostics from the preload are otherwise dropped on a
679
714
  * green run (the child's stderr is only shown on failure), so they are
680
715
  * surfaced at warn here, or folded into the missing-coverage message.
681
716
  */
682
717
  private checkCoverageData;
718
+ /** {@link checkCoverageData} for a green dry run whose coverage file was missing, unreadable or empty. */
719
+ private missingCoverageResult;
683
720
  /**
684
721
  * Warn when a completed dry run used more than {@link DRY_RUN_TIMEOUT_WARN_RATIO}
685
722
  * of bun.timeout. bun.timeout now governs only the dry run (mutant runs follow
@@ -708,17 +745,20 @@ export declare class BunTestRunner implements TestRunner {
708
745
  * earlier versions wrote.
709
746
  *
710
747
  * A registry that cannot be written is only warned about, as in earlier versions,
711
- * unless the campaign has a watch list: its mutant runs would then not watch what the
712
- * dry run left out, so the failure is returned, as the dry run's Error message.
748
+ * unless the campaign has a watch list (its mutant runs would then not watch what the
749
+ * dry run left out) or an earlier run's registry stays in place (other workers would
750
+ * load it for this campaign): the failure is then returned, as the dry run's Error message.
713
751
  *
714
- * @returns Undefined, or the Error message when a campaign with a watch list could not be published
752
+ * @returns Undefined, or the Error message when a campaign could not be published (see registryWriteFailed)
715
753
  */
716
754
  private buildAndPersistTestRegistry;
717
755
  /**
718
756
  * A registry write failed: the dry run's Error message (M-publish) when the campaign has a
719
- * watch list, naming the file that could not be written; otherwise a warning, as in
720
- * earlier versions (the worker that ran the dry run still has its in-memory copy; other
721
- * workers fall back to raw names and log a warning), and undefined.
757
+ * watch list, naming the file that could not be written. For any other green run (a
758
+ * campaign) it is an Error too when an earlier run's registry is still in place: other
759
+ * workers would load its test names, test-file selection and the rest for this campaign.
760
+ * Otherwise a warning, as in earlier versions (the worker that ran the dry run still has
761
+ * its in-memory copy; other workers fall back to raw names and log a warning), and undefined.
722
762
  */
723
763
  private registryWriteFailed;
724
764
  /**
@@ -729,7 +769,8 @@ export declare class BunTestRunner implements TestRunner {
729
769
  private writeRegistry;
730
770
  /**
731
771
  * A new campaign's state for the registry: a new generation, W, and (inPlace only) the
732
- * fingerprint of E; W is written first, under the generation's own name.
772
+ * fingerprint of every file matched by mutate (test files included, as init() computes
773
+ * it in rejectIfCampaignStopped); W is written first, under the generation's own name.
733
774
  */
734
775
  private writeCampaignFiles;
735
776
  /**
@@ -996,8 +1037,9 @@ export declare class BunTestRunner implements TestRunner {
996
1037
  *
997
1038
  * Also collects any cross-test async coverage-bleed observations recorded
998
1039
  * by the preload (see {@link emitCoverageBleedWarnings}) and warns about
999
- * them. This method's sole call site is dryRun, so bleed detection is
1000
- * dry-run-only by construction — mutant runs never reach this code.
1040
+ * them, except with coverageAnalysis 'all' and 'off', which hand Stryker no per-test
1041
+ * attribution for a bleed to get wrong ('off' records no hit at all). This method's sole call site is dryRun,
1042
+ * so bleed detection is dry-run-only by construction — mutant runs never reach this code.
1001
1043
  */
1002
1044
  private collectAndRemapCoverage;
1003
1045
  /**
package/dist/index.js CHANGED
@@ -561,6 +561,9 @@ function refuseMessage(problems, incremental) {
561
561
  function unpublishedCampaignMessage(file, cause, watched) {
562
562
  return `stryker-bun-runner: cannot write ${escapeControlCharacters(file)} (${displayError(cause)}). The mutant runs need it to watch the ${count(watched, "file")} matched by mutate that the dry run ` + "neither imported before the tests nor saw load, so the dry run stops here. No mutant was scored. " + "Make the run's temporary directory writable, or set bun.alwaysImport to 'all' to import every mutated file first, as earlier versions did.";
563
563
  }
564
+ function staleRegistryMessage(file, cause, registry) {
565
+ return `stryker-bun-runner: cannot write ${escapeControlCharacters(file)} (${displayError(cause)}), so ${escapeControlCharacters(registry)} still holds an earlier dry run's test names, ` + "test file selection, durations and coverage by test file. The mutant runs of the other workers would use them for this run, so the dry run stops here. No mutant was scored. " + `Make the run's temporary directory writable, or remove ${escapeControlCharacters(registry)}.`;
566
+ }
564
567
  function seconds(ms) {
565
568
  return (ms / 1000).toFixed(1);
566
569
  }
@@ -580,6 +583,7 @@ import picomatch from "picomatch";
580
583
 
581
584
  // src/coverage/preload-logic.ts
582
585
  import { appendFileSync, closeSync, constants, openSync, readFileSync as readFileSync2, realpathSync as realpathSync2, renameSync, unlinkSync, writeSync } from "node:fs";
586
+ var COVERAGE_KEYS_ONLY_ENV = "__STRYKER_COVERAGE_KEYS_ONLY__";
583
587
  var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
584
588
  var PRELOAD_TIMINGS_ENV = "__STRYKER_PRELOAD_TIMINGS__";
585
589
  var PRELOAD_TIMINGS_PREFIX = "[Stryker Timings] ";
@@ -1270,9 +1274,14 @@ import path6 from "node:path";
1270
1274
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1271
1275
  import { glob } from "tinyglobby";
1272
1276
 
1277
+ // src/utils/code-files.ts
1278
+ var CODE_EXTENSION_PATTERN = String.raw`(?:[jt]sx?|[mc][jt]s)`;
1279
+ var CODE_FILE_RE = new RegExp(String.raw`\.${CODE_EXTENSION_PATTERN}$`);
1280
+ var DECLARATION_FILE_RE = /\.d\.[mc]?ts$/;
1281
+
1273
1282
  // src/utils/test-name-pattern.ts
1274
1283
  var MAX_TEST_NAME_PATTERN_LENGTH = 1e5;
1275
- var TEST_FILE_SUFFIX_PATTERN = String.raw`[._](?:test|spec)\.(?:[jt]sx?|[mc][jt]s)`;
1284
+ var TEST_FILE_SUFFIX_PATTERN = String.raw`[._](?:test|spec)\.${CODE_EXTENSION_PATTERN}`;
1276
1285
  var TEST_FILE_SUFFIX_RE = new RegExp(`${TEST_FILE_SUFFIX_PATTERN}$`, "i");
1277
1286
  var dedupSuffixRe = / \[\d+\]$/;
1278
1287
  var metaRe = /[.*+?^${}()|[\]\\/]/g;
@@ -1332,13 +1341,24 @@ async function resolveEagerModulesFromGlobs(mutateGlobs, cwd = process.cwd()) {
1332
1341
  ignore: negativePatterns,
1333
1342
  expandDirectories: false
1334
1343
  });
1335
- const sourceFileRe = /\.(?:tsx?|[cm]?js)$/;
1336
- const dtsRe = /\.d\.[cm]?ts$/;
1337
- const filtered = paths.filter((p) => sourceFileRe.test(p) && !dtsRe.test(p) && !TEST_FILE_SUFFIX_RE.test(p));
1344
+ const filtered = paths.filter((p) => CODE_FILE_RE.test(p) && !DECLARATION_FILE_RE.test(p) && !TEST_FILE_SUFFIX_RE.test(p));
1338
1345
  const resolved = filtered.map((p) => path6.resolve(p));
1339
1346
  resolved.sort((a, b) => a.localeCompare(b));
1340
1347
  return resolved;
1341
1348
  }
1349
+ async function withoutSelectedTestFiles(eager, testFiles, resolve = realpath2) {
1350
+ if (testFiles.length === 0) {
1351
+ return { kept: [...eager], removed: [] };
1352
+ }
1353
+ const real = async (files) => Promise.all(files.map(async (file) => resolve(file).catch(() => file)));
1354
+ const [eagerReal, testReal] = await Promise.all([real(eager), real(testFiles)]);
1355
+ const tests = new Set([...testFiles, ...testReal]);
1356
+ const isTest = eager.map((file, index) => tests.has(file) || tests.has(eagerReal[index]));
1357
+ return {
1358
+ kept: eager.filter((_file, index) => !isTest[index]),
1359
+ removed: eager.filter((_file, index) => isTest[index])
1360
+ };
1361
+ }
1342
1362
  function resolvePreloadTemplate(moduleDir) {
1343
1363
  const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
1344
1364
  if (isBundled) {
@@ -1590,6 +1610,15 @@ function sumHitsByMutant(coverage) {
1590
1610
  }
1591
1611
  return totals;
1592
1612
  }
1613
+ function reachedOnly(coverage) {
1614
+ const reached = {};
1615
+ for (const [mutantId, total] of sumHitsByMutant(coverage)) {
1616
+ if (total > 0) {
1617
+ reached[mutantId] = total;
1618
+ }
1619
+ }
1620
+ return { static: reached, perTest: {} };
1621
+ }
1593
1622
  function restoreHitTotals(rawCoverage, mapped) {
1594
1623
  const rawTotals = sumHitsByMutant(rawCoverage);
1595
1624
  const result = {
@@ -2568,6 +2597,7 @@ function buildChildEnv(options, spawnDepth) {
2568
2597
  __STRYKER_HIT_LIMIT__: options.hitLimit === undefined ? undefined : String(options.hitLimit),
2569
2598
  __STRYKER_HIT_LIMIT_TOKEN__: options.hitLimitToken,
2570
2599
  __STRYKER_COVERAGE_FILE__: options.coverageFile === "" ? undefined : options.coverageFile,
2600
+ [COVERAGE_KEYS_ONLY_ENV]: options.coverageKeysOnly === true ? "1" : undefined,
2571
2601
  __STRYKER_SYNC_PORT__: options.syncPort ? String(options.syncPort) : undefined,
2572
2602
  [SYNC_TOKEN_ENV]: options.syncToken,
2573
2603
  [DRY_RUN_PLAN_ENV]: options.dryRunPlan,
@@ -3960,7 +3990,14 @@ class SyncServer {
3960
3990
  this.pendingDrainClients.add(ws);
3961
3991
  return;
3962
3992
  }
3963
- this.drainInFlight ??= this.drainHandler();
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);
4000
+ }
3964
4001
  const inFlight = this.drainInFlight;
3965
4002
  (async () => {
3966
4003
  try {
@@ -4666,6 +4703,7 @@ function nonEmptyString(value) {
4666
4703
  var SAVE_TIME_LIMIT_MS = 5000;
4667
4704
  var OUTPUT_FILE_HINT = "To save the full output of the bun test process when this happens, set the bun.dryRunOutputFile option to a file path in your Stryker configuration and run again.";
4668
4705
  var REGISTRY_FILE = "registry.json";
4706
+ var NO_TEST_FILES = { entries: undefined, expanded: undefined };
4669
4707
 
4670
4708
  class WriteFailure extends Error {
4671
4709
  file;
@@ -5192,7 +5230,9 @@ class BunTestRunner {
5192
5230
  this.cachedEagerModulesCwd = eagerCwd;
5193
5231
  this.logger.debug("Resolved %d eager modules from mutate globs", this.cachedEagerModules.length);
5194
5232
  }
5195
- await this.rejectIfCampaignStopped(tempDir, this.cachedEagerModules);
5233
+ if (this.coverageAnalysis !== "off") {
5234
+ await this.rejectIfCampaignStopped(tempDir, this.cachedEagerModules);
5235
+ }
5196
5236
  this.preloadScriptPath = await generatePreloadScript({
5197
5237
  tempDir,
5198
5238
  coverageFile: this.coverageFilePath
@@ -5283,9 +5323,11 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
5283
5323
  }
5284
5324
  this.testFileDurations = parseTestFileDurations(parsed.testFileDurations);
5285
5325
  this.setTestFileCoverage(TestFileCoverage.fromJson(parsed.mutantTestFiles));
5286
- this.timeoutCorrectionMs = parsed.timeoutCorrectionMs;
5287
- const campaign = parseCampaignState(parsed.campaign);
5288
- this.campaign = campaign === undefined ? undefined : { ...campaign, dir: path15.dirname(registryPath), watched: new Set(campaign.watchList) };
5326
+ if (this.coverageAnalysis !== "off") {
5327
+ this.timeoutCorrectionMs = parsed.timeoutCorrectionMs;
5328
+ const campaign = parseCampaignState(parsed.campaign);
5329
+ this.campaign = campaign === undefined ? undefined : { ...campaign, dir: path15.dirname(registryPath), watched: new Set(campaign.watchList) };
5330
+ }
5289
5331
  this.logger.debug("Loaded dryRun registry from %s (%d entries)", registryPath, this.cachedTestNames.size);
5290
5332
  } catch (err) {
5291
5333
  const code = err.code;
@@ -5424,14 +5466,13 @@ ${stack}` : baseFailureMessage;
5424
5466
  this.applyDryRunTestFiles(options);
5425
5467
  this.logger.debug("Running dry run with inspector-based coverage collection...");
5426
5468
  const cwd = process.cwd();
5427
- const eager = this.cachedEagerModules ?? [];
5428
- const always = this.selectAlwaysImported(eager, cwd);
5429
- const ctx = {
5469
+ const matched = this.cachedEagerModules ?? [];
5470
+ const launchContext = {
5430
5471
  options,
5431
5472
  coverageAnalysis,
5432
5473
  cwd,
5433
- eager,
5434
- always,
5474
+ eager: matched,
5475
+ matched,
5435
5476
  runDir: this.tempDir ?? tmpdir2(),
5436
5477
  startedAt,
5437
5478
  profile,
@@ -5441,6 +5482,13 @@ ${stack}` : baseFailureMessage;
5441
5482
  if (this.inPlace && this.tempDir !== undefined) {
5442
5483
  await removeQuietly(path15.join(this.tempDir, ABORT_MARKER_FILE));
5443
5484
  }
5485
+ if (coverageAnalysis === "off") {
5486
+ return this.runWithoutCoverage(launchContext);
5487
+ }
5488
+ const tests = matched.length === 0 ? NO_TEST_FILES : await this.dryRunTestFiles(cwd);
5489
+ const { eager, removed } = await this.withoutTestFilesRun(launchContext, tests);
5490
+ const always = this.selectAlwaysImported(eager, removed, cwd);
5491
+ const ctx = { ...launchContext, eager, always, tests };
5444
5492
  const legacy = legacyReason(eager, always);
5445
5493
  if (legacy !== null) {
5446
5494
  this.logger.debug("Dry run: %s, so the runner imports all of them before the tests, with no import scan", legacy === "empty" ? "mutate matches no file" : "bun.alwaysImport keeps every file mutate matches");
@@ -5457,10 +5505,48 @@ ${stack}` : baseFailureMessage;
5457
5505
  }
5458
5506
  return this.runTwoRuns(ctx, { kind: "scan" });
5459
5507
  }
5460
- selectAlwaysImported(eager, cwd) {
5508
+ async runWithoutCoverage(ctx) {
5509
+ this.logger.debug("Dry run: coverageAnalysis is 'off', so the runner imports nothing before the tests, records no mutant coverage and runs the tests once");
5510
+ this.noteOptionsWithoutEffect();
5511
+ this.beforeLaunch(ctx);
5512
+ const imported = [];
5513
+ const pass = await this.runInspectedPass(ctx, imported, undefined);
5514
+ return this.publishDryRun(ctx, { ...pass, list: imported, record: undefined, elapsedMs: 0 });
5515
+ }
5516
+ noteOptionsWithoutEffect() {
5517
+ const set = [
5518
+ ...this.alwaysImport === undefined ? [] : ["bun.alwaysImport"],
5519
+ ...this.importDiscovery === undefined ? [] : ["bun.importDiscovery"]
5520
+ ];
5521
+ if (set.length > 0) {
5522
+ this.logger.info("%s %s no effect with coverageAnalysis 'off': its dry run imports no mutated file before the tests", set.join(" and "), set.length === 1 ? "has" : "have");
5523
+ }
5524
+ }
5525
+ async dryRunTestFiles(cwd) {
5526
+ const { testFiles } = await this.dryRunFiles(cwd);
5527
+ return { entries: testFiles, expanded: testFiles === undefined ? undefined : await expandTestFileEntries(testFiles, cwd, this.logger) };
5528
+ }
5529
+ async withoutTestFilesRun(ctx, tests) {
5530
+ const { expanded } = tests;
5531
+ let selected = [];
5532
+ if (expanded !== undefined) {
5533
+ selected = "files" in expanded ? expanded.files : tests.entries.map((entry) => path15.resolve(ctx.cwd, entry));
5534
+ }
5535
+ const split = await withoutSelectedTestFiles(ctx.matched, selected);
5536
+ if (split.removed.length > 0) {
5537
+ this.logger.debug("Dry run: %d file(s) matched by mutate are test files the dry run runs, so they are never imported before the tests: %s", split.removed.length, split.removed.map((file) => shownPath(file, ctx.cwd)).join(", "));
5538
+ }
5539
+ return { eager: split.kept, removed: split.removed };
5540
+ }
5541
+ selectAlwaysImported(eager, removed, cwd) {
5461
5542
  const selection = selectAlways(eager, this.alwaysImport, cwd);
5462
5543
  for (const pattern of selection.unmatched) {
5463
- this.logger.warn("bun.alwaysImport pattern %s matches none of the %d files matched by mutate", JSON.stringify(pattern), eager.length);
5544
+ const tests = selectAlways(removed, [pattern], cwd).files;
5545
+ if (tests.length > 0) {
5546
+ this.logger.warn("bun.alwaysImport pattern %s matches only test files the dry run runs (%s), and a test file is never imported before the tests", JSON.stringify(pattern), listText(tests.map((file) => shownPath(file, cwd))));
5547
+ } else {
5548
+ this.logger.warn("bun.alwaysImport pattern %s matches none of the %d files matched by mutate", JSON.stringify(pattern), eager.length);
5549
+ }
5464
5550
  }
5465
5551
  return selection.files;
5466
5552
  }
@@ -5508,15 +5594,14 @@ ${stack}` : baseFailureMessage;
5508
5594
  }
5509
5595
  }
5510
5596
  async importScanInput(ctx) {
5511
- const { testFiles } = await this.dryRunFiles(ctx.cwd);
5512
- if (testFiles === undefined) {
5597
+ const { expanded } = ctx.tests;
5598
+ if (expanded === undefined) {
5513
5599
  return { problem: "the dry run hands bun no list of test files (bun finds them itself), so the runner cannot name the test files to scan" };
5514
5600
  }
5515
5601
  const launch = scanLaunchArguments(this.bunArgs ?? [], { ...process.env, ...this.env }, ctx.cwd);
5516
5602
  if ("problem" in launch) {
5517
5603
  return launch;
5518
5604
  }
5519
- const expanded = await expandTestFileEntries(testFiles, ctx.cwd, this.logger);
5520
5605
  if ("problem" in expanded) {
5521
5606
  return expanded;
5522
5607
  }
@@ -5856,7 +5941,8 @@ ${outputLine}`;
5856
5941
  const { tests, testNameIndex, testFileCoverage, processResult, parsed, totalElapsedMs } = publication;
5857
5942
  const correction = timeoutCorrection(ctx.extraMs, performance.now() - ctx.startedAt, tests.map((test) => test.timeSpentMs));
5858
5943
  ctx.profile?.at("coverageChecked");
5859
- const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched: watchList(ctx.eager, launch.list, seen), eager: ctx.eager } : undefined;
5944
+ const watched = ctx.coverageAnalysis === "off" ? [] : watchList(ctx.eager, launch.list, seen);
5945
+ const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, matched: ctx.matched } : undefined;
5860
5946
  const unpublished = await this.buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaign);
5861
5947
  ctx.profile?.at("registryWritten");
5862
5948
  if (unpublished !== undefined) {
@@ -5921,6 +6007,7 @@ ${outputLine}`;
5921
6007
  preloadScript: this.preloadScriptPath,
5922
6008
  dryRunPlan: planFile,
5923
6009
  coverageFile,
6010
+ coverageKeysOnly: coverageAnalysis === "off",
5924
6011
  inspect: true,
5925
6012
  sequentialMode: true,
5926
6013
  syncPort,
@@ -6082,7 +6169,7 @@ exit=%s timedOut=%s
6082
6169
  }
6083
6170
  }
6084
6171
  async buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, inspectorState, run, spawnInfo, profile) {
6085
- const { coverage: mutantCoverage, inspectorIdToProjectFile, coverageKeys, testFileCoverage, rawCoverage, counterKeyToTestName } = await this.collectAndRemapCoverage(run.coverageFile, testHierarchy, executionOrder, profile);
6172
+ const { coverage: mutantCoverage, inspectorIdToProjectFile, coverageKeys, testFileCoverage, rawCoverage, counterKeyToTestName } = await this.collectAndRemapCoverage(run.coverageFile, testHierarchy, executionOrder, run.coverageAnalysis, profile);
6086
6173
  profile?.at("coverageMapped");
6087
6174
  const { tests, testNameIndex } = this.buildTestsFromInspector(testHierarchy, [...new Set(executionOrder)], parsed, totalElapsedMs, inspectorIdToProjectFile);
6088
6175
  tests.sort((a, b) => a.name.localeCompare(b.name));
@@ -6106,16 +6193,17 @@ exit=%s timedOut=%s
6106
6193
  if (coverageResult) {
6107
6194
  return { result: coverageResult };
6108
6195
  }
6196
+ const off = run.coverageAnalysis === "off";
6197
+ const complete = { status: DryRunStatus.Complete, tests };
6198
+ if (mutantCoverage !== undefined && !off) {
6199
+ complete.mutantCoverage = run.coverageAnalysis === "all" ? reachedOnly(mutantCoverage) : mutantCoverage;
6200
+ }
6109
6201
  return {
6110
- result: {
6111
- status: DryRunStatus.Complete,
6112
- tests,
6113
- mutantCoverage
6114
- },
6202
+ result: complete,
6115
6203
  publication: {
6116
6204
  tests,
6117
6205
  testNameIndex,
6118
- testFileCoverage,
6206
+ testFileCoverage: off ? undefined : testFileCoverage,
6119
6207
  rawCoverage,
6120
6208
  testNames: counterKeyToTestName,
6121
6209
  processResult: result,
@@ -6126,8 +6214,7 @@ exit=%s timedOut=%s
6126
6214
  }
6127
6215
  checkCoverageData(coverage, tests, coverageAnalysis, stderr, coverageFile) {
6128
6216
  const preloadLines = extractPreloadCoverageDiagnostics(stderr);
6129
- const coverageMissing = coverage === undefined && coverageAnalysis !== "off";
6130
- if (!coverageMissing || tests.some((t) => t.status === TestStatus.Failed)) {
6217
+ if (coverage !== undefined || tests.some((t) => t.status === TestStatus.Failed)) {
6131
6218
  if (preloadLines.length > 0) {
6132
6219
  this.logger.warn(`The coverage preload reported problems on the dry-run child's stderr:
6133
6220
  %s`, preloadLines.join(`
@@ -6138,20 +6225,29 @@ exit=%s timedOut=%s
6138
6225
  }
6139
6226
  return null;
6140
6227
  }
6228
+ return this.missingCoverageResult(coverageAnalysis, preloadLines, coverageFile);
6229
+ }
6230
+ missingCoverageResult(coverageAnalysis, preloadLines, coverageFile) {
6231
+ const file = coverageFile ?? "(none configured)";
6141
6232
  const coverageDir = coverageFile === undefined ? tmpdir2() : path15.dirname(coverageFile);
6142
- const parts = [
6143
- `stryker-bun-runner: the dry run produced no mutant coverage data — the coverage file ${coverageFile ?? "(none configured)"} was missing, unreadable or empty. ` + "Without it Stryker runs the full test suite for every mutant, which is far slower than running each mutant's covering tests. " + "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).`
6144
- ];
6145
- if (coverageAnalysis === "perTest") {
6146
- parts.push("Failing the dry run because coverageAnalysis is 'perTest'; set coverageAnalysis to 'all' or 'off' to run without per-test coverage instead.");
6147
- }
6148
- if (preloadLines.length > 0) {
6149
- parts.push(`Coverage preload diagnostics from the child's stderr:
6233
+ 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
+ const diagnostics = preloadLines.length > 0 ? [`Coverage preload diagnostics from the child's stderr:
6150
6235
  ${preloadLines.join(`
6151
- `)}`);
6236
+ `)}`] : [];
6237
+ if (coverageAnalysis === "off") {
6238
+ const what = `stryker-bun-runner: the dry run's record of which test file ran each test, ${file}, was missing, unreadable or empty, ` + "so each test is named after the file bun reports for it: a test that a shared helper file defines is credited to that file, not to the test file that ran it.";
6239
+ this.logger.warn("%s", [what, causes, ...diagnostics].join(" "));
6240
+ return null;
6152
6241
  }
6153
- const message = parts.join(" ");
6154
- if (coverageAnalysis === "perTest") {
6242
+ const fails = coverageAnalysis === "perTest" || coverageAnalysis === "all";
6243
+ const what = `stryker-bun-runner: the dry run produced no mutant coverage data — the coverage file ${file} was missing, unreadable or empty. ` + "Without it Stryker runs the full test suite for every mutant, which is far slower than running each mutant's covering tests.";
6244
+ const message = [
6245
+ what,
6246
+ causes,
6247
+ ...fails ? [`Failing the dry run because coverageAnalysis is '${coverageAnalysis}'; set coverageAnalysis to 'off' to run without coverage instead.`] : [],
6248
+ ...diagnostics
6249
+ ].join(" ");
6250
+ if (fails) {
6155
6251
  this.logger.error("%s", message);
6156
6252
  return { status: DryRunStatus.Error, errorMessage: message };
6157
6253
  }
@@ -6199,14 +6295,24 @@ ${preloadLines.join(`
6199
6295
  await this.writeRegistry(indexes, testFileCoverage, campaignInput);
6200
6296
  return;
6201
6297
  } catch (error) {
6202
- return this.registryWriteFailed(error, campaignInput?.watched.length ?? 0);
6298
+ return this.registryWriteFailed(error, campaignInput);
6203
6299
  }
6204
6300
  }
6205
- registryWriteFailed(error, watched) {
6301
+ async registryWriteFailed(failure, campaignInput) {
6302
+ const watched = campaignInput?.watched.length ?? 0;
6206
6303
  if (watched > 0) {
6207
- return error instanceof WriteFailure ? unpublishedCampaignMessage(error.file, error.message, watched) : unpublishedCampaignMessage("the run's temporary directory", errorText(error), watched);
6304
+ return failure instanceof WriteFailure ? unpublishedCampaignMessage(failure.file, failure.message, watched) : unpublishedCampaignMessage("the run's temporary directory", errorText(failure), watched);
6208
6305
  }
6209
- this.warnRegistryWriteFailed(errorText(error));
6306
+ if (campaignInput !== undefined && failure instanceof WriteFailure) {
6307
+ const registryPath = path15.join(path15.dirname(failure.file), REGISTRY_FILE);
6308
+ const earlier = await fsPromises3.lstat(registryPath).catch(() => {
6309
+ return;
6310
+ });
6311
+ if (earlier !== undefined) {
6312
+ return staleRegistryMessage(failure.file, failure.message, registryPath);
6313
+ }
6314
+ }
6315
+ this.warnRegistryWriteFailed(errorText(failure));
6210
6316
  return;
6211
6317
  }
6212
6318
  async writeRegistry(indexes, testFileCoverage, campaignInput) {
@@ -6251,7 +6357,7 @@ ${preloadLines.join(`
6251
6357
  generation,
6252
6358
  watchList: [...watched],
6253
6359
  watchListFile,
6254
- fingerprint: watchListFile === null || !this.inPlace ? null : await campaignFingerprint(campaignInput.eager)
6360
+ fingerprint: watchListFile === null || !this.inPlace ? null : await campaignFingerprint(campaignInput.matched)
6255
6361
  };
6256
6362
  if (watchListFile !== null) {
6257
6363
  const file = path15.join(runDir, watchListFile);
@@ -6708,7 +6814,7 @@ ${outputLine}`;
6708
6814
  errorMessage
6709
6815
  };
6710
6816
  }
6711
- async collectAndRemapCoverage(coverageFile, testHierarchy, executionOrder, profile) {
6817
+ async collectAndRemapCoverage(coverageFile, testHierarchy, executionOrder, coverageAnalysis, profile) {
6712
6818
  const testMap = new Map(testHierarchy.map((t) => [t.id, t]));
6713
6819
  if (!coverageFile) {
6714
6820
  return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined, counterKeyToTestName: new Map };
@@ -6724,7 +6830,9 @@ ${outputLine}`;
6724
6830
  }
6725
6831
  const testFileCoverage = TestFileCoverage.fromPerTest(rawCoverage.perTest);
6726
6832
  const { coverage, inspectorIdToProjectFile, counterKeyToTestName, rawKeyCount, orphanedKeyCount } = mapCoverageToInspectorIds(rawCoverage, executionOrder, testMap, this.logger);
6727
- this.emitCoverageBleedWarnings(lateHits, counterKeyToTestName);
6833
+ if (coverageAnalysis !== "all" && coverageAnalysis !== "off") {
6834
+ this.emitCoverageBleedWarnings(lateHits, counterKeyToTestName);
6835
+ }
6728
6836
  return {
6729
6837
  coverage,
6730
6838
  inspectorIdToProjectFile,
@@ -267,6 +267,7 @@ function installLoadSensors(deps) {
267
267
  // src/coverage/preload-logic.ts
268
268
  var PreloadError = Error;
269
269
  var preloadFs = { appendFileSync, closeSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeSync };
270
+ var COVERAGE_KEYS_ONLY_ENV = "__STRYKER_COVERAGE_KEYS_ONLY__";
270
271
  var HIT_LIMIT_TOKEN_ENV = "__STRYKER_HIT_LIMIT_TOKEN__";
271
272
  var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
272
273
  function getPreloadConfig() {
@@ -276,7 +277,8 @@ function getPreloadConfig() {
276
277
  coverageFile: process.env.__STRYKER_COVERAGE_FILE__,
277
278
  activeMutant: process.env.__STRYKER_ACTIVE_MUTANT__,
278
279
  hitLimit: parseHitLimit(process.env.__STRYKER_HIT_LIMIT__),
279
- hitLimitToken: process.env[HIT_LIMIT_TOKEN_ENV]
280
+ hitLimitToken: process.env[HIT_LIMIT_TOKEN_ENV],
281
+ keysOnly: process.env[COVERAGE_KEYS_ONLY_ENV] === "1"
280
282
  };
281
283
  }
282
284
  function parseHitLimit(raw) {
@@ -428,6 +430,13 @@ function serializeCoverageData(mutantCoverage, lateHits = [], gapTracker) {
428
430
  };
429
431
  return JSON.stringify(data);
430
432
  }
433
+ function testKeysOnly(mutantCoverage) {
434
+ const perTest = {};
435
+ for (const key of Object.keys(mutantCoverage?.perTest ?? {})) {
436
+ perTest[key] = {};
437
+ }
438
+ return { perTest, static: {} };
439
+ }
431
440
  var COVERAGE_APPEND_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW;
432
441
  function writeCoverageToFile(coverageFile, data) {
433
442
  const line = typeof data === "string" ? data : JSON.stringify(data);
@@ -916,7 +925,7 @@ Object.defineProperty(describe2, "concurrent", { value: describe2, writable: tru
916
925
  Object.defineProperty(test, "concurrent", { value: test, writable: true, configurable: true });
917
926
  Object.defineProperty(it, "concurrent", { value: it, writable: true, configurable: true });
918
927
  var config = getPreloadConfig();
919
- var { syncPort, syncToken, coverageFile, activeMutant, hitLimit, hitLimitToken } = config;
928
+ var { syncPort, syncToken, coverageFile, activeMutant, hitLimit, hitLimitToken, keysOnly } = config;
920
929
  delete process.env[HIT_LIMIT_TOKEN_ENV];
921
930
  delete process.env[SYNC_TOKEN_ENV];
922
931
  var planFile = process.env[DRY_RUN_PLAN_ENV];
@@ -1019,7 +1028,8 @@ var writeCoverageData = () => {
1019
1028
  if (!shouldCollectCoverage2 || !coverageFile) {
1020
1029
  return;
1021
1030
  }
1022
- const data = serializeCoverageData(strykerGlobal.mutantCoverage, lateHits, gapTracker);
1031
+ const recorded = keysOnly ? testKeysOnly(strykerGlobal.mutantCoverage) : strykerGlobal.mutantCoverage;
1032
+ const data = serializeCoverageData(recorded, keysOnly ? [] : lateHits, gapTracker);
1023
1033
  if (timings) {
1024
1034
  timings["at.coverageFormatted"] = nowEpoch();
1025
1035
  timings["bytes.coverage"] = data.length;
@@ -1033,6 +1043,45 @@ var writeCoverageData = () => {
1033
1043
  console.error(`[Stryker Coverage] Failed to write coverage to ${coverageFile}: ${error instanceof Error ? error.message : String(error)}`);
1034
1044
  }
1035
1045
  };
1046
+ var drainAndClose = async () => {
1047
+ if (ws && ws.readyState === WebSocket.OPEN) {
1048
+ try {
1049
+ await new Promise((resolve) => {
1050
+ const wsForDrain = ws;
1051
+ const timeout = setTimeout(() => {
1052
+ console.warn("[Stryker] Timeout waiting for drain acknowledgment");
1053
+ resolve();
1054
+ }, DRAIN_ACK_TIMEOUT_MS);
1055
+ wsForDrain.onmessage = (event) => {
1056
+ if (event.data === "drained") {
1057
+ clearTimeout(timeout);
1058
+ resolve();
1059
+ }
1060
+ };
1061
+ wsForDrain.onerror = () => {
1062
+ clearTimeout(timeout);
1063
+ resolve();
1064
+ };
1065
+ try {
1066
+ if (timings) {
1067
+ timings["at.drainRequested"] = nowEpoch();
1068
+ }
1069
+ wsForDrain.send("drain-request");
1070
+ } catch {
1071
+ clearTimeout(timeout);
1072
+ resolve();
1073
+ }
1074
+ });
1075
+ } catch (error) {
1076
+ console.warn("[Stryker] Error during drain handshake:", error);
1077
+ }
1078
+ }
1079
+ if (timings) {
1080
+ timings["at.drained"] = nowEpoch();
1081
+ preloadFs.writeSync(2, formatPreloadTimings(timings));
1082
+ }
1083
+ ws?.close();
1084
+ };
1036
1085
  if (shouldCollectCoverage2) {
1037
1086
  beforeEach(() => {
1038
1087
  const hookStart = timings ? performance.now() : 0;
@@ -1087,42 +1136,6 @@ if (shouldCollectCoverage2) {
1087
1136
  writeCoverageData();
1088
1137
  lateHits.length = 0;
1089
1138
  writeDryRunRecord();
1090
- if (ws && ws.readyState === WebSocket.OPEN) {
1091
- try {
1092
- await new Promise((resolve) => {
1093
- const wsForDrain = ws;
1094
- const timeout = setTimeout(() => {
1095
- console.warn("[Stryker] Timeout waiting for drain acknowledgment");
1096
- resolve();
1097
- }, DRAIN_ACK_TIMEOUT_MS);
1098
- wsForDrain.onmessage = (event) => {
1099
- if (event.data === "drained") {
1100
- clearTimeout(timeout);
1101
- resolve();
1102
- }
1103
- };
1104
- wsForDrain.onerror = () => {
1105
- clearTimeout(timeout);
1106
- resolve();
1107
- };
1108
- try {
1109
- if (timings) {
1110
- timings["at.drainRequested"] = nowEpoch();
1111
- }
1112
- wsForDrain.send("drain-request");
1113
- } catch {
1114
- clearTimeout(timeout);
1115
- resolve();
1116
- }
1117
- });
1118
- } catch (error) {
1119
- console.warn("[Stryker] Error during drain handshake:", error);
1120
- }
1121
- }
1122
- if (timings) {
1123
- timings["at.drained"] = nowEpoch();
1124
- preloadFs.writeSync(2, formatPreloadTimings(timings));
1125
- }
1126
- ws?.close();
1139
+ await drainAndClose();
1127
1140
  });
1128
1141
  }
@@ -4,6 +4,12 @@ import { readFileSync, realpathSync, statSync } from "fs";
4
4
  import { createRequire, isBuiltin } from "module";
5
5
  import path from "path";
6
6
  import { pathToFileURL } from "url";
7
+
8
+ // src/utils/code-files.ts
9
+ var CODE_EXTENSION_PATTERN = String.raw`(?:[jt]sx?|[mc][jt]s)`;
10
+ var CODE_FILE_RE = new RegExp(String.raw`\.${CODE_EXTENSION_PATTERN}$`);
11
+
12
+ // src/coverage/import-scan.ts
7
13
  var INSTRUMENTER_GLOBAL_IDIOM = 'globalThis.Math === Math && globalThis || new Function("return this")()';
8
14
 
9
15
  class ScanProblem extends Error {
@@ -533,7 +539,6 @@ function loaderOf(file) {
533
539
  }
534
540
  return /\.[cm]js$/.test(file) ? "js" : "jsx";
535
541
  }
536
- var CODE_FILE = /\.(?:[cm]?[jt]s|[jt]sx)$/;
537
542
  var JSX_RUNTIME = /^.+\/jsx(?:-dev)?-runtime$/;
538
543
  var DIRECTORY_CONFIGS = ["tsconfig.json", "jsconfig.json"];
539
544
  var RUNTIME = "/jsx-runtime";
@@ -582,6 +587,7 @@ function real(file) {
582
587
  return file;
583
588
  }
584
589
  }
590
+ var SCAN_DEFINE = Object.fromEntries(["process.env.NODE_ENV", "process.env.BUN_ENV", "process.browser"].map((key) => [key, key]));
585
591
 
586
592
  class ImportScan {
587
593
  input;
@@ -594,7 +600,7 @@ class ImportScan {
594
600
  notes = [];
595
601
  tsconfig;
596
602
  transpilers = new Map;
597
- outputScanner = new Bun.Transpiler({ loader: "js" });
603
+ outputScanner = new Bun.Transpiler({ loader: "js", define: SCAN_DEFINE });
598
604
  resolutions = new Map;
599
605
  requires = new Map;
600
606
  configChains = new Map;
@@ -697,7 +703,7 @@ class ImportScan {
697
703
  const key = `${loader} ${autoImportJSX}`;
698
704
  let transpiler = this.transpilers.get(key);
699
705
  if (transpiler === undefined) {
700
- const options = { loader, trimUnusedImports: loader === "ts" || loader === "tsx", autoImportJSX };
706
+ const options = { loader, trimUnusedImports: loader === "ts" || loader === "tsx", autoImportJSX, define: SCAN_DEFINE };
701
707
  try {
702
708
  transpiler = new Bun.Transpiler({ ...options, ...this.tsconfig === undefined ? {} : { tsconfig: this.tsconfig } });
703
709
  } catch (error) {
@@ -790,7 +796,7 @@ class ImportScan {
790
796
  if (importTarget !== requireTarget) {
791
797
  return { kind: "unknown", reason: `${where} resolves differently for import and require` };
792
798
  }
793
- return CODE_FILE.test(importTarget) ? { kind: "follow", file: importTarget } : { kind: "ignore", projectFile: true };
799
+ return CODE_FILE_RE.test(importTarget) ? { kind: "follow", file: importTarget } : { kind: "ignore", projectFile: true };
794
800
  }
795
801
  isProjectCode(target) {
796
802
  return path.isAbsolute(target) && (!this.isPackageCode(target) || this.candidatesAt.has(target));
@@ -890,6 +896,7 @@ if (import.meta.main) {
890
896
  export {
891
897
  INSTRUMENTER_GLOBAL_IDIOM,
892
898
  MACRO_ATTRIBUTE,
899
+ SCAN_DEFINE,
893
900
  ScanProblem,
894
901
  analyseOutput,
895
902
  generatedJsxResolution,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hughescr/stryker-bun-runner",
3
- "version": "1.6.1",
3
+ "version": "1.7.1",
4
4
  "description": "Stryker mutation testing test runner plugin for Bun (bun test), with per-test coverage",
5
5
  "keywords": [
6
6
  "stryker",