@cosyte/vitest-config 0.1.3 → 0.1.6

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,56 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.6
4
+
5
+ ### Patch Changes
6
+
7
+ - ecb933d: Barrels are read, not named. `cosyteVitest` and `cosyteStryker` used to leave every `index.ts` out
8
+ of coverage and mutation testing. They now read each `.ts` file under `src/` (declaration files
9
+ aside) and leave out only a barrel: a file whose every statement is an import that binds names or
10
+ an export of names, with at least one export. So a library's coverage and its default mutate list
11
+ now include:
12
+
13
+ - every `index.ts` that holds any other statement: a function, a class, a constant, a call, a type
14
+ alias, an interface, a side-effect import;
15
+ - every file the reading does not understand, whatever its name.
16
+
17
+ They now leave out a file of nothing but re-exports under any name, not only `index.ts`.
18
+ `DEFAULT_MUTATE` no longer names `index.ts`; `cosyteStryker()` adds a `!` entry for each barrel it
19
+ found. Both take a new `root` option, the directory whose `src/` is read, the working directory by
20
+ default. Tests, declarations, `__fixtures__` and `generated` stay out by name, as before.
21
+
22
+ A library whose `index.ts` holds code measures it for the first time when it adopts this version,
23
+ so its coverage and mutation scores can fall below its floor.
24
+
25
+ `cosyteStryker` now sets `ignoreStatic: true`. A static mutant, in code that runs once when a
26
+ module loads, can be tested only by running every test again; on our HL7 library they were 43% of
27
+ the mutants and about 94% of a full run's time. Ignored mutants are not in the score, so a full
28
+ run's score can move either way, and the ratchet lists an ignored mutant in a pull request's
29
+ changed lines with Stryker's reason. A package whose module-level tables are what it checks passes
30
+ `stryker: { ignoreStatic: false }`.
31
+
32
+ - Updated dependencies [a926e03]
33
+ - @cosyte/script-utils@0.1.10
34
+
35
+ ## 0.1.5
36
+
37
+ ### Patch Changes
38
+
39
+ - 0f9bc66: `cosyte-mutate full` can run in shards. With `COSYTE_MUTATE_SHARD=<k>/<n>` set, it mutates only the files of the config whose 32-bit FNV-1a hash of the path is `k - 1` mod `n`, so every file is in exactly one of the `n` shards, and writes `reports/mutation/shard-<k>-of-<n>.json` and its HTML beside the full report, never `mutation.json`; a shard with no file writes an empty report and exits 0 without starting Stryker, and a malformed value exits 2. With `COSYTE_MUTATE_INCREMENTAL_FILE` set, Stryker keeps its incremental results in that file (`incremental: true`). With neither variable set, a full run is unchanged, and a changed run reads neither. `parseShard`, `fnv1a32`, `filesInShard`, `expandMutate` and `shardReportPath` are exported from `@cosyte/vitest-config/mutate`.
40
+
41
+ ## 0.1.4
42
+
43
+ ### Patch Changes
44
+
45
+ - 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.
46
+ - 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.
47
+ - 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.
48
+ - Updated dependencies [65208bf]
49
+ - Updated dependencies [57847cb]
50
+ - Updated dependencies [cc43161]
51
+ - Updated dependencies [5a0470a]
52
+ - @cosyte/script-utils@0.1.9
53
+
3
54
  ## 0.1.3
4
55
 
