@cosyte/vitest-config 0.1.3 → 0.1.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 57847cb: The snippet harness can run every code sample, not only the ones tagged `runnable`: `docSnippetSuite({ every: true })` runs each `ts`, `typescript`, `tsx`, `js`, `javascript` and `mjs` block, and a block that cannot run says why in its fence (`ts no-run <reason>`), which the test report lists as skipped with that reason; a `no-run` with no reason fails. In that mode a JavaScript sample runs as a `.mjs` module, so TypeScript syntax in it fails, and a `tsx` sample as a `.tsx` module; each sample `extractSamples` returns names its module in a new `extension` field, which `runSnippet` reads. New exports: `extractSamples`, `planSamples` and `SAMPLE_LANGS`. Without `every`, nothing changes: every `runnable` block, `tsx` included, still runs as a `.ts` module.
8
+ - 65208bf: In every-sample mode, `docSnippetSuite({ every: true })` now type-checks each TypeScript sample (`ts`, `typescript`, `tsx`) against the package's types before it runs it, so a sample with a type error fails even though it would run. The samples compile as a reader's project would compile them: each its own module, importing the package by its published name, under the project's `tsconfig.json` (the new `tsconfig` option, or the one in the working directory) with emit, its folders and the unused-name checks off. A sample whose types cannot be checked says why in its fence, `ts no-typecheck <reason>`; it still runs, its test name carries the reason, and a `no-typecheck` with no reason fails. This needs `typescript`, now an optional peer dependency. Walking `docsDir`, every-sample mode also leaves out the generated reference under `api/`, whose examples are parts of a signature's documentation; `includeGenerated: true` walks it too. New export: `typecheckSamples`. Without `every`, nothing changes.
9
+ - 5a0470a: Adds mutation testing beside the Vitest config. `@cosyte/vitest-config/stryker` exports `cosyteStryker(options?)`, a StrykerJS config for the Vitest runner (resolved from this package, so it works under pnpm), with per-test coverage in Vitest's forks pool, every mutant kept (static ones too), no score threshold of its own, and the JSON report at `reports/mutation/mutation.json`. The new bin, `cosyte-mutate`, runs `full` over everything the config names, or `changed --base <ref>` over only the source files changed against the merge base of that ref and HEAD, writing `reports/mutation/changed.json`; a change with no changed source file starts no run, writes an empty report and exits 0, and a run that cannot start exits 2. `@cosyte/vitest-config/mutate` is the bin's body. `@stryker-mutator/core` and `@stryker-mutator/vitest-runner` 10 are optional peer dependencies, and so is `@cosyte/script-utils`, which a changed run imports when it starts to read what a change touched, so a package that does not mutate installs nothing new; a changed run without it exits 2 and names it. `cosyteVitest` also adds the `json-summary` coverage reporter, so a coverage run writes `coverage/coverage-summary.json`, the totals `cosyte-ratchet` compares with a floor file; the `text`, `html` and `lcov` reporters, the thresholds and the excludes are unchanged.
10
+ - Updated dependencies [65208bf]
11
+ - Updated dependencies [57847cb]
12
+ - Updated dependencies [cc43161]
13
+ - Updated dependencies [5a0470a]
14
+ - @cosyte/script-utils@0.1.9
15
+
3
16
  ## 0.1.3
4
17
 
5
18
  ### Patch Changes
