@cosyte/vitest-config 0.1.2 → 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/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
+ }
package/package.json CHANGED
@@ -1,14 +1,16 @@
1
1
  {
2
2
  "name": "@cosyte/vitest-config",
3
- "version": "0.1.2",
4
- "description": "Shared Vitest config (v8 coverage, per-directory >=90 gates) for @cosyte/* packages.",
3
+ "version": "0.1.4",
4
+ "description": "Shared Vitest config (v8 coverage, per-directory >=90 gates) and StrykerJS mutation testing config for @cosyte/* packages.",
5
5
  "keywords": [
6
6
  "vitest",
7
7
  "coverage",
8
8
  "test",
9
9
  "doctest",
10
10
  "documentation",
11
- "cosyte"
11
+ "cosyte",
12
+ "stryker",
13
+ "mutation-testing"
12
14
  ],
13
15
  "homepage": "https://github.com/cosyte/config/tree/main/packages/vitest-config#readme",
14
16
  "repository": {
@@ -21,6 +23,9 @@
21
23
  "type": "module",
22
24
  "main": "index.js",
23
25
  "types": "index.d.ts",
26
+ "bin": {
27
+ "cosyte-mutate": "bin/cosyte-mutate.js"
28
+ },
24
29
  "exports": {
25
30
  ".": {
26
31
  "types": "./index.d.ts",
@@ -29,6 +34,14 @@
29
34
  "./snippets": {
30
35
  "types": "./snippets.d.ts",
31
36
  "default": "./snippets.js"
37
+ },
38
+ "./stryker": {
39
+ "types": "./stryker.d.ts",
40
+ "default": "./stryker.js"
41
+ },
42
+ "./mutate": {
43
+ "types": "./mutate.d.ts",
44
+ "default": "./mutate.js"
32
45
  }
33
46
  },
34
47
  "files": [
@@ -36,6 +49,11 @@
36
49
  "index.d.ts",
37
50
  "snippets.js",
38
51
  "snippets.d.ts",
52
+ "stryker.js",
53
+ "stryker.d.ts",
54
+ "mutate.js",
55
+ "mutate.d.ts",
56
+ "bin",
39
57
  "README.md",
40
58
  "CHANGELOG.md"
41
59
  ],
@@ -43,8 +61,38 @@
43
61
  "access": "public"
44
62
  },
45
63
  "peerDependencies": {
64
+ "@stryker-mutator/core": "^10.0.0",
65
+ "@stryker-mutator/vitest-runner": "^10.0.0",
46
66
  "@vitest/coverage-v8": "^4.0.0 || ^5.0.0",
47
67
  "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
48
- "vitest": "^4.0.0 || ^5.0.0"
68
+ "vitest": "^4.0.0 || ^5.0.0",
69
+ "typescript": ">=5.0.0",
70
+ "@cosyte/script-utils": "^0.1.9"
71
+ },
72
+ "peerDependenciesMeta": {
73
+ "@cosyte/script-utils": {
74
+ "optional": true
75
+ },
76
+ "@stryker-mutator/core": {
77
+ "optional": true
78
+ },
79
+ "@stryker-mutator/vitest-runner": {
80
+ "optional": true
81
+ },
82
+ "typescript": {
83
+ "optional": true
84
+ }
85
+ },
86
+ "devDependencies": {
87
+ "@stryker-mutator/core": "10.1.1",
88
+ "@stryker-mutator/vitest-runner": "10.1.1",
89
+ "@vitest/coverage-v8": "5.1.0",
90
+ "vite": "8.3.6",
91
+ "vitest": "5.1.0",
92
+ "typescript": "5.9.3",
93
+ "@cosyte/script-utils": "^0.1.9"
94
+ },
95
+ "scripts": {
96
+ "test": "vitest run --coverage"
49
97
  }
50
98
  }
package/snippets.d.ts CHANGED
@@ -9,7 +9,7 @@
9
9
 
10
10
  /** One extracted runnable snippet, in document order. */
11
11
  export interface RunnableSnippet {
12
- /** The fence language (`ts` / `typescript` / `tsx`). */
12
+ /** The fence language (`ts` / `typescript` / `tsx`; a sample may also be `js` / `javascript` / `mjs`). */
13
13
  lang: string;
14
14
  /** Fence info-string tokens after the language (e.g. `["runnable", "throws"]`). */
15
15
  meta: string[];
@@ -19,6 +19,79 @@ export interface RunnableSnippet {
19
19
  line: number;
20
20
  /** Whether the block is tagged `throws` (expected to throw rather than run clean). */
21
21
  throws: boolean;
22
+ /**
23
+ * The extension of the module {@link runSnippet} writes the snippet to. Absent, it is `.ts`, which
24
+ * is what every snippet {@link extractRunnableSnippets} returns runs as.
25
+ */
26
+ extension?: string;
27
+ }
28
+
29
+ /** One extracted code sample, in document order: a TypeScript or JavaScript block, tagged or not. */
30
+ export interface Sample extends RunnableSnippet {
31
+ /**
32
+ * The reason the block is not run: the words after its `no-run` tag (empty when the tag has no
33
+ * reason, which the suite reports as an error), or `null` for a block that runs.
34
+ */
35
+ skip: string | null;
36
+ /**
37
+ * The reason the sample is run but not type-checked: the words after its `no-typecheck` tag
38
+ * (empty when the tag has no reason, which the suite reports as an error), or `null` otherwise.
39
+ * Of `no-run` and `no-typecheck`, the first in the fence counts, and what follows it is its reason.
40
+ */
41
+ noTypecheck: string | null;
42
+ /** The module it runs as: `.mjs` for a `js`, `javascript` or `mjs` sample, `.tsx` for `tsx`, else `.ts`. */
43
+ extension: ".ts" | ".tsx" | ".mjs";
44
+ }
45
+
46
+ /** One type error in a sample. */
47
+ export interface SampleTypeError {
48
+ /** The markdown line it is on. */
49
+ line: number;
50
+ /** TypeScript's error code, as in `TS2322`. */
51
+ code: number;
52
+ /** TypeScript's message, on one line. */
53
+ message: string;
54
+ }
55
+
56
+ /** Options for {@link typecheckSamples}. */
57
+ export interface TypecheckSamplesOptions {
58
+ /** The `tsconfig.json` to compile under. Default: the one in the working directory, if any. */
59
+ tsconfig?: string;
60
+ /**
61
+ * Where each sample is written to be compiled; it must sit inside the project, so the package's
62
+ * name resolves. Default `.cosyte-doc-snippets/typecheck` in the working directory.
63
+ */
64
+ dir?: string;
65
+ }
66
+
67
+ /** The fence languages that make a block a code sample: TypeScript and JavaScript. */
68
+ export declare const SAMPLE_LANGS: ReadonlySet<string>;
69
+
70
+ /** What a suite does with one sample. */
71
+ export interface SamplePlanStep {
72
+ /** The test name: the file, relative to the root, and the sample's first code line. */
73
+ label: string;
74
+ /** Run it, skip it with its reason, or report a `no-run` or `no-typecheck` that gives no reason. */
75
+ kind: "run" | "skip" | "invalid";
76
+ /**
77
+ * Why it is skipped or invalid; for a run, why it is not type-checked, or `null` when nothing is
78
+ * left out.
79
+ */
80
+ reason: string | null;
81
+ /** Whether the sample is type-checked before it runs: a TypeScript sample, in every-sample mode. */
82
+ typecheck: boolean;
83
+ /** The sample. */
84
+ snippet: Sample;
85
+ }
86
+
87
+ /** Options for {@link planSamples}. */
88
+ export interface PlanSamplesOptions {
89
+ /** Take every sample rather than only the `runnable` ones. Default `false`. */
90
+ every?: boolean;
91
+ /** What labels are relative to. Default: the working directory. */
92
+ root?: string;
93
+ /** Fence opt-in tag when `every` is off. Default `"runnable"`. */
94
+ runnableTag?: string;
22
95
  }
23
96
 
24
97
  /** Options for {@link extractRunnableSnippets}. */
@@ -35,6 +108,8 @@ export interface RunSnippetOptions {
35
108
  tmpDir?: string;
36
109
  /** Force the expected-to-throw expectation even for a raw-string snippet. */
37
110
  throws?: boolean;
111
+ /** The snippet's type errors, from {@link typecheckSamples}: when any, it fails before it runs. */
112
+ typeErrors?: SampleTypeError[];
38
113
  }
39
114
 
40
115
  /** Options for {@link docSnippetSuite}. */
@@ -55,8 +130,55 @@ export interface DocSnippetSuiteOptions {
55
130
  requireSnippet?: boolean;
56
131
  /** Where temp modules are written (must be inside the project root). */
57
132
  tmpDir?: string;
133
+ /**
134
+ * Run every TypeScript and JavaScript sample, not only the `runnable` ones; a `no-run <reason>`
135
+ * sample is listed as skipped with its reason, and a `no-run` with no reason fails. Each
136
+ * TypeScript sample is type-checked before it runs, unless it carries `no-typecheck <reason>`.
137
+ * Walking `docsDir`, the generated `api/` folder is left out. Default `false`.
138
+ */
139
+ every?: boolean;
140
+ /** In every-sample mode, walk the generated `api/` folder of `docsDir` too. Default `false`. */
141
+ includeGenerated?: boolean;
142
+ /** The `tsconfig.json` samples are type-checked under. Default: the one in the working directory. */
143
+ tsconfig?: string;
58
144
  }
59
145
 
146
+ /**
147
+ * Extract every code sample from a markdown string: each `ts`, `typescript`, `tsx`, `js`,
148
+ * `javascript` or `mjs` block, tagged or not, in document order.
149
+ *
150
+ * @param markdown - The markdown source.
151
+ * @returns One entry per sample.
152
+ */
153
+ export declare function extractSamples(markdown: string): Sample[];
154
+
155
+ /**
156
+ * Decide what a suite does with each sample in a set of markdown files.
157
+ *
158
+ * @param files - Markdown file paths.
159
+ * @param options - Options.
160
+ * @returns One step per sample, in file and document order.
161
+ */
162
+ export declare function planSamples(
163
+ files: string[],
164
+ options?: PlanSamplesOptions,
165
+ ): SamplePlanStep[];
166
+
167
+ /**
168
+ * Type-check TypeScript samples against the package's types, each as its own module, under the
169
+ * project's `tsconfig.json` with emit and the unused-name checks off. Needs `typescript`.
170
+ *
171
+ * @param samples - The samples: their code, the markdown line of their first code line, and the
172
+ * extension they compile as (`.ts` when absent).
173
+ * @param options - Options.
174
+ * @returns For each sample, in order, its errors; empty for one that compiles.
175
+ * @throws When the config cannot be read or the program as a whole has an error.
176
+ */
177
+ export declare function typecheckSamples(
178
+ samples: Array<Pick<RunnableSnippet, "code" | "line" | "extension">>,
179
+ options?: TypecheckSamplesOptions,
180
+ ): Promise<SampleTypeError[][]>;
181
+
60
182
  /**
61
183
  * Extract the opt-in runnable snippets from a markdown string, in document order.
62
184
  *