@cosyte/vitest-config 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +50 -2
- package/package.json +10 -1
- package/snippets.d.ts +110 -0
- package/snippets.js +298 -0
package/CHANGELOG.md
CHANGED
|
@@ -8,5 +8,19 @@ this file is hand-maintained. The package stays on the **`0.0.x`-until-first-alp
|
|
|
8
8
|
|
|
9
9
|
### Added
|
|
10
10
|
|
|
11
|
+
- Declared `vite` (`^6 || ^7 || ^8`) as a peer dependency — Vitest 4 requires vite >= 6, and the
|
|
12
|
+
resolver otherwise keeps an incompatible vite 5 (missing the `./module-runner` export). _(Added after
|
|
13
|
+
`0.0.1` published; ships in the next release.)_
|
|
14
|
+
- **Doc/code-agreement harness** on a new `@cosyte/vitest-config/snippets` subpath — `docSnippetSuite()`
|
|
15
|
+
plus the factored primitives (`extractRunnableSnippets`, `rewriteAssertions`, `remapImports`,
|
|
16
|
+
`runSnippet`). It extracts every fenced ` ```ts runnable ` block from a package's `docs-content/`,
|
|
17
|
+
compiles it, executes it against the package, and asserts its inline `// => value` results — the
|
|
18
|
+
documentation analog of the conformance runners, so a green docs build can never carry a snippet
|
|
19
|
+
that silently disagrees with the code. devDep-only; Vitest is already a peer, so no new dependency.
|
|
20
|
+
|
|
21
|
+
## [0.0.1] - 2026-06-25
|
|
22
|
+
|
|
23
|
+
### Added
|
|
24
|
+
|
|
11
25
|
- Initial release: `cosyteVitest(opts)` — v8 coverage, standard excludes, and enabled, gating
|
|
12
26
|
per-directory thresholds at >= 90.
|
package/README.md
CHANGED
|
@@ -7,10 +7,11 @@ declarations), and **enabled, gating** per-directory thresholds at **>= 90**.
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
|
-
pnpm add -D @cosyte/vitest-config vitest @vitest/coverage-v8
|
|
10
|
+
pnpm add -D @cosyte/vitest-config vitest @vitest/coverage-v8 vite
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
`vitest
|
|
13
|
+
`vitest`, `@vitest/coverage-v8`, and `vite` are peer dependencies (Vitest 4 needs `vite` >= 6 — install
|
|
14
|
+
it explicitly so the resolver doesn't keep an incompatible vite 5).
|
|
14
15
|
|
|
15
16
|
## Use
|
|
16
17
|
|
|
@@ -28,5 +29,52 @@ Each entry in `coverageDirs` adds a per-directory `src/<dir>/**` gate at >= 90 o
|
|
|
28
29
|
gate. Use `coverageThresholds` to add or override specific keys, and `test` for any other Vitest
|
|
29
30
|
options.
|
|
30
31
|
|
|
32
|
+
## Doc/code agreement — `@cosyte/vitest-config/snippets`
|
|
33
|
+
|
|
34
|
+
The `/snippets` subpath is the **documentation analog of the conformance runners**: it proves the
|
|
35
|
+
examples in a package's `docs-content/` still do what the prose claims. A copy-pasteable snippet that
|
|
36
|
+
silently returns the wrong field — a dose, a code, an identifier — is a clinical-harm failure mode
|
|
37
|
+
wearing a documentation costume, so a green docs build carrying a wrong snippet is exactly what this
|
|
38
|
+
prevents.
|
|
39
|
+
|
|
40
|
+
Mark a fenced block **opt-in** with ` ```ts runnable ` and assert its output inline with `// =>`:
|
|
41
|
+
|
|
42
|
+
````md
|
|
43
|
+
```ts runnable
|
|
44
|
+
import { parseHl7 } from "@cosyte/hl7";
|
|
45
|
+
|
|
46
|
+
const { warnings } = parseHl7(raw);
|
|
47
|
+
warnings.length; // => 0
|
|
48
|
+
```
|
|
49
|
+
````
|
|
50
|
+
|
|
51
|
+
`docSnippetSuite()` walks a docs directory, turns each runnable block into a Vitest `test` labelled by
|
|
52
|
+
file and line, compiles it, and executes it — a line of the form `<expr>; // => <value>` becomes
|
|
53
|
+
`expect(<expr>).toStrictEqual(<value>)`. A block tagged ` ```ts runnable throws ` must throw instead.
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
// test/docs-content.test.ts
|
|
57
|
+
import { join } from "node:path";
|
|
58
|
+
import { docSnippetSuite } from "@cosyte/vitest-config/snippets";
|
|
59
|
+
|
|
60
|
+
docSnippetSuite({
|
|
61
|
+
docsDir: join(import.meta.dirname, "..", "docs-content"),
|
|
62
|
+
// Point a snippet's `import ... from "@cosyte/hl7"` at what you want to prove against — this repo's
|
|
63
|
+
// source for a fast local gate, or `../dist/index.js` (after `pnpm build`) for artifact fidelity.
|
|
64
|
+
resolve: (spec) =>
|
|
65
|
+
spec === "@cosyte/hl7" ? join(import.meta.dirname, "..", "src", "index.ts") : undefined,
|
|
66
|
+
});
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Options: `docsDir` / `files`, `include` (default `.md` / `.mdx`), `resolve` (import-specifier
|
|
70
|
+
remapper), `runnableTag` (default `"runnable"`), `name`, `requireSnippet`, `tmpDir`. A package with no
|
|
71
|
+
runnable snippets yields an empty, passing suite — absence degrades quietly; a _wrong_ snippet fails
|
|
72
|
+
loudly. The primitives (`extractRunnableSnippets`, `rewriteAssertions`, `remapImports`, `runSnippet`)
|
|
73
|
+
are exported too, for bespoke wiring.
|
|
74
|
+
|
|
75
|
+
> `runSnippet` writes a transient `.ts` module under `tmpDir` (default `.cosyte-doc-snippets/` in the
|
|
76
|
+
> project root) and imports it so Vitest transforms the TypeScript — add `.cosyte-doc-snippets*/` to
|
|
77
|
+
> `.gitignore`. It must stay inside the project root; files under `node_modules` are not transformed.
|
|
78
|
+
|
|
31
79
|
Part of [cosyte/config](https://github.com/cosyte/config) — one enforced toolchain for the `@cosyte/*`
|
|
32
80
|
suite.
|
package/package.json
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cosyte/vitest-config",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.2",
|
|
4
4
|
"description": "Shared Vitest config (v8 coverage, per-directory >=90 gates) for @cosyte/* packages.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"vitest",
|
|
7
7
|
"coverage",
|
|
8
8
|
"test",
|
|
9
|
+
"doctest",
|
|
10
|
+
"documentation",
|
|
9
11
|
"cosyte"
|
|
10
12
|
],
|
|
11
13
|
"homepage": "https://github.com/cosyte/config/tree/main/packages/vitest-config#readme",
|
|
@@ -23,11 +25,17 @@
|
|
|
23
25
|
".": {
|
|
24
26
|
"types": "./index.d.ts",
|
|
25
27
|
"default": "./index.js"
|
|
28
|
+
},
|
|
29
|
+
"./snippets": {
|
|
30
|
+
"types": "./snippets.d.ts",
|
|
31
|
+
"default": "./snippets.js"
|
|
26
32
|
}
|
|
27
33
|
},
|
|
28
34
|
"files": [
|
|
29
35
|
"index.js",
|
|
30
36
|
"index.d.ts",
|
|
37
|
+
"snippets.js",
|
|
38
|
+
"snippets.d.ts",
|
|
31
39
|
"README.md",
|
|
32
40
|
"CHANGELOG.md"
|
|
33
41
|
],
|
|
@@ -36,6 +44,7 @@
|
|
|
36
44
|
},
|
|
37
45
|
"peerDependencies": {
|
|
38
46
|
"@vitest/coverage-v8": "^4.0.0",
|
|
47
|
+
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
|
|
39
48
|
"vitest": "^4.0.0"
|
|
40
49
|
}
|
|
41
50
|
}
|
package/snippets.d.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The doc/code-agreement harness — the documentation analog of the parser conformance runners.
|
|
3
|
+
*
|
|
4
|
+
* Every fenced block a `docs-content` page opts in (```` ```ts runnable ````) is extracted, its
|
|
5
|
+
* inline `// => value` assertions compiled to real `expect(...)` checks, and the whole block executed
|
|
6
|
+
* against the built package inside the running Vitest process. A green docs build carrying a wrong
|
|
7
|
+
* snippet is the exact failure this prevents.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** One extracted runnable snippet, in document order. */
|
|
11
|
+
export interface RunnableSnippet {
|
|
12
|
+
/** The fence language (`ts` / `typescript` / `tsx`). */
|
|
13
|
+
lang: string;
|
|
14
|
+
/** Fence info-string tokens after the language (e.g. `["runnable", "throws"]`). */
|
|
15
|
+
meta: string[];
|
|
16
|
+
/** The snippet source (dedented to the fence's own indentation). */
|
|
17
|
+
code: string;
|
|
18
|
+
/** 1-based line of the snippet's first code line, for failure attribution. */
|
|
19
|
+
line: number;
|
|
20
|
+
/** Whether the block is tagged `throws` (expected to throw rather than run clean). */
|
|
21
|
+
throws: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Options for {@link extractRunnableSnippets}. */
|
|
25
|
+
export interface ExtractOptions {
|
|
26
|
+
/** Fence opt-in tag. Default `"runnable"`. */
|
|
27
|
+
runnableTag?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Options for {@link runSnippet}. */
|
|
31
|
+
export interface RunSnippetOptions {
|
|
32
|
+
/** Import-specifier remapper (e.g. package name → its built `dist`). */
|
|
33
|
+
resolve?: (specifier: string) => string | undefined;
|
|
34
|
+
/** Temp directory for the emitted module (must live inside the project root). */
|
|
35
|
+
tmpDir?: string;
|
|
36
|
+
/** Force the expected-to-throw expectation even for a raw-string snippet. */
|
|
37
|
+
throws?: boolean;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Options for {@link docSnippetSuite}. */
|
|
41
|
+
export interface DocSnippetSuiteOptions {
|
|
42
|
+
/** Directory to walk for markdown (recursively). Ignored when `files` is given. */
|
|
43
|
+
docsDir?: string;
|
|
44
|
+
/** Explicit markdown file paths, overriding `docsDir`. */
|
|
45
|
+
files?: string[];
|
|
46
|
+
/** Filename filter for `docsDir` walking. Default: `.md` / `.mdx`. */
|
|
47
|
+
include?: RegExp;
|
|
48
|
+
/** Import-specifier remapper (e.g. package name → its built `dist`). */
|
|
49
|
+
resolve?: (specifier: string) => string | undefined;
|
|
50
|
+
/** Fence opt-in tag. Default `"runnable"`. */
|
|
51
|
+
runnableTag?: string;
|
|
52
|
+
/** Suite label. Default `"doc/code agreement"`. */
|
|
53
|
+
name?: string;
|
|
54
|
+
/** Assert at least one runnable snippet exists. Default `false`. */
|
|
55
|
+
requireSnippet?: boolean;
|
|
56
|
+
/** Where temp modules are written (must be inside the project root). */
|
|
57
|
+
tmpDir?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Extract the opt-in runnable snippets from a markdown string, in document order.
|
|
62
|
+
*
|
|
63
|
+
* @param markdown - The markdown source.
|
|
64
|
+
* @param opts - Options.
|
|
65
|
+
* @returns One entry per ```` ```ts runnable ```` block.
|
|
66
|
+
*/
|
|
67
|
+
export declare function extractRunnableSnippets(
|
|
68
|
+
markdown: string,
|
|
69
|
+
opts?: ExtractOptions,
|
|
70
|
+
): RunnableSnippet[];
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Rewrite inline `<expr>; // => <value>` doctest lines into `expect(<expr>).toStrictEqual(<value>)`.
|
|
74
|
+
*
|
|
75
|
+
* @param code - The snippet source.
|
|
76
|
+
* @returns The rewritten source and the number of assertions added.
|
|
77
|
+
*/
|
|
78
|
+
export declare function rewriteAssertions(code: string): { code: string; assertions: number };
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Rewrite the module specifiers in a snippet's `import ... from "<spec>"` clauses.
|
|
82
|
+
*
|
|
83
|
+
* @param code - The snippet source.
|
|
84
|
+
* @param resolveFn - Specifier mapper; `undefined`/same-spec returns are no-ops.
|
|
85
|
+
* @returns The source with remapped `from "..."` clauses.
|
|
86
|
+
*/
|
|
87
|
+
export declare function remapImports(
|
|
88
|
+
code: string,
|
|
89
|
+
resolveFn: ((specifier: string) => string | undefined) | undefined,
|
|
90
|
+
): string;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Compile and execute one snippet as an ES module in the running Vitest process. Resolves on success;
|
|
94
|
+
* rejects (AssertionError or the thrown error) on failure. A block tagged `throws` must throw.
|
|
95
|
+
*
|
|
96
|
+
* @param snippet - A snippet object or its raw source.
|
|
97
|
+
* @param opts - Options.
|
|
98
|
+
*/
|
|
99
|
+
export declare function runSnippet(
|
|
100
|
+
snippet: RunnableSnippet | string,
|
|
101
|
+
opts?: RunSnippetOptions,
|
|
102
|
+
): Promise<void>;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Register a Vitest suite that proves every runnable `docs-content` snippet agrees with the code.
|
|
106
|
+
* A package with no `docs-content` (or no runnable blocks) yields an empty, passing suite.
|
|
107
|
+
*
|
|
108
|
+
* @param options - Options.
|
|
109
|
+
*/
|
|
110
|
+
export declare function docSnippetSuite(options?: DocSnippetSuiteOptions): void;
|
package/snippets.js
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join, relative } from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
|
|
5
|
+
import { afterAll, describe, expect, test } from "vitest";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The doc/code-agreement harness — the documentation analog of the parser conformance runners.
|
|
9
|
+
*
|
|
10
|
+
* A `docs-content` example a developer can copy into a production integration is only safe if it
|
|
11
|
+
* still does what the prose claims *against the built package*. A snippet that silently mis-reads a
|
|
12
|
+
* dose, an allergy, a code system, or a patient identifier is the clinical-harm failure mode wearing
|
|
13
|
+
* a documentation costume — so a green docs build carrying a wrong snippet is the exact thing this
|
|
14
|
+
* catches. Every fenced block a package opts in (```` ```ts runnable ````) is extracted, its inline
|
|
15
|
+
* `// => value` assertions are compiled to real `expect(...)` checks, and the whole block is executed
|
|
16
|
+
* as an ES module in the running Vitest process. If it throws — or an assertion fails — the docs
|
|
17
|
+
* build fails, loudly, next to the file and line.
|
|
18
|
+
*
|
|
19
|
+
* Lives in `@cosyte/vitest-config` (not the framework-agnostic `@cosyte/test-utils`) on purpose:
|
|
20
|
+
* {@link docSnippetSuite} registers Vitest `describe`/`test` blocks, so it belongs with the Vitest
|
|
21
|
+
* config every parser already depends on — zero new devDep, one versioned implementation on the
|
|
22
|
+
* Changesets train, devDep-only.
|
|
23
|
+
*
|
|
24
|
+
* @packageDocumentation
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** Fence languages treated as executable TypeScript. */
|
|
28
|
+
const RUNNABLE_LANGS = new Set(["ts", "typescript", "tsx"]);
|
|
29
|
+
|
|
30
|
+
/** Monotonic counter so every emitted temp module gets a unique, cache-busting filename. */
|
|
31
|
+
let moduleCounter = 0;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Extract the opt-in runnable snippets from a markdown string.
|
|
35
|
+
*
|
|
36
|
+
* A block is runnable when its fence info string names a TypeScript language *and* carries the
|
|
37
|
+
* opt-in tag, e.g. ```` ```ts runnable ````. Everything else — prose, shell, un-tagged `ts` blocks
|
|
38
|
+
* — is ignored: opt-in, never opt-out, so documenting non-executable pseudocode stays possible.
|
|
39
|
+
* The `throws` meta tag marks a block expected to throw rather than run clean.
|
|
40
|
+
*
|
|
41
|
+
* @param {string} markdown - The markdown source.
|
|
42
|
+
* @param {{ runnableTag?: string }} [opts] - Options; `runnableTag` overrides the default `"runnable"`.
|
|
43
|
+
* @returns {Array<{ lang: string, meta: string[], code: string, line: number, throws: boolean }>}
|
|
44
|
+
* One entry per runnable block, in document order. `line` is the 1-based line of the block's first
|
|
45
|
+
* code line (so a failure points at the snippet, not the fence).
|
|
46
|
+
*/
|
|
47
|
+
export function extractRunnableSnippets(markdown, opts = {}) {
|
|
48
|
+
const runnableTag = opts.runnableTag ?? "runnable";
|
|
49
|
+
const lines = markdown.split(/\r?\n/);
|
|
50
|
+
const out = [];
|
|
51
|
+
let i = 0;
|
|
52
|
+
while (i < lines.length) {
|
|
53
|
+
const open = lines[i].match(/^(\s*)(`{3,}|~{3,})\s*(.*)$/);
|
|
54
|
+
if (!open) {
|
|
55
|
+
i++;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const [, indent, fence, info] = open;
|
|
59
|
+
const firstCodeLine = i + 2; // 1-based line of the first body line
|
|
60
|
+
const body = [];
|
|
61
|
+
let j = i + 1;
|
|
62
|
+
let closed = false;
|
|
63
|
+
while (j < lines.length) {
|
|
64
|
+
const close = lines[j].match(/^(\s*)(`{3,}|~{3,})\s*$/);
|
|
65
|
+
if (
|
|
66
|
+
close &&
|
|
67
|
+
close[2][0] === fence[0] &&
|
|
68
|
+
close[2].length >= fence.length &&
|
|
69
|
+
close[1].length === indent.length
|
|
70
|
+
) {
|
|
71
|
+
closed = true;
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
body.push(indent && lines[j].startsWith(indent) ? lines[j].slice(indent.length) : lines[j]);
|
|
75
|
+
j++;
|
|
76
|
+
}
|
|
77
|
+
const tokens = info.trim().split(/\s+/).filter(Boolean);
|
|
78
|
+
const lang = tokens[0]?.toLowerCase();
|
|
79
|
+
const meta = tokens.slice(1);
|
|
80
|
+
if (RUNNABLE_LANGS.has(lang) && meta.includes(runnableTag)) {
|
|
81
|
+
out.push({
|
|
82
|
+
lang,
|
|
83
|
+
meta,
|
|
84
|
+
code: body.join("\n"),
|
|
85
|
+
line: firstCodeLine,
|
|
86
|
+
throws: meta.includes("throws"),
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
i = closed ? j + 1 : j;
|
|
90
|
+
}
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Rewrite inline doctest assertions into real `expect(...)` calls.
|
|
96
|
+
*
|
|
97
|
+
* A line of the form `<expression>; // => <value>` becomes `expect(<expression>).toStrictEqual(<value>)`.
|
|
98
|
+
* The right-hand side is any JavaScript expression (a literal, `[]`, an object, another call) — it is
|
|
99
|
+
* evaluated in the snippet's own scope, so it can reference values the snippet defined. Lines without
|
|
100
|
+
* the `// =>` marker are left untouched and simply execute for their side effects (and must not throw).
|
|
101
|
+
*
|
|
102
|
+
* @param {string} code - The snippet source.
|
|
103
|
+
* @returns {{ code: string, assertions: number }} The rewritten source and how many assertions it grew.
|
|
104
|
+
*/
|
|
105
|
+
export function rewriteAssertions(code) {
|
|
106
|
+
let assertions = 0;
|
|
107
|
+
const rewritten = code
|
|
108
|
+
.split(/\r?\n/)
|
|
109
|
+
.map((line) => {
|
|
110
|
+
const m = line.match(/^(\s*)(.+?);\s*\/\/\s*=>\s*(.+?)\s*$/);
|
|
111
|
+
if (!m) return line;
|
|
112
|
+
assertions++;
|
|
113
|
+
const [, ws, expr, expected] = m;
|
|
114
|
+
return `${ws}expect(${expr}).toStrictEqual(${expected});`;
|
|
115
|
+
})
|
|
116
|
+
.join("\n");
|
|
117
|
+
return { code: rewritten, assertions };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Rewrite the module specifiers in a snippet's `import ... from "<spec>"` clauses.
|
|
122
|
+
*
|
|
123
|
+
* Lets a suite point a snippet's `import { parseHl7 } from "@cosyte/hl7"` at the *built* package
|
|
124
|
+
* (`dist/`) rather than whatever the test-time resolver picks, so the docs are proven against the
|
|
125
|
+
* artifact a consumer actually installs. A `resolve` that returns `undefined`/the same spec is a
|
|
126
|
+
* no-op for that import.
|
|
127
|
+
*
|
|
128
|
+
* @param {string} code - The snippet source.
|
|
129
|
+
* @param {((specifier: string) => string | undefined) | undefined} resolveFn - Specifier mapper.
|
|
130
|
+
* @returns {string} The source with remapped `from "..."` clauses.
|
|
131
|
+
*/
|
|
132
|
+
export function remapImports(code, resolveFn) {
|
|
133
|
+
if (!resolveFn) return code;
|
|
134
|
+
return code.replace(/(\bfrom\s*)(["'])([^"']+)\2/g, (full, kw, quote, spec) => {
|
|
135
|
+
const mapped = resolveFn(spec);
|
|
136
|
+
return mapped && mapped !== spec ? `${kw}${quote}${mapped}${quote}` : full;
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Compile and execute one snippet as an ES module in the running Vitest process.
|
|
142
|
+
*
|
|
143
|
+
* The snippet is remapped, its assertions rewritten, an `expect` import prepended, and the result
|
|
144
|
+
* written to a unique temp `.ts` file under `tmpDir` (which MUST live inside the project root so
|
|
145
|
+
* Vitest transforms it — files under `node_modules` are treated as external and would reach Node as
|
|
146
|
+
* raw TypeScript). It is then dynamically imported: Vitest's module runner transforms the TypeScript
|
|
147
|
+
* and runs it. A block tagged `throws` must throw; any other block must run clean. The temp file is
|
|
148
|
+
* always removed afterwards.
|
|
149
|
+
*
|
|
150
|
+
* Exported directly (not only via {@link docSnippetSuite}) so the harness can be unit-tested: a
|
|
151
|
+
* deliberately-wrong snippet must make this reject.
|
|
152
|
+
*
|
|
153
|
+
* @param {{ code: string, throws?: boolean } | string} snippet - A snippet object or its raw source.
|
|
154
|
+
* @param {{ resolve?: (specifier: string) => string | undefined, tmpDir?: string, throws?: boolean }} [opts]
|
|
155
|
+
* Options.
|
|
156
|
+
* @returns {Promise<void>} Resolves on success; rejects (AssertionError or the thrown error) on failure.
|
|
157
|
+
*/
|
|
158
|
+
export async function runSnippet(snippet, opts = {}) {
|
|
159
|
+
const code = typeof snippet === "string" ? snippet : snippet.code;
|
|
160
|
+
const throwsExpected =
|
|
161
|
+
(typeof snippet === "string" ? false : snippet.throws) || opts.throws || false;
|
|
162
|
+
const tmpDir = opts.tmpDir ?? defaultTmpDir();
|
|
163
|
+
|
|
164
|
+
const remapped = remapImports(code, opts.resolve);
|
|
165
|
+
const { code: asserted } = rewriteAssertions(remapped);
|
|
166
|
+
const moduleSource = `import { expect } from "vitest";\n${asserted}\n`;
|
|
167
|
+
|
|
168
|
+
mkdirSync(tmpDir, { recursive: true });
|
|
169
|
+
const file = join(tmpDir, `snippet-${process.pid}-${moduleCounter++}.ts`);
|
|
170
|
+
writeFileSync(file, moduleSource, "utf8");
|
|
171
|
+
try {
|
|
172
|
+
if (throwsExpected) {
|
|
173
|
+
// Weaker guarantee, by design: a `throws` block is green if the import rejects for ANY reason —
|
|
174
|
+
// the documented error, but also a compile error or a bad specifier. It proves "this does not
|
|
175
|
+
// run clean," not "this fails the specific way the prose claims." Assert the precise failure
|
|
176
|
+
// inside the snippet (a try/catch with an `// =>` on the caught code/message) when that matters.
|
|
177
|
+
let threw = false;
|
|
178
|
+
try {
|
|
179
|
+
await import(pathToFileURL(file).href);
|
|
180
|
+
} catch {
|
|
181
|
+
threw = true;
|
|
182
|
+
}
|
|
183
|
+
if (!threw) throw new Error("snippet tagged `throws` completed without throwing");
|
|
184
|
+
} else {
|
|
185
|
+
await import(pathToFileURL(file).href);
|
|
186
|
+
}
|
|
187
|
+
} finally {
|
|
188
|
+
try {
|
|
189
|
+
rmSync(file, { force: true });
|
|
190
|
+
} catch {
|
|
191
|
+
// best-effort cleanup; a leaked temp file never fails the run
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Register a Vitest suite that proves every runnable `docs-content` snippet agrees with the code.
|
|
198
|
+
*
|
|
199
|
+
* Point it at a `docsDir` (or an explicit `files` list); it walks the markdown, turns each opt-in
|
|
200
|
+
* runnable block into a `test` labelled by file and line, and executes it against the built package.
|
|
201
|
+
* A package with no `docs-content` (or no runnable blocks) yields an empty, passing suite — the docs
|
|
202
|
+
* site's build-on-missing-content invariant has a testing analog here: absence degrades quietly, a
|
|
203
|
+
* *wrong* snippet fails loudly. Set `requireSnippet` when a repo wants to assert its docs carry at
|
|
204
|
+
* least one executed example.
|
|
205
|
+
*
|
|
206
|
+
* @param {object} [options] - Options.
|
|
207
|
+
* @param {string} [options.docsDir] - Directory to walk for markdown (recursively). Ignored if `files` is given.
|
|
208
|
+
* @param {string[]} [options.files] - Explicit markdown file paths, overriding `docsDir`.
|
|
209
|
+
* @param {RegExp} [options.include] - Filename filter for `docsDir` walking. Default: `.md`/`.mdx`.
|
|
210
|
+
* @param {(specifier: string) => string | undefined} [options.resolve] - Import-specifier remapper (e.g. name → dist).
|
|
211
|
+
* @param {string} [options.runnableTag] - Fence opt-in tag. Default `"runnable"`.
|
|
212
|
+
* @param {string} [options.name] - Suite label. Default `"doc/code agreement"`.
|
|
213
|
+
* @param {boolean} [options.requireSnippet] - Assert at least one runnable snippet exists. Default `false`.
|
|
214
|
+
* @param {string} [options.tmpDir] - Where temp modules are written (must be inside the project root).
|
|
215
|
+
* @returns {void}
|
|
216
|
+
*/
|
|
217
|
+
export function docSnippetSuite(options = {}) {
|
|
218
|
+
const {
|
|
219
|
+
docsDir,
|
|
220
|
+
files,
|
|
221
|
+
include = /\.mdx?$/i,
|
|
222
|
+
resolve: resolveFn,
|
|
223
|
+
runnableTag = "runnable",
|
|
224
|
+
name = "doc/code agreement",
|
|
225
|
+
requireSnippet = false,
|
|
226
|
+
tmpDir = defaultTmpDir(),
|
|
227
|
+
} = options;
|
|
228
|
+
|
|
229
|
+
const mdFiles = files ?? (docsDir ? collectMarkdown(docsDir, include) : []);
|
|
230
|
+
|
|
231
|
+
describe(name, () => {
|
|
232
|
+
afterAll(() => {
|
|
233
|
+
try {
|
|
234
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
235
|
+
} catch {
|
|
236
|
+
// best-effort cleanup
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
let total = 0;
|
|
241
|
+
for (const filePath of mdFiles) {
|
|
242
|
+
const snippets = extractRunnableSnippets(readFileSync(filePath, "utf8"), { runnableTag });
|
|
243
|
+
total += snippets.length;
|
|
244
|
+
for (const snippet of snippets) {
|
|
245
|
+
const label = `${relative(process.cwd(), filePath)}:${snippet.line}`;
|
|
246
|
+
test(label, async () => {
|
|
247
|
+
await runSnippet(snippet, { resolve: resolveFn, tmpDir });
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (requireSnippet) {
|
|
253
|
+
test("carries at least one runnable snippet", () => {
|
|
254
|
+
expect(total, "no `ts runnable` blocks found in docs-content").toBeGreaterThan(0);
|
|
255
|
+
});
|
|
256
|
+
} else if (total === 0) {
|
|
257
|
+
// A package with docs but no runnable examples yet (the common scaffold state) would otherwise
|
|
258
|
+
// leave this an empty suite — which Vitest reports as a "no test found in file" failure. A
|
|
259
|
+
// passing no-op keeps the wired suite green until the first snippet is tagged `runnable`.
|
|
260
|
+
test("no runnable snippets to check", () => {});
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Default temp directory: inside the project root (never `node_modules`, which Vitest won't transform). */
|
|
266
|
+
function defaultTmpDir() {
|
|
267
|
+
return join(process.cwd(), ".cosyte-doc-snippets");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Recursively collect markdown files under a directory. A missing directory yields `[]` — a package
|
|
272
|
+
* without `docs-content` produces an empty suite rather than a crash.
|
|
273
|
+
*
|
|
274
|
+
* @param {string} dir - Root directory.
|
|
275
|
+
* @param {RegExp} include - Filename filter.
|
|
276
|
+
* @returns {string[]} Absolute-or-relative file paths, sorted for stable test ordering.
|
|
277
|
+
*/
|
|
278
|
+
function collectMarkdown(dir, include) {
|
|
279
|
+
let entries;
|
|
280
|
+
try {
|
|
281
|
+
entries = readdirSync(dir);
|
|
282
|
+
} catch {
|
|
283
|
+
return [];
|
|
284
|
+
}
|
|
285
|
+
const out = [];
|
|
286
|
+
for (const entry of entries.sort()) {
|
|
287
|
+
const full = join(dir, entry);
|
|
288
|
+
let s;
|
|
289
|
+
try {
|
|
290
|
+
s = statSync(full);
|
|
291
|
+
} catch {
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
if (s.isDirectory()) out.push(...collectMarkdown(full, include));
|
|
295
|
+
else if (include.test(entry)) out.push(full);
|
|
296
|
+
}
|
|
297
|
+
return out;
|
|
298
|
+
}
|