5
56
  ### 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`, whole or one shard of it, 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,166 @@ 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; // => true
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
+ ### A full run in shards
153
+
154
+ A full run of a large library takes hours on one machine, so it can be split across parallel jobs.
155
+ Two variables, read only by `full`, do it:
156
+
157
+ - `COSYTE_MUTATE_SHARD=<k>/<n>` mutates only shard `k` of `n`, and writes `shard-<k>-of-<n>.json`
158
+ in place of the full report.
159
+ - `COSYTE_MUTATE_INCREMENTAL_FILE=<file>` keeps Stryker's incremental results in that file, so a
160
+ later run retests only the mutants whose code or tests changed.
161
+
162
+ ```sh
163
+ COSYTE_MUTATE_SHARD=3/8 COSYTE_MUTATE_INCREMENTAL_FILE=reports/mutation/incremental.json \
164
+ pnpm exec cosyte-mutate full
165
+ ```
166
+
167
+ A shard lists every file the config's `mutate` patterns name under the working directory (never
168
+ inside `node_modules`, `.git` or Stryker's temp directory), and keeps those whose 32-bit FNV-1a hash
169
+ of the path, relative and with forward slashes, is `k - 1` mod `n`. So over shards 1 to `n` every
170
+ file is mutated exactly once, and a file stays in its shard from run to run however many files are
171
+ added elsewhere. The report, `reports/mutation/shard-<k>-of-<n>.json` with its HTML beside it, goes
172
+ where `mutation.json` would, and never as `mutation.json`, so no shard is read as the package's
173
+ score: the shards' reports are merged into one `mutation.json` before `cosyte-ratchet` reads it,
174
+ which is what the weekly mutation workflow in cosyte/.github does. A shard that holds no file writes
175
+ an empty report and exits 0 without starting Stryker. A `COSYTE_MUTATE_SHARD` that is not two whole
176
+ numbers with `1 <= k <= n` exits 2. The incremental file is relative to the working directory and
177
+ reaches Stryker as `incrementalFile`, with `incremental: true`, with or without a shard. Unset or
178
+ empty, neither variable changes anything, and a changed run reads neither.
179
+
180
+ ```ts runnable
181
+ import { filesInShard, fnv1a32 } from "@cosyte/vitest-config/mutate";
182
+
183
+ fnv1a32("src/a.ts") % 2; // => 0
184
+ filesInShard(["src/a.ts", "src/b.ts"], { k: 1, n: 2 }); // => ["src/a.ts"]
185
+ ```
186
+
187
+ The `/mutate` entry point is the bin's body and the pieces it is built of, for a caller that runs
188
+ it from its own script. `selectChangedFiles` is the rule a changed run picks its files by:
189
+
190
+ ```ts runnable
191
+ import { selectChangedFiles } from "@cosyte/vitest-config/mutate";
192
+
193
+ const picked = selectChangedFiles({
194
+ changed: ["src/a.ts", "src/a.test.ts", "README.md"],
195
+ root: "/repo",
196
+ cwd: "/repo",
197
+ patterns: ["src/**/*.ts", "!src/**/*.test.ts"],
198
+ });
199
+ picked; // => ["src/a.ts"]
200
+ ```
201
+
202
+ ### What the Stryker config sets, and why
203
+
204
+ `cosyteStryker({ mutate, root, vitestConfig, stryker })` takes the file list, the directory read for
205
+ barrels, the Vitest config file, and any other Stryker option, merged last, so a package can change
206
+ anything below. What each default is
207
+ and why:
208
+
209
+ | setting | default | why |
210
+ | ------------------ | ------------------------------------------- | ---------------------------------------------------------------------------- |
211
+ | `testRunner` | `vitest`, resolved from this package | Stryker cannot find a plugin by name under pnpm |
212
+ | `vitest.pool` | `forks` | Vitest's own default; Stryker's is threads, where `process.chdir()` throws |
213
+ | `coverageAnalysis` | `perTest` | each mutant runs only the tests that reach it |
214
+ | `mutate` | `src/**/*.ts` without tests, barrels, types | the same files `@cosyte/vitest-config` measures coverage over |
215
+ | `ignoreStatic` | `true` | a static mutant reruns every test; on a library they are most of a run |
216
+ | `thresholds.break` | `null` | the floor file decides a drop, not Stryker |
217
+ | reports | JSON and HTML under `reports/mutation/` | JSON for the ratchet and CI, HTML for a person reading the surviving mutants |
218
+
219
+ A static mutant is one in code that runs once, when a module loads: a table of patterns, a frozen
220
+ map. Stryker can test one only by running every test again, so on a library they take most of a
221
+ run's time: on our HL7 parser, 5,328 of 12,280 mutants were static, and Stryker estimated them at 94%
222
+ of the run. With `ignoreStatic: true` they are left out of the score; coverage still holds every such
223
+ line to having run, and the ratchet lists an ignored mutant in a pull request's changed lines with
224
+ Stryker's reason, so a reviewer sees it. A package whose module-level tables are the thing it checks,
225
+ such as a PHI scanner's patterns, passes `stryker: { ignoreStatic: false }`, and that is the override
226
+ worth arguing about in review.
227
+
228
+ ### Which files are barrels
229
+
230
+ A barrel is a file that holds nothing but re-exports: every statement an import that binds names, or
231
+ an export of names, and at least one export. Coverage and the default mutate list leave barrels out,
232
+ and the rule reads each `.ts` file under `src/` (but declaration files), never its name: an `index.ts`
233
+ that holds a parser is measured, and a file of re-exports with any other name is left out. One
234
+ statement of real code (a declaration, a call, a side-effect import, a type alias) makes a file real
235
+ code, and so does anything the reading does not understand, because a file wrongly called a barrel
236
+ hides code from both gates. Both configs read `src/` under the working directory, or under `root`
237
+ when it is given.
238
+
239
+ ### An exception, and why it needs two comments
240
+
241
+ A mutant that cannot be killed (an equivalent mutant, or a line only a child process reaches) gets
242
+ an inline exception that names its reason:
243
+
244
+ ```js
245
+ // Stryker disable next-line ConditionalExpression: both branches return the same value here
246
+ ```
247
+
248
+ Mutation testing does not read coverage's ignore hints, so a line excluded from coverage with
249
+ `/* v8 ignore next -- reason */` still has its mutants, and they show as not covered. Such a line
250
+ needs both comments, each with its reason. `cosyte-ratchet check --base` lists every exception in
251
+ changed code, so the pull request can carry the list.
252
+
253
+ ## The 90 gates and the floor file
254
+
255
+ The 90 thresholds are one fixed minimum for every package, and they fail the test run itself. The
256
+ floor file, `quality-floor.json`, held by `cosyte-ratchet` in `@cosyte/script-utils`, is each
257
+ repository's own record of what it measured, and it only rises. The two do different jobs:
258
+
259
+ - A package above 90 on a metric is held by its floor, which sits at what it measured; the 90 gate
260
+ is a backstop that does not fire.
261
+ - A package below 90 on a metric lowers that one key with `coverageThresholds`, and its floor still
262
+ holds the measured value, so the number can only rise from there.
263
+ - A pull request's own changed lines are held to 100 by the ratchet, whatever either number says.
264
+
265
+ The `json-summary` and `lcov` reports this config writes are the two the ratchet reads.
266
+
100
267
  ## PHI and safety