package/README.md CHANGED
@@ -14,7 +14,7 @@
14
14
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/cosyte/config/blob/main/LICENSE)
15
15
  [![Node](https://img.shields.io/badge/node-%3E%3D22.14-brightgreen.svg)](https://nodejs.org)
16
16
 
17
- Shared Vitest config (v8 coverage, per-directory >=90 gates) for @cosyte/\* packages.
17
+ Shared Vitest config (v8 coverage, per-directory >=90 gates) and StrykerJS mutation testing config for @cosyte/\* packages.
18
18
 
19
19
  ## Why this exists
20
20
 
@@ -27,6 +27,10 @@ The nearest alternative is a hand-written `vitest.config.ts` per repository with
27
27
  copied in. That is the drift this removes, and it is also where the second half of this package comes
28
28
  from: nothing in that alternative proves the examples in your documentation still work.
29
29
 
30
+ The third half is mutation testing. Coverage says a line ran; it does not say a test would notice
31
+ if the line were wrong. `@cosyte/vitest-config/stryker` runs the same Vitest suites under StrykerJS,
32
+ which changes the code one small way at a time and counts the changes no test noticed.
33
+
30
34
  ## Status
31
35
 
32
36
  `@cosyte/vitest-config` is on the Cosyte 0.1.x line: the public API is settled and bump types follow ordinary semver.
@@ -36,6 +40,10 @@ Still moving: the coverage exclude list and the snippet-suite options (`runnable
36
40
  the `cosyteVitest(options)` signature are the settled parts, and a change to either is recorded with
37
41
  the bump type it deserves rather than absorbed into a patch.
38
42
 
43
+ The mutation-testing entry points, `/stryker`, `/mutate` and the `cosyte-mutate` bin, are new and
44
+ the least settled part. In particular, the changed-files run mutates each changed file whole;
45
+ whether it should mutate only the changed lines, which is faster on a large file, is open.
46
+
39
47
  ## Install
40
48
 
41
49
  ```sh
@@ -46,6 +54,15 @@ pnpm add -D @cosyte/vitest-config vitest @vitest/coverage-v8 vite
46
54
  Install `vite` explicitly: Vitest 4 and 5 require major version 6 or later, and without a direct
47
55
  declaration the resolver will happily keep an incompatible vite 5. Node `>=22.14`. ESM only.
48
56
 
57
+ For mutation testing, also install the optional peers: StrykerJS 10 and its Vitest runner, and
58
+ `@cosyte/script-utils`, which `cosyte-mutate changed` reads a change with. A package that uses only
59
+ the Vitest config installs none of them; `cosyte-mutate changed` without `@cosyte/script-utils`
60
+ exits 2 and names it.
61
+
62
+ ```sh
63
+ pnpm add -D @stryker-mutator/core @stryker-mutator/vitest-runner @cosyte/script-utils
64
+ ```
65
+
49
66
  ## Usage
50
67
 
51
68
  `vitest.config.ts` exports what the factory returns:
@@ -67,6 +84,9 @@ gate, which is what stops a well-covered helper directory paying for an untested
67
84
  | -------------------------------- | ------------------------------------------------------------------- |
68
85
  | `@cosyte/vitest-config` | the `cosyteVitest(opts?)` factory, returning a Vitest config object |
69
86
  | `@cosyte/vitest-config/snippets` | the doc/code-agreement harness described under the API below |
87
+ | `@cosyte/vitest-config/stryker` | `cosyteStryker(options?)`, the shared StrykerJS config |
88
+ | `@cosyte/vitest-config/mutate` | `runMutate`, the body of the `cosyte-mutate` bin, and its parts |
89
+ | `cosyte-mutate` (bin) | `full`, and `changed --base <ref>` |
70
90
 
71
91
  They are separate subpaths because they are separately adoptable, and importing the config never
72
92
  loads the harness. `extractRunnableSnippets` is the primitive that decides what runs, and it reports
@@ -90,17 +110,113 @@ consumer cannot reach:
90
110
  for any other Vitest option. Both are merged last, so a repo that genuinely cannot hold >= 90 in
91
111
  one directory lowers that one key rather than abandoning the config.
92
112
  - `docSnippetSuite` takes `docsDir` or `files`, `include` (default `.md` and `.mdx`), `resolve`,
93
- `runnableTag` (default `"runnable"`), `name`, `requireSnippet` and `tmpDir`.
113
+ `runnableTag` (default `"runnable"`), `name`, `requireSnippet`, `tmpDir`, `every`,
114
+ `includeGenerated` and `tsconfig`.
115
+
116
+ `cosyteStryker` takes `mutate`, `vitestConfig` and `stryker` (any other Stryker option, merged
117
+ last); its defaults and the reason for each are tabled under the mutation section below.
94
118
 
95
119
  A package with no runnable snippets yields an empty, passing suite unless `requireSnippet` is set:
96
120
  absence degrades quietly, a _wrong_ snippet fails loudly. Lowering a coverage threshold is the
97
121
  override worth arguing about in review, because unlike the others it changes what CI will let
98
122
  through.
99
123
 
124
+ ## Mutation testing: `/stryker` and `cosyte-mutate`
125
+
126
+ A `stryker.config.mjs` at the package root exports what the factory returns:
127
+
128
+ ```ts runnable
129
+ import { cosyteStryker } from "@cosyte/vitest-config/stryker";
130
+
131
+ const config = cosyteStryker();
132
+ config.testRunner; // => "vitest"
133
+ config.ignoreStatic; // => false
134
+ config.jsonReporter; // => { fileName: "reports/mutation/mutation.json" }
135
+ ```
136
+
137
+ Then, from the same directory:
138
+
139
+ ```sh
140
+ pnpm exec cosyte-mutate full # every file the config names
141
+ pnpm exec cosyte-mutate changed --base origin/main # only what this change touched
142
+ pnpm exec cosyte-ratchet check --skip coverage --base origin/main
143
+ ```
144
+
145
+ `full` writes `reports/mutation/mutation.json`, the report the floor file's mutation score is read
146
+ from. `changed` writes `reports/mutation/changed.json` beside it, so a run over a few files is never
147
+ read as the whole package's score. A change with no changed source file starts no run: it writes an
148
+ empty report, so the ratchet can tell "ran, nothing to mutate" from "never ran", and exits 0.
149
+ `cosyte-mutate` exits 0 when the run finished and 2 when it could not run; it does not judge the
150
+ score.
151
+
152
+ The `/mutate` entry point is the bin's body and the pieces it is built of, for a caller that runs
153
+ it from its own script. `selectChangedFiles` is the rule a changed run picks its files by:
154
+
155
+ ```ts runnable
156
+ import { selectChangedFiles } from "@cosyte/vitest-config/mutate";
157
+
158
+ const picked = selectChangedFiles({
159
+ changed: ["src/a.ts", "src/a.test.ts", "README.md"],
160
+ root: "/repo",
161
+ cwd: "/repo",
162
+ patterns: ["src/**/*.ts", "!src/**/*.test.ts"],
163
+ });
164
+ picked; // => ["src/a.ts"]
165
+ ```
166
+
167
+ ### What the Stryker config sets, and why
168
+
169
+ `cosyteStryker({ mutate, vitestConfig, stryker })` takes the file list, the Vitest config file, and
170
+ any other Stryker option, merged last, so a package can change anything below. What each default is
171
+ and why:
172
+
173
+ | setting | default | why |
174
+ | ------------------ | ------------------------------------------- | ---------------------------------------------------------------------------- |
175
+ | `testRunner` | `vitest`, resolved from this package | Stryker cannot find a plugin by name under pnpm |
176
+ | `vitest.pool` | `forks` | Vitest's own default; Stryker's is threads, where `process.chdir()` throws |
177
+ | `coverageAnalysis` | `perTest` | each mutant runs only the tests that reach it |
178
+ | `mutate` | `src/**/*.ts` without tests, barrels, types | the same files `@cosyte/vitest-config` measures coverage over |
179
+ | `ignoreStatic` | `false` | static mutants are module-level tables, such as a scanner's patterns: kept |
180
+ | `thresholds.break` | `null` | the floor file decides a drop, not Stryker |
181
+ | reports | JSON and HTML under `reports/mutation/` | JSON for the ratchet and CI, HTML for a person reading the surviving mutants |
182
+
183
+ Setting `ignoreStatic: true` makes a run faster and is the override worth arguing about in review: it
184
+ drops every mutant in module-level code from the score without an inline reason for any of them.
185
+
186
+ ### An exception, and why it needs two comments
187
+
188
+ A mutant that cannot be killed (an equivalent mutant, or a line only a child process reaches) gets
189
+ an inline exception that names its reason:
190
+
191
+ ```js
192
+ // Stryker disable next-line ConditionalExpression: both branches return the same value here
193
+ ```
194
+
195
+ Mutation testing does not read coverage's ignore hints, so a line excluded from coverage with
196
+ `/* v8 ignore next -- reason */` still has its mutants, and they show as not covered. Such a line
197
+ needs both comments, each with its reason. `cosyte-ratchet check --base` lists every exception in
198
+ changed code, so the pull request can carry the list.
199
+
200
+ ## The 90 gates and the floor file
201
+
202
+ The 90 thresholds are one fixed minimum for every package, and they fail the test run itself. The
203
+ floor file, `quality-floor.json`, held by `cosyte-ratchet` in `@cosyte/script-utils`, is each
204
+ repository's own record of what it measured, and it only rises. The two do different jobs:
205
+
206
+ - A package above 90 on a metric is held by its floor, which sits at what it measured; the 90 gate
207
+ is a backstop that does not fire.
208
+ - A package below 90 on a metric lowers that one key with `coverageThresholds`, and its floor still
209
+ holds the measured value, so the number can only rise from there.
210
+ - A pull request's own changed lines are held to 100 by the ratchet, whatever either number says.
211
+
212
+ The `json-summary` and `lcov` reports this config writes are the two the ratchet reads.
213
+
100
214
  ## PHI and safety
101
215
 
102
216
  This package is test configuration. It processes no patient data: it configures a test runner and,
103
- through `/snippets`, compiles and executes the code blocks you point it at.
217
+ through `/snippets`, compiles and executes the code blocks you point it at. Through `/stryker` it
218
+ runs your own tests against altered copies of your own source, in a sandbox directory
219
+ (`.stryker-tmp/`) inside your project; add it and `reports/mutation/` to `.gitignore`.
104
220
 
105
221
  Two consequences worth stating plainly, because `/snippets` does run code. It executes the snippets
106
222
  in your own documentation, in your own process, so a documentation example must never contain real
@@ -112,7 +228,7 @@ a test fixture's would. Use synthetic data in documentation, as in tests.
112
228
 
113
229
  ### `cosyteVitest(options)`
114
230
 
115
- The baseline config: v8 coverage with `text` / `html` / `lcov` reporters, the standard excludes
231
+ The baseline config: v8 coverage with `text` / `html` / `lcov` / `json-summary` reporters, the standard excludes
116
232
  (barrels, fixtures, generated code, declarations), and **enabled, gating** per-directory thresholds
117
233
  at **>= 90**.
118
234
 
@@ -154,13 +270,57 @@ docSnippetSuite({
154
270
  ```
155
271
 
156
272
  Options: `docsDir` / `files`, `include` (default `.md` / `.mdx`), `resolve` (import-specifier
157
- remapper), `runnableTag` (default `"runnable"`), `name`, `requireSnippet`, `tmpDir`. A package with no
273
+ remapper), `runnableTag` (default `"runnable"`), `name`, `requireSnippet`, `tmpDir`, `every`,
274
+ `includeGenerated`, `tsconfig`. A package with no
158
275
  runnable snippets yields an empty, passing suite: absence degrades quietly; a _wrong_ snippet fails
159
276
  loudly. The primitives (`extractRunnableSnippets`, `rewriteAssertions`, `remapImports`, `runSnippet`)
160
277
  are exported too, for bespoke wiring.
161
278
 
162
- > `runSnippet` writes a transient `.ts` module under `tmpDir` (default `.cosyte-doc-snippets/` in the
163
- > project root) and imports it so Vitest transforms the TypeScript: add `.cosyte-doc-snippets*/` to
279
+ #### Every sample, not only the tagged ones
280
+
281
+ `docSnippetSuite({ every: true })` runs every `ts`, `typescript`, `tsx`, `js`, `javascript` and `mjs`
282
+ block, tagged or not, which is what the docs-content standard asks of a library (decision record 0006
283
+ in cosyte/config). In this mode a JavaScript sample runs as a `.mjs` module, so TypeScript syntax in
284
+ it fails, and a `tsx` sample runs as `.tsx`; without `every`, every `runnable` block runs as `.ts`, as
285
+ before. A block that cannot run says why in its fence, and the test report lists it as skipped with
286
+ that reason:
287
+
288
+ ````md
289
+ ```ts no-run opens a listener that stays open for the life of the process
290
+ const server = createServer().listen(2575);
291
+ ```
292
+ ````
293
+
294
+ A `no-run` with no reason fails the suite. Shell, JSON and text blocks are not samples and are never
295
+ run. `extractSamples(markdown)` and `planSamples(files, options)` are the primitives behind it.
296
+
297
+ Walking `docsDir`, this mode leaves out the `api/` folder under it: the reference generator writes
298
+ those pages from TSDoc, and their examples are parts of a signature's documentation, not samples.
299
+ `includeGenerated: true` walks it too. A suite given `files`, or without `every`, reads what it is
300
+ given, as before.
301
+
302
+ Each TypeScript sample (`ts`, `typescript`, `tsx`) is also type-checked against the package's types
303
+ before it runs, so a sample with a type error fails even though it would run: a reader who copies it
304
+ into a TypeScript project would not get it to compile. The samples are compiled as a reader's project
305
+ would compile them, each as its own module importing the package by its published name, under the
306
+ project's `tsconfig.json` (the one `tsconfig` names, or the one in the working directory) with emit
307
+ and the unused-name checks turned off. A library resolves its own name to its built declarations
308
+ through its `exports`, so build before the suite runs, as the suite already does to run the samples
309
+ against `dist/`. This needs the `typescript` package, an optional peer dependency. A sample whose types
310
+ cannot be checked, such as one that shows what happens when a caller ignores them, says why in its
311
+ fence; it still runs, and its test name carries the reason:
312
+
313
+ ````md
314
+ ```ts throws no-typecheck passes a number where the types ask for a string, to show it throws
315
+ parseMessage(42);
316
+ ```
317
+ ````
318
+
319
+ A `no-typecheck` with no reason fails the suite, as a bare `no-run` does. `typecheckSamples(samples,
320
+ options)` is the primitive behind it. Without `every`, nothing is type-checked.
321
+
322
+ > `runSnippet` writes a transient `.ts` module (or the `extension` a sample names) under `tmpDir`
323
+ > (default `.cosyte-doc-snippets/` in the project root) and imports it so Vitest transforms the TypeScript: add `.cosyte-doc-snippets*/` to
164
324
  > `.gitignore`. It must stay inside the project root; files under `node_modules` are not transformed.
165
325
 
166
326
  ## Contributing
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ // cosyte-mutate: StrykerJS with the shared config, over everything (`full`) or over the source
3
+ // files a change touched (`changed --base <ref>`). It exits with the run's own code: 0 the run
4
+ // finished, 2 it could not run. The score is judged by cosyte-ratchet, from @cosyte/script-utils.
5
+
6
+ import { runMutate } from "../mutate.js";
7
+
8
+ /**
9
+ * Answer `--help` the way every Cosyte gate does: print it and exit 0 at a terminal; under CI
10
+ * print it to stderr with a refusal and exit 2, because a CI step that only asks for help checks
11
+ * nothing and must not pass.
12
+ *
13
+ * @param {string} help The help text.
14
+ * @returns {number} The exit code.
15
+ */
16
+ function answerHelp(help) {
17
+ const ci = process.env.CI;
18
+ if (ci === undefined || ci === "" || ci === "false" || ci === "0") {
19
+ process.stdout.write(help);
20
+ return 0;
21
+ }
22
+ process.stderr.write(help);
23
+ process.stderr.write(
24
+ `cosyte-mutate: refusing --help under CI (CI=${ci}). It prints this text and runs nothing, ` +
25
+ "so a CI step that runs it must not pass.\n",
26
+ );
27
+ return 2;
28
+ }
29
+
30
+ const args = process.argv.slice(2);
31
+ const io = {
32
+ cwd: process.cwd(),
33
+ out: (text) => process.stdout.write(text),
34
+ err: (text) => process.stderr.write(text),
35
+ };
36
+ if (args.includes("--help") || args.includes("-h")) {
37
+ let help = "";
38
+ await runMutate({ ...io, argv: ["--help"], out: (text) => (help += text) });
39
+ process.exitCode = answerHelp(help);
40
+ } else {
41
+ process.exitCode = await runMutate({ ...io, argv: args });
42
+ }
package/index.js CHANGED
@@ -3,7 +3,7 @@ import { defineConfig } from "vitest/config";
3
3
  const GATE = { lines: 90, branches: 90, functions: 90, statements: 90 };
4
4
 
5
5
  /**
6
- * Standard Vitest config for `@cosyte/*` packages: v8 coverage with `text`/`html`/`lcov` reporters,
6
+ * Standard Vitest config for `@cosyte/*` packages: v8 coverage with `text`/`html`/`lcov`/`json-summary` reporters,
7
7
  * the standard excludes (barrels, fixtures, generated, declarations), and **enabled, gating**
8
8
  * per-directory thresholds at >= 90. List your source subdirectories in `coverageDirs` to get a
9
9
  * per-directory gate on each (on top of the global gate).
@@ -26,7 +26,9 @@ export function cosyteVitest(opts = {}) {
26
26
  test: {
27
27
  coverage: {
28
28
  provider: "v8",
29
- reporter: ["text", "html", "lcov"],
29
+ // lcov and json-summary are what `cosyte-ratchet` (@cosyte/script-utils) reads: the
30
+ // changed lines that ran, and the totals the floor file holds.
31
+ reporter: ["text", "html", "lcov", "json-summary"],
30
32
  reportsDirectory: "./coverage",
31
33
  include: ["src/**/*.ts"],
32
34
  exclude: [
package/mutate.d.ts ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Reads what a change touched: `readChanges` from `@cosyte/script-utils/changes`, an optional peer
3
+ * dependency. Declared here so these types do not need that package installed.
4
+ */
5
+ export type ChangeReader = (opts: { base: string; cwd: string }) => {
6
+ root: string;
7
+ files: Map<string, Set<number>>;
8
+ };
9
+
10
+ /** The config file a run reads when `--config` names none. */
11
+ export declare const DEFAULT_CONFIG: "stryker.config.mjs";
12
+
13
+ /** Thrown for anything that stops a run before Stryker starts. */
14
+ export declare class MutateUnreadable extends Error {
15
+ constructor(message: string);
16
+ }
17
+
18
+ /** Parse `cosyte-mutate`'s command line. */
19
+ export declare function parseMutateArgs(argv: string[]): {
20
+ mode: "full" | "changed";
21
+ base: string | null;
22
+ config: string;
23
+ };
24
+
25
+ /** Pick the changed files a config mutates, relative to the working directory, sorted. */
26
+ export declare function selectChangedFiles(input: {
27
+ changed: Iterable<string>;
28
+ root: string;
29
+ cwd: string;
30
+ patterns: readonly string[];
31
+ }): string[];
32
+
33
+ /** Where a full run writes its JSON report. */
34
+ export declare function fullReportPath(config: Record<string, unknown>): string;
35
+
36
+ /** Where a changed run writes its JSON report: `changed.json` beside the full report. */
37
+ export declare function changedReportPath(config: Record<string, unknown>): string;
38
+
39
+ /** An empty report in the mutation-testing-report-schema shape. */
40
+ export declare function emptyReport(projectRoot: string): string;
41
+
42
+ /** Load a Stryker config module and return its default export. */
43
+ export declare function loadConfig(
44
+ path: string,
45
+ ): Promise<Record<string, unknown> & { mutate: string[] }>;
46
+
47
+ /**
48
+ * Load `readChanges` from `@cosyte/script-utils/changes`, the optional peer dependency a changed run
49
+ * needs; rejects, naming the package, when it is not installed.
50
+ */
51
+ export declare function loadChangeReader(
52
+ load?: (specifier: string) => Promise<unknown>,
53
+ ): Promise<ChangeReader>;
54
+
55
+ /** Start StrykerJS with these options and wait for it to finish. */
56
+ export declare function runStryker(options: Record<string, unknown>): Promise<void>;
57
+
58
+ /**
59
+ * Run `cosyte-mutate` and resolve to its exit code: 0 the run finished, 2 it could not run.
60
+ *
61
+ * @example
62
+ * ```js
63
+ * import { runMutate } from "@cosyte/vitest-config/mutate";
64
+ * process.exitCode = await runMutate({
65
+ * argv: ["changed", "--base", "origin/main"],
66
+ * cwd: process.cwd(),
67
+ * out: (text) => process.stdout.write(text),
68
+ * err: (text) => process.stderr.write(text),
69
+ * });
70
+ * ```
71
+ */
72
+ export declare function runMutate(opts: {
73
+ argv: string[];
74
+ cwd: string;
75
+ out: (text: string) => void;
76
+ err: (text: string) => void;
77
+ changes?: ChangeReader;
78
+ stryker?: (options: Record<string, unknown>) => Promise<void>;
79
+ }): Promise<number>;
package/mutate.js ADDED
@@ -0,0 +1,264 @@
1
+ // @cosyte/vitest-config/mutate
2
+ //
3
+ // THE TWO RUNS: `full` mutates everything the config names and writes the report the floor file's
4
+ // mutation score is read from; `changed` mutates only the source files a change touched against a
5
+ // base ref, and writes its report to a separate file, `changed.json` beside the full one, so a run
6
+ // over a few files can never be read as the package's score.
7
+ //
8
+ // What a change touched is read from git by @cosyte/script-utils/changes, the same reading the
9
+ // ratchet judges changed lines with, so the two cannot disagree about which files a pull request
10
+ // changed. It is an optional peer dependency, imported only when a changed run starts, so a package
11
+ // that uses only the Vitest config installs nothing for it. A changed run with no changed source file starts no mutation run: it writes an empty
12
+ // report, so the ratchet can tell "ran, nothing to mutate" from "never ran", and exits 0.
13
+ //
14
+ // Exit codes: 0 the run finished (the score is judged by cosyte-ratchet, not here); 2 it could not
15
+ // run (bad arguments, no config, git could not answer, Stryker failed).
16
+
17
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
18
+ import { dirname, join, matchesGlob, relative, resolve, sep } from "node:path";
19
+ import { pathToFileURL } from "node:url";
20
+
21
+ import { FULL_REPORT, htmlReportFor } from "./stryker.js";
22
+
23
+ /** The config file a run reads when `--config` names none, relative to the working directory. */
24
+ export const DEFAULT_CONFIG = "stryker.config.mjs";
25
+
26
+ /** Thrown for anything that stops a run before Stryker starts. Exit 2. */
27
+ export class MutateUnreadable extends Error {
28
+ /**
29
+ * @param {string} message What stopped the run.
30
+ */
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = "MutateUnreadable";
34
+ }
35
+ }
36
+
37
+ const HELP = `cosyte-mutate: run StrykerJS with the shared config, over everything or over a change.
38
+
39
+ cosyte-mutate full [--config <file>]
40
+ cosyte-mutate changed --base <ref> [--config <file>]
41
+
42
+ full mutates every file the config names and writes its JSON report where the config says
43
+ (reports/mutation/mutation.json with @cosyte/vitest-config/stryker).
44
+ changed mutates only the source files changed against the merge base of <ref> and HEAD (with
45
+ edits not yet committed and untracked files), and writes changed.json beside the full
46
+ report. With no changed source file it writes an empty report and exits 0.
47
+ --config the Stryker config file, default ${DEFAULT_CONFIG}, relative to the working directory.
48
+
49
+ Exit 0 when the run finished (cosyte-ratchet judges the score), 2 when it could not run.
50
+ `;
51
+
52
+ /**
53
+ * Parse the command line.
54
+ *
55
+ * @param {string[]} argv The arguments after the bin's name.
56
+ * @returns {{ mode: "full" | "changed", base: string | null, config: string }} The options.
57
+ */
58
+ export function parseMutateArgs(argv) {
59
+ const [mode, ...rest] = argv;
60
+ if (mode !== "full" && mode !== "changed") {
61
+ throw new MutateUnreadable(`the mode must be full or changed, not ${JSON.stringify(mode)}`);
62
+ }
63
+ const options = { mode, base: null, config: DEFAULT_CONFIG };
64
+ for (let i = 0; i < rest.length; i += 2) {
65
+ const flag = rest[i];
66
+ const value = rest[i + 1];
67
+ if (flag !== "--base" && flag !== "--config") {
68
+ throw new MutateUnreadable(`unknown argument ${JSON.stringify(flag)}`);
69
+ }
70
+ if (value === undefined || value.startsWith("--")) {
71
+ throw new MutateUnreadable(`${flag} needs a value`);
72
+ }
73
+ if (flag === "--base") options.base = value;
74
+ else options.config = value;
75
+ }
76
+ if (mode === "changed" && options.base === null) {
77
+ throw new MutateUnreadable(
78
+ "changed needs --base <ref>, the ref the change is measured against",
79
+ );
80
+ }
81
+ if (mode === "full" && options.base !== null) {
82
+ throw new MutateUnreadable("full takes no --base: it mutates everything the config names");
83
+ }
84
+ return options;
85
+ }
86
+
87
+ /**
88
+ * Pick the changed files a config mutates: each must match one of its patterns and none of its
89
+ * `!` patterns. Patterns and the result are relative to the working directory, as Stryker reads
90
+ * them; a changed file outside it is never picked.
91
+ *
92
+ * @param {object} input The inputs.
93
+ * @param {Iterable<string>} input.changed Changed files, relative to the repository root.
94
+ * @param {string} input.root The repository root.
95
+ * @param {string} input.cwd The directory Stryker runs in.
96
+ * @param {readonly string[]} input.patterns The config's `mutate` patterns.
97
+ * @returns {string[]} The files to mutate, sorted.
98
+ */
99
+ export function selectChangedFiles({ changed, root, cwd, patterns }) {
100
+ const include = patterns.filter((p) => !p.startsWith("!"));
101
+ const exclude = patterns.filter((p) => p.startsWith("!")).map((p) => p.slice(1));
102
+ const picked = [];
103
+ for (const file of changed) {
104
+ const path = relative(cwd, resolve(root, file)).split(sep).join("/");
105
+ if (path.startsWith("../")) continue;
106
+ if (!include.some((p) => matchesGlob(path, p))) continue;
107
+ if (exclude.some((p) => matchesGlob(path, p))) continue;
108
+ picked.push(path);
109
+ }
110
+ return picked.sort();
111
+ }
112
+
113
+ /**
114
+ * Where a full run writes its JSON report: the config's `jsonReporter.fileName`, or Stryker's own
115
+ * default, which is also this package's.
116
+ *
117
+ * @param {Record<string, any>} config The loaded Stryker config.
118
+ * @returns {string} The path, relative to the working directory.
119
+ */
120
+ export function fullReportPath(config) {
121
+ const full = config.jsonReporter?.fileName;
122
+ return typeof full === "string" ? full : FULL_REPORT;
123
+ }
124
+
125
+ /**
126
+ * Where a changed run writes its report: `changed.json` beside the full report.
127
+ *
128
+ * @param {Record<string, any>} config The loaded Stryker config.
129
+ * @returns {string} The path, relative to the working directory.
130
+ */
131
+ export function changedReportPath(config) {
132
+ return join(dirname(fullReportPath(config)), "changed.json");
133
+ }
134
+
135
+ /**
136
+ * An empty report in the mutation-testing-report-schema shape: no file, no mutant.
137
+ *
138
+ * @param {string} projectRoot The directory the run would have run in.
139
+ * @returns {string} The JSON text.
140
+ */
141
+ export function emptyReport(projectRoot) {
142
+ return `${JSON.stringify({
143
+ schemaVersion: "2",
144
+ thresholds: { high: 100, low: 90 },
145
+ projectRoot,
146
+ files: {},
147
+ })}\n`;
148
+ }
149
+
150
+ /**
151
+ * Load a Stryker config module and return its default export.
152
+ *
153
+ * @param {string} path The config file, absolute.
154
+ * @returns {Promise<Record<string, any>>} The config.
155
+ */
156
+ export async function loadConfig(path) {
157
+ let mod;
158
+ try {
159
+ mod = await import(pathToFileURL(path).href);
160
+ } catch (cause) {
161
+ throw new MutateUnreadable(`the Stryker config ${path} could not be loaded: ${cause.message}`);
162
+ }
163
+ const config = mod.default;
164
+ if (typeof config !== "object" || config === null || !Array.isArray(config.mutate)) {
165
+ throw new MutateUnreadable(`the Stryker config ${path} exports no config with a mutate list`);
166
+ }
167
+ return config;
168
+ }
169
+
170
+ /**
171
+ * Load the change reader from @cosyte/script-utils, the optional peer dependency a changed run needs.
172
+ *
173
+ * @param {(specifier: string) => Promise<any>} [load] Imports a module; replaced in tests.
174
+ * @returns {Promise<(opts: { base: string, cwd?: string }) => { root: string, files: Map<string, Set<number>> }>}
175
+ * Its `readChanges`.
176
+ */
177
+ export async function loadChangeReader(load = (specifier) => import(specifier)) {
178
+ try {
179
+ const { readChanges } = await load("@cosyte/script-utils/changes");
180
+ return readChanges;
181
+ } catch (cause) {
182
+ throw new MutateUnreadable(
183
+ "a changed run reads what a change touched with @cosyte/script-utils, an optional peer " +
184
+ `dependency of @cosyte/vitest-config; install it beside this package (${cause.message})`,
185
+ );
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Start StrykerJS with these options and wait for it to finish.
191
+ *
192
+ * @param {Record<string, unknown>} options Stryker options; `configFile` names the config, and
193
+ * the rest override it.
194
+ * @returns {Promise<void>} Resolves when the run finishes.
195
+ */
196
+ export async function runStryker(options) {
197
+ const { Stryker } = await import("@stryker-mutator/core");
198
+ await new Stryker(options).runMutationTest();
199
+ }
200
+
201
+ /**
202
+ * Run `cosyte-mutate`.
203
+ *
204
+ * @param {object} opts Options.
205
+ * @param {string[]} opts.argv The arguments after the bin's name.
206
+ * @param {string} opts.cwd The directory Stryker runs in.
207
+ * @param {(text: string) => void} opts.out Writes to stdout.
208
+ * @param {(text: string) => void} opts.err Writes to stderr.
209
+ * @param {(opts: { base: string, cwd: string }) => { root: string, files: Map<string, Set<number>> }} [opts.changes]
210
+ * Reads what a change touched; replaced in tests. Left out, a changed run loads it from
211
+ * @cosyte/script-utils.
212
+ * @param {typeof runStryker} [opts.stryker] Starts Stryker; replaced in tests.
213
+ * @returns {Promise<number>} The exit code.
214
+ */
215
+ export async function runMutate({ argv, cwd, out, err, changes, stryker = runStryker }) {
216
+ if (argv.includes("--help") || argv.includes("-h")) {
217
+ out(HELP);
218
+ return 0;
219
+ }
220
+ try {
221
+ const options = parseMutateArgs(argv);
222
+ const configFile = resolve(cwd, options.config);
223
+ const config = await loadConfig(configFile);
224
+ if (options.mode === "full") {
225
+ // A report left from an earlier run must not outlive a run that failed.
226
+ rmSync(resolve(cwd, fullReportPath(config)), { force: true });
227
+ out(`cosyte-mutate: mutating everything ${options.config} names\n`);
228
+ await stryker({ configFile });
229
+ return 0;
230
+ }
231
+ const readChanges = changes ?? (await loadChangeReader());
232
+ const change = readChanges({ base: options.base, cwd });
233
+ const files = selectChangedFiles({
234
+ changed: change.files.keys(),
235
+ root: change.root,
236
+ cwd,
237
+ patterns: config.mutate,
238
+ });
239
+ const report = changedReportPath(config);
240
+ rmSync(resolve(cwd, report), { force: true });
241
+ if (files.length === 0) {
242
+ mkdirSync(dirname(resolve(cwd, report)), { recursive: true });
243
+ writeFileSync(resolve(cwd, report), emptyReport(cwd));
244
+ out(
245
+ `cosyte-mutate: no changed source file against ${options.base}; nothing to mutate. Wrote an empty ${report}.\n`,
246
+ );
247
+ return 0;
248
+ }
249
+ out(`cosyte-mutate: mutating ${files.length} changed file(s) against ${options.base}:\n`);
250
+ for (const file of files) out(` ${file}\n`);
251
+ await stryker({
252
+ configFile,
253
+ mutate: files,
254
+ jsonReporter: { fileName: report },
255
+ htmlReporter: { fileName: htmlReportFor(report) },
256
+ });
257
+ return 0;
258
+ } catch (error) {
259
+ // The change reader's own refusal is known by name: its class lives in the optional peer.
260
+ const known = error instanceof MutateUnreadable || error?.name === "ChangesUnreadable";
261
+ err(`cosyte-mutate: could not run: ${known ? error.message : String(error?.stack ?? error)}\n`);
262
+ return 2;
263
+ }
264
+ }