bivium 0.3.3 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +285 -45
- package/dist/cli.js +1854 -0
- package/{index.d.ts → dist/index.d.ts} +148 -151
- package/dist/index.js +8 -0
- package/dist/shared.js +4745 -0
- package/package.json +24 -20
- package/CHANGELOG.md +0 -287
- package/cli.js +0 -62
- package/index.js +0 -1
- package/shared-xrgq64gt.js +0 -10
package/package.json
CHANGED
|
@@ -1,26 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bivium",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"license": "MIT",
|
|
3
|
+
"version": "0.5.0",
|
|
5
4
|
"description": "Run only the tests a change can affect, and never miss one.",
|
|
5
|
+
"license": "MIT",
|
|
6
6
|
"author": "Eric Liu (https://github.com/metonym)",
|
|
7
|
-
"type": "module",
|
|
8
|
-
"main": "./index.js",
|
|
9
|
-
"types": "./index.d.ts",
|
|
10
|
-
"exports": {
|
|
11
|
-
".": {
|
|
12
|
-
"types": "./index.d.ts",
|
|
13
|
-
"default": "./index.js"
|
|
14
|
-
},
|
|
15
|
-
"./package.json": "./package.json"
|
|
16
|
-
},
|
|
17
|
-
"bin": {
|
|
18
|
-
"bivium": "./cli.js"
|
|
19
|
-
},
|
|
20
|
-
"sideEffects": false,
|
|
21
|
-
"engines": {
|
|
22
|
-
"node": ">=22"
|
|
23
|
-
},
|
|
24
7
|
"repository": {
|
|
25
8
|
"type": "git",
|
|
26
9
|
"url": "git+https://github.com/metonym/bivium.git"
|
|
@@ -38,5 +21,26 @@
|
|
|
38
21
|
"vitest",
|
|
39
22
|
"playwright",
|
|
40
23
|
"zero-dependency"
|
|
41
|
-
]
|
|
24
|
+
],
|
|
25
|
+
"type": "module",
|
|
26
|
+
"main": "./dist/index.js",
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"default": "./dist/index.js"
|
|
32
|
+
},
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"bin": {
|
|
36
|
+
"bivium": "./dist/cli.js"
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"dist",
|
|
40
|
+
"docs"
|
|
41
|
+
],
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=22"
|
|
44
|
+
},
|
|
45
|
+
"sideEffects": false
|
|
42
46
|
}
|
package/CHANGELOG.md
DELETED
|
@@ -1,287 +0,0 @@
|
|
|
1
|
-
# Changelog
|
|
2
|
-
|
|
3
|
-
## 0.3.3 — 2026-11-03
|
|
4
|
-
|
|
5
|
-
**Performance**
|
|
6
|
-
|
|
7
|
-
- 0.3.2 fetched a partial clone's merge-base reads in one batch, to save
|
|
8
|
-
round trips (#55). git already fetches reads made at once in parallel,
|
|
9
|
-
so it saved none, and its check for missing blobs ran first: the batch
|
|
10
|
-
is removed. A file unchanged since the merge base is still read from
|
|
11
|
-
the working tree, and each path once.
|
|
12
|
-
|
|
13
|
-
**Fixes**
|
|
14
|
-
|
|
15
|
-
- A plan in a clone without the base branch, or without the history back
|
|
16
|
-
to where the branch forked from it, such as `actions/checkout`'s
|
|
17
|
-
default one-commit fetch, failed with `git diff … failed`. It now says
|
|
18
|
-
which is missing, and that a shallow clone needs `fetch-depth: 0`.
|
|
19
|
-
|
|
20
|
-
**Docs**
|
|
21
|
-
|
|
22
|
-
- The README's CI section explains the checkout a plan needs: history
|
|
23
|
-
back to the merge base, and when to add `filter: blob:none` (a large
|
|
24
|
-
history) or leave it off (a small one).
|
|
25
|
-
|
|
26
|
-
## 0.3.2 — 2026-11-03
|
|
27
|
-
|
|
28
|
-
**Performance**
|
|
29
|
-
|
|
30
|
-
- In a partial clone (`filter: blob:none`), the merge-base versions a
|
|
31
|
-
plan reads (a changed lockfile, `package.json` or barrel) are fetched
|
|
32
|
-
in one round trip, where git fetched each on its own: on a CI runner,
|
|
33
|
-
each took seconds. A file unchanged since the merge base is read from
|
|
34
|
-
the working tree, with no git call (#55).
|
|
35
|
-
|
|
36
|
-
**Fixes**
|
|
37
|
-
|
|
38
|
-
- A change to a `tsconfig.json` (or a file one `extends`) or a
|
|
39
|
-
`package.json` under `roots` selected no test, though it can change
|
|
40
|
-
how every file under it resolves or runs: a `paths` mapping, `type`,
|
|
41
|
-
`exports`. It now selects the tests of the files it governs, the ones
|
|
42
|
-
it's the nearest of its kind to. A change that leaves the parsed file
|
|
43
|
-
the same, or only changes `package.json` metadata such as `version`,
|
|
44
|
-
still selects nothing (#54).
|
|
45
|
-
|
|
46
|
-
## 0.3.1 — 2026-11-03
|
|
47
|
-
|
|
48
|
-
**Features**
|
|
49
|
-
|
|
50
|
-
- `bivium check` lists the files under a suite's `root` that no test
|
|
51
|
-
reaches and the config doesn't exempt: a change to any of them runs
|
|
52
|
-
the whole suite by the orphan rule. Each comes with a fix by what it
|
|
53
|
-
looks like (`reads` for a test's snapshot, `wiring` for a runner's
|
|
54
|
-
config, `nonInputs` otherwise), and `check --json` has them as
|
|
55
|
-
`unreached`. It's reported, not a failure (#48).
|
|
56
|
-
- A `urls` value can be a list: the page first, then what else it loads
|
|
57
|
-
that no import says, such as a router's layouts (`/about` →
|
|
58
|
-
`app/(marketing)/about/page.tsx`, `app/(marketing)/layout.tsx`,
|
|
59
|
-
`app/layout.tsx`). The page must exist; the rest are edges where they
|
|
60
|
-
do (#26).
|
|
61
|
-
- A file's `@depends-on`, or an `edges` key that names it, now also
|
|
62
|
-
covers its `goto()` calls whose URL bivium can't read, such as a loop
|
|
63
|
-
over a list of routes: list the pages they open, and the file is no
|
|
64
|
-
longer unknown (#27).
|
|
65
|
-
|
|
66
|
-
## 0.3.0 — 2026-11-02
|
|
67
|
-
|
|
68
|
-
**Breaking changes**
|
|
69
|
-
|
|
70
|
-
- A changed `ignore`d file the graph reads selects only the tests that
|
|
71
|
-
reach it through an edge. It no longer trips the orphan rule (with
|
|
72
|
-
the default `root`, any ignored change ran the whole suite), and no
|
|
73
|
-
longer selects the tests whose dependencies are unknown, so a
|
|
74
|
-
docs-only change selects `none` (#31, #32).
|
|
75
|
-
- A suite's `root`, and `roots`, with a wildcard is an error. Both take
|
|
76
|
-
paths, so `root: "components/**"` matched nothing and the orphan rule
|
|
77
|
-
quietly stopped for it (#21).
|
|
78
|
-
- A usage or configuration error (no command, an unknown command,
|
|
79
|
-
option or suite) exits 2. It exited 1, as `check` does when it finds
|
|
80
|
-
problems (#40).
|
|
81
|
-
- `plan`'s and `check`'s text output changed (see CLI).
|
|
82
|
-
|
|
83
|
-
**Features**
|
|
84
|
-
|
|
85
|
-
- `suites.<name>.types: false` says a suite runs code: a change that
|
|
86
|
-
reaches its tests only through `import type`, `export type … from`,
|
|
87
|
-
JSDoc types or declaration files selects none of them. The default
|
|
88
|
-
keeps today's selection, which a type-checking suite needs. `why`
|
|
89
|
-
labels these edges `type` (#38).
|
|
90
|
-
- `suites.<name>.setup` names the files a runner loads before every
|
|
91
|
-
test (`setupFiles`, `--require`, `globalSetup`): every test of the
|
|
92
|
-
suite depends on them and on what they import (#35).
|
|
93
|
-
- `// @lists <glob>` selects a test when a match is added, deleted or
|
|
94
|
-
renamed, not when one is edited, for a test that lists files without
|
|
95
|
-
reading them (#25).
|
|
96
|
-
- An `edges` key can name generated files git doesn't list, such as
|
|
97
|
-
`.velite/*`: an import that resolves under it, with an extension or
|
|
98
|
-
as an index, lands there instead of being unresolved (#20).
|
|
99
|
-
- A root `pnpm-lock.yaml` (v6 or v9) is diffed like `bun.lock`. Its
|
|
100
|
-
settings, overrides, catalogs, patches and pnpm's own version still
|
|
101
|
-
run everything, as does one bivium can't read (#34).
|
|
102
|
-
- `loadedByName` lists the packages a test may load other than by an
|
|
103
|
-
import (`jsdom`, `ts-jest`). Set, any other package without a `bin`
|
|
104
|
-
is import-only, so a lockfile bump that reaches one no test imports
|
|
105
|
-
selects only its importers (#23).
|
|
106
|
-
- `knownUnknowns` lists the unknown nodes `check` allows, each with a
|
|
107
|
-
reason, and `check` fails on one it doesn't list or an entry that's
|
|
108
|
-
no longer unknown (#24).
|
|
109
|
-
- `bivium graph` ranks each suite's files by how many tests a change to
|
|
110
|
-
one selects; `--json` exports the graph with each node's fan-in
|
|
111
|
-
(#36).
|
|
112
|
-
|
|
113
|
-
**CLI**
|
|
114
|
-
|
|
115
|
-
- Options can come before the command, and `--help` or `-h` anywhere
|
|
116
|
-
prints usage and exits 0.
|
|
117
|
-
- `plan` prints each selection's scale (`unit tests: 3 of 822 files`)
|
|
118
|
-
and tells a full run (`all (full run)`) from every test reaching a
|
|
119
|
-
change. `plan --json` and `plan()` add `totals`, and `causes`, each
|
|
120
|
-
reason as data.
|
|
121
|
-
- `check` leads with counts by cause, and a fix for an unresolved
|
|
122
|
-
specifier names the file that's there: a sibling with another
|
|
123
|
-
extension, a file outside `roots`, or one git ignores.
|
|
124
|
-
- `why --format json` is `why --json` (#40).
|
|
125
|
-
|
|
126
|
-
**Performance**
|
|
127
|
-
|
|
128
|
-
- The walk tests each distinct pattern (`edges`, `@depends-on`,
|
|
129
|
-
`import.meta.glob`, `reads`) once per node it visits, however many
|
|
130
|
-
files declare it. With 4,000 tests and
|
|
131
|
-
`{ "tests/*.test.ts": "src/setup.ts" }`, a plan took 0.81 s, and now
|
|
132
|
-
0.08 s (#39).
|
|
133
|
-
- A plan that reads files holds only what it extracted from each, not
|
|
134
|
-
the file's text, and reads 64 at a time. A cold plan of 7,000 files
|
|
135
|
-
needs a 20 MB heap on Node instead of over 64 MB, and peaks at 124 MB
|
|
136
|
-
of RSS instead of 285 MB (Bun: 88 MB instead of 115 MB) (#42).
|
|
137
|
-
- The orphan rule's walk from each changed file stops at the first test
|
|
138
|
-
or page it reaches, as does the lockfile check for a package a test
|
|
139
|
-
imports: with 350 changes in 5,900 files, the selection step took
|
|
140
|
-
21.7 ms and now 8.1 ms.
|
|
141
|
-
|
|
142
|
-
**Fixes**
|
|
143
|
-
|
|
144
|
-
- An `alias` key that ends in `/` (`{ "@/": "src/" }`, as Vite
|
|
145
|
-
configs spell it) matches the specifiers that start with it. It
|
|
146
|
-
matched none (#29).
|
|
147
|
-
- A missing `x.js` resolves to `x.tsx` and `x.d.ts` as well as `x.ts`
|
|
148
|
-
(and the `.mjs` and `.cjs` variants), through `exports` and `imports`
|
|
149
|
-
targets too, so `@acme/ui/Button.js` reaches
|
|
150
|
-
`packages/ui/src/Button.ts`. A value import that finds only `x.d.ts`
|
|
151
|
-
is unknown: what runs isn't in the graph (#28).
|
|
152
|
-
- A doubled slash in a specifier resolves through `alias` and tsconfig
|
|
153
|
-
`paths` (#33).
|
|
154
|
-
- A specifier that starts with a dot but not `./` or `../` (`.velite`)
|
|
155
|
-
is bare, as TypeScript reads it (#20).
|
|
156
|
-
- An `edges` or `reads` key that names one file declares what it reads
|
|
157
|
-
from disk, as `@depends-on` and `@reads` do (#22).
|
|
158
|
-
- The lexer reads a JSX element with type arguments in `.tsx`
|
|
159
|
-
(`<List<string> />`) instead of falling back to the regex extractor
|
|
160
|
-
(#30).
|
|
161
|
-
- A type import from `fs` doesn't count as reading the disk, and
|
|
162
|
-
`check` lists an unresolved specifier once per file.
|
|
163
|
-
|
|
164
|
-
**Docs**
|
|
165
|
-
|
|
166
|
-
- The README has one table for what to do with a changed file no test
|
|
167
|
-
reaches, recipes for Vitest and Jest, pnpm workspaces, Playwright
|
|
168
|
-
and generated code, and what a plan costs in CI (#41).
|
|
169
|
-
|
|
170
|
-
## 0.2.1 — 2026-10-28
|
|
171
|
-
|
|
172
|
-
**Performance**
|
|
173
|
-
|
|
174
|
-
- `git merge-base` runs only when something needs the commit:
|
|
175
|
-
`plan()`, `plan --json`, or a narrower whose files changed. Base
|
|
176
|
-
versions of changed files are read by the blob ID the diff names.
|
|
177
|
-
Git's CPU per plan drops 21 to 24% on carbon-components-svelte and
|
|
178
|
-
sveld.
|
|
179
|
-
- A bare specifier is resolved once per owning `package.json` and
|
|
180
|
-
nearest `tsconfig.json`, and probing checks only matching extensions:
|
|
181
|
-
13 to 30% fewer instructions building the graph on real
|
|
182
|
-
repositories.
|
|
183
|
-
- The lexer's first pass in a fresh process is 23% faster on Bun and
|
|
184
|
-
32% on Node, with identical extractions.
|
|
185
|
-
|
|
186
|
-
**Fixes**
|
|
187
|
-
|
|
188
|
-
- Without the cache, a file staged as new and then deleted from disk
|
|
189
|
-
no longer counts as present.
|
|
190
|
-
|
|
191
|
-
**Docs**
|
|
192
|
-
|
|
193
|
-
- The CI example clones with `filter: blob:none`: on
|
|
194
|
-
carbon-components-svelte the checkout went from 6.3 s to 3.8 s.
|
|
195
|
-
|
|
196
|
-
## 0.2.0 — 2026-10-27
|
|
197
|
-
|
|
198
|
-
**Breaking changes**
|
|
199
|
-
|
|
200
|
-
- `bivium check` now reports an `edges` or `reads` key that matches no
|
|
201
|
-
node, and a value that matches nothing for any match, so a config
|
|
202
|
-
with a stale `edges` entry fails it. Allow one in `deadGlobs`.
|
|
203
|
-
- tsconfig `paths` and `baseUrl` are read, after `alias` and before
|
|
204
|
-
`package.json` `exports`, so a specifier that was unresolved (and
|
|
205
|
-
ran its tests on every change) may now resolve.
|
|
206
|
-
- `bivium why --json` reports the finer edge kinds and new fields.
|
|
207
|
-
|
|
208
|
-
**Features**
|
|
209
|
-
|
|
210
|
-
- A changed root `bun.lock` or `package-lock.json` seeds the packages
|
|
211
|
-
it changed and their dependents instead of running everything. A
|
|
212
|
-
changed package no test imports still runs everything unless it's
|
|
213
|
-
listed in the new `inert` key.
|
|
214
|
-
- `edges` values can use `$1`, `$2`… for what the key's wildcards
|
|
215
|
-
matched, and the new `reads` key is `@reads` in the config, for
|
|
216
|
-
files that can't hold a comment (snapshots, `package.json`).
|
|
217
|
-
- `#name` subpath imports resolve through the importing file's own
|
|
218
|
-
`package.json` `imports`.
|
|
219
|
-
- `%sveltekit.assets%/x` in an `app.html` maps to the project's
|
|
220
|
-
`static/x`.
|
|
221
|
-
- `bivium why` names what spells each edge (`goto`, `html`, `name`,
|
|
222
|
-
`export`, `depends-on`, `edges`, `reads`), aligns its columns, says
|
|
223
|
-
how many other changes reach the test, and takes `--format
|
|
224
|
-
tree|chain|source` and `--all`. A test that isn't selected says
|
|
225
|
-
what the file's chains reach instead.
|
|
226
|
-
|
|
227
|
-
**Fixes**
|
|
228
|
-
|
|
229
|
-
- `bivium why` cites the call that spells an edge, not a comment that
|
|
230
|
-
mentions the file.
|
|
231
|
-
|
|
232
|
-
## 0.1.2 — 2026-10-27
|
|
233
|
-
|
|
234
|
-
**Features**
|
|
235
|
-
|
|
236
|
-
- `hermetic` (globs) lists files whose disk reads and non-literal
|
|
237
|
-
imports reach no file of the repository, such as a library's `fs`
|
|
238
|
-
calls on its caller's paths. They no longer count as unknown; an
|
|
239
|
-
unresolved import, a non-literal glob or `goto()`, and any
|
|
240
|
-
`@depends-on` or `@reads` still do.
|
|
241
|
-
|
|
242
|
-
**Fixes**
|
|
243
|
-
|
|
244
|
-
- `bivium check` no longer counts a test that only `@reads` an
|
|
245
|
-
unknown node as running on any change, which `plan` never does.
|
|
246
|
-
|
|
247
|
-
## 0.1.1 — 2026-10-26
|
|
248
|
-
|
|
249
|
-
**Fixes**
|
|
250
|
-
|
|
251
|
-
- `bivium --version` (and `-v`) prints the version instead of failing
|
|
252
|
-
as an unknown command.
|
|
253
|
-
|
|
254
|
-
## 0.1.0 — 2026-10-26
|
|
255
|
-
|
|
256
|
-
The first release of bivium, the test selector extracted from
|
|
257
|
-
carbon-components-svelte's `test:changed`.
|
|
258
|
-
|
|
259
|
-
**Features**
|
|
260
|
-
|
|
261
|
-
- `bivium plan` prints each suite's selection (`all`, `none` or the test
|
|
262
|
-
files) and why a suite runs in full; `--json` prints it with the base,
|
|
263
|
-
merge base, changed files and narrower results; `--github` writes each
|
|
264
|
-
suite's selection to `$GITHUB_OUTPUT` as `<name>-tests`, or a suite's
|
|
265
|
-
`output`.
|
|
266
|
-
- `bivium run [--suite <name>]` runs a suite's command with its selection.
|
|
267
|
-
- `bivium why <test> [file]` prints the shortest chain of edges from a
|
|
268
|
-
changed file, or from `file`, to a test, with the line of each edge.
|
|
269
|
-
- `bivium check [--max-unknown <n>]` lists the nodes whose dependencies
|
|
270
|
-
can't be read, with locations, fixes and the tests each one makes run on
|
|
271
|
-
any change, and fails when more than `n` reach a test. Ones no test
|
|
272
|
-
reaches are listed apart: they widen no plan.
|
|
273
|
-
- `bivium check` fails on a dead glob: an `@depends-on`, `@reads` or
|
|
274
|
-
`import.meta.glob` pattern that matches no file, or matches files that
|
|
275
|
-
are ignored and outside the graph, so a change to them selects nothing.
|
|
276
|
-
`deadGlobs` in the config allows one with a reason, and an entry that
|
|
277
|
-
matches no dead glob fails the check too.
|
|
278
|
-
- `narrowers` in the config replace a change's coarse seeds with finer
|
|
279
|
-
ones from a semantic diff. They can only narrow.
|
|
280
|
-
- `plan()` and `defineConfig()` from code; given a config, `plan()` types
|
|
281
|
-
its result by the suite names.
|
|
282
|
-
- A one-pass lexer for JavaScript, TypeScript, JSX, Svelte, Vue, Astro and
|
|
283
|
-
HTML, with a regex fallback, and an extraction cache keyed by git blob.
|
|
284
|
-
|
|
285
|
-
**Requirements**
|
|
286
|
-
|
|
287
|
-
- Node ≥ 22 (≥ 22.18 for a `bivium.config.ts`), or Bun.
|
package/cli.js
DELETED
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{version,globToRegExp,sorted,QUERY,UNDECLARED_READS,RELATIVE,aliasPath,createResolver,SCANNED,formatOf,extract,finish,gotoPage,walksByTypes,importersOf,affectedBy,formatSelection,orphanOf,plural,computePlan,prepare}from"./shared-xrgq64gt.js";import{spawnSync}from"node:child_process";import{appendFileSync}from"node:fs";import{statSync}from"node:fs";import{join as join2,posix}from"node:path";function fanIn(graph,suite){let ids=new Map,nodes=[...graph.keys()];for(let[i,node]of nodes.entries())ids.set(node,i);let matches=new Map,matching=(re)=>{let found=matches.get(re.source);if(!found){found=[];for(let[i,node]of nodes.entries())if(re.test(node))found.push(i);matches.set(re.source,found)}return found},forward=[],direct=[];for(let node of nodes){let deps=graph.get(node),out=[],read=[];if(deps){for(let file of deps.files){if(!suite.types&&deps.types?.has(file))continue;let id=ids.get(file);if(id!==void 0)out.push(id)}for(let re of deps.patterns)out.push(...matching(re));for(let re of[...deps.reads,...deps.lists??[]])read.push(...matching(re))}forward.push(out),direct.push(read)}let counts=new Uint32Array(nodes.length),stamp=new Int32Array(nodes.length).fill(-1),stack=[];for(let[t,test]of nodes.entries()){if(!suite.isTest(test))continue;let reached=[],visit=(id)=>{if(stamp[id]===t)return;stamp[id]=t,reached.push(id)};visit(t),stack.push(t);while(stack.length>0){let at=stack.pop()??0;for(let next of forward[at]){if(stamp[next]===t)continue;visit(next),stack.push(next)}}for(let id of[...reached])for(let read of direct[id])visit(read);for(let id of reached)counts[id]++}let result=new Map;for(let[i,node]of nodes.entries())result.set(node,counts[i]);return result}function graphReport(graph,suites){let counts=suites.map((suite)=>[suite.name,fanIn(graph,suite)]),unknown=[...graph].filter(([,deps])=>deps.unknown.length>0).map(([node])=>node),everyChange=walksByTypes(graph,unknown,{includeUnknown:!1,readers:!1});return{suites:Object.fromEntries(suites.map((suite)=>[suite.name,{total:[...graph.keys()].filter(suite.isTest).length,everyChange:sorted(everyChange(suite.types)).filter(suite.isTest)}])),nodes:[...graph].map(([node,deps])=>({node,imports:sorted(deps.files),importers:sorted(importersOf(graph,node)),fanIn:Object.fromEntries(counts.map(([name,count])=>[name,count.get(node)??0])),unknown:deps.unknown.length>0}))}}function buckets(total){let list=[[0,0],[1,1]];for(let low=2,high=10;low<total;low=high+1,high*=10)list.push([low,Math.min(high,total-1)]);if(total>1)list.push([total,total]);return list}function formatGraph(report,top){let lines=[],files=report.nodes.filter(({node})=>!node.startsWith("pkg:")&&!node.includes("#"));for(let[name,{total:tests,everyChange}]of Object.entries(report.suites)){let any=everyChange.length;lines.push(`${name}: ${plural(tests,"test")}${any>0?`; ${any} run on any change (\`bivium check\` says why)`:""}`);let ranked=files.map(({node,fanIn:reach})=>[node,reach[name]??0]).filter(([,count])=>count>0).sort(([a,x],[b,y])=>y-x||(a<b?-1:1)),width=Math.max(String(tests).length,5);if(ranked.length>0){lines.push(` ${"tests".padStart(width)} file`);for(let[id,count]of ranked.slice(0,top))lines.push(` ${String(count).padStart(width)} ${id}`);if(ranked.length>top)lines.push(` … ${ranked.length-top} more (--top <n> shows more)`)}lines.push(` files by how many ${name} tests a change to one selects:`);let rows=buckets(tests).map(([low,high])=>{let label=low===high?String(low):`${low}–${high}`,count=files.filter(({fanIn:reach})=>{let n=reach[name]??0;return n>=low&&n<=high}).length;return[label,count]}),labelWidth=Math.max(...rows.map(([label])=>label.length));for(let[label,count]of rows)lines.push(` ${label.padStart(labelWidth)} ${count}`)}return lines.join(`
|
|
3
|
-
`)}import{readFile}from"node:fs/promises";import{isAbsolute,join}from"node:path";var DISK_READ=/\bfrom\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\brequire\s*\(\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\bBun\.(?:file|Glob|spawn)/,NON_LITERAL_IMPORT=/\b(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\s*(?:<[^>]*>)?\(\s*(?!["'][^"'`$]*["']\s*[,)])/,GLOB_CALL=/\bimport\.meta\.glob/,QUOTED_CAUSE=/"([^"]+)"/,LOADS=/\b(?:import|export|from|require|mock|doMock|unmock|importActual|importMock)\b|\b(?:src|href)\s*=/,GOTO_CALL=/\bgoto\s*\(/;function lineAt(source,index){let line=1;for(let i=source.indexOf(`
|
|
4
|
-
`);i!==-1&&i<index;i=source.indexOf(`
|
|
5
|
-
`,i+1))line++;return line}function lineOf(source,needle){let index=typeof needle==="string"?source.indexOf(needle):source.search(needle);return index===-1?void 0:lineAt(source,index)}function commentRanges(source){let ranges=[];for(let i=0;i<source.length;i++){let c=source[i];if(c==='"'||c==="'"){while(++i<source.length&&source[i]!==c&&source[i]!==`
|
|
6
|
-
`)if(source[i]==="\\")i++}else if(c==="`"){while(++i<source.length&&source[i]!=="`")if(source[i]==="\\")i++}else if(source.startsWith("//",i)){let end=source.indexOf(`
|
|
7
|
-
`,i);ranges.push([i,end===-1?source.length:end]),i=end===-1?source.length:end}else if(source.startsWith("/*",i)||source.startsWith("<!--",i)){let close=c==="/"?"*/":"-->",end=source.indexOf(close,i+2),stop=end===-1?source.length:end+close.length;ranges.push([i,stop]),i=stop-1}}return ranges}function lineTextAt(source,index){let start=source.lastIndexOf(`
|
|
8
|
-
`,index-1)+1,end=source.indexOf(`
|
|
9
|
-
`,index);return source.slice(start,end===-1?source.length:end)}function bestLine(source,needles,near){let comments,inComment=(index)=>(comments??=commentRanges(source),comments.some(([start,end])=>index>=start&&index<end)),code,any;for(let needle of needles)for(let index=source.indexOf(needle);index!==-1;index=source.indexOf(needle,index+1)){if(any??=index,inComment(index))continue;if(near===void 0||near.test(lineTextAt(source,index)))return lineAt(source,index);code??=index}let found=code??any;return found===void 0?void 0:lineAt(source,found)}function specifierLine(source,specifier){let quoted=['"',"'","`"].map((quote)=>`${quote}${specifier}${quote}`);return bestLine(source,quoted,LOADS)??bestLine(source,[specifier])}function gotoLine(source,argument,page){return(argument===void 0?void 0:bestLine(source,[argument],GOTO_CALL))??bestLine(source,[page.slice(page.lastIndexOf("/")+1)],GOTO_CALL)}function callLine(source,call){return bestLine(source,[call])}function causeLine(source,cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED_CAUSE.exec(cause)?.[1];return specifier===void 0?void 0:specifierLine(source,specifier)}if(cause==="non-literal dynamic import")return lineOf(source,NON_LITERAL_IMPORT);if(cause==="non-literal glob import")return lineOf(source,GLOB_CALL);if(cause===UNDECLARED_READS)return lineOf(source,DISK_READ);if(cause.startsWith("non-literal goto("))return lineOf(source,cause.slice(12,-1));let url=QUOTED_CAUSE.exec(cause)?.[1];return url===void 0?void 0:lineOf(source,url)}function textLine(source,text){return lineOf(source,text)}function annotationLine(source,tag,glob){let index=source.split(`
|
|
10
|
-
`).findIndex((line)=>line.includes(tag)&&line.includes(glob));return index===-1?void 0:index+1}function lineText(source,line){let start=0;for(let n=1;n<line;n++){let next=source.indexOf(`
|
|
11
|
-
`,start);if(next===-1)return"";start=next+1}let end=source.indexOf(`
|
|
12
|
-
`,start);return source.slice(start,end===-1?source.length:end).trim()}async function sourceOf(root,file){try{return await readFile(isAbsolute(file)?file:join(root,file),"utf-8")}catch{return}}function fileOf(node){let hash=node.indexOf("#");return hash===-1?node:node.slice(0,hash)}async function causesOf(root,computed,node){let file=fileOf(node),source=await sourceOf(root,file);return(computed.graph.get(node)?.unknown??[]).map((cause)=>{if(source===void 0)return{cause};let line=causeLine(source,cause);return line===void 0?{cause}:{cause,at:`${file}:${line}`,text:lineText(source,line)}})}var EXAMPLES=3,TAGS={"depends-on":"@depends-on",reads:"@reads",lists:"@lists",glob:"import.meta.glob",edges:"edges",setup:"setup"},QUOTED=/"([^"]+)"/;function fixFor(cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED.exec(cause)?.[1]??"";if(specifier.startsWith("./%sveltekit.assets%/"))return"no file in the SvelteKit project's `static/` (a custom `kit.files.assets` isn't read): fix the path, or add an `edges` entry for it";if(RELATIVE.test(specifier))return"no file at that path: fix the import, or add an `edges` entry if a build generates it";if(specifier.startsWith("#"))return"map it in the `imports` of the file's package.json, or with `alias`";return"declare the package in a package.json, list it in `external` if a dependency installs it, or map it with `alias` or tsconfig `paths`"}if(cause.startsWith("only declarations for "))return"only a declaration file is there, so what runs isn't in the graph: if a build writes it, name it in `edges` with its inputs, or import it with `import type` if only its types are used";if(cause==="non-literal dynamic import")return"spell the path as a string literal, load the files with `import.meta.glob` and literal patterns, or list the file in `hermetic` if it only imports paths its caller passes";if(cause==="non-literal glob import")return"pass `import.meta.glob` literal patterns";if(cause===UNDECLARED_READS)return"name what it reads: `// @depends-on <glob>`, or `// @reads <glob>` for files read as text, or an `edges` or `reads` entry for the file in the config; list the file in `hermetic` if it reads no file of the repository";if(cause.startsWith("non-literal goto("))return"pass `goto()` a literal URL, or a template whose path before `?` or `#` is literal; or name the pages it can open with `// @depends-on <glob>`";if(cause.startsWith("missing fixture "))return"no page at that URL: fix the URL, or the suite's `urls`";if(cause.startsWith("goto("))return"map the URL to a file with the suite's `urls`";return"see the cause"}function isFile(path){return statSync(path,{throwIfNoEntry:!1})?.isFile()??!1}function stemOf(path){let slash=path.lastIndexOf("/"),dot=path.indexOf(".",slash+2);return dot===-1?path:path.slice(0,dot)}function nearMisses(root,config,{graph,listed}){let stems,listedSet=new Set(listed),siblings=(path)=>{if(!stems){stems=new Map;for(let file of listed){let stem=stemOf(file),list=stems.get(stem);list?list.push(file):stems.set(stem,[file])}}return stems.get(stemOf(path))??[]},candidates=(base)=>[base,...config.extensions.map((ext)=>base+ext),...config.extensions.map((ext)=>`${base}/index${ext}`)];return(node,cause)=>{if(!cause.startsWith("unresolved "))return;let specifier=(QUOTED.exec(cause)?.[1]??"").replace(QUERY,""),base=RELATIVE.test(specifier)?posix.join(posix.dirname(fileOf(node)),specifier):config.alias.map((alias)=>aliasPath(alias,specifier)).find((path)=>path!==void 0);if(base===void 0||base.startsWith("../"))return;let tried=candidates(base),outside=tried.find((path)=>listedSet.has(path)&&!graph.has(path));if(outside!==void 0)return`${outside} exists, but outside \`roots\`: add it to \`roots\``;let unlisted=tried.find((path)=>isFile(join2(root,path)));if(unlisted!==void 0&&!listedSet.has(unlisted))return`${unlisted} exists, but git doesn't list it (ignored?): if a build writes it, name it in \`edges\` with its inputs`;let sibling=siblings(base).find((file)=>graph.has(file));if(sibling!==void 0)return`${sibling} exists: import it by that name, or add its extension to \`extensions\``;return}}function declaredGlobs(node,extraction){let relative=finish(node,extraction).globs;return[...extraction.dependsOn.map((glob)=>({kind:"depends-on",glob,pattern:globToRegExp(glob)})),...extraction.reads.map((glob)=>({kind:"reads",glob,pattern:globToRegExp(glob)})),...extraction.lists.map((glob)=>({kind:"lists",glob,pattern:globToRegExp(glob)})),...extraction.globs.map((glob,i)=>({kind:"glob",glob,pattern:globToRegExp(relative[i])}))]}function problemOf(matches,ignored){if(matches===0)return"matches nothing";if(ignored===0)return;return ignored===matches?"matches only ignored files":"partly ignored"}function deadOf(node,kind,glob,patterns,listed,skipped){let matches=listed.filter((file)=>patterns.some((re)=>re.test(file))),ignored=sorted(matches.filter(skipped)),problem=problemOf(matches.length,ignored.length);if(problem===void 0)return;return{node,kind,glob,problem,matches:matches.length,ignored:ignored.length,examples:ignored.slice(0,EXAMPLES),fix:problem==="matches nothing"?"fix the path":"point it at files the selector reads, or allowlist it in `deadGlobs` with a reason"}}function configDeadGlobs(config,{graph,listed},skipped){let file=config.file??"the config",found=[],entries=[...config.generated.map((map)=>["edges",map]),...config.reads.map((map)=>["reads",map])];for(let[kind,map]of entries){let patterns=map.values.map(()=>new Map),matched=!1;for(let node of graph.keys()){let targets=map.targets(node);if(!targets)continue;matched=!0;for(let[i,re]of targets.entries())patterns[i]?.set(re.source,re)}if(!matched){found.push({node:file,kind,glob:map.key,problem:"matches nothing",matches:0,ignored:0,examples:[],fix:"fix the path: no file the graph reads matches it"});continue}for(let[i,glob]of map.values.entries()){let expanded=[...patterns[i]?.values()??[]],dead=deadOf(file,kind,glob,expanded,listed,skipped);if(dead)found.push(dead)}}for(let suite of config.suites)for(let glob of suite.setup){let pattern=globToRegExp(glob),dead=deadOf(file,"setup",glob,[pattern],listed,skipped);if(dead)found.push(dead)}return found}async function findDeadGlobs(root,config,computed){let{graph,extractions,listed}=computed,skipped=(file)=>config.isIgnored(file)&&!graph.has(file),found=[];for(let node of graph.keys()){let extraction=extractions.get(node);if(!extraction)continue;for(let{kind,glob,pattern}of declaredGlobs(node,extraction)){let dead=deadOf(node,kind,glob,[pattern],listed,skipped);if(dead)found.push(dead)}}let configured=configDeadGlobs(config,computed,skipped),nodes=[...new Set([...found.map(({node})=>node),...configured.map(({node})=>node)])],texts=await Promise.all(nodes.map((node)=>sourceOf(root,node))),sources=new Map(nodes.map((node,i)=>[node,texts[i]])),locate=(dead,line)=>{let source=sources.get(dead.node),at=source===void 0?void 0:line(source);return at===void 0?dead:{...dead,at:`${dead.node}:${at}`}};return[...found.map((dead)=>locate(dead,(source)=>dead.kind==="glob"?specifierLine(source,dead.glob):annotationLine(source,TAGS[dead.kind],dead.glob))),...configured.map((dead)=>locate(dead,(source)=>specifierLine(source,dead.glob)))]}var CONFIG_FILE=/(?:^|[./_-])(?:config|setup|teardown|harness)(?:[./_-]|$)|^tsconfig[^/]*\.json$|^\.[^/]*rc(?:\.[^/]+)?$/;function unreachedFix(file,tests){let name=posix.basename(file),owner=tests.find((test)=>name.startsWith(`${posix.basename(test)}.`));if(owner!==void 0)return`if ${owner} reads it, add \`reads: { "${owner}": "${file}" }\` (or \`// @reads ${file}\` in the test)`;if(CONFIG_FILE.test(name))return"if the runner loads it, name it in the suite's `wiring` (or `setup`, if it runs before every test), which makes the full run deliberate";return"if a test reads or runs it, say so with `reads` or `@depends-on` in that test or what loads it; if none can observe it, list it in the suite's `nonInputs`, or delete it if it's dead"}function unreachedFiles(config,{graph}){let found=[],files=[...graph.keys()].filter((node)=>!node.startsWith("pkg:")&&!node.includes("#"));for(let suite of config.suites){let reached=fanIn(graph,suite),tests=files.filter(suite.isTest);for(let file of files){if((reached.get(file)??0)>0)continue;if(config.isIgnored(file)||config.isSelf(file))continue;if(suite.isWiring(file))continue;if(!orphanOf(graph,config,suite,file))continue;found.push({suite:suite.name,file,fix:unreachedFix(file,tests)})}}return found}async function check(root,config,computed){let nodes=[...computed.graph].filter(([,deps])=>deps.unknown.length>0).map(([node])=>node),testsOf=(node)=>{let reach=walksByTypes(computed.graph,[node],{includeUnknown:!1,readers:!1}),found=new Set;for(let suite of config.suites)for(let test of reach(suite.types))if(suite.isTest(test))found.add(test);return sorted(found)},nearMiss=nearMisses(root,config,computed),known=new Map((config.knownUnknowns??[]).map((entry)=>[entry.file,entry.reason])),unknown=await Promise.all(nodes.map(async(node)=>{let causes=(await causesOf(root,computed,node)).map(({cause,at})=>{let fix=nearMiss(node,cause)??fixFor(cause);return at===void 0?{cause,fix}:{cause,at,fix}}),reason=known.get(node),entry={node,causes,tests:testsOf(node)};if(reason!==void 0)entry.known=reason;return entry})),fallbacks=[...computed.fallbacks].map(([file,reason])=>({file,reason})),dead=await findDeadGlobs(root,config,computed),unreached=unreachedFiles(config,computed),allows=(entry,found)=>entry.file===found.node&&entry.glob===found.glob;return{unknown,fallbacks,unparsedTsconfigs:computed.unparsedTsconfigs,deadGlobs:dead.filter((found)=>!config.deadGlobs.some((entry)=>allows(entry,found))),unlistedUnknowns:config.knownUnknowns?unknown.filter((entry)=>entry.tests.length>0&&entry.known===void 0).map((entry)=>entry.node):[],staleKnownUnknowns:(config.knownUnknowns??[]).filter((entry)=>!nodes.includes(entry.file)).map((entry)=>({...entry,fix:"remove the entry: its dependencies are known now"})),unreached,staleDeadGlobs:config.deadGlobs.filter((entry)=>!dead.some((found)=>allows(entry,found))).map((entry)=>({...entry,fix:"remove the entry: its glob is no longer dead"}))}}function summary({problem,matches,ignored,examples}){if(problem==="matches nothing")return problem;let shown=[...examples,...ignored>examples.length?["…"]:[]],count=problem==="partly ignored"?`${ignored} of ${matches}`:`${ignored}`;return`${problem} (${count}: ${shown.join(", ")})`}function widening(report){return report.unknown.filter((node)=>node.tests.length>0)}function failed(report,max){return max!==void 0&&widening(report).length>max||report.unlistedUnknowns.length>0||report.staleKnownUnknowns.length>0||report.deadGlobs.length>0||report.staleDeadGlobs.length>0}function pushUnknown(lines,{node,causes,tests,known}){lines.push(known===void 0?node:`${node} (known: ${known})`);for(let{cause,at,fix}of causes)lines.push(` ✗ ${cause}${at?` ${at}`:""}`,` fix: ${fix}`);if(tests.length>0){let more=tests.length>3?`, and ${tests.length-3} more`:"";lines.push(` runs on any change: ${tests.slice(0,3).join(", ")}${more}`)}}function categoryOf(cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED.exec(cause)?.[1]??"";if(RELATIVE.test(specifier))return"unresolved relative import";if(specifier.startsWith("#"))return"unresolved # import";return"unresolved bare import (a package, alias or path)"}if(cause.startsWith("only declarations for "))return"a .js import with only its declarations there";if(cause.startsWith("non-literal goto("))return"non-literal goto()";if(cause.startsWith("goto("))return"goto() URL no `urls` pattern maps";if(cause.startsWith("missing fixture "))return"goto() of a missing page";return cause}var POSITION=/(?: in <>)? at \d+.*$/,BLANK_LINES=/\n{3,}/g;function counted(counts){return[...counts].sort(([a,x],[b,y])=>y-x||(a<b?-1:1)).map(([what,count])=>`${count} ${what}`)}function summaryLines(report){let widen=widening(report),lines=[];if(widen.length>0){let tests=new Set(widen.flatMap((node)=>node.tests));lines.push(`${plural(widen.length,"node")} with unknown dependencies ${widen.length===1?"reaches":"reach"} ${plural(tests.size,"test")}, which ${tests.size===1?"runs":"run"} on any change:`);let causes=new Map;for(let node of widen)for(let category of new Set(node.causes.map(({cause})=>categoryOf(cause))))causes.set(category,(causes.get(category)??0)+1);lines.push(...counted(causes).map((line)=>` ${line}`))}let idle=report.unknown.length-widen.length;if(idle>0)lines.push(`${plural(idle,"more node")} with unknown dependencies no test reaches`);if(report.fallbacks.length>0){let reasons=new Map;for(let{reason}of report.fallbacks){let what=reason.replace(POSITION,"");reasons.set(what,(reasons.get(what)??0)+1)}lines.push(`${plural(report.fallbacks.length,"file")} read by the regex extractor: ${counted(reasons).join(", ")}`)}let problems=[[report.unparsedTsconfigs.length,"tsconfig file that doesn't parse","tsconfig files that don't parse"],[report.deadGlobs.length,"dead glob","dead globs"],[report.staleDeadGlobs.length,"stale `deadGlobs` entry","stale `deadGlobs` entries"],[report.unlistedUnknowns.length,"unknown not in `knownUnknowns`","unknowns not in `knownUnknowns`"],[report.staleKnownUnknowns.length,"stale `knownUnknowns` entry","stale `knownUnknowns` entries"],[report.unreached.length,"file under a suite's root that no test reaches","files under a suite's root that no test reaches"]];for(let[count,one,many]of problems)if(count>0)lines.push(plural(count,one,many));return lines.length===0?[]:["Summary:",...lines.map((line)=>` ${line}`),""]}var UNREACHED_SHOWN=10;function pushUnreached(lines,unreached){if(unreached.length===0)return;lines.push("","Files under a suite's root that no test reaches: a change to one runs the whole suite:");for(let suite of new Set(unreached.map((entry)=>entry.suite))){let entries=unreached.filter((entry)=>entry.suite===suite);lines.push(` ${suite} (${entries.length})`);for(let{file,fix}of entries.slice(0,UNREACHED_SHOWN))lines.push(` ${file}`,` fix: ${fix}`);let rest=entries.slice(UNREACHED_SHOWN);if(rest.length===0)continue;let dirs=new Map;for(let{file}of rest){let dir=posix.dirname(file);dirs.set(dir,(dirs.get(dir)??0)+1)}let counts=[...dirs].sort(([a,x],[b,y])=>y-x||(a<b?-1:1)).map(([dir,count])=>`${dir}/ (${count})`);lines.push(` … ${rest.length} more in ${counts.slice(0,5).join(", ")}${counts.length>5?", …":""} (--json lists each)`)}}function formatReport(report,max){let lines=summaryLines(report),widen=widening(report);for(let unknown of widen)pushUnknown(lines,unknown);let idle=report.unknown.filter((node)=>node.tests.length===0);if(idle.length>0){lines.push("","Unknown, but no test depends on them, so they widen nothing:");for(let unknown of idle)pushUnknown(lines,unknown)}if(report.fallbacks.length>0){lines.push("","Read by the regex extractor, which the lexer couldn't read:");for(let{file,reason}of report.fallbacks)lines.push(` ${file}: ${reason}`)}if(pushUnreached(lines,report.unreached),report.unparsedTsconfigs.length>0){lines.push("","tsconfig files that don't parse, whose `paths` are ignored:");for(let{file,reason}of report.unparsedTsconfigs)lines.push(` ${file}: ${reason}`)}if(report.deadGlobs.length>0){lines.push("","Dead globs: a change to what they match, or to some of it, selects nothing:");let node;for(let dead of report.deadGlobs){if(dead.node!==node)lines.push(` ${dead.node}`);node=dead.node,lines.push(` ✗ ${dead.kind} ${dead.glob}: ${summary(dead)}${dead.at?` ${dead.at}`:""}`,` fix: ${dead.fix}`)}}if(report.staleDeadGlobs.length>0){lines.push("","`deadGlobs` entries that match no dead glob:");for(let{file,glob,fix}of report.staleDeadGlobs)lines.push(` ${file}: ${glob}`,` fix: ${fix}`)}if(report.staleKnownUnknowns.length>0){lines.push("","`knownUnknowns` entries whose dependencies are known:");for(let{file,fix}of report.staleKnownUnknowns)lines.push(` ${file}`,` fix: ${fix}`)}let count=widen.length,limit=max===void 0?"":` (at most ${max})`;lines.push("",`${count} ${count===1?"node":"nodes"} with unknown dependencies ${count===1?"reaches":"reach"} a test${limit}: each such test runs on any change.`);let unlisted=report.unlistedUnknowns.length;if(unlisted>0)lines.push(`${unlisted} of them not in \`knownUnknowns\`: fix ${unlisted===1?"it":"them"}, or list ${unlisted===1?"it":"them"} with a reason.`);if(idle.length>0)lines.push(`${idle.length} more no test reaches.`);let staleKnown=report.staleKnownUnknowns.length;if(staleKnown>0)lines.push(`${plural(staleKnown,"stale `knownUnknowns` entry","stale `knownUnknowns` entries")}.`);let dead=report.deadGlobs.length,stale=report.staleDeadGlobs.length;if(dead>0)lines.push(`${plural(dead,"dead glob")} not in \`deadGlobs\`.`);if(stale>0)lines.push(`${plural(stale,"stale `deadGlobs` entry","stale `deadGlobs` entries")}.`);return lines.join(`
|
|
13
|
-
`).replace(BLANK_LINES,`
|
|
14
|
-
|
|
15
|
-
`).trimStart()}var CONFIG_EDGES="edges in the config",CONFIG_SETUP="setup in the config",CONFIGURED={edges:CONFIG_EDGES,setup:CONFIG_SETUP},CONFIG_READS="reads in the config";async function edgeAt(context,node,via){let spelled=CONFIGURED[via.kind];if(spelled!==void 0)return{at:spelled};if(via.kind==="unknown")return{};let file=fileOf(node),source=SCANNED.test(file)?await sourceOf(context.root,file):void 0,configured=(maps)=>maps.some((map)=>map.targets(node)?.some((re)=>re.test(via.from)));if(via.kind==="reads"&&configured(context.config.reads)){if(!(source!==void 0&&extract(formatOf(file),source).reads.some((glob)=>globToRegExp(glob).test(via.from))))return{at:CONFIG_READS}}if(source===void 0)return{};let line=edgeLine(context,node,via,source);return line===void 0?{}:{at:`${file}:${line}`,text:lineText(source,line)}}function edgeLine({config,resolve},node,via,source){let file=fileOf(node),extraction=extract(formatOf(file),source),matches=(glob)=>globToRegExp(glob).test(via.from);if(via.kind==="reads"||via.kind==="depends-on"||via.kind==="lists"){let tag=`@${via.kind}`,glob={reads:extraction.reads,"depends-on":extraction.dependsOn,lists:extraction.lists}[via.kind].find(matches);return(glob===void 0?void 0:annotationLine(source,tag,glob))??textLine(source,tag)}if(via.kind==="glob"){let relative=finish(file,extraction).globs,glob=extraction.globs.find((_,i)=>matches(relative[i]));return(glob===void 0?void 0:specifierLine(source,glob))??callLine(source,"import.meta.glob")}let target=fileOf(via.from);if(via.kind==="goto"){let argument=extraction.gotos.find((candidate)=>gotoPage(config,file,candidate)?.includes(target));return gotoLine(source,argument,target)}let loads=(specifier)=>{let resolved=resolve(file,specifier);return resolved!==void 0&&"files"in resolved&&resolved.files.includes(target)};if(via.kind==="export"){let barrel=extraction.barrel;if(!barrel)return;let own=barrel.names.get(node.slice(node.indexOf("#")+1)),specifier=[...own===void 0?[]:[own],...barrel.names.values(),...barrel.stars].find(loads);return specifier===void 0?void 0:specifierLine(source,specifier)}let imported=extraction.imports.find(({specifier})=>loads(specifier));return imported===void 0?void 0:specifierLine(source,imported.specifier)}function rootCause(computed,rootNode,from){if(from!==void 0)return"given";if(computed.changed.includes(rootNode))return"changed";let bumped=computed.plan.packageCauses.get(rootNode);if(bumped!==void 0)return bumped;let setting=computed.plan.settingCauses.get(rootNode);if(setting!==void 0)return setting;if(computed.barrelNames.includes(rootNode))return"barrel name moved";for(let{narrower,result}of computed.narrowed)if("seeds"in result&&result.seeds.includes(rootNode))return`seeded by the ${narrower.name} narrower`;return"changed"}function walks(computed,{name,types},from){let{plan,graph}=computed;if(from!==void 0)return[{seeds:[from],opaque:void 0,types}];let{quiet,layout}=plan,narrowings=plan.narrowings.get(name);if(!narrowings)return[{seeds:plan.seeds,quiet,layout,opaque:void 0,types}];let matched=new Set(narrowings.flatMap((narrowing)=>narrowing.matched));return[{seeds:plan.seeds.filter((seed)=>!matched.has(seed)),quiet,layout,opaque:void 0,types},...narrowings.map((narrowing)=>({seeds:[...narrowing.matched,...narrowing.seeds].filter((seed)=>graph.has(seed)||computed.changed.includes(seed)),opaque:narrowing.narrower.opaque,layout,types}))]}function shortestChain(computed,candidates,test){for(let{seeds,...options}of candidates){let parents=new Map;if(!affectedBy(computed.graph,seeds,{...options,parents}).has(test))continue;let edges=[],node=test;for(let via=parents.get(node);via;via=parents.get(node))if(edges.push([node,via]),node=via.from,via.kind==="unknown")break;return{edges,root:node}}return}function reachers(computed,candidates,test,except){let found=new Set,unseen=(seed)=>seed!==except&&!found.has(seed);for(let{seeds,quiet=[],...options}of candidates){for(let seed of seeds.filter(unseen))if(affectedBy(computed.graph,[seed],options).has(test))found.add(seed);for(let seed of quiet.filter(unseen))if(affectedBy(computed.graph,[],{...options,quiet:[seed]}).has(test))found.add(seed)}return sorted(found)}async function chainOf(context,{edges,root},from){let last=edges.at(-1),[links,causes]=await Promise.all([Promise.all(edges.map(async([node,via])=>({node,kind:via.kind,...await edgeAt(context,node,via)}))),last?.[1].kind==="unknown"?causesOf(context.root,context.computed,last[0]):[]]);return{links,root,cause:rootCause(context.computed,root,from),unknown:causes.map((cause)=>({...cause,fix:fixFor(cause.cause)}))}}function unselected(config,computed,suite,from){let changed=computed.changed.length;if(from===void 0)return{kind:"unselected",suite,changed};let reachedBy=walksByTypes(computed.graph,[from],{includeUnknown:!1}),reaches={},example;for(let{name,isTest,types}of config.suites){let tests=sorted(reachedBy(types)).filter((node)=>isTest(node));if(tests.length===0)continue;if(reaches[name]=tests.length,name===suite||example===void 0)example=tests[0]}return{kind:"unselected",suite,from,changed,reaches,...example!==void 0&&{example}}}async function explain(root,config,computed,test,from,{all=!1}={}){let suite=config.suites.find((candidate)=>candidate.isTest(test));if(!suite)throw Error(`bivium why: ${test} is no suite's test`);if(!computed.graph.has(test))throw Error(`bivium why: no file ${test}`);if(from===void 0&&computed.plan.full.includes(suite.name))return{kind:"full",suite:suite.name,reasons:computed.plan.reasons};let candidates=walks(computed,suite,from),found=shortestChain(computed,candidates,test);if(!found)return unselected(config,computed,suite.name,from);let context={root,config,computed,resolve:createResolver({files:new Set(computed.graph.keys()),config,packages:computed.packages,tsconfigs:computed.tsconfigs})},everything=found.edges.at(-1)?.[1].kind==="unknown",more=from!==void 0||everything?[]:reachers(computed,candidates,test,found.root),[chain,others]=await Promise.all([chainOf(context,found,from),Promise.all((all?more:[]).map((seed)=>{let alone=candidates.map((walk)=>({...walk,seeds:walk.seeds.filter((candidate)=>candidate===seed),quiet:walk.quiet?.filter((candidate)=>candidate===seed)})),other=shortestChain(computed,alone,test);return other&&chainOf(context,other,void 0)}))]);return{kind:"chain",suite:suite.name,test,...chain,more,others:others.filter((other)=>other!==void 0)}}var FORMATS=["tree","chain","source"];function isFormat(value){return FORMATS.some((format)=>format===value)}var VERBS={import:"imported by",type:"type-imported by",setup:"a setup file of",goto:"opened by",html:"loaded by page",name:"imported by",glob:"globbed by","depends-on":"depended on by",edges:"an input of",reads:"read as text by",lists:"listed by",unknown:"depends on every change"},LIST=3;function nameOf(node){return node.slice(node.indexOf("#")+1)}function aligned(rows){let width=Math.max(0,...rows.filter(([,at])=>at!==void 0).map(([text])=>text.length));return rows.map(([text,at])=>at===void 0?text:`${text.padEnd(width)} ${at}`)}function tree(test,chain){let rows=[[test,void 0]],width=Math.max(0,...chain.links.filter((link)=>link.kind!=="unknown").map((link)=>link.kind.length)),indent="";for(let[i,link]of chain.links.entries()){let next=chain.links[i+1]?.node??chain.root;if(link.kind==="unknown"){rows.push([`${indent}└─ depends on every change:`,void 0]);for(let{cause,at}of chain.unknown)rows.push([`${indent} ✗ ${cause}`,at]);indent+=" ",rows.push([`${indent}└─ ${next}`,void 0]),indent+=" ";break}rows.push([`${indent}└─ ${link.kind.padEnd(width)} ${next}`,link.at]),indent+=" "}return rows.push([`${indent}● ${chain.cause}`,void 0]),aligned(rows)}function verbOf(link){return link.kind==="export"?`exported as ${nameOf(link.node)}`:VERBS[link.kind]}function whereOf(link){let configured=CONFIGURED[link.kind];if(configured!==void 0)return`${link.node} (${configured})`;return link.at??link.node}function steps(links){let rows=[...links].reverse().map((link)=>[verbOf(link),whereOf(link)]),width=Math.max(0,...rows.map(([verb])=>verb.length));return rows.map(([verb,where],i)=>`${verb.padEnd(width)} ${where}${i===rows.length-1?" ← selected":""}`)}function header({root,cause}){if(cause==="changed")return`${root} changed`;if(cause==="given")return`if ${root} changes`;return`${root}: ${cause}`}function chained(test,chain){let unknownAt=chain.links.findIndex((link)=>link.kind==="unknown");if(unknownAt===-1)return[header(chain),...steps(chain.links).map((step)=>` ${step}`)];let node=chain.links[unknownAt].node,where=chain.unknown.map(({at})=>at??node),width=Math.max(0,...where.map((at)=>at.length)),lines=[`${test} runs on every change`];for(let[i,{cause,fix}]of chain.unknown.entries())lines.push(` because ${where[i].padEnd(width)} ${cause}`,` fix: ${fix}`);if(unknownAt>0)lines.push(` reached via ${node}`,...steps(chain.links.slice(0,unknownAt)).map((step)=>` ${step}`));return lines}var LINE_NUMBER=/:(\d+)$/;function lineNumber(at){return at===void 0?void 0:LINE_NUMBER.exec(at)?.[1]}function sourced(test,chain){let unknownAt=chain.links.findIndex((link)=>link.kind==="unknown"),hops=unknownAt===-1?chain.links:chain.links.slice(0,unknownAt),numbers=[...chain.links,...chain.unknown].map(({at})=>lineNumber(at)),width=Math.max(0,...numbers.map((n)=>n?.length??0)),gutter=" ".repeat(width),cited=(at,text)=>{let n=lineNumber(at);return n===void 0||text===void 0?[]:[`${n.padStart(width)} | ${text}`]},count=plural(hops.length,"hop","hops"),lines=unknownAt===-1?[`selected: ${test} ← ${chain.root} (${count}${chain.cause==="changed"?"":`, ${chain.cause}`})`]:[`selected: ${test} ← every change (${unknownAt===0?"its dependencies can't be read":`${count} to ${chain.links[unknownAt].node}, whose dependencies can't be read`})`];lines.push("");for(let link of hops){let configured=CONFIGURED[link.kind],where=configured===void 0?link.at??link.node:link.node,kind=configured??link.kind;lines.push(`${gutter}--> ${where} ${kind}`,...cited(link.at,link.text))}if(unknownAt===-1)return lines.push(`${gutter}● ${chain.root}: ${chain.cause}`),lines;let node=chain.links[unknownAt].node;for(let{cause,at,text,fix}of chain.unknown)lines.push(`${gutter}✗ ${at??node} ${cause}`,...cited(at,text),`${gutter} = fix: ${fix}`);return lines}var RENDER={tree,chain:chained,source:sourced};function moreLine(more,all){let shown=more.slice(0,LIST).join(", "),rest=more.length>LIST?", …":"";return`+ ${plural(more.length,"more change reaches","more changes reach")} this test: ${shown}${rest}${all?"":" (--all shows each chain)"}`}function unselectedMessage(explanation){let{from,changed,reaches,example}=explanation;if(from===void 0)return changed===0?"Not selected: nothing changed.":`Not selected: ${changed===1?"the changed file doesn't reach":`none of the ${changed} changed files reaches`} it.`;let counts=Object.entries(reaches??{}).map(([suite,count])=>`${count} ${suite}`),total=Object.values(reaches??{}).reduce((a,b)=>a+b,0);return[`Not selected by a change to ${from}: no chain reaches it.`,total===0?"Its chains reach no test.":`Its chains reach ${plural(total,"test","tests")} (${counts.join(", ")}), such as ${example}.`].join(`
|
|
16
|
-
`)}function formatExplanation(explanation,format="tree"){if(explanation.kind==="full")return[`The ${explanation.suite} suite runs in full:`,...explanation.reasons.map((reason)=>` ${reason}`)].join(`
|
|
17
|
-
`);if(explanation.kind==="unselected")return unselectedMessage(explanation);let{test,more,others}=explanation,render=RENDER[format],lines=render(test,explanation);if(more.length>0)lines.push(moreLine(more,others.length>0));for(let other of others)lines.push("",...render(test,other));return lines.join(`
|
|
18
|
-
`)}var USAGE=`Usage:
|
|
19
|
-
bivium plan [base] [--json] [--github] print the tests a change can affect
|
|
20
|
-
bivium run [base] [--suite <name>] run a suite's selected tests
|
|
21
|
-
bivium why <test> [file] [--base <ref>] the chain from a change (or file) to a test
|
|
22
|
-
[--format <f>] [--all] [--json]
|
|
23
|
-
bivium check [--max-unknown <n>] [--json]
|
|
24
|
-
what the graph can't read, and dead globs
|
|
25
|
-
bivium graph [--suite <name>] [--top <n>] [--json]
|
|
26
|
-
each file's test fan-in, and the graph
|
|
27
|
-
bivium --version print the version
|
|
28
|
-
bivium --help print this
|
|
29
|
-
|
|
30
|
-
base defaults to the config's base, else the upstream default branch.
|
|
31
|
-
Options go before or after the command.
|
|
32
|
-
|
|
33
|
-
Options:
|
|
34
|
-
--config <file> config file (default: bivium.config.{ts,mts,mjs,js,json})
|
|
35
|
-
--cwd <dir> repository (default: the current directory)
|
|
36
|
-
--no-cache read every file; don't read or write the extraction cache
|
|
37
|
-
--suite <name> for run: the suite (default: the first one); for graph:
|
|
38
|
-
only this suite (default: every one)
|
|
39
|
-
--json for plan, why, check and graph: print JSON
|
|
40
|
-
--github for plan: also write each suite's selection to
|
|
41
|
-
$GITHUB_OUTPUT as <output>=all|none|<files>
|
|
42
|
-
--base <ref> for why and check: the base ref
|
|
43
|
-
--format <f> for why: tree (default), chain (from the change to the
|
|
44
|
-
test), source (each hop's line of source) or json
|
|
45
|
-
--all for why: every change's chain to the test, not only the
|
|
46
|
-
shortest
|
|
47
|
-
--max-unknown <n> for check: fail when more unknown nodes than this reach
|
|
48
|
-
a test
|
|
49
|
-
--top <n> for graph: how many files to list per suite (default: 10)
|
|
50
|
-
|
|
51
|
-
Exit status: 0 done; 1 check found problems; 2 a usage or configuration
|
|
52
|
-
error. run exits with its command's status.
|
|
53
|
-
|
|
54
|
-
Examples:
|
|
55
|
-
bivium plan origin/main --json
|
|
56
|
-
bivium why tests/Button.test.ts src/Button.svelte --format chain
|
|
57
|
-
bivium check --json`,WHITESPACE=/\s+/,VALUED=new Set(["--config","--cwd","--suite","--base","--format","--max-unknown","--top"]),COMMON=["--config","--cwd","--no-cache"],FLAGS={plan:[...COMMON,"--json","--github"],run:[...COMMON,"--suite"],why:[...COMMON,"--base","--json","--format","--all"],check:[...COMMON,"--base","--max-unknown","--json"],graph:[...COMMON,"--suite","--top","--json"]},POSITIONAL={plan:1,run:1,why:2,check:0,graph:0};function parseArgs(command,argv){let known=FLAGS[command]??[],flags=new Map,positional=[];for(let i=0;i<argv.length;i++){let arg=argv[i];if(!arg.startsWith("--")){positional.push(arg);continue}if(!known.includes(arg))throw Error(`bivium ${command}: unknown option ${arg}`);if(!VALUED.has(arg)){flags.set(arg,"");continue}let value=argv[++i];if(value===void 0||value.startsWith("--"))throw Error(`bivium: ${arg} needs a value`);flags.set(arg,value)}if(positional.length>(POSITIONAL[command]??0))throw Error(`bivium ${command}: unexpected ${positional.at(-1)}`);return{flags,positional}}function commandFor(run,files){let words=run.split(WHITESPACE).filter(Boolean),at=words.indexOf("{files}");if(at===-1)return[...words,...files];return[...words.slice(0,at),...files,...words.slice(at+1)]}function logSelection(label,selection,total,forced){let files=total===1?"file":"files",count;if(selection.mode==="some")count=`${selection.files.length} of ${total} ${files}`;else if(selection.mode==="none")count="none";else if(forced)count="all (full run)";else count=`all ${total} ${files} (each reaches a change)`;if(console.log(`${label}: ${count}`),selection.mode==="some")for(let file of selection.files)console.log(` ${file}`)}function logPlan({plan,narrowed}){for(let reason of plan.reasons)console.log(`Full run: ${reason}`);for(let line of plan.packages)console.log(line);for(let line of plan.settings)console.log(line);for(let{narrower,result}of narrowed)if("note"in result&&result.note)console.log(`${narrower.name}: ${result.note}`);for(let[name,selection]of Object.entries(plan.suites)){let total=plan.totals[name]??0;logSelection(`${name} tests`,selection,total,plan.full.includes(name))}}function writeOutputs(config,{plan}){let output=process.env.GITHUB_OUTPUT;if(!output)throw Error("bivium: GITHUB_OUTPUT is not set");let lines=config.suites.map((suite)=>`${suite.output}=${formatSelection(plan.suites[suite.name])}
|
|
58
|
-
`);appendFileSync(output,lines.join(""))}async function inspect(command,{flags,positional}){let format=flags.get("--format")??"tree";if(format!=="json"&&!isFormat(format))throw Error("bivium why: --format takes tree, chain, source or json");let{root,base,config}=await prepare({cwd:flags.get("--cwd"),base:flags.get("--base")??(command==="check"?"HEAD":void 0),configFile:flags.get("--config")}),computed=await computePlan(root,base,config,{...flags.has("--no-cache")&&{cache:!1}});if(command==="check"){let maxFlag=flags.get("--max-unknown"),max=maxFlag===void 0?void 0:Number(maxFlag);if(max!==void 0&&!Number.isInteger(max))throw Error("bivium check: --max-unknown takes a whole number");let report=await check(root,config,computed);return console.log(flags.has("--json")?JSON.stringify(report,null,2):formatReport(report,max)),failed(report,max)?1:0}let[test,file]=positional;if(test===void 0)throw Error("bivium why: which test?");let explanation=await explain(root,config,computed,test,file,{all:flags.has("--all")});return console.log(flags.has("--json")||format==="json"?JSON.stringify(explanation,null,2):formatExplanation(explanation,format)),0}async function graphCommand({flags}){let top=Number(flags.get("--top")??"10");if(!Number.isInteger(top)||top<0)throw Error("bivium graph: --top takes a whole number");let{root,base,config}=await prepare({cwd:flags.get("--cwd"),base:"HEAD",configFile:flags.get("--config")}),name=flags.get("--suite"),suites=name===void 0?config.suites:config.suites.filter((suite)=>suite.name===name);if(suites.length===0)throw Error(`bivium: no suite "${name}"`);let{graph}=await computePlan(root,base,config,{...flags.has("--no-cache")&&{cache:!1}}),report=graphReport(graph,suites);return console.log(flags.has("--json")?JSON.stringify(report,null,2):formatGraph(report,top)),0}async function runCommand(command,{flags,positional}){let{root,base,config}=await prepare({cwd:flags.get("--cwd"),base:positional[0],configFile:flags.get("--config")}),suiteName=flags.get("--suite"),suite=suiteName===void 0?config.suites[0]:config.suites.find((candidate)=>candidate.name===suiteName);if(!suite)throw Error(`bivium: no suite "${suiteName}"`);let computed=await computePlan(root,base,config,{...flags.has("--no-cache")&&{cache:!1},...command==="run"&&{suites:[suite.name]},mergeBase:command==="plan"&&flags.has("--json")});if(command==="plan"){if(flags.has("--json")){let{suites,reasons,causes,totals,packages}=computed.plan,narrowed=computed.narrowed.map((ran)=>({name:ran.narrower.name,result:ran.result}));console.log(JSON.stringify({base,mergeBase:await computed.mergeBase(),changed:computed.changed,suites,reasons,causes,totals,packages,narrowed},null,2))}else logPlan(computed);if(flags.has("--github"))writeOutputs(config,computed);return 0}if(logPlan(computed),!suite.run)throw Error(`bivium: suite "${suite.name}" has no run command`);let selection=computed.plan.suites[suite.name];if(selection.mode==="none")return console.log(`No ${suite.name} tests affected against ${base}; skipping.`),0;let[program,...args]=commandFor(suite.run,selection.mode==="some"?selection.files:[]);return spawnSync(program,args,{cwd:root,stdio:"inherit"}).status??1}function commandAt(argv){for(let i=0;i<argv.length;i++){let arg=argv[i];if(!arg.startsWith("-"))return i;if(VALUED.has(arg))i++}return-1}async function main(argv){if(argv.includes("--help")||argv.includes("-h"))return console.log(USAGE),0;if(argv.includes("--version")||argv.includes("-v"))return console.log(version),0;let at=commandAt(argv),command=at===-1?void 0:argv[at];if(command==="help")return console.log(USAGE),0;if(command===void 0){let first=argv[0],why=first===void 0?"":`unknown option ${first}
|
|
59
|
-
|
|
60
|
-
`;return console.error(`bivium: ${why}${USAGE}`),2}if(!(command in FLAGS))return console.error(`bivium: unknown command "${command}"
|
|
61
|
-
|
|
62
|
-
${USAGE}`),2;let rest=[...argv.slice(0,at),...argv.slice(at+1)];try{let args=parseArgs(command,rest);if(command==="why"||command==="check")return await inspect(command,args);if(command==="graph")return await graphCommand(args);return await runCommand(command,args)}catch(error){return console.error(error instanceof Error?error.message:String(error)),2}}process.exitCode=await main(process.argv.slice(2));
|
package/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{defineConfig2,plan2}from"./shared-xrgq64gt.js";export{defineConfig2 as defineConfig,plan2 as plan};
|