101
268
 
102
269
  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.
270
+ through `/snippets`, compiles and executes the code blocks you point it at. Through `/stryker` it
271
+ runs your own tests against altered copies of your own source, in a sandbox directory
272
+ (`.stryker-tmp/`) inside your project; add it and `reports/mutation/` to `.gitignore`.
104
273
 
105
274
  Two consequences worth stating plainly, because `/snippets` does run code. It executes the snippets
106
275
  in your own documentation, in your own process, so a documentation example must never contain real
@@ -112,8 +281,9 @@ a test fixture's would. Use synthetic data in documentation, as in tests.
112
281
 
113
282
  ### `cosyteVitest(options)`
114
283
 
115
- The baseline config: v8 coverage with `text` / `html` / `lcov` reporters, the standard excludes
116
- (barrels, fixtures, generated code, declarations), and **enabled, gating** per-directory thresholds
284
+ The baseline config: v8 coverage with `text` / `html` / `lcov` / `json-summary` reporters, the standard excludes
285
+ (tests, fixtures, generated code, declarations, and the barrels it finds by reading `src/` under
286
+ `options.root`, the working directory by default), and **enabled, gating** per-directory thresholds
117
287
  at **>= 90**.
118
288
 
119
289
  ### Doc/code agreement: `@cosyte/vitest-config/snippets`
@@ -154,13 +324,57 @@ docSnippetSuite({
154
324
  ```
155
325
 
156
326
  Options: `docsDir` / `files`, `include` (default `.md` / `.mdx`), `resolve` (import-specifier
157
- remapper), `runnableTag` (default `"runnable"`), `name`, `requireSnippet`, `tmpDir`. A package with no
327
+ remapper), `runnableTag` (default `"runnable"`), `name`, `requireSnippet`, `tmpDir`, `every`,
328
+ `includeGenerated`, `tsconfig`. A package with no
158
329
  runnable snippets yields an empty, passing suite: absence degrades quietly; a _wrong_ snippet fails
159
330
  loudly. The primitives (`extractRunnableSnippets`, `rewriteAssertions`, `remapImports`, `runSnippet`)
160
331
  are exported too, for bespoke wiring.
161
332
 
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
333
+ #### Every sample, not only the tagged ones
334
+
335
+ `docSnippetSuite({ every: true })` runs every `ts`, `typescript`, `tsx`, `js`, `javascript` and `mjs`
336
+ block, tagged or not, which is what the docs-content standard asks of a library (decision record 0006
337
+ in cosyte/config). In this mode a JavaScript sample runs as a `.mjs` module, so TypeScript syntax in
338
+ it fails, and a `tsx` sample runs as `.tsx`; without `every`, every `runnable` block runs as `.ts`, as
339
+ before. A block that cannot run says why in its fence, and the test report lists it as skipped with
340
+ that reason:
341
+
342
+ ````md
343
+ ```ts no-run opens a listener that stays open for the life of the process
344
+ const server = createServer().listen(2575);
345
+ ```
346
+ ````
347
+
348
+ A `no-run` with no reason fails the suite. Shell, JSON and text blocks are not samples and are never
349
+ run. `extractSamples(markdown)` and `planSamples(files, options)` are the primitives behind it.
350
+
351
+ Walking `docsDir`, this mode leaves out the `api/` folder under it: the reference generator writes
352
+ those pages from TSDoc, and their examples are parts of a signature's documentation, not samples.
353
+ `includeGenerated: true` walks it too. A suite given `files`, or without `every`, reads what it is
354
+ given, as before.
355
+
356
+ Each TypeScript sample (`ts`, `typescript`, `tsx`) is also type-checked against the package's types
357
+ before it runs, so a sample with a type error fails even though it would run: a reader who copies it
358
+ into a TypeScript project would not get it to compile. The samples are compiled as a reader's project
359
+ would compile them, each as its own module importing the package by its published name, under the
360
+ project's `tsconfig.json` (the one `tsconfig` names, or the one in the working directory) with emit
361
+ and the unused-name checks turned off. A library resolves its own name to its built declarations
362
+ through its `exports`, so build before the suite runs, as the suite already does to run the samples
363
+ against `dist/`. This needs the `typescript` package, an optional peer dependency. A sample whose types
364
+ cannot be checked, such as one that shows what happens when a caller ignores them, says why in its
365
+ fence; it still runs, and its test name carries the reason:
366
+
367
+ ````md
368
+ ```ts throws no-typecheck passes a number where the types ask for a string, to show it throws
369
+ parseMessage(42);
370
+ ```
371
+ ````
372
+
373
+ A `no-typecheck` with no reason fails the suite, as a bare `no-run` does. `typecheckSamples(samples,
374
+ options)` is the primitive behind it. Without `every`, nothing is type-checked.
375
+
376
+ > `runSnippet` writes a transient `.ts` module (or the `extension` a sample names) under `tmpDir`
377
+ > (default `.cosyte-doc-snippets/` in the project root) and imports it so Vitest transforms the TypeScript: add `.cosyte-doc-snippets*/` to
164
378
  > `.gitignore`. It must stay inside the project root; files under `node_modules` are not transformed.
165
379
 
166
380
  ## 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.d.ts CHANGED
@@ -8,6 +8,11 @@ export interface CosyteVitestOptions {
8
8
  coverageThresholds?: Record<string, unknown>;
9
9
  /** Extra Vitest `test` options, merged last. */
10
10
  test?: Record<string, unknown>;
11
+ /**
12
+ * The project root whose `src/` is read for barrels (files that hold nothing but re-exports),
13
+ * which coverage leaves out. Defaults to the working directory.
14
+ */
15
+ root?: string;
11
16
  }
12
17
 
13
18
  /**
package/index.js CHANGED
@@ -1,17 +1,23 @@
1
1
  import { defineConfig } from "vitest/config";
2
2
 
3
+ import { findBarrels } from "./stryker.js";
4
+
3
5
  const GATE = { lines: 90, branches: 90, functions: 90, statements: 90 };
4
6
 
5
7
  /**
6
- * Standard Vitest config for `@cosyte/*` packages: v8 coverage with `text`/`html`/`lcov` reporters,
7
- * the standard excludes (barrels, fixtures, generated, declarations), and **enabled, gating**
8
- * per-directory thresholds at >= 90. List your source subdirectories in `coverageDirs` to get a
9
- * per-directory gate on each (on top of the global gate).
8
+ * Standard Vitest config for `@cosyte/*` packages: v8 coverage with `text`/`html`/`lcov`/`json-summary` reporters,
9
+ * the standard excludes (tests, declarations, fixtures, generated code, and the barrels under `src/`),
10
+ * and **enabled, gating** per-directory thresholds at >= 90. List your source subdirectories in
11
+ * `coverageDirs` to get a per-directory gate on each (on top of the global gate).
12
+ *
13
+ * A barrel is a file that holds nothing but re-exports, decided by reading each file under `src/`
14
+ * (see `findBarrels` in `stryker.js`), never by its name: an `index.ts` that holds code is measured.
10
15
  *
11
16
  * @param {object} [opts] - Options.
12
17
  * @param {string[]} [opts.coverageDirs] - `src/<dir>` subdirs to gate per-directory (e.g. `["parser"]`).
13
18
  * @param {Record<string, unknown>} [opts.coverageThresholds] - Extra/override `coverage.thresholds` keys.
14
19
  * @param {Record<string, unknown>} [opts.test] - Extra Vitest `test` options, merged last.
20
+ * @param {string} [opts.root] - The project root whose `src/` is read for barrels; the working directory by default.
15
21
  * @returns {import("vitest/config").UserConfig} The Vitest config.
16
22
  * @example
17
23
  * // vitest.config.ts
@@ -26,16 +32,18 @@ export function cosyteVitest(opts = {}) {
26
32
  test: {
27
33
  coverage: {
28
34
  provider: "v8",
29
- reporter: ["text", "html", "lcov"],
35
+ // lcov and json-summary are what `cosyte-ratchet` (@cosyte/script-utils) reads: the
36
+ // changed lines that ran, and the totals the floor file holds.
37
+ reporter: ["text", "html", "lcov", "json-summary"],
30
38
  reportsDirectory: "./coverage",
31
39
  include: ["src/**/*.ts"],
32
40
  exclude: [
33
41
  "**/*.test.ts",
34
42
  "**/*.spec.ts",
35
- "**/index.ts",
36
43
  "**/*.d.ts",
37
44
  "**/__fixtures__/**",
38
45
  "**/generated/**",
46
+ ...findBarrels(opts.root),
39
47
  ],
40
48
  thresholds: { ...GATE, ...perDir, ...(opts.coverageThresholds ?? {}) },
41
49
  },
package/mutate.d.ts ADDED
@@ -0,0 +1,118 @@
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
+ /** The variable a sharded full run reads its share from: `<k>/<n>`. */
14
+ export declare const SHARD_VARIABLE: "COSYTE_MUTATE_SHARD";
15
+
16
+ /** The variable naming the file Stryker reads and writes its incremental results in. */
17
+ export declare const INCREMENTAL_VARIABLE: "COSYTE_MUTATE_INCREMENTAL_FILE";
18
+
19
+ /** One shard of a full run: shard `k` of `n`, from 1. */
20
+ export interface Shard {
21
+ k: number;
22
+ n: number;
23
+ }
24
+
25
+ /** Thrown for anything that stops a run before Stryker starts. */
26
+ export declare class MutateUnreadable extends Error {
27
+ constructor(message: string);
28
+ }
29
+
30
+ /** Parse `cosyte-mutate`'s command line. */
31
+ export declare function parseMutateArgs(argv: string[]): {
32
+ mode: "full" | "changed";
33
+ base: string | null;
34
+ config: string;
35
+ };
36
+
37
+ /** Pick the changed files a config mutates, relative to the working directory, sorted. */
38
+ export declare function selectChangedFiles(input: {
39
+ changed: Iterable<string>;
40
+ root: string;
41
+ cwd: string;
42
+ patterns: readonly string[];
43
+ }): string[];
44
+
45
+ /**
46
+ * Read `<k>/<n>`, two whole numbers with 1 <= k <= n; null when unset or empty. Throws
47
+ * `MutateUnreadable` on any other value.
48
+ */
49
+ export declare function parseShard(value: string | undefined): Shard | null;
50
+
51
+ /** 32-bit FNV-1a over the UTF-8 bytes of a text: the hash a file's shard is read from. */
52
+ export declare function fnv1a32(text: string): number;
53
+
54
+ /** The files of one shard: those whose `fnv1a32` hash mod `n` is `k - 1`. */
55
+ export declare function filesInShard(files: readonly string[], shard: Shard): string[];
56
+
57
+ /**
58
+ * List the files under `cwd` that the `mutate` patterns name, relative to it, sorted; never inside a
59
+ * `node_modules` or `.git` directory or Stryker's temp directory (default `.stryker-tmp`).
60
+ */
61
+ export declare function expandMutate(input: {
62
+ cwd: string;
63
+ patterns: readonly string[];
64
+ tempDirName?: string;
65
+ }): string[];
66
+
67
+ /** Where a sharded full run writes its JSON report: `shard-<k>-of-<n>.json` beside the full report. */
68
+ export declare function shardReportPath(config: Record<string, unknown>, shard: Shard): string;
69
+
70
+ /** Where a full run writes its JSON report. */
71
+ export declare function fullReportPath(config: Record<string, unknown>): string;
72
+
73
+ /** Where a changed run writes its JSON report: `changed.json` beside the full report. */
74
+ export declare function changedReportPath(config: Record<string, unknown>): string;
75
+
76
+ /** An empty report in the mutation-testing-report-schema shape. */
77
+ export declare function emptyReport(projectRoot: string): string;
78
+
79
+ /** Load a Stryker config module and return its default export. */
80
+ export declare function loadConfig(
81
+ path: string,
82
+ ): Promise<Record<string, unknown> & { mutate: string[] }>;
83
+
84
+ /**
85
+ * Load `readChanges` from `@cosyte/script-utils/changes`, the optional peer dependency a changed run
86
+ * needs; rejects, naming the package, when it is not installed.
87
+ */
88
+ export declare function loadChangeReader(
89
+ load?: (specifier: string) => Promise<unknown>,
90
+ ): Promise<ChangeReader>;
91
+
92
+ /** Start StrykerJS with these options and wait for it to finish. */
93
+ export declare function runStryker(options: Record<string, unknown>): Promise<void>;
94
+
95
+ /**
96
+ * Run `cosyte-mutate` and resolve to its exit code: 0 the run finished, 2 it could not run.
97
+ *
98
+ * @example
99
+ * ```js
100
+ * import { runMutate } from "@cosyte/vitest-config/mutate";
101
+ * process.exitCode = await runMutate({
102
+ * argv: ["changed", "--base", "origin/main"],
103
+ * cwd: process.cwd(),
104
+ * out: (text) => process.stdout.write(text),
105
+ * err: (text) => process.stderr.write(text),
106
+ * });
107
+ * ```
108
+ */
109
+ export declare function runMutate(opts: {
110
+ argv: string[];
111
+ cwd: string;
112
+ /** Where a full run reads `COSYTE_MUTATE_SHARD` and `COSYTE_MUTATE_INCREMENTAL_FILE`; default `process.env`. */
113
+ env?: Record<string, string | undefined>;
114
+ out: (text: string) => void;
115
+ err: (text: string) => void;
116
+ changes?: ChangeReader;
117
+ stryker?: (options: Record<string, unknown>) => Promise<void>;
118
+ }): Promise<number>;