bivium 0.3.2 → 0.4.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/CHANGELOG.md +51 -0
- package/README.md +31 -8
- package/cli.js +3 -3
- package/index.js +1 -1
- package/package.json +1 -1
- package/shared-nbrvkwk9.js +10 -0
- package/shared-8v4dra0r.js +0 -11
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,56 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0 — 2026-11-04
|
|
4
|
+
|
|
5
|
+
**Features**
|
|
6
|
+
|
|
7
|
+
- `bivium check` fails on a repository path a test spells in a string
|
|
8
|
+
that a change to wouldn't select it: a fixture directory it hands to
|
|
9
|
+
the code under test, or a script a `hermetic` test spawns. Each comes
|
|
10
|
+
with the `reads`, `edges` or annotation that declares it. A path whose
|
|
11
|
+
change runs the suite anyway (`wiring`, `self`, the orphan rule)
|
|
12
|
+
doesn't fail, and an unreached file's fix names where it's spelled.
|
|
13
|
+
`check --json` has them as `undeclaredPaths`. On
|
|
14
|
+
carbon-preprocess-svelte it found the CLI a hermetic test spawns.
|
|
15
|
+
- A lockfile change to bivium itself is inert: no test runs it, so a
|
|
16
|
+
bump changes which tests later plans pick, not what any test does. It
|
|
17
|
+
selects only the tests that import bivium, where it ran everything
|
|
18
|
+
because no test imports it. On carbon-components-svelte a bivium bump
|
|
19
|
+
ran all 704 unit tests and every e2e test; it now runs the 2 that
|
|
20
|
+
import its CSS narrower.
|
|
21
|
+
|
|
22
|
+
**Fixes**
|
|
23
|
+
|
|
24
|
+
- `check` spells out each fix at the first node it's for and points back
|
|
25
|
+
to it after (`fix: as for test/u.test.js`), so a report of many alike
|
|
26
|
+
nodes isn't one sentence repeated.
|
|
27
|
+
- The note for a `tsconfig.json` or `package.json` change that leaves
|
|
28
|
+
resolution alone reads as a sentence:
|
|
29
|
+
`only version changed, so no file resolves or runs differently`.
|
|
30
|
+
|
|
31
|
+
## 0.3.3 — 2026-11-03
|
|
32
|
+
|
|
33
|
+
**Performance**
|
|
34
|
+
|
|
35
|
+
- 0.3.2 fetched a partial clone's merge-base reads in one batch, to save
|
|
36
|
+
round trips (#55). git already fetches reads made at once in parallel,
|
|
37
|
+
so it saved none, and its check for missing blobs ran first: the batch
|
|
38
|
+
is removed. A file unchanged since the merge base is still read from
|
|
39
|
+
the working tree, and each path once.
|
|
40
|
+
|
|
41
|
+
**Fixes**
|
|
42
|
+
|
|
43
|
+
- A plan in a clone without the base branch, or without the history back
|
|
44
|
+
to where the branch forked from it, such as `actions/checkout`'s
|
|
45
|
+
default one-commit fetch, failed with `git diff … failed`. It now says
|
|
46
|
+
which is missing, and that a shallow clone needs `fetch-depth: 0`.
|
|
47
|
+
|
|
48
|
+
**Docs**
|
|
49
|
+
|
|
50
|
+
- The README's CI section explains the checkout a plan needs: history
|
|
51
|
+
back to the merge base, and when to add `filter: blob:none` (a large
|
|
52
|
+
history) or leave it off (a small one).
|
|
53
|
+
|
|
3
54
|
## 0.3.2 — 2026-11-03
|
|
4
55
|
|
|
5
56
|
**Performance**
|
package/README.md
CHANGED
|
@@ -86,10 +86,10 @@ A file it can't lex cleanly is read by a regex extractor instead, which over-app
|
|
|
86
86
|
| `reads` | File glob → the files it reads as text, as with `@reads`: only a direct change to one counts, so their imports and unknowns don't spread to it. An `edges` or `reads` key that names one file (no wildcard) declares what it reads, as its own `@depends-on` or `@reads` would, so its disk reads aren't unknown. Values take `$1`… as in `edges`: `{ "tests/*.test.ts": "tests/__snapshots__/$1.test.ts.snap" }` |
|
|
87
87
|
| `self` | The selector's own files: a change to one runs everything. The config file is always one |
|
|
88
88
|
| `importOnly` | Files only an import reaches: deleting one never orphans a suite |
|
|
89
|
-
| `hermetic` | Files whose disk reads and non-literal imports reach no file of the repository: a library's `fs` calls on its caller's paths, a test that reads only the temporary files it writes. They add no unknown |
|
|
89
|
+
| `hermetic` | Files whose disk reads and non-literal imports reach no file of the repository: a library's `fs` calls on its caller's paths, a test that reads only the temporary files it writes. They add no unknown, and `check` still flags a repository path one spells that nothing declares |
|
|
90
90
|
| `barrels` | Modules that may bind named imports. Default: every module made only of re-exports |
|
|
91
91
|
| `external` | Packages a dependency installs that your code imports without declaring |
|
|
92
|
-
| `inert` | Packages no test uses except by importing them: linters, formatters, type packages (`["@biomejs/biome", "knip", "@types/*"]`). A [lockfile change](#lockfiles) that only they reach selects nothing. With `loadedByName` set, only packages with a `bin` need listing |
|
|
92
|
+
| `inert` | Packages no test uses except by importing them: linters, formatters, type packages (`["@biomejs/biome", "knip", "@types/*"]`). A [lockfile change](#lockfiles) that only they reach selects nothing. With `loadedByName` set, only packages with a `bin` need listing. bivium itself always is |
|
|
93
93
|
| `loadedByName` | Packages a test may load other than by an import: a test environment or a plugin a config names by string (`["jsdom", "ts-jest"]`). Setting it, even to `[]`, says every other package without a `bin` is loaded only by imports, so a [lockfile change](#lockfiles) that reaches one no test imports selects only its importers. A package with a `bin` always counts as one a test may run |
|
|
94
94
|
| `extensions` | Suffixes tried after a specifier |
|
|
95
95
|
| `deadGlobs` | Dead globs `check` allows, each `{ file, glob, reason }`, the glob as `file` spells it |
|
|
@@ -118,6 +118,8 @@ A file outside `roots` that isn't ignored runs everything: it's the backstop for
|
|
|
118
118
|
|
|
119
119
|
`bivium check` lists every file under a suite's `root` that no test reaches and the config doesn't exempt, with a fix for each by what it looks like: a test's snapshot, a runner's config, or anything else. It's the list to work through when adopting bivium, and a new entry is a gap someone just added.
|
|
120
120
|
|
|
121
|
+
A file's own disk reads make it unknown, but a test that hands a path to the code under test (`typecheck({ workspace: "tests/fixtures" })`), or a `hermetic` one that reads it, reads nothing the graph can see. So `check` also reads the string literals in each test, and in what the tests reach under a suite's `root`, for repository paths: relative to the root when they have a slash (`join(root, "tests/fixtures")`), and relative to the file (`new URL("fixtures", import.meta.url)`). It fails on one a change to which wouldn't select the tests that reach the file, with the `reads`, `edges` or annotation that declares it. A path whose change runs the suite anyway, as `wiring`, `self` or by the orphan rule, doesn't fail, and an unreached file's fix names where it's spelled. Strings inside brackets are skipped as data (`["src/a.ts", …]`, `map["key"]`), as are the directories a file is in and paths outside the graph. A path a test only names, such as an expected output, takes `// @lists <path>`.
|
|
122
|
+
|
|
121
123
|
## Recipes
|
|
122
124
|
|
|
123
125
|
**Vitest or Jest.** Name the setup files the runner loads, mirror `resolve.alias` (a Vite key like `"@/"` works as written), give snapshots to their tests, and, for a suite that runs code, skip type-only edges:
|
|
@@ -159,7 +161,7 @@ e2e: {
|
|
|
159
161
|
|
|
160
162
|
A dependency bump changes a lockfile, which no file imports. When a root `bun.lock`, `package-lock.json` (v2 or v3) or `pnpm-lock.yaml` (v6 or v9) changes, bivium diffs it against the merge base and seeds the walk with the `pkg:` nodes of the packages whose entries changed, and of every package that depends on one, so a `svelte` bump selects what imports `svelte`, or a package built on it. A `package.json` whose only change is to dependencies the lockfile records the same way counts as those packages changing.
|
|
161
163
|
|
|
162
|
-
A changed package can also be used in ways the graph can't see: a CLI a test spawns, a runner, a type package. So when a change reaches a package that a `package.json` declares, or that some file imports, and that no test imports, everything runs, with the reason (`bun.lock: playwright 1.63.0 → 1.64.0, and no test imports it`), unless the package is `inert
|
|
164
|
+
A changed package can also be used in ways the graph can't see: a CLI a test spawns, a runner, a type package. So when a change reaches a package that a `package.json` declares, or that some file imports, and that no test imports, everything runs, with the reason (`bun.lock: playwright 1.63.0 → 1.64.0, and no test imports it`), unless the package is `inert` (bivium itself always is: a bump changes which tests later plans pick, not what a test does). With `loadedByName` set, only a package with a `bin` in the lockfile, or one it lists, counts as used that way: a bump that reaches a library only a CMS config imports selects nothing. Everything also runs for a lockfile bivium can't parse, one whose settings other than its packages changed (`overrides`, patches, pnpm's `settings`, `catalogs`, or the version of pnpm itself), and a `package.json` change the lockfile doesn't record. Other lockfiles (`yarn.lock`, `bun.lockb`) are files like any other: outside the roots, a change to one runs everything.
|
|
163
165
|
|
|
164
166
|
```console
|
|
165
167
|
$ bunx bivium plan
|
|
@@ -185,7 +187,7 @@ unit tests: 4 of 12 files
|
|
|
185
187
|
| `bivium plan [base] [--json] [--github]` | Prints each suite's selection (`none`, the files out of how many, `all` files when each reaches a change, or `all (full run)`) and why a suite runs in full. `--json` adds the base, merge base, changed files, narrower results, changed packages, each suite's test count (`totals`), and the reasons as data (`causes`, each a `FullRunCause`: `{ kind, suites, file?, package?, narrower?, message }`). `--github` also writes each suite's selection to `$GITHUB_OUTPUT` |
|
|
186
188
|
| `bivium run [base] [--suite <name>]` | Runs the suite's `run` command with its selection (default: the first suite), or skips it when nothing is affected |
|
|
187
189
|
| `bivium why <test> [file] [--format tree\|chain\|source\|json] [--all]` | The shortest chain of edges from a changed file, or from `file`, to the test, with what spells each edge and the line it's on, and how many other changes reach the test. `--format tree` (the default) draws it from the test; `chain` reads from the change to the test; `source` prints each hop's line of source; `json` (or `--json`) prints the chain as data. `--all` shows every change's chain. For a test that isn't selected, it says what the file's chains reach instead |
|
|
188
|
-
| `bivium check [--max-unknown <n>] [--json]` | Counts what it found by cause first, then lists every node with unknown dependencies, with where and how to fix each cause, and fails when more than `n` of them reach a test, or on one `knownUnknowns` doesn't list. A node no test depends on is listed apart and not counted: plans only run tests, so it widens nothing. Also lists the files under a suite's `root` that no test reaches, each with a fix (a change to one runs the whole suite; see [A change no test reaches](#a-change-no-test-reaches)), `tsconfig.json` files that don't parse, and [dead globs](#dead-globs), and fails on one `deadGlobs` doesn't allow or on an entry that matches none. `--json` prints the report as data |
|
|
190
|
+
| `bivium check [--max-unknown <n>] [--json]` | Counts what it found by cause first, then lists every node with unknown dependencies, with where and how to fix each cause, and fails when more than `n` of them reach a test, or on one `knownUnknowns` doesn't list. A node no test depends on is listed apart and not counted: plans only run tests, so it widens nothing. Also lists the files under a suite's `root` that no test reaches, each with a fix (a change to one runs the whole suite; see [A change no test reaches](#a-change-no-test-reaches)), `tsconfig.json` files that don't parse, and [dead globs](#dead-globs), and fails on one `deadGlobs` doesn't allow or on an entry that matches none. Fails on a repository path a test spells that nothing declares (see [A change no test reaches](#a-change-no-test-reaches)). `--json` prints the report as data |
|
|
189
191
|
| `bivium graph [--suite <name>] [--top <n>] [--json]` | How many of each suite's tests a change to each file selects through the graph (leaving out the tests that run on any change, which it counts apart): the `n` files that reach the most, and how files spread from none to every test. A few hub files that reach most tests are what make plans wide. `--json` prints each suite's `total` and `everyChange` tests, and every node with its `imports` and `importers` (file edges), `fanIn` per suite and whether it's `unknown` |
|
|
190
192
|
|
|
191
193
|
`--config`, `--cwd` and `--no-cache` work with every command, before or after it, and `why` and `check` take `--base <ref>`. `--help` (or `-h`) prints usage. An unknown command, option or `--format` is an error. Exit status: 0 when done, 1 when `check` finds problems, 2 for a usage or configuration error; `run` exits with its command's status.
|
|
@@ -272,9 +274,7 @@ jobs:
|
|
|
272
274
|
steps:
|
|
273
275
|
- uses: actions/checkout@v7
|
|
274
276
|
with:
|
|
275
|
-
# History
|
|
276
|
-
# fetches the few a plan reads (a changed barrel or lockfile) in
|
|
277
|
-
# one round trip.
|
|
277
|
+
# History back to the merge base; see "The checkout" below.
|
|
278
278
|
fetch-depth: 0
|
|
279
279
|
filter: blob:none
|
|
280
280
|
- uses: oven-sh/setup-bun@v2
|
|
@@ -297,9 +297,32 @@ jobs:
|
|
|
297
297
|
- run: bunx vitest run ${{ needs.plan.outputs.unit != 'all' && needs.plan.outputs.unit || '' }}
|
|
298
298
|
```
|
|
299
299
|
|
|
300
|
+
### The checkout
|
|
301
|
+
|
|
302
|
+
A plan compares the branch with its merge base: the commit where it forked from the base branch. So the job needs the history back to that commit, not just the commit under test. `actions/checkout` fetches one commit by default (`fetch-depth: 1`), with no base branch, and the plan stops with what's missing:
|
|
303
|
+
|
|
304
|
+
```
|
|
305
|
+
bivium: origin/main and HEAD share no commit here, so there's no merge base to diff against. The clone is shallow: fetch the history (actions/checkout: `fetch-depth: 0`).
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
`fetch-depth: 0` fetches every commit. Only a job that plans needs it; one that runs every test anyway, such as a push to the default branch, can keep the default: `fetch-depth: ${{ github.event_name == 'pull_request' && '0' || '1' }}`.
|
|
309
|
+
|
|
310
|
+
The history git fetches is three kinds of object: commits, trees (each directory's file names, each with the ID of its content) and blobs (the contents). A plan needs the commits, to find the merge base, and the trees, to list what changed. Of the blobs it needs the working tree's, which the checkout has, and the merge base's version of a few changed files only: a lockfile, a `package.json`, a `tsconfig.json`, a barrel, and what a narrower reads. So pick the clone by how big the history is:
|
|
311
|
+
|
|
312
|
+
| History | Checkout | What a plan pays |
|
|
313
|
+
| :--- | :--- | :--- |
|
|
314
|
+
| Small: a full clone takes a second or two | `fetch-depth: 0` | Nothing more: every old version is already on disk |
|
|
315
|
+
| Large: years of commits, big files | `fetch-depth: 0` and `filter: blob:none` | A fetch from the remote for the old versions it reads, when a change needs any: about a second, sometimes several |
|
|
316
|
+
|
|
317
|
+
`filter: blob:none` makes a partial clone: every commit and tree, and only the blobs the checkout needs. Git fetches any other blob when something reads it, and fetches for reads made at once run in parallel. Without the filter, a large history's old contents are most of the download; with it, a small repository pays a round trip to the remote for contents it could have had for free.
|
|
318
|
+
|
|
319
|
+
### The cache
|
|
320
|
+
|
|
300
321
|
The cache holds what bivium extracted from each file, keyed by git blob, so a warm plan reads only the files a branch changed. Key it on the merge base: a pull request can restore caches from the default branch, whose run at that commit is the one to hit. Without `node_modules`, the cache lives in `.bivium/cache`; it writes a `.gitignore` so it never shows up as a change.
|
|
301
322
|
|
|
302
|
-
What a plan costs
|
|
323
|
+
### What a plan costs
|
|
324
|
+
|
|
325
|
+
Measured on an Apple M-series laptop under load (median of five, wall time):
|
|
303
326
|
|
|
304
327
|
| Repository | Files | Bun, no cache | Bun, warm | Node 24, no cache | Node 24, warm | Cache |
|
|
305
328
|
|:---|---:|---:|---:|---:|---:|---:|
|
package/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
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-
|
|
2
|
+
import{version,globToRegExp,inRoot,sorted,QUERY,UNDECLARED_READS,RELATIVE,aliasPath,createResolver,SCANNED,formatOf,extract,stringsOf,finish,gotoPage,walksByTypes,importersOf,affectedBy,formatSelection,orphanOf,plural,computePlan,prepare}from"./shared-nbrvkwk9.js";import{spawnSync}from"node:child_process";import{appendFileSync}from"node:fs";import{statSync}from"node:fs";import{join as join2,posix as posix2}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
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
4
|
`);i!==-1&&i<index;i=source.indexOf(`
|
|
5
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]!==`
|
|
@@ -9,10 +9,10 @@ import{version,globToRegExp,sorted,QUERY,UNDECLARED_READS,RELATIVE,aliasPath,cre
|
|
|
9
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
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
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(`
|
|
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)}})}import{posix}from"node:path";var PATH_LIKE=/^[\w@.+~()[\]-]+(?:\/[\w@.+~()[\]-]+)*$/,LETTER=/[a-z]/i,LEADING_SLASHES=/^\/+/,TRAILING_SLASHES=/\/+$/,DOT_RELATIVE=/^\.\.?\//;function candidates(file,text){let path=text.replace(TRAILING_SLASHES,""),rooted=path.startsWith("/");if(rooted)path=path.replace(LEADING_SLASHES,"");if(!PATH_LIKE.test(path)||!LETTER.test(path))return[];let dir=posix.dirname(file),found;if(rooted)found=path.includes("/")?[posix.normalize(path)]:[];else if(DOT_RELATIVE.test(path))found=[posix.join(dir,path)];else if(path.includes("/"))found=[posix.normalize(path),posix.join(dir,path)];else found=[posix.join(dir,path)];return found.filter((p)=>p!=="."&&!p.startsWith("../"))}function fixFor(file,path,dir){if(dir)return`if it reads them, add \`reads: { "${file}": "${path}/**" }\` (or \`// @reads ${path}/**\`), \`@depends-on\` if it runs them, \`@lists\` if it only names them`;if(SCANNED.test(path))return`if it runs it, add \`edges: { "${file}": "${path}" }\` (or \`// @depends-on ${path}\`), \`@reads\` if it reads it as text, \`@lists\` if it only names it`;return`if it reads it, add \`reads: { "${file}": "${path}" }\` (or \`// @reads ${path}\`), \`@lists\` if it only names it`}function spellers(config,{graph}){let found=new Map;for(let suite of config.suites){let reached=fanIn(graph,suite);for(let[node,deps]of graph){if(deps.unknown.length>0||!SCANNED.test(node))continue;if(node.startsWith("pkg:")||node.includes("#"))continue;if(suite.isTest(node)||(reached.get(node)??0)>0&&suite.roots.some((root)=>inRoot(node,root))){let suites=found.get(node);suites?suites.push(suite):found.set(node,[suite])}}}return new Map(sorted(found.keys()).map((node)=>[node,found.get(node)??[]]))}function runsAnyway(config,{graph},suites,targets){if(targets.some((file)=>config.isSelf(file)||suites.some((suite)=>suite.isWiring(file))))return"wiring";return targets.some((file)=>!config.isIgnored(file)&&suites.some((suite)=>orphanOf(graph,config,suite,file)))?"orphan":void 0}async function spelledPaths(root,config,computed){let{graph}=computed,files=new Set,dirs=new Map;for(let node of graph.keys()){if(node.startsWith("pkg:")||node.includes("#"))continue;files.add(node);for(let dir=posix.dirname(node);dir!==".";){let list=dirs.get(dir);list?list.push(node):dirs.set(dir,[node]),dir=posix.dirname(dir)}}let found={undeclared:[],orphaned:[]},spelling=spellers(config,computed),nodes=[...spelling.keys()],sources=await Promise.all(nodes.map((node)=>sourceOf(root,node)));for(let[i,node]of nodes.entries()){let source=sources[i],suites=spelling.get(node)??[],through=[...affectedBy(graph,[node],{includeUnknown:!1})].filter((path)=>suites.some((suite)=>suite.isTest(path)));if(source===void 0)continue;let seen=new Set;for(let text of stringsOf(formatOf(node),source)??[])for(let path of candidates(node,text)){if(seen.has(path)||path===node)continue;seen.add(path);let dir=!files.has(path);if(dir&&node.startsWith(`${path}/`))continue;let targets=dir?dirs.get(path):[path];if(!targets)continue;let selected=affectedBy(graph,targets);if(through.every((test)=>selected.has(test)))continue;let anyway=runsAnyway(config,computed,suites,targets);if(anyway==="wiring")continue;let line=specifierLine(source,text),entry={file:node,path,dir,fix:fixFor(node,path,dir)};if(line!==void 0)entry.at=`${node}:${line}`;found[anyway==="orphan"?"orphaned":"undeclared"].push(entry)}}return found}var EXAMPLES=3,TAGS={"depends-on":"@depends-on",reads:"@reads",lists:"@lists",glob:"import.meta.glob",edges:"edges",setup:"setup"},QUOTED=/"([^"]+)"/;function fixFor2(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)?posix2.join(posix2.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,spelled){let named=spelled.find(({path})=>file===path||file.startsWith(`${path}/`));if(named!==void 0)return`${named.at??named.file} names ${named.path}: ${named.fix}`;let name=posix2.basename(file),owner=tests.find((test)=>name.startsWith(`${posix2.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},spelled){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,spelled)})}}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)??fixFor2(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),spelled=await spelledPaths(root,config,computed),unreached=unreachedFiles(config,computed,[...spelled.undeclared,...spelled.orphaned]),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,undeclaredPaths:spelled.undeclared,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||report.undeclaredPaths.length>0}function pushUnknown(lines,{node,causes,tests,known},shown){lines.push(known===void 0?node:`${node} (known: ${known})`);for(let{cause,at,fix}of causes){let first=shown.get(fix);if(first===void 0)shown.set(fix,node);lines.push(` ✗ ${cause}${at?` ${at}`:""}`,` fix: ${first===void 0?fix:`as for ${first}`}`)}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.undeclaredPaths.length,"path spelled in code that nothing declares","paths spelled in code that nothing declares"],[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=posix2.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 pushUndeclared(lines,spelled){if(spelled.length===0)return;lines.push("","Paths spelled in code that nothing declares: a change there doesn't select the tests that reach the file:");let file;for(let{file:node,path,dir,at,fix}of spelled){if(node!==file)lines.push(` ${node}`);file=node,lines.push(` ✗ ${dir?`${path}/`:path}${at?` ${at}`:""}`,` fix: ${fix}`)}}function formatReport(report,max){let lines=summaryLines(report),widen=widening(report),shown=new Map;for(let unknown of widen)pushUnknown(lines,unknown,shown);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,shown)}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(pushUndeclared(lines,report.undeclaredPaths),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 undeclared=report.undeclaredPaths.length;if(undeclared>0)lines.push(`${plural(undeclared,"path","paths")} spelled in code that nothing declares.`);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
13
|
`).replace(BLANK_LINES,`
|
|
14
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(`
|
|
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:fixFor2(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
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
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
18
|
`)}var USAGE=`Usage:
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineConfig2,plan2}from"./shared-
|
|
1
|
+
import{defineConfig2,plan2}from"./shared-nbrvkwk9.js";export{defineConfig2 as defineConfig,plan2 as plan};
|
package/package.json
CHANGED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{readFile as readFile3,stat}from"node:fs/promises";import{join as join4,posix as posix6,resolve as resolve2}from"node:path";import{existsSync}from"node:fs";import{mkdir,readFile,rename,unlink,writeFile}from"node:fs/promises";import{isAbsolute,join}from"node:path";var version="0.4.0";var SCANNER_VERSION=6,MAGIC="bivium-extractions",FILE="extractions.json";function isHeader(value){return typeof value==="object"&&value!==null&&"magic"in value&&value.magic===MAGIC&&"bivium"in value&&value.bivium===version&&"scanner"in value&&value.scanner===SCANNER_VERSION&&"rows"in value&&typeof value.rows==="number"&&"strings"in value&&typeof value.strings==="number"}function cacheDir(root,cache){if(cache===!1)return;if(typeof cache==="string")return isAbsolute(cache)?cache:join(root,cache);let modules=join(root,"node_modules");return existsSync(modules)?join(modules,".cache","bivium"):join(root,".bivium","cache")}class ExtractionCache{#rows=new Map;#strings=[];#used=new Map;#dirty=!1;dir;constructor(dir){this.dir=dir}static async open(dir){let cache=new ExtractionCache(dir);if(!dir)return cache;let text=await readFile(join(dir,FILE),"utf-8").catch(()=>"");if(text)cache.#load(text);return cache}#load(text){try{let parsed=JSON.parse(text);if(!Array.isArray(parsed))return;let[header,strings,rows]=parsed;if(!isHeader(header)||!Array.isArray(strings)||!Array.isArray(rows)||header.strings!==strings.length||header.rows!==rows.length)return;this.#strings=strings;for(let row of rows)if(Array.isArray(row)&&typeof row[0]==="string")this.#rows.set(row[0],row)}catch{}}get size(){return this.#rows.size}get(oid,format){let key=`${format}:${oid}`,used=this.#used.get(key);if(used)return used;let row=this.#rows.get(key);if(!row)return;let extraction;try{extraction=decode(row,this.#strings)}catch{this.#rows.delete(key);return}return this.#used.set(key,extraction),extraction}set(oid,format,extraction){let key=`${format}:${oid}`;this.#used.set(key,extraction),this.#dirty=!0}async save(){if(!this.dir||!this.#dirty)return;let table=new Strings,rows=[];for(let[key,extraction]of this.#used)rows.push(encode(key,extraction,table));let stale=Math.floor(this.#used.size/2);for(let[key,row]of this.#rows){if(stale===0)break;if(this.#used.has(key))continue;try{rows.push(encode(key,decode(row,this.#strings),table)),stale--}catch{}}let header={magic:MAGIC,bivium:version,scanner:SCANNER_VERSION,rows:rows.length,strings:table.list.length},file=join(this.dir,FILE),temp=`${file}.${process.pid}.${Date.now()}.tmp`;try{await mkdir(this.dir,{recursive:!0});let ignore=join(this.dir,".gitignore");if(!existsSync(ignore))await writeFile(ignore,`*
|
|
2
|
+
`);await writeFile(temp,JSON.stringify([header,table.list,rows])),await rename(temp,file),this.#dirty=!1}catch{await unlink(temp).catch(()=>{return})}}}class Strings{list=[];#ids=new Map;id(value){let id=this.#ids.get(value);if(id===void 0)id=this.list.length,this.list.push(value),this.#ids.set(value,id);return id}ids(values){return values.length===0?0:values.map((value)=>this.id(value))}}function typeIndexes(imports){let indexes=[];for(let[i,ref]of imports.entries())if(ref.type)indexes.push(i);return indexes.length===0?0:indexes}function encode(key,e,table){let imports=e.imports.map(({specifier,names})=>names?[table.id(specifier),...names.map((n)=>table.id(n))]:table.id(specifier)),barrel=e.barrel&&[[...e.barrel.names].flatMap(([name,from])=>[table.id(name),table.id(from)]),table.ids(e.barrel.stars)];return[key,imports.length===0?0:imports,table.ids(e.globs),table.ids(e.gotos),table.ids(e.dependsOn),table.ids(e.reads),table.ids(e.unknown),e.fallback===void 0?0:table.id(e.fallback),barrel??0,typeIndexes(e.imports),table.ids(e.lists)]}function decode(row,strings){let str=(id)=>{let value=typeof id==="number"?strings[id]:void 0;if(typeof value!=="string")throw Error("bad string id");return value},list=(ids)=>{if(ids===0)return[];if(!Array.isArray(ids))throw Error("bad list");return ids.map(str)},refs=row[1]===0?[]:row[1];if(!Array.isArray(refs))throw Error("bad imports");let imports=refs.map((item)=>Array.isArray(item)?{specifier:str(item[0]),names:item.slice(1).map(str)}:{specifier:str(item)});if(row[9]!==0){if(!Array.isArray(row[9]))throw Error("bad types");for(let i of row[9]){let ref=typeof i==="number"?imports[i]:void 0;if(!ref)throw Error("bad type index");ref.type=!0}}let extraction={imports,globs:list(row[2]),gotos:list(row[3]),dependsOn:list(row[4]),reads:list(row[5]),lists:list(row[10]),unknown:list(row[6])};if(row[7]!==0)extraction.fallback=str(row[7]);if(row[8]!==0){if(!Array.isArray(row[8]))throw Error("bad barrel");let[pairs,stars]=row[8];if(!Array.isArray(pairs))throw Error("bad barrel names");let names=new Map;for(let i=0;i<pairs.length;i+=2)names.set(str(pairs[i]),str(pairs[i+1]));extraction.barrel={names,stars:list(stars)}}return extraction}import{existsSync as existsSync2,readFileSync}from"node:fs";import{isAbsolute as isAbsolute2,join as join2,relative,resolve}from"node:path";import{pathToFileURL}from"node:url";var GLOB_LITERAL=/[.+^$()|[\]\\]/g,REGEX_SPECIAL=/[.*+?^${}()|[\]\\]/g,DIGIT=/[0-9]/,CAPTURE_REFERENCE=/\$(\d+)/g;function compile(glob,{capture=!1,captures}={}){let source="",wildcards=0,group=(body)=>(wildcards++,capture?`(${body})`:body);for(let i=0;i<glob.length;i++){let char=glob[i];if(captures&&char==="$"&&DIGIT.test(glob[i+1]??"")){let end=i+1;while(DIGIT.test(glob[end]??""))end++;let text=captures[Number(glob.slice(i+1,end))-1];source+=text===void 0?".*":text.replace(REGEX_SPECIAL,"\\$&"),i=end-1}else if(char==="*"&&glob[i+1]==="*"){let slash=glob[i+2]==="/";source+=group(slash?"(?:.*/)?":".*"),i+=slash?2:1}else if(char==="*")source+=group("[^/]*");else if(char==="?")source+=group("[^/]");else if(char==="{")wildcards++,source+=capture?"(":"(?:";else if(char==="}")source+=")";else if(char===",")source+="|";else source+=char.replace(GLOB_LITERAL,"\\$&")}return{source:`^${source}$`,wildcards}}function globToRegExp(glob){return new RegExp(compile(glob).source)}function captureGlob(glob){let{source,wildcards}=compile(glob,{capture:!0});return{pattern:new RegExp(source),wildcards}}function captureReferences(glob){return[...glob.matchAll(CAPTURE_REFERENCE)].map((match)=>Number(match[1]))}function expandGlob(glob,captures){return new RegExp(compile(glob,{captures}).source)}function matcher(globs=[]){let list=typeof globs==="string"?[globs]:globs;if(list.length===0)return()=>!1;let res=list.map(globToRegExp);return(path)=>res.some((re)=>re.test(path))}function defineConfig2(config){return config}var DEFAULT_EXTENSIONS=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".d.ts",".svelte",".vue",".json"];function list(value,fallback){if(value===void 0)return[...fallback];return typeof value==="string"?[value]:[...value]}var LEADING_DOT_SLASH=/^\.\//,TRAILING_SLASHES=/\/+$/;function normalizeRoot(root){return root.replace(LEADING_DOT_SLASH,"").replace(TRAILING_SLASHES,"")||"."}function pathMaps(record={}){return Object.entries(record).map(([key,globs])=>{let{pattern,wildcards}=captureGlob(key),values=list(globs,[]),fixed=values.map((value)=>captureReferences(value).length===0?globToRegExp(value):void 0);return{key,exact:wildcards===0,pattern,values,targets:(path)=>{let match=pattern.exec(path);if(!match)return;let captures=match.slice(1);return values.map((value,i)=>fixed[i]??expandGlob(value,captures))}}})}function isInertOf(inert){let listed=matcher(inert);return(name)=>name==="bivium"||listed(name)}function resolveConfig(config){let names=Object.keys(config.suites);if(names.length===0)throw Error("bivium config: no suites");let suites=Object.entries(config.suites).map(([name,suite])=>({name,isTest:matcher(suite.tests),run:suite.run,roots:list(suite.root,["."]).map(normalizeRoot),urls:Object.entries(suite.urls??{}).map(([key,targets])=>({key,targets:list(targets,[])})),isPage:matcher(suite.pages),isWiring:matcher(suite.wiring),isSetup:matcher(suite.setup),setup:list(suite.setup,[]),isNonInput:matcher(suite.nonInputs),output:suite.output??`${name}-tests`,types:suite.types??!0})),narrowers=(config.narrowers??[]).map((narrower)=>{let unknown=narrower.suites?.find((name)=>!names.includes(name));if(unknown!==void 0)throw Error(`bivium config: narrower ${narrower.name} names no suite ${unknown}`);return{name:narrower.name,match:matcher(narrower.match),opaque:matcher(narrower.opaque),suites:[...narrower.suites??names],narrow:async(context)=>checkResult(await narrower.narrow(context))}});return{suites,narrowers,roots:list(config.roots,["."]).map(normalizeRoot),isIgnored:matcher(config.ignore),alias:Object.entries(config.alias??{}).map(([key,path])=>[key.replace(TRAILING_SLASHES,"")||key,normalizeRoot(path)]).sort(([a],[b])=>b.length-a.length),generated:pathMaps(config.edges),reads:pathMaps(config.reads),isSelf:matcher(config.self),isImportOnly:matcher(config.importOnly),isHermetic:matcher(config.hermetic),isBarrel:config.barrels?matcher(config.barrels):()=>!0,external:new Set(config.external),isInert:isInertOf(config.inert),...config.loadedByName!==void 0&&{isLoadedByName:matcher(config.loadedByName)},extensions:config.extensions??DEFAULT_EXTENSIONS,deadGlobs:config.deadGlobs??[],...config.knownUnknowns&&{knownUnknowns:config.knownUnknowns},base:config.base,cache:config.cache}}function inRoot(file,root){return root==="."||file===root||file.startsWith(`${root}/`)}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isStrings(value){return Array.isArray(value)&&value.every((item)=>typeof item==="string")}function isGlobs(value){return typeof value==="string"||isStrings(value)}function isStringRecord(value){return isRecord(value)&&Object.values(value).every((item)=>typeof item==="string")}function isGlobsRecord(value){return isRecord(value)&&Object.values(value).every(isGlobs)}function isBoolean(value){return typeof value==="boolean"}function isString(value){return typeof value==="string"}function isCache(value){return typeof value==="boolean"||typeof value==="string"}function field(record,key,is,path,expected){let value=record[key];if(value===void 0||is(value))return value;throw Error(`bivium config: ${path}${key} must be ${expected}`)}var SUITE_KEYS=new Set(["tests","run","root","urls","pages","wiring","setup","nonInputs","output","types"]),NARROWER_KEYS=new Set(["name","match","opaque","suites","narrow"]),DEAD_GLOB_KEYS=new Set(["file","glob","reason"]),KNOWN_UNKNOWN_KEYS=new Set(["file","reason"]),CONFIG_KEYS=new Set(["suites","narrowers","roots","ignore","alias","edges","reads","self","importOnly","hermetic","barrels","external","inert","loadedByName","extensions","deadGlobs","knownUnknowns","base","cache"]);function checkKeys(record,known,path){for(let key of Object.keys(record))if(!known.has(key))throw Error(`bivium config: unknown key ${path}${key}`)}function checkSuite(name,value){if(!isRecord(value))throw Error(`bivium config: suites.${name} must be an object`);let at=`suites.${name}.`;checkKeys(value,SUITE_KEYS,at);let tests=field(value,"tests",isGlobs,at,"a glob or a list of globs");if(tests===void 0||tests.length===0)throw Error(`bivium config: suite ${name} has no tests`);let globs="a glob or a list of globs";return{tests,run:field(value,"run",isString,at,"a command"),root:paths(value,"root",at),urls:field(value,"urls",isGlobsRecord,at,"a map of URL patterns"),pages:field(value,"pages",isGlobs,at,globs),wiring:field(value,"wiring",isGlobs,at,globs),setup:field(value,"setup",isGlobs,at,globs),nonInputs:field(value,"nonInputs",isGlobs,at,globs),output:field(value,"output",isString,at,"an output name"),types:field(value,"types",isBoolean,at,"a boolean")}}var WILDCARD=/[*?{}[\]]/;function paths(record,key,at){let value=field(record,key,isGlobs,at,"a path or a list of paths");for(let path of typeof value==="string"?[value]:value??[]){let wildcard=WILDCARD.exec(path);if(!wildcard)continue;let prefix=normalizeRoot(path.slice(0,wildcard.index));throw Error(`bivium config: ${at}${key} takes paths, not globs: "${path}" (the directory is "${prefix}")`)}return value}function isResult(value){if(!isRecord(value))return!1;if("all"in value)return typeof value.all==="string";return"seeds"in value&&isStrings(value.seeds)&&(!("note"in value)||typeof value.note==="string")}function checkResult(value){if(isResult(value))return value;throw Error("returned neither { seeds: string[] } nor { all: string }")}function checkNarrower(value,at){if(!isRecord(value))throw Error(`bivium config: ${at} must be an object`);checkKeys(value,NARROWER_KEYS,`${at}.`);let name=field(value,"name",isString,`${at}.`,"a string"),match=field(value,"match",isGlobs,`${at}.`,"globs"),opaque=field(value,"opaque",isGlobs,`${at}.`,"globs"),suites=field(value,"suites",isStrings,`${at}.`,"suite names"),{narrow}=value;if(name===void 0||match===void 0||opaque===void 0)throw Error(`bivium config: ${at} needs a name, match and opaque`);if(typeof narrow!=="function")throw Error(`bivium config: ${at}.narrow must be a function`);return{name,match,opaque,suites,narrow:async(context)=>{let result=await Reflect.apply(narrow,value,[context]);return checkResult(result)}}}function checkDeadGlob(value,at){if(!isRecord(value))throw Error(`bivium config: ${at} must be an object`);checkKeys(value,DEAD_GLOB_KEYS,`${at}.`);let file=field(value,"file",isString,`${at}.`,"a path"),glob=field(value,"glob",isString,`${at}.`,"a glob"),reason=field(value,"reason",isString,`${at}.`,"a string");if(!(file&&glob&&reason))throw Error(`bivium config: ${at} needs a file, glob and reason`);return{file,glob,reason}}function checkKnownUnknown(value,at){if(!isRecord(value))throw Error(`bivium config: ${at} must be an object`);checkKeys(value,KNOWN_UNKNOWN_KEYS,`${at}.`);let file=field(value,"file",isString,`${at}.`,"a path"),reason=field(value,"reason",isString,`${at}.`,"a string");if(!(file&&reason))throw Error(`bivium config: ${at} needs a file and reason`);return{file,reason}}function checkCaptures(name,record){for(let[key,globs]of Object.entries(record??{})){let{wildcards}=captureGlob(key);for(let value of list(globs,[])){let bad=captureReferences(value).find((n)=>n<1||n>wildcards);if(bad===void 0)continue;let has=`${wildcards} ${wildcards===1?"wildcard":"wildcards"}`,why=bad<1?"captures count from $1":`its key has ${has}`;throw Error(`bivium config: ${name}["${key}"] refers to $${bad} in ${value}, but ${why}`)}}}function checkConfig(value){if(!isRecord(value))throw Error("bivium config: not an object");if(!isRecord(value.suites))throw Error("bivium config: suites must be an object");checkKeys(value,CONFIG_KEYS,"");let{narrowers,deadGlobs,knownUnknowns}=value;if(narrowers!==void 0&&!Array.isArray(narrowers))throw Error("bivium config: narrowers must be a list");if(deadGlobs!==void 0&&!Array.isArray(deadGlobs))throw Error("bivium config: deadGlobs must be a list");if(knownUnknowns!==void 0&&!Array.isArray(knownUnknowns))throw Error("bivium config: knownUnknowns must be a list");let suites={};for(let[name,suite]of Object.entries(value.suites))suites[name]=checkSuite(name,suite);let globs="a glob or a list of globs",edges=field(value,"edges",isGlobsRecord,"","a map of globs"),reads=field(value,"reads",isGlobsRecord,"","a map of globs");return checkCaptures("edges",edges),checkCaptures("reads",reads),{suites,narrowers:narrowers?.map((narrower,i)=>checkNarrower(narrower,`narrowers[${i}]`)),roots:paths(value,"roots",""),ignore:field(value,"ignore",isGlobs,"",globs),alias:field(value,"alias",isStringRecord,"","a map of paths"),edges,reads,self:field(value,"self",isGlobs,"",globs),importOnly:field(value,"importOnly",isGlobs,"",globs),hermetic:field(value,"hermetic",isGlobs,"",globs),barrels:field(value,"barrels",isGlobs,"",globs),external:field(value,"external",isStrings,"","a list of packages"),inert:field(value,"inert",isGlobs,"",globs),loadedByName:field(value,"loadedByName",isGlobs,"",globs),extensions:field(value,"extensions",isStrings,"","a list"),deadGlobs:deadGlobs?.map((entry,i)=>checkDeadGlob(entry,`deadGlobs[${i}]`)),knownUnknowns:knownUnknowns?.map((entry,i)=>checkKnownUnknown(entry,`knownUnknowns[${i}]`)),base:field(value,"base",isString,"","a ref"),cache:field(value,"cache",isCache,"","a directory or a boolean")}}var CONFIG_FILES=["bivium.config.ts","bivium.config.mts","bivium.config.mjs","bivium.config.js","bivium.config.json"];async function readConfig(file){if(file.endsWith(".json"))return JSON.parse(readFileSync(file,"utf-8"));let module=await import(pathToFileURL(file).href);return isRecord(module)?module.default:void 0}async function loadConfig(root,path){let file=path===void 0?CONFIG_FILES.map((name)=>join2(root,name)).find((f)=>existsSync2(f)):resolve(process.cwd(),path);if(!file||!existsSync2(file))throw Error(`bivium: no config found${path?` at ${path}`:` in ${root}`}`);let inside=relative(root,file);return{config:resolveConfig(checkConfig(await readConfig(file))),file:inside.startsWith("..")||isAbsolute2(inside)?file:inside}}import{spawn}from"node:child_process";import{readFile as readFile2}from"node:fs/promises";import{join as join3}from"node:path";function byCodeUnit(a,b){if(a===b)return 0;return a<b?-1:1}function sorted(values){return[...values].sort(byCodeUnit)}function git(cwd,...args){return new Promise((resolve,reject)=>{let child=spawn("git",args,{cwd}),chunks=[];child.stdout.on("data",(chunk)=>chunks.push(chunk)),child.on("error",reject),child.on("close",(status)=>{resolve({status:status??1,stdout:Buffer.concat(chunks).toString("utf-8")})})})}async function gitOrThrow(cwd,...args){let result=await git(cwd,...args);if(result.status!==0)throw Error(`git ${args.join(" ")} failed`);return result.stdout}function lines(output){return output.split(`
|
|
3
|
+
`).filter(Boolean)}var INDEX_ENTRY=/^(\S) (\d{6}) ([0-9a-f]+) (\d)\t(.*)$/,RAW_ENTRY=/^:(\d{6}) \d{6} ([0-9a-f]+) [0-9a-f]+ ([A-Z])\d*\t(.*)$/;async function missingHistory(cwd,base){let[known,forked,shallow]=await Promise.all([git(cwd,"rev-parse","--verify","--quiet",`${base}^{commit}`),git(cwd,"merge-base",base,"HEAD"),git(cwd,"rev-parse","--is-shallow-repository")]),fix=shallow.stdout.trim()==="true"?" The clone is shallow: fetch the history (actions/checkout: `fetch-depth: 0`).":"";if(known.status!==0)return Error(`bivium: no commit ${base} here to diff against: fetch it.${fix}`);if(forked.status!==0)return Error(`bivium: ${base} and HEAD share no commit here, so there's no merge base to diff against.${fix}`);return}function mergeBaseOf(cwd,base){let pending;return()=>{if(pending===void 0)pending=gitOrThrow(cwd,"merge-base",base,"HEAD").then((out)=>out.trim()),pending.catch(()=>{return});return pending}}async function readRevision(cwd,base,roots,{blobs=!1,mergeBase:eager=!1}={}){let mergeBase=mergeBaseOf(cwd,base);if(eager)mergeBase();let diffArgs=["--no-renames","--merge-base",base],[listing,diff,staged]=await Promise.all([gitOrThrow(cwd,"ls-files","-s","-v","-o","--exclude-standard"),gitOrThrow(cwd,"diff","--raw","--no-abbrev",...diffArgs),gitOrThrow(cwd,"diff","--cached","--name-only",...diffArgs)]).catch(async(error)=>{throw await missingHistory(cwd,base)??error}),entries=lines(listing),untracked=[];for(let line of entries)if(line.startsWith("? "))untracked.push(line.slice(2));let before=new Map,diffed=[],layout=new Set(untracked);for(let line of lines(diff)){let entry=RAW_ENTRY.exec(line);if(!entry)throw Error(`git diff: unexpected line ${line}`);let[,mode,oid,status,path]=entry;if(diffed.push(path),status==="A"||status==="D")layout.add(path);if(status==="A")before.set(path,void 0);else if("MTD".includes(status)&&mode!=="160000")before.set(path,oid)}let reads=new Map,readBase=(path)=>{let read=reads.get(path);if(read===void 0)read=readBaseOnce(path),reads.set(path,read);return read},readBaseOnce=(path)=>{if(!before.has(path)){if(present.has(path))return readFile2(join3(cwd,path),"utf-8").catch(()=>mergeBase().then((commit)=>show(cwd,`${commit}:${path}`)));return mergeBase().then((commit)=>show(cwd,`${commit}:${path}`))}let oid=before.get(path);return oid===void 0?Promise.resolve(void 0):show(cwd,oid)},changed=[...new Set([...diffed,...untracked])],dirty=new Set([...changed,...lines(staged)]),underRoots=(path)=>roots.some((root)=>inRoot(path,root)),files=new Set,tracked=new Set,present=new Set,oids=new Map;for(let line of entries){let entry=INDEX_ENTRY.exec(line);if(!entry){if(line.startsWith("? ")&&underRoots(line.slice(2)))files.add(line.slice(2));continue}let[,tag,mode,oid,stage,path]=entry;if(tracked.add(path),mode==="160000"||!underRoots(path))continue;if(files.add(path),dirty.has(path)||stage!=="0"||tag!=="H")continue;if(mode!=="100644"&&mode!=="100755")continue;if(present.add(path),blobs)oids.set(path,oid)}return{files:sorted(files),listed:[...tracked,...untracked],changed,layout,mergeBase,readBase,blobs:oids,present}}async function show(cwd,object){let result=await git(cwd,"show",object);return result.status===0?result.stdout:void 0}async function defaultBase(cwd){let head=await git(cwd,"symbolic-ref","--short","refs/remotes/origin/HEAD");if(head.status===0&&head.stdout.trim())return head.stdout.trim();let refs=["origin/main","origin/master","main","master"],found=await Promise.all(refs.map((ref)=>git(cwd,"rev-parse","--verify","--quiet",ref))),branch=refs.find((_,i)=>found[i].status===0);if(branch)return branch;throw Error("bivium: no base given and no default branch found")}var COMMENTS=/\/\/.*$|\/\*[\s\S]*?\*\//gm,AS=/\s+as\s+/,TYPE_PREFIX=/^type\s+/,NAMED_EXPORT=/export\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']\s*;?/g,STAR_EXPORT=/export\s+(?:type\s+)?\*(?:\s+as\s+([\w$]+))?\s+from\s*["']([^"']+)["']\s*;?/g,BARREL_FILE=/\.[cm]?[jt]sx?$/,ONLY_SEPARATORS=/^[\s;]*$/,STARTS_WITH_EXPORT=/^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*export\b/;function parseBarrel(path,source){return BARREL_FILE.test(path)?parseReExports(source):void 0}function parseReExports(source){if(!STARTS_WITH_EXPORT.test(source))return;let code=source.replace(COMMENTS,""),barrel={names:new Map,stars:[]},rest=code.replace(NAMED_EXPORT,(_,list,from)=>{for(let part of list.split(",")){let name=part.trim().replace(TYPE_PREFIX,"").split(AS).pop();if(name)barrel.names.set(name,from)}return""});if(rest=rest.replace(STAR_EXPORT,(_,name,from)=>{if(name)barrel.names.set(name,from);else barrel.stars.push(from);return""}),barrel.names.size+barrel.stars.length===0)return;return ONLY_SEPARATORS.test(rest)?barrel:void 0}import{builtinModules}from"node:module";import{posix}from"node:path";var QUERY=/[?#].*$/,UNDECLARED_READS="reads the disk without @depends-on",RELATIVE=/^\.\.?(?:\/|$)/,URL_REF=/^[a-z]+:|^\/\//,LIST_SEPARATOR=/[\s,]+(?![^{]*\})/,DEPENDS_ON=/^\s*(?:\/\/|\/?\*+)\s*@depends-on\s+(.+?)\s*(?:\*\/)?\s*$/gm,READS=/^\s*(?:\/\/|\/?\*+)\s*@reads\s+(.+?)\s*(?:\*\/)?\s*$/gm,LISTS=/^\s*(?:\/\/|\/?\*+)\s*@lists\s+(.+?)\s*(?:\*\/)?\s*$/gm,GLOB_REGISTRY=/^\s*(?:\/\/|\/?\*+)\s*@glob-registry\b/m,AS2=/\s+as\s+/,TYPE_PREFIX2=/^type\s+/,NAMED_CLAUSE=/\{([^}]*)\}/,DEFAULT_OR_NAMESPACE=/^\s*[\w$*]/;function namedBindings(clause){let named=NAMED_CLAUSE.exec(clause);if(!named||DEFAULT_OR_NAMESPACE.test(clause.replace(NAMED_CLAUSE,"")))return;return named[1].split(",").map((part)=>part.trim().replace(TYPE_PREFIX2,"").split(AS2)[0].trim()).filter(Boolean)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isStringRecord2(value){return isRecord2(value)&&Object.values(value).every((item)=>typeof item==="string")}function toPackageJson(value){if(!isRecord2(value))return{};let json={};if(typeof value.name==="string")json.name=value.name;if(value.exports!==void 0)json.exports=value.exports;if(isRecord2(value.imports))json.imports=value.imports;if(typeof value.main==="string")json.main=value.main;let{sideEffects}=value;if(typeof sideEffects==="boolean"||Array.isArray(sideEffects)&&sideEffects.every((glob)=>typeof glob==="string"))json.sideEffects=sideEffects;for(let field of DEP_FIELDS){let deps=value[field];if(isStringRecord2(deps))json[field]=deps}return json}var BUILTINS=new Set(builtinModules),RUNTIME_BUILTIN=/^(?:node:|bun(?:$|:))/,JS_EXTENSION=/\.(?:js|jsx|mjs|cjs)$/,TS_SOURCES={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]},NODE_PREFIX=/^node:/,INVALID_IMPORT_TARGET=/^[./#]/,SVELTEKIT_ASSETS="./%sveltekit.assets%/",INDEX="/index",SVELTE_CONFIGS=["js","mjs","cjs","ts","mts"].map((ext)=>`svelte.config.${ext}`),DEP_FIELDS=["dependencies","devDependencies","peerDependencies","optionalDependencies"];function packageName(specifier){let parts=specifier.split("/");return specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0]}function builtin(specifier){if(RUNTIME_BUILTIN.test(specifier)){let name=specifier.replace(NODE_PREFIX,"");return specifier.startsWith("bun")?specifier:`node:${name.split("/")[0]}`}let name=specifier.split("/")[0];return BUILTINS.has(specifier)||BUILTINS.has(name)?`node:${name}`:void 0}function targets(value,out=[]){if(typeof value==="string")out.push(value);else if(Array.isArray(value))for(let item of value)targets(item,out);else if(value&&typeof value==="object")for(let item of Object.values(value))targets(item,out);return out}function subpathMap(exports){if(typeof exports==="string"||Array.isArray(exports))return{".":exports};if(!isRecord2(exports))return;return Object.keys(exports).some((key)=>key.startsWith("."))?exports:{".":exports}}function mapTargets(map,subpath){if(subpath in map&&!subpath.includes("*"))return targets(map[subpath]);let best;for(let key of Object.keys(map)){let star=key.indexOf("*");if(star===-1)continue;let prefix=key.slice(0,star),suffix=key.slice(star+1);if(subpath.length>=key.length-1&&subpath.startsWith(prefix)&&subpath.endsWith(suffix)&&(!best||prefix.length>best.key.indexOf("*")||prefix.length===best.key.indexOf("*")&&key.length>best.key.length))best={key,match:subpath.slice(prefix.length,subpath.length-suffix.length)}}if(!best)return;let{match}=best;return targets(map[best.key]).map((target)=>target.replaceAll("*",match))}function exportTargets(exports,subpath){let map=subpathMap(exports);return map&&mapTargets(map,subpath)}function byDepth(packages){return[...packages].sort(([a],[b])=>b.length-a.length)}function owner(packages,file){return byDepth(packages).find(([dir])=>dir==="."||file.startsWith(`${dir}/`))}function aliasPath([key,target],specifier){if(specifier!==key&&!specifier.startsWith(`${key}/`))return;let rest=specifier.slice(key.length+1);if(target===".")return posix.normalize(rest||".");return posix.normalize(rest?`${target}/${rest}`:target)}function createResolver({files,config,packages,tsconfigs=new Map}){let generated=(path)=>config.generated.some(({pattern})=>pattern.test(path)),{extensions}=config,exists=(path)=>files.has(path),suffixed=new Map,indexes=new Map,byTail=[],undotted=[];for(let i=0;i<extensions.length;i++){let ext=extensions[i],dot=ext.lastIndexOf(".");if(dot===-1)undotted.push(i);else{let list=byTail[ext.length-dot];if(list)list.push(i);else byTail[ext.length-dot]=[i]}}let addSuffixed=(i,file)=>{let ext=extensions[i];if(!file.endsWith(ext))return;let base=file.slice(0,file.length-ext.length),list=suffixed.get(base);if(list)list.push([i,file]);else{let created=[[i,file]];if(suffixed.set(base,created),base.endsWith(INDEX))indexes.set(base.slice(0,-INDEX.length),created)}};for(let file of files){let dot=file.lastIndexOf(".");if(dot!==-1)for(let i of byTail[file.length-dot]??[])addSuffixed(i,file);for(let i of undotted)addSuffixed(i,file)}for(let list of suffixed.values())if(list.length>1)list.sort(([a],[b])=>a-b);let deepestFirst=byDepth(packages),local=new Map;for(let[dir,json]of deepestFirst)if(json.name&&!local.has(json.name))local.set(json.name,dir);let declaredIn=(dir)=>{let names=new Set;for(let[pkgDir,json]of deepestFirst){if(pkgDir!=="."&&dir!==pkgDir&&!dir.startsWith(`${pkgDir}/`))continue;for(let field of DEP_FIELDS)for(let name of Object.keys(json[field]??{}))names.add(name)}return names},tsSources=(path)=>{let js=JS_EXTENSION.exec(path);if(!js)return[];let stem=path.slice(0,js.index);return(TS_SOURCES[js[0]]??[]).map((ext)=>stem+ext).filter((file)=>generated(file)||exists(file))},exact=(path)=>generated(path)||exists(path)?[path]:tsSources(path),probe=(base,guess=!1)=>{if(generated(base))return[base];let found=[];if(exists(base))found.push(base);for(let[,file]of suffixed.get(base)??[])found.push(file);if(found.length===0)found.push(...tsSources(base));for(let[,file]of indexes.get(base)??[])found.push(file);if(found.length===0&&!guess&&config.generated.length>0){for(let ext of extensions)if(generated(base+ext))found.push(base+ext);for(let ext of extensions)if(generated(`${base}/index${ext}`))found.push(`${base}/index${ext}`)}return found},tsDeepestFirst=[...tsconfigs].sort(([a],[b])=>b.length-a.length),scopes=new Map,scopeOf=(from)=>{let contains=([dir])=>dir==="."||from.startsWith(`${dir}/`),pkg=deepestFirst.findIndex(contains),ts=tsDeepestFirst.findIndex(contains),key=`${pkg} ${ts}`,scope=scopes.get(key);if(!scope){let owning=pkg===-1?void 0:deepestFirst[pkg];scope={owning,ts:ts===-1?void 0:tsDeepestFirst[ts][1],declared:declaredIn(owning?.[0]??"."),resolved:new Map},scopes.set(key,scope)}return scope},svelteKitRoot=(dir)=>{for(let at=dir;;at=posix.dirname(at)){if(at==="."||packages.has(at))return at;if(SVELTE_CONFIGS.some((name)=>exists(`${at}/${name}`)))return at}},inPackage=(dir,path)=>dir==="."?path:posix.join(dir,path),resolveLocal=(dir,json,subpath)=>{if(json.exports!==void 0){let list=exportTargets(json.exports,subpath);return[...new Set((list??[]).flatMap((target)=>exact(inPackage(dir,posix.normalize(target)))))]}if(subpath===".")return probe(inPackage(dir,posix.normalize(json.main??"index")));return probe(inPackage(dir,subpath.slice(2)))},resolveImport=(scope,bare)=>{let{owning}=scope,imports=owning?.[1].imports,list=owning&&imports&&mapTargets(imports,bare);if(!list)return;let found=[],pkg;for(let target of list){if(target.startsWith("./")){for(let path of exact(inPackage(owning[0],posix.normalize(target))))if(!found.includes(path))found.push(path);continue}if(INVALID_IMPORT_TARGET.test(target))continue;let specifier=target.replace(QUERY,""),resolved=specifier===""?void 0:resolveBare(scope,specifier);if(resolved===void 0)return;if("pkg"in resolved)pkg??=resolved.pkg;else for(let file of resolved.files)if(!found.includes(file))found.push(file)}if(found.length>0)return{files:found};return pkg===void 0?void 0:{pkg}},resolveRelative=(fromDir,bare)=>{if(bare.startsWith(SVELTEKIT_ASSETS)){let rest=bare.slice(SVELTEKIT_ASSETS.length),found=probe(posix.join(svelteKitRoot(fromDir),"static",rest));return found.length>0?{files:found}:void 0}let found=probe(posix.join(fromDir,bare));return found.length>0?{files:found}:void 0},resolveBare=(scope,bare)=>{for(let alias of config.alias){let path=aliasPath(alias,bare);if(path===void 0)continue;let found=probe(path);if(found.length>0)return{files:found}}let{ts}=scope,mapped=ts&&mapTargets(ts.paths,bare);if(mapped){let found=[...new Set(mapped.flatMap((path)=>probe(posix.normalize(path))))];if(found.length>0)return{files:found}}if(bare.startsWith("#"))return resolveImport(scope,bare);let name=packageName(bare),dir=local.get(name);if(dir!==void 0){let subpath=`.${bare.slice(name.length)}`,found=resolveLocal(dir,packages.get(dir)??{},subpath);return found.length>0?{files:found}:void 0}if(ts?.baseUrl!==void 0){let found=probe(posix.join(ts.baseUrl,bare),!0);if(found.length>0)return{files:found}}let node=builtin(bare);if(node)return{pkg:node};if(scope.declared.has(name)||config.external.has(name))return{pkg:name};return},dirs=new Map,directoryOf=(from)=>{let dir=posix.dirname(from),found=dirs.get(dir);if(!found)found={dir,relative:new Map,scope:scopeOf(from)},dirs.set(dir,found);return found},lastFrom,last;return(from,specifier)=>{if(from!==lastFrom||!last)lastFrom=from,last=directoryOf(from);let{dir,relative,scope}=last,hash=specifier.startsWith("#")?"#":"",isRelative=RELATIVE.test(specifier),memo=isRelative?relative:scope.resolved;if(memo.has(specifier))return memo.get(specifier);let bare=hash+specifier.slice(hash.length).replace(QUERY,""),resolved;if(bare!==""&&bare!=="#")resolved=isRelative?resolveRelative(dir,bare):resolveBare(scope,bare);return memo.set(specifier,resolved),resolved}}import{posix as posix2}from"node:path";function createLexed(){return{imports:[],globs:[],gotos:[],dependsOn:[],reads:[],lists:[],registry:!1,nonLiteralImport:!1,nonLiteralGlob:!1,readsDisk:!1}}class LexError extends Error{}var TS={jsx:!1,tsx:!1},JS={jsx:!0,tsx:!1},TSX={jsx:!0,tsx:!0},JS_FILE=/\.[cm]?jsx?$/;function dialectOf(path){if(path.endsWith(".tsx"))return TSX;if(JS_FILE.test(path))return JS;return TS}var T_START=0,T_PUNCT=1,T_OPERAND=2,T_IDENT=3,T_DOT=4,T_CLOSE_PAREN=5,T_CLOSE_KW=6,T_CLOSE_BLOCK=7,T_ARROW=8,T_SEMI=9,T_LBRACE=10,M_PAREN=0,M_PAREN_KW=1,M_BRACKET=2,M_BLOCK=3,M_EXPR=4,M_TEMPLATE=5,DISK=new Set(["fs","node:fs","fs/promises","node:fs/promises","child_process","node:child_process"]),VI_CALLS=new Set(["mock","doMock","unmock","importActual","importMock"]),CALL_IMPORT=0,CALL_PROPERTY=1,CALL_MOCK=2,CALL_ACTUAL=3,src="",end=0,out=createLexed(),dialect=TS,nextAt=-1,nextImport=-1,LS=String.fromCharCode(8232),PS=String.fromCharCode(8233),oddLines=!1,templateOpen=!1;function fail(message,at){throw new LexError(`${message} at ${at}`)}function openFile(source,sink){src=source,out=sink,nextAt=-1,nextImport=-1,oddLines=source.includes("\r")||source.includes(LS)||source.includes(PS)}function lexRange(start,stop,language=TS){dialect=language,end=stop;let i=start;if(src.charCodeAt(i)===65279)i++;if(src.charCodeAt(i)===35&&src.charCodeAt(i+1)===33)i=lineEnd(i);code(i,!1)}function lexExpression(start,stop){return dialect=TS,end=stop,code(start,!0)}function isUnicodeSpace(c){return c===160||c===65279||c===5760||c>=8192&&c<=8202||c===8232||c===8233||c===8239||c===8287||c===12288}var IDENT=new Uint8Array(128);for(let c=0;c<128;c++)if(c>=97&&c<=122||c>=65&&c<=90||c===36||c===95)IDENT[c]=3;else if(c>=48&&c<=57)IDENT[c]=2;function isIdentStart(c){return c<128?(IDENT[c]&1)!==0:c>=128&&!isUnicodeSpace(c)}function isIdentPart(c){return c<128?IDENT[c]!==0:c>=128&&!isUnicodeSpace(c)}function identEnd(start){let i=start,s=src,n=end;while(i<n){let c=s.charCodeAt(i);if(c<128?IDENT[c]===0:isUnicodeSpace(c))break;i++}return i}function isWord(i,word){return i+word.length<=end&&src.startsWith(word,i)&&!isIdentPart(src.charCodeAt(i+word.length))}function lineEnd(start){let i=start;if(oddLines){while(i<end){let c=src.charCodeAt(i);if(c===10||c===13||c===8232||c===8233)return i;i++}return end}let e=src.indexOf(`
|
|
4
|
+
`,i);return e===-1||e>end?end:e}function skipTrivia(start){let i=start;while(i<end){let c=src.charCodeAt(i);if(c===32||c>=9&&c<=13||c>=128&&isUnicodeSpace(c))i++;else if(c===47&&src.charCodeAt(i+1)===47)i=lineEnd(i+2);else if(c===47&&src.charCodeAt(i+1)===42){let e=src.indexOf("*/",i+2);if(e===-1||e+2>end)return end;i=e+2}else break}return i}function stringEnd(i){let quote=src.charCodeAt(i),j=i+1;while(j<end){let c=src.charCodeAt(j);if(c===quote)return j+1;if(c===92){j+=src.charCodeAt(j+1)===13&&src.charCodeAt(j+2)===10?3:2;continue}if(c===10||c===13)return-1;j++}return-1}function template(start){let j=start;while(j<end){let c=src.charCodeAt(j);if(c===96)return templateOpen=!1,j+1;if(c===92){j+=2;continue}if(c===36&&src.charCodeAt(j+1)===123)return templateOpen=!0,j+2;j++}return fail("unterminated template",j)}function templatePart(start,stack){let e=template(start);if(out.strings&&!stack.includes(M_BRACKET))out.strings.push(src.slice(start,templateOpen?e-2:e-1));return e}function regex(i){let j=i+1,inClass=!1;for(;;){if(j>=end)fail("unterminated regex",i);let c=src.charCodeAt(j);if(c===92){j+=2;continue}if(c===10||c===13)fail("unterminated regex",i);if(inClass){if(c===93)inClass=!1}else if(c===47)break;else if(c===91)inClass=!0;j++}return identEnd(j+1)}function isOneOf(start,stop,words){if(stop-start!==words[0].length)return!1;let c=src.charCodeAt(start);for(let word of words)if(word.charCodeAt(0)===c&&src.startsWith(word,start))return!0;return!1}var EXPRESSION_KEYWORDS=[],PAREN_KEYWORDS=[],BLOCK_KEYWORDS=[];function byLength(table,words){for(let word of words)table[word.length]=[...table[word.length]??[],word]}byLength(EXPRESSION_KEYWORDS,["in","do","new","case","else","void","throw","yield","await","return","typeof","delete","default","instanceof"]);byLength(PAREN_KEYWORDS,["if","for","with","while"]);byLength(BLOCK_KEYWORDS,["do","try","else","finally"]);function isKeyword(table,start,stop){let words=table[stop-start];return words!==void 0&&isOneOf(start,stop,words)}function isExpressionKeyword(start,stop){return isKeyword(EXPRESSION_KEYWORDS,start,stop)}function valueEnded(last,wordStart,wordEnd,wordIsProperty){return last===T_OPERAND||last===T_CLOSE_PAREN||last===T_IDENT&&(wordIsProperty||!isExpressionKeyword(wordStart,wordEnd))}function isParenKeyword(start,stop){return isKeyword(PAREN_KEYWORDS,start,stop)}function isBlockKeyword(start,stop){return isKeyword(BLOCK_KEYWORDS,start,stop)}function isWordAt(start,stop,word){return stop-start===word.length&&src.startsWith(word,start)}var KEYWORD_SHAPE=new Uint8Array(1024);for(let word of["vi","Bun","goto","import","export","require"])KEYWORD_SHAPE[word.length<<7|word.charCodeAt(0)]=1;function keyword(c,i,j,property){switch(j-i){case 2:if(src.charCodeAt(i+1)===105)vi(j);break;case 3:if(src.startsWith("Bun",i))bun(j);break;case 4:if(property&&src.startsWith("goto",i))goto(j);break;case 6:if(!property){if(c===105&&src.startsWith("import",i))importAt(j);else if(c===101&&src.startsWith("export",i))exportAt(j)}break;case 7:if(src.startsWith("require",i))requireAt(j,property);break}}function code(start,brace){let i=start,s=src,n=end,stack=[],last=T_START,wordStart=0,wordEnd=0,wordIsProperty=!1;while(i<n){let c=s.charCodeAt(i);if(c<128?(IDENT[c]&1)!==0:!isUnicodeSpace(c)){let j=i+1;while(j<n){let d=s.charCodeAt(j);if(d<128?IDENT[d]===0:isUnicodeSpace(d))break;j++}let property=last===T_DOT;if(c<128&&j-i<8&&KEYWORD_SHAPE[j-i<<7|c]!==0)keyword(c,i,j,property);last=T_IDENT,wordStart=i,wordEnd=j,wordIsProperty=property,i=j;continue}switch(c){case 32:case 9:case 10:case 11:case 12:case 13:i++;continue;case 47:{let next=src.charCodeAt(i+1);if(next===47){let e=lineEnd(i+2);comment(i,e,!1),i=e}else if(next===42){let e=src.indexOf("*/",i+2);if(e===-1||e+2>end)fail("unterminated comment",i);comment(i,e+2,!0),i=e+2}else if(valueEnded(last,wordStart,wordEnd,wordIsProperty))i++,last=T_PUNCT;else i=regex(i),last=T_OPERAND;continue}case 39:case 34:{let e=stringEnd(i);if(e===-1)fail("unterminated string",i);if(out.strings&&!stack.includes(M_BRACKET))out.strings.push(src.slice(i+1,e-1));i=e,last=T_OPERAND;continue}case 96:if(i=templatePart(i+1,stack),templateOpen)stack.push(M_TEMPLATE),last=T_PUNCT;else last=T_OPERAND;continue;case 123:{let block=last===T_START||last===T_SEMI||last===T_LBRACE||last===T_CLOSE_PAREN||last===T_CLOSE_KW||last===T_CLOSE_BLOCK||last===T_ARROW||last===T_IDENT&&!wordIsProperty&&isBlockKeyword(wordStart,wordEnd);stack.push(block?M_BLOCK:M_EXPR),last=T_LBRACE,i++;continue}case 125:{if(stack.length===0){if(brace)return i+1;fail("unbalanced }",i)}let open=stack.pop();if(open===M_TEMPLATE){if(i=templatePart(i+1,stack),templateOpen)stack.push(M_TEMPLATE),last=T_PUNCT;else last=T_OPERAND;continue}if(open===M_BLOCK)last=T_CLOSE_BLOCK;else if(open===M_EXPR)last=T_OPERAND;else fail("unbalanced }",i);i++;continue}case 40:stack.push(last===T_IDENT&&!wordIsProperty&&isParenKeyword(wordStart,wordEnd)?M_PAREN_KW:M_PAREN),last=T_PUNCT,i++;continue;case 41:{let open=stack.pop();if(open===M_PAREN)last=T_CLOSE_PAREN;else if(open===M_PAREN_KW)last=T_CLOSE_KW;else fail("unbalanced )",i);i++;continue}case 91:stack.push(M_BRACKET),last=T_PUNCT,i++;continue;case 93:if(stack.pop()!==M_BRACKET)fail("unbalanced ]",i);last=T_OPERAND,i++;continue;case 59:last=T_SEMI,i++;continue;case 46:if(src.charCodeAt(i+1)===46&&src.charCodeAt(i+2)===46)last=T_PUNCT,i+=3;else if(isDigit(src.charCodeAt(i+1)))i=numberEnd(i+1),last=T_OPERAND;else last=T_DOT,i++;continue;case 61:if(src.charCodeAt(i+1)===62)last=T_ARROW,i+=2;else last=T_PUNCT,i++;continue;case 43:case 45:if(src.charCodeAt(i+1)===c)last=last===T_OPERAND||last===T_IDENT||last===T_CLOSE_PAREN?T_OPERAND:T_PUNCT,i+=2;else last=T_PUNCT,i++;continue;case 33:last=valueEnded(last,wordStart,wordEnd,wordIsProperty)&&src.charCodeAt(i+1)!==61?T_OPERAND:T_PUNCT,i++;continue;case 60:if(src.charCodeAt(i+1)===60||src.charCodeAt(i+1)===61)last=T_PUNCT,i+=2;else if(!valueEnded(last,wordStart,wordEnd,wordIsProperty)&&dialect.jsx&&isJsxStart(i))i=jsxElement(i),last=T_OPERAND;else last=T_PUNCT,i++;continue;case 35:if(isIdentStart(src.charCodeAt(i+1)))i=identEnd(i+1),last=T_OPERAND;else last=T_PUNCT,i++;continue;default:if(isDigit(c)){i=numberEnd(i+1),last=T_OPERAND;continue}if(c<128)last=T_PUNCT;i++;continue}}if(brace)fail("unterminated expression",i);if(stack.length>0)fail(stack[stack.length-1]===M_TEMPLATE?"unterminated template":"unbalanced brackets",i);return i}function isDigit(c){return c>=48&&c<=57}function numberEnd(start){let i=start;while(i<end){let c=src.charCodeAt(i);if(isIdentPart(c)||c===46)i++;else break}return i}function comment(start,stop,block){if(nextAt<start)nextAt=indexOrEnd("@",start);while(nextAt<stop){if(src.startsWith("@depends-on",nextAt)||src.startsWith("@reads",nextAt)||src.startsWith("@lists",nextAt)||src.startsWith("@glob-registry",nextAt)){annotations(start,stop),nextAt=indexOrEnd("@",stop);break}nextAt=indexOrEnd("@",nextAt+1)}if(block&&src.charCodeAt(start+2)===42){if(nextImport<start)nextImport=indexOrEnd("import",start);while(nextImport<stop)jsdocImport(start,nextImport,stop),nextImport=indexOrEnd("import",nextImport+6)}}function indexOrEnd(text,from){let at=src.indexOf(text,from);return at===-1?src.length:at}var BLANK=/^[ \t]*$/;function annotations(start,stop){let lineStart=src.lastIndexOf(`
|
|
5
|
+
`,start-1)+1,prefix=src.slice(lineStart,start),text=(BLANK.test(prefix)?prefix:"x")+src.slice(start,stop);for(let[,list]of text.matchAll(DEPENDS_ON))out.dependsOn.push(...list.split(LIST_SEPARATOR).filter(Boolean));for(let[,list]of text.matchAll(READS))out.reads.push(...list.split(LIST_SEPARATOR).filter(Boolean));for(let[,list]of text.matchAll(LISTS))out.lists.push(...list.split(LIST_SEPARATOR).filter(Boolean));if(GLOB_REGISTRY.test(text))out.registry=!0}var JSDOC_IMPORT_TYPE=/import\s*\(\s*(["'`])([^"'`\n]+)\1\s*\)/y,JSDOC_IMPORT_TAG=/@import\s+([^;"'`]*?)\s*from\s*(["'])([^"'\n]+)\2/y,JSDOC_LINE_STAR=/\n\s*\*/g;function inTagType(start,at){let depth=0,outer=-1;for(let i=start;i<at;i++){let c=src.charCodeAt(i);if(c===123){if(depth++===0)outer=i}else if(c===125&&depth>0)depth--}if(depth===0)return!1;let p=outer-1;while(p>start&&isSpace(src.charCodeAt(p)))p--;while(p>start&&isIdentPart(src.charCodeAt(p)))p--;return src.charCodeAt(p)===64&&p+1<outer}function jsdocImport(start,at,stop){if(src.charCodeAt(at-1)===64){JSDOC_IMPORT_TAG.lastIndex=at-1;let tag=JSDOC_IMPORT_TAG.exec(src);if(tag&&JSDOC_IMPORT_TAG.lastIndex<=stop){let clause=tag[1].replace(JSDOC_LINE_STAR,`
|
|
6
|
+
`),names=clause.includes("{")?namedBindings(clause):void 0;out.imports.push(names?{specifier:tag[3],names,type:!0}:{specifier:tag[3],type:!0})}return}if(isIdentPart(src.charCodeAt(at-1))||src.charCodeAt(at-1)===46)return;if(!inTagType(start,at))return;JSDOC_IMPORT_TYPE.lastIndex=at;let type=JSDOC_IMPORT_TYPE.exec(src);if(type&&JSDOC_IMPORT_TYPE.lastIndex<=stop)out.imports.push({specifier:type[2],type:!0})}function record(specifier,names,disk,type=!1){if(specifier==="")return;let ref=names?{specifier,names}:{specifier};if(type)ref.type=!0;if(out.imports.push(ref),disk&&!type&&DISK.has(specifier))out.readsDisk=!0}function isSpace(c){return c===32||c>=9&&c<=13}function isQuote(c){return c===39||c===34}function importAt(j){let k=skipTrivia(j),c=src.charCodeAt(k);if(c===40)call(k,CALL_IMPORT);else if(c===46)meta(k);else if(isQuote(c)){let e=stringEnd(k);if(e!==-1)record(src.slice(k+1,e-1),void 0,!0)}else declaration(k)}function declaration(k){let clauseStart=k,type=!1;if(src.startsWith("type",k)&&isSpace(src.charCodeAt(k+4))){clauseStart=k+5;while(clauseStart<end&&isSpace(src.charCodeAt(clauseStart)))clauseStart++;let next=skipTrivia(k+4);type=!(isWord(next,"from")&&isQuote(src.charCodeAt(skipTrivia(next+4))))}let p=k;for(let steps=0;steps<256;steps++){if(p=skipTrivia(p),p>=end)return;let c=src.charCodeAt(p);if(isIdentStart(c)){let q=identEnd(p+1);if(q-p===4&&src.startsWith("from",p)){let r=skipTrivia(q);if(isQuote(src.charCodeAt(r))){let e=stringEnd(r);if(e!==-1)record(src.slice(r+1,e-1),clauseNames(clauseStart,p),!0,type);return}}p=q}else if(c===123){if(p=braceEnd(p),p===-1)return}else if(c===42||c===44)p++;else return}}function clauseNames(start,stop){let clause=src.slice(start,stop);if(!clause.includes("{"))return;return namedBindings(clause.replace(COMMENTS2,""))}var COMMENTS2=/\/\/.*$|\/\*[\s\S]*?\*\//gm;function braceEnd(open){let p=open,depth=0;while(p<end){let c=src.charCodeAt(p);if(c===123)depth++,p++;else if(c===125){if(p++,--depth===0)return p}else if(isQuote(c)){if(p=stringEnd(p),p===-1)return-1}else if(c===47&&src.charCodeAt(p+1)===47)p=lineEnd(p+2);else if(c===47&&src.charCodeAt(p+1)===42){let e=src.indexOf("*/",p+2);if(e===-1)return-1;p=e+2}else if(c===59||c===40||c===96)return-1;else p++}return-1}function exportAt(j){let p=skipTrivia(j),type=!1;if(isWord(p,"type")){let q=skipTrivia(p+4),c=src.charCodeAt(q);if(c===123||c===42)p=q,type=!0}let clauseStart=p,c=src.charCodeAt(p),q;if(c===123){if(q=braceEnd(p),q===-1)return}else if(c===42){if(q=skipTrivia(p+1),isWord(q,"as")){q=skipTrivia(q+2);let n=src.charCodeAt(q);if(isQuote(n))q=stringEnd(q);else if(isIdentStart(n))q=identEnd(q+1);else return;if(q===-1)return}}else return;if(q=skipTrivia(q),!isWord(q,"from"))return;let r=skipTrivia(q+4);if(!isQuote(src.charCodeAt(r)))return;let e=stringEnd(r);if(e===-1)return;record(src.slice(r+1,e-1),clauseNames(clauseStart,q),!0,type)}function call(k,kind){let a=skipTrivia(k+1),c=src.charCodeAt(a);if(c===41)return;let e;if(isQuote(c))e=stringEnd(a);else if(c===96){if(e=template(a+1),templateOpen)e=-1}else e=-1;let next=e===-1?-1:src.charCodeAt(skipTrivia(e));if(next===44||next===41)record(src.slice(a+1,e-1),void 0,kind===CALL_IMPORT||kind===CALL_PROPERTY||kind===CALL_ACTUAL);else if(kind!==CALL_PROPERTY&&!isSignature(k,a))out.nonLiteralImport=!0}function isSignature(k,a){if(isIdentStart(src.charCodeAt(a))){let p=skipTrivia(identEnd(a+1)),c=src.charCodeAt(p);if(c===58||c===63&&src.charCodeAt(skipTrivia(p+1))===58)return!0}let close=parenEnd(k);return close!==-1&&src.charCodeAt(skipTrivia(close))===123}function parenEnd(k){let depth=0,p=k;while(p<end){let c=src.charCodeAt(p);if(c===40||c===91||c===123)depth++;else if(c===41||c===93||c===125){if(--depth===0)return p+1}else if(isQuote(c)||c===96){if(p=c===96?templateEnd(p):stringEnd(p),p===-1)return-1;continue}else if(c===47&&(src.charCodeAt(p+1)===47||src.charCodeAt(p+1)===42)){p=skipTrivia(p);continue}p++}return-1}function requireAt(j,property){let k=skipTrivia(j);if(src.charCodeAt(k)===40)call(k,property?CALL_PROPERTY:CALL_IMPORT)}function vi(j){let p=skipTrivia(j);if(src.charCodeAt(p)!==46)return;let q=skipTrivia(p+1),r=identEnd(q),name=src.slice(q,r);if(!VI_CALLS.has(name))return;let s=skipTrivia(r);if(src.charCodeAt(s)===60){if(s=genericEnd(s),s===-1){out.nonLiteralImport=!0;return}s=skipTrivia(s)}if(src.charCodeAt(s)===40)call(s,name==="importActual"?CALL_ACTUAL:CALL_MOCK)}function meta(k){let m=skipTrivia(k+1);if(!isWord(m,"meta"))return;let p=skipTrivia(m+4);if(src.charCodeAt(p)!==46)return;let q=skipTrivia(p+1),r=identEnd(q);if(!isWordAt(q,r,"glob")&&!isWordAt(q,r,"globEager"))return;let s=skipTrivia(r);if(src.charCodeAt(s)===60){if(s=genericEnd(s),s===-1){out.nonLiteralGlob=!0;return}s=skipTrivia(s)}if(src.charCodeAt(s)===40)globArgument(s)}function genericEnd(start){let p=start,depth=0;while(p<end&&p-start<4096){let c=src.charCodeAt(p);if(c===60)depth++;else if(c===62&&src.charCodeAt(p-1)!==61){if(--depth===0)return p+1}else if(isQuote(c)){if(p=stringEnd(p),p===-1)return-1;continue}else if(c===96){if(p=template(p+1),templateOpen)return-1;continue}else if(c===59&&depth===0)return-1;p++}return-1}function literalEnd(a){let c=src.charCodeAt(a);if(isQuote(c))return stringEnd(a);if(c===96){let e=template(a+1);return templateOpen?-1:e}return-1}function globArgument(k){let a=skipTrivia(k+1),patterns=[],e;if(src.charCodeAt(a)===91){a=skipTrivia(a+1);for(;;){if(src.charCodeAt(a)===93){e=a+1;break}let f=literalEnd(a);if(f===-1){e=-1;break}patterns.push(src.slice(a+1,f-1)),a=skipTrivia(f);let c=src.charCodeAt(a);if(c===44)a=skipTrivia(a+1);else if(c!==93){e=-1;break}}}else if(e=literalEnd(a),e!==-1)patterns.push(src.slice(a+1,e-1));let next=e===-1?-1:src.charCodeAt(skipTrivia(e));if(next===44||next===41)out.globs.push(...patterns);else out.nonLiteralGlob=!0}function goto(j){let k=skipTrivia(j);if(src.charCodeAt(k)!==40)return;let a=skipTrivia(k+1),p=a,depth=0;while(p<end){let c=src.charCodeAt(p);if((c===44||c===41)&&depth===0)break;if(c===40||c===91||c===123)depth++;else if(c===41||c===93||c===125)depth--;else if(isQuote(c)||c===96){let e=c===96?templateEnd(p):stringEnd(p);if(e===-1)return;p=e;continue}p++}out.gotos.push(src.slice(a,p).trim())}function templateEnd(p){let q=template(p+1);while(templateOpen){let depth=1;while(q<end&&depth>0){let c=src.charCodeAt(q);if(c===123)depth++;else if(c===125)depth--;else if(isQuote(c)){if(q=stringEnd(q),q===-1)return-1;continue}else if(c===96){if(q=templateEnd(q),q===-1)return-1;continue}q++}if(depth>0)return-1;q=template(q)}return q}function bun(j){if(src.charCodeAt(j)!==46)return;if(src.startsWith("file",j+1)||src.startsWith("Glob",j+1)||src.startsWith("spawn",j+1))out.readsDisk=!0}function isJsxStart(i){let c=src.charCodeAt(i+1);if(c===62)return!0;if(!isIdentStart(c))return!1;if(!dialect.tsx)return!0;let p=skipTrivia(identEnd(i+2));return src.charCodeAt(p)!==44&&!isWord(p,"extends")}function jsxNameEnd(start){let p=start;while(p<end){let c=src.charCodeAt(p);if(isIdentPart(c)||c===45||c===46||c===58)p++;else break}return p}function jsxElement(i){let p=i+1;if(src.charCodeAt(p)===62)return jsxChildren(p+1);if(p=jsxNameEnd(p),dialect.tsx){let q=skipTrivia(p);if(src.charCodeAt(q)===60){if(p=genericEnd(q),p===-1)fail("unterminated JSX type arguments",q)}}for(;;){if(p=skipTrivia(p),p>=end)fail("unterminated JSX",i);let c=src.charCodeAt(p);if(c===47&&src.charCodeAt(p+1)===62)return p+2;if(c===62)return jsxChildren(p+1);if(c===123){p=code(p+1,!0);continue}if(!isIdentStart(c))fail(`bad JSX attribute in <> at ${i}:`,p);if(p=skipTrivia(jsxNameEnd(p)),src.charCodeAt(p)!==61)continue;p=skipTrivia(p+1);let v=src.charCodeAt(p);if(isQuote(v)){let e=src.indexOf(src[p],p+1);if(e===-1||e>=end)fail("unterminated JSX attribute",p);p=e+1}else if(v===123)p=code(p+1,!0);else if(v===60)p=jsxElement(p);else fail("bad JSX attribute",p)}}function jsxChildren(start){let p=start;while(p<end){let c=src.charCodeAt(p);if(c===60){if(src.charCodeAt(p+1)===47){let e=src.indexOf(">",p);if(e===-1||e>=end)break;return e+1}p=jsxElement(p)}else if(c===123)p=code(p+1,!0);else p++}return fail("unterminated JSX",p)}function hostOf(path){let dot=path.lastIndexOf("."),ext=path.slice(dot+1);return ext==="svelte"||ext==="vue"||ext==="astro"||ext==="html"?ext:void 0}var TAG_REF=/^<(?:script|link|iframe)\b[^>]*\b(?:src|href)=(?:"([^"]+)"|'([^']+)'|([^\s"'=<>`]+))/,GENERICS=/\sgenerics=(["'])/,LANG_JSX=/\slang=["']?(?:jsx|tsx)\b/,LOWERCASE=/[a-z]/,FENCE_OPEN=/^\s*---[ \t]*\r?\n/,FENCE_CLOSE=/^---[ \t]*$/m;function isTag(src,i,name){for(let k=0;k<name.length;k++)if((src.charCodeAt(i+1+k)|32)!==name.charCodeAt(k))return!1;let c=src.charCodeAt(i+1+name.length);return c===62||c===47||c===32||c>=9&&c<=13}function tagEnd(src,i){let j=i+1;while(j<src.length){let c=src.charCodeAt(j);if(c===62)return j+1;if(c===34||c===39){let e=src.indexOf(src[j],j+1);if(e===-1)break;j=e+1}else j++}throw new LexError(`unterminated tag at ${i}`)}function closeTag(src,from,name){let lower=src.indexOf(`</${name}`,from);if(lower!==-1)return lower;let any=src.slice(from).search(new RegExp(`</${name}`,"i"));if(any===-1)throw new LexError(`unterminated <${name}> at ${from}`);return from+any}function indexOrEnd2(src,text,from){let at=src.indexOf(text,from);return at===-1?src.length:at}function lexHost(src,out,host){let n=src.length,i=0;if(host==="astro")i=frontmatter(src);let nextTag=-1,nextBrace=host==="svelte"?-1:n;while(i<n){if(nextTag<i)nextTag=indexOrEnd2(src,"<",i);if(nextBrace<i)nextBrace=indexOrEnd2(src,"{",i);if(i=Math.min(nextTag,nextBrace),i>=n)break;if(src.charCodeAt(i)===123){let j=i+1,sigil=src.charCodeAt(j);if(sigil===35||sigil===58||sigil===64||sigil===47&&LOWERCASE.test(src[j+1]??""))j++;i=lexExpression(j,n);continue}if(src.startsWith("<!--",i)){let e=src.indexOf("-->",i+4);if(e===-1)throw new LexError(`unterminated comment at ${i}`);i=e+3}else if(isTag(src,i,"script")){let open=tagEnd(src,i),tag=src.slice(i,open);if(host==="html"||host==="vue")ref(tag,out);let generics=tag.match(GENERICS);if(generics?.index!==void 0){let start=i+generics.index+generics[0].length,stop=src.indexOf(generics[1],start);if(stop!==-1&&stop<open)lexRange(start,stop,TS)}let close=closeTag(src,open,"script"),dialect=LANG_JSX.test(tag)?TSX:TS;lexRange(open,close,dialect),i=close+8}else if(isTag(src,i,"style"))i=closeTag(src,tagEnd(src,i),"style")+7;else if(host==="html"&&(isTag(src,i,"link")||isTag(src,i,"iframe"))){let open=tagEnd(src,i);ref(src.slice(i,open),out),i=open}else i++}}function ref(tag,out){let match=TAG_REF.exec(tag),value=match&&(match[1]??match[2]??match[3]);if(value&&!URL_REF.test(value))out.imports.push({specifier:RELATIVE.test(value)?value:`./${value}`})}function frontmatter(src){let start=FENCE_OPEN.exec(src);if(!start)return 0;let from=start[0].length,close=src.slice(from).search(FENCE_CLOSE);if(close===-1)throw new LexError("unterminated frontmatter");return lexRange(from,from+close,TS),from+close+3}var COMMENTS3=/\/\/.*$|\/\*[\s\S]*?\*\//gm,QUOTED=/["']([^"']+)["']/g,STATIC_IMPORT=/(?:^|[\n;>])\s*(?:import|export)\s+(?:type\s+)?([^;"'`]*?)\s*from\s*["']([^"'\n]+)["']/g,SIDE_EFFECT_IMPORT=/(?:^|[\n;>])\s*import\s*["']([^"'\n]+)["']/g,CALL_WITH_LITERAL=/\b(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\(\s*(["'`])([^"'`$\n]+)\1\s*[,)]/g,NON_LITERAL_CALL=/(?<![.\w])(?:import|require)\(\s*(?!["'`])[^)\s]/,TEMPLATE_CALL=/(?<![.\w])(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\(\s*`[^`]*\$\{/,GLOB_CALL=/\bimport\.meta\.glob(?:<(?:[^<>]|<[^<>]*>)*>)?\(\s*(\[[^\]]*\]|["'][^"']*["'])/g,GLOB_CALL_ANY=/\bimport\.meta\.glob[<(]/g,GOTO=/\.goto\(\s*([^,)]*)/g,HTML_REF=/<(?:script|link|iframe)\b[^>]*\b(?:src|href)=["']([^"']+)["']/g,READS_DISK=/\b(?:from|import|require|importActual)\s*\(?\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\bBun\.(?:file|Glob|spawn)/;function extractRegex(source,html){let result={imports:[],globs:[],gotos:[],dependsOn:[],reads:[],lists:[],unknown:[]};if(html){for(let[,ref]of source.matchAll(HTML_REF))if(!URL_REF.test(ref))result.imports.push({specifier:RELATIVE.test(ref)?ref:`./${ref}`})}for(let[,clause,specifier]of source.matchAll(STATIC_IMPORT)){let names=namedBindings(clause.replace(COMMENTS3,""));result.imports.push(names?{specifier,names}:{specifier})}for(let[,specifier]of source.matchAll(SIDE_EFFECT_IMPORT))result.imports.push({specifier});let calls=source.includes("import(")||source.includes("require(")||source.includes("vi.");for(let[,,specifier]of calls?source.matchAll(CALL_WITH_LITERAL):[])result.imports.push({specifier});if(calls&&(NON_LITERAL_CALL.test(source)||TEMPLATE_CALL.test(source)))result.unknown.push("non-literal dynamic import");let globbing=source.includes("import.meta.glob"),globs=globbing?[...source.matchAll(GLOB_CALL)]:[];if(globbing&&globs.length!==[...source.matchAll(GLOB_CALL_ANY)].length)result.unknown.push("non-literal glob import");for(let[,argument]of GLOB_REGISTRY.test(source)?[]:globs)for(let[,glob]of argument.matchAll(QUOTED)){if(glob.startsWith("!"))continue;result.globs.push(glob.replace(QUERY,""))}if(source.includes(".goto("))for(let[,argument]of source.matchAll(GOTO))result.gotos.push(argument.trim());if(result.dependsOn=[...source.includes("@depends-on")?source.matchAll(DEPENDS_ON):[]].flatMap(([,list])=>list.split(LIST_SEPARATOR).filter(Boolean)),result.reads=[...source.includes("@reads")?source.matchAll(READS):[]].flatMap(([,list])=>list.split(LIST_SEPARATOR).filter(Boolean)),result.lists=[...source.includes("@lists")?source.matchAll(LISTS):[]].flatMap(([,list])=>list.split(LIST_SEPARATOR).filter(Boolean)),(source.includes("fs")||source.includes("child_process")||source.includes("Bun."))&&READS_DISK.test(source)&&result.dependsOn.length+result.reads.length+result.lists.length===0)result.unknown.push(UNDECLARED_READS);return result}var SCANNED=/\.(?:svelte|vue|astro|html|[cm]?[jt]sx?)$/;function formatOf(path){let host=hostOf(path);if(host)return host;let dialect=dialectOf(path);if(dialect===TSX)return"tsx";return dialect===JS?"js":"ts"}function extract(format,source){let lexed=createLexed(),extraction;try{if(openFile(source,lexed),isHost(format))lexHost(source,lexed,format);else lexRange(0,source.length,DIALECTS[format]);extraction=fromLexed(lexed)}catch(error){let fallback=error instanceof LexError?error.message:`lexer error: ${error}`;extraction={...extractRegex(source,format==="html"),fallback}}if(!isHost(format)){let barrel=parseReExports(source);if(barrel)extraction.barrel=barrel}return detach(extraction)}function stringsOf(format,source){let lexed=createLexed(),strings=[];lexed.strings=strings;try{if(openFile(source,lexed),isHost(format))lexHost(source,lexed,format);else lexRange(0,source.length,DIALECTS[format])}catch{return}return strings}function own(text){return JSON.parse(JSON.stringify(text))}function detach(extraction){let list=(texts)=>texts.map(own),{imports,barrel,fallback}=extraction,detached={imports:imports.map(({specifier,names,type})=>{let ref=names?{specifier:own(specifier),names:list(names)}:{specifier:own(specifier)};if(type)ref.type=!0;return ref}),globs:list(extraction.globs),gotos:list(extraction.gotos),dependsOn:list(extraction.dependsOn),reads:list(extraction.reads),lists:list(extraction.lists),unknown:extraction.unknown};if(fallback!==void 0)detached.fallback=fallback;if(barrel)detached.barrel={names:new Map([...barrel.names].map(([name,from])=>[own(name),own(from)])),stars:list(barrel.stars)};return detached}function finish(path,extraction,{gotos=!1}={}){let{globs}=extraction,dir=globs.length>0?posix2.dirname(path):"",result={imports:extraction.imports,globs:globs.map((glob)=>posix2.join(dir,glob)),gotos:gotos?extraction.gotos:[],dependsOn:extraction.dependsOn,reads:extraction.reads,lists:extraction.lists,unknown:extraction.unknown};if(extraction.fallback!==void 0)result.fallback=extraction.fallback;return result}var DIALECTS={ts:TS,tsx:TSX,js:JS},isHost=(format)=>format!=="ts"&&format!=="tsx"&&format!=="js";function fromLexed(lexed){let unknown=[];if(lexed.nonLiteralImport)unknown.push("non-literal dynamic import");if(lexed.nonLiteralGlob)unknown.push("non-literal glob import");let globs=[];for(let glob of lexed.registry?[]:lexed.globs){if(glob.startsWith("!"))continue;globs.push(glob.replace(QUERY,""))}let declared=lexed.dependsOn.length+lexed.reads.length+lexed.lists.length;if(lexed.readsDisk&&declared===0)unknown.push(UNDECLARED_READS);return{imports:lexed.imports,globs,gotos:lexed.gotos,dependsOn:lexed.dependsOn,reads:lexed.reads,lists:lexed.lists,unknown}}var STRING_LITERAL=/^["'`]([^"'`$]*)["'`]$/,STATIC_PATH_TEMPLATE=/^`([^`$?#]*)[?#][^`]*`$/;function gotoUrl(argument){return STRING_LITERAL.exec(argument)?.[1]??STATIC_PATH_TEMPLATE.exec(argument)?.[1]}var leaf=()=>({files:new Set,patterns:[],reads:[],unknown:[]}),LEADING_DOT_SLASH2=/^\.\//,JS_SPECIFIER=/\.[cm]?jsx?$/,DECLARATION=/\.d(?:\.[^/.]+)?\.[cm]?ts$/;function addPattern(deps,pattern,kind){if(deps.patterns.push(pattern),kind==="glob")return;deps.patternKinds??=new Map,deps.patternKinds.set(pattern,kind)}var NON_LITERAL_GOTO="non-literal goto(",HERMETIC_CAUSES=new Set([UNDECLARED_READS,"non-literal dynamic import"]);function sideEffectful(owning){let sideEffects=owning?.[1].sideEffects;if(sideEffects===!1)return()=>!1;if(!Array.isArray(sideEffects))return()=>!0;let dir=owning?.[0]??".";return matcher(sideEffects.map((glob)=>{if(!glob.includes("/"))return`**/${glob}`;let path=glob.replace(LEADING_DOT_SLASH2,"");return dir==="."?path:`${dir}/${path}`}))}function gotoSuite(config,path){return config.suites.find((suite)=>suite.urls.length>0&&suite.roots.some((root)=>inRoot(path,root)))}function mapUrl(suite,url){for(let{key,targets}of suite.urls){let star=key.indexOf("*");if(star===-1){if(url===key)return targets;continue}let prefix=key.slice(0,star),suffix=key.slice(star+1);if(url.startsWith(prefix)&&url.endsWith(suffix)){let match=url.slice(prefix.length,url.length-suffix.length);return targets.map((target)=>target.replaceAll("*",match))}}return}function gotoPage(config,path,argument){let suite=gotoSuite(config,path),url=gotoUrl(argument);return suite===void 0||url===void 0?void 0:mapUrl(suite,url.replace(QUERY,""))}function graphFrom(files,extractions,{config,packages,tsconfigs}){let graph=new Map,paths=[...files],exists=new Set(paths),resolve=createResolver({files:exists,config,packages,tsconfigs}),scans=new Map,barrels=new Map;for(let path of paths){let extraction=extractions.get(path);if(!extraction)continue;let gotos=gotoSuite(config,path)!==void 0;if(scans.set(path,finish(path,extraction,{gotos})),extraction.barrel&&config.isBarrel(path))barrels.set(path,extraction.barrel)}let named=new Map,effects=new Map,nameUnknown=new Map;for(let[path,barrel]of barrels){let effectful=sideEffectful(owner(packages,path));if(effectful(path))continue;let resolveTarget=(specifier)=>{let resolved=resolve(path,specifier);return resolved&&"files"in resolved?resolved.files:void 0},always=[];for(let specifier of[...barrel.names.values(),...barrel.stars])for(let file of resolveTarget(specifier)??[])if(effectful(file)&&!always.includes(file))always.push(file);let names=new Map;for(let[name,specifier]of barrel.names){let targets=resolveTarget(specifier);if(!targets)nameUnknown.set(`${path}#${name}`,[`unresolved "${specifier}"`]);names.set(name,targets??[])}named.set(path,names),effects.set(path,always)}let external=new Set;for(let path of paths){let found=scans.get(path);if(!found){graph.set(path,leaf());continue}let deps=leaf(),valued=new Set,typed=new Set,declaration=DECLARATION.test(path);for(let{specifier,names,type}of found.imports){let resolved=resolve(path,specifier),add=(node)=>{deps.files.add(node),(type===!0||declaration||DECLARATION.test(node)?typed:valued).add(node)};if(resolved===void 0){let cause=`unresolved "${specifier}"`;if(!deps.unknown.includes(cause))deps.unknown.push(cause)}else if("pkg"in resolved)add(`pkg:${resolved.pkg}`),external.add(`pkg:${resolved.pkg}`);else{if(type!==!0&&!declaration&&JS_SPECIFIER.test(specifier.replace(QUERY,""))&&resolved.files.every((file)=>DECLARATION.test(file))){let cause=`only declarations for "${specifier}"`;if(!deps.unknown.includes(cause))deps.unknown.push(cause)}for(let file of resolved.files){let barrel=names&&named.get(file);if(!barrel||!names){add(file);continue}for(let name of names)add(barrel.has(name)?`${file}#${name}`:file)}}}for(let node of typed){if(valued.has(node))continue;deps.types??=new Set,deps.types.add(node)}deps.unknown.push(...config.isHermetic(path)?found.unknown.filter((cause)=>!HERMETIC_CAUSES.has(cause)):found.unknown);for(let glob of found.globs)addPattern(deps,globToRegExp(glob),"glob");let suite=found.gotos.length>0?gotoSuite(config,path):void 0;if(suite)for(let argument of found.gotos){let url=gotoUrl(argument);if(url===void 0){if(found.dependsOn.length===0)deps.unknown.push(`${NON_LITERAL_GOTO}${argument})`)}else if(url!=="about:blank"){let mapped=mapUrl(suite,url.replace(QUERY,""));if(mapped===void 0)deps.unknown.push(`goto("${url}")`);else if(exists.has(mapped[0]??""))for(let page of mapped.filter((file)=>exists.has(file))){if(!deps.files.has(page))deps.pages??=new Set,deps.pages.add(page);deps.files.add(page)}else deps.unknown.push(`missing fixture "${url}"`)}}for(let glob of found.dependsOn)addPattern(deps,globToRegExp(glob),"depends-on");for(let glob of found.reads)deps.reads.push(globToRegExp(glob));if(found.lists.length>0)deps.lists=found.lists.map(globToRegExp);let names=named.get(path);if(names)deps.barrel=names;graph.set(path,deps)}for(let[path,names]of named)for(let[name,targets]of names){let id=`${path}#${name}`;graph.set(id,{...leaf(),files:new Set([...targets,...effects.get(path)??[]]),unknown:nameUnknown.get(id)??[]})}for(let id of external)graph.set(id,leaf());for(let suite of config.suites){let setup=paths.filter(suite.isSetup);if(setup.length===0)continue;for(let path of paths){let deps=suite.isTest(path)?graph.get(path):void 0;if(!deps)continue;for(let file of setup){if(file===path)continue;deps.types?.delete(file),deps.files.add(file),deps.setup??=new Set,deps.setup.add(file)}}}for(let deps of[...graph.values()])for(let file of deps.files)if(!graph.has(file)&&isGenerated(config,file))graph.set(file,leaf());for(let[path,deps]of graph){let depends=!1,declared=!1;for(let edge of config.generated){let inputs=edge.targets(path);if(!inputs)continue;depends||=edge.exact;for(let input of inputs)addPattern(deps,input,"edges")}for(let read of config.reads){let globs=read.targets(path);if(!globs)continue;declared||=read.exact,deps.reads.push(...globs)}if(depends||declared)deps.unknown=deps.unknown.filter((cause)=>cause!==UNDECLARED_READS&&!(depends&&cause.startsWith(NON_LITERAL_GOTO)))}return graph}function isGenerated(config,path){return config.generated.some(({pattern})=>pattern.test(path))}function changedBarrelNames(before,after){let names=new Set([...before.keys(),...after.keys()]),key=(files)=>files?.join("\x00");return[...names].filter((name)=>key(before.get(name))!==key(after.get(name)))}function baseBarrelNames(path,source,{config,packages,tsconfigs},graph){let barrel=source===void 0?void 0:parseBarrel(path,source);if(!barrel)return;let resolve=createResolver({files:new Set(graph.keys()),config,packages,tsconfigs}),names=new Map;for(let[name,specifier]of barrel.names){let resolved=resolve(path,specifier);names.set(name,resolved&&"files"in resolved?resolved.files:[])}return names}var indexes=new WeakMap,REGEX_SYNTAX="[](){}|*+?.^$";function literalOf(re){let{source}=re;if(!source.startsWith("^")||!source.endsWith("$"))return;let path="";for(let i=1;i<source.length-1;i++){let char=source[i];if(char==="\\")path+=source[++i];else if(REGEX_SYNTAX.includes(char))return;else path+=char}return path}function patterns(){let literal=new Map,wild=[],bySource=new Map;return{literal,wild,add:(re,node,kind)=>{let group=bySource.get(re.source);if(!group){group={re,nodes:[],kinds:[]},bySource.set(re.source,group);let path=literalOf(re);if(path===void 0)wild.push(group);else{let list=literal.get(path);list?list.push(group):literal.set(path,[group])}}if(group.nodes.at(-1)===node)return;group.nodes.push(node),group.kinds.push(kind)}}}function reverseIndex(graph){let cached=indexes.get(graph);if(cached)return cached;let dependents=new Map,globbers=patterns(),readers=patterns(),listers=patterns(),unknown=[];for(let[path,deps]of graph){for(let file of deps.files){let list=dependents.get(file);list?list.push(path):dependents.set(file,[path])}for(let re of deps.patterns)globbers.add(re,path,deps.patternKinds?.get(re)??"glob");for(let re of deps.reads)readers.add(re,path,"reads");for(let re of deps.lists??[])listers.add(re,path,"lists");if(deps.unknown.length>0)unknown.push(path)}let index={dependents,globbers,readers,listers,unknown};return indexes.set(graph,index),index}function runtimeDependents(graph,index){if(index.runtime)return index.runtime;let runtime=new Map;for(let[path,deps]of graph)for(let file of deps.files){if(deps.types?.has(file))continue;let list=runtime.get(file);list?list.push(path):runtime.set(file,[path])}return index.runtime=runtime,runtime}function reaches(graph,changed,match,options={}){let reached=affectedBy(graph,changed,{...options,until:match});for(let path of reached)if(match(path))return!0;return!1}function walksByTypes(graph,changed,options={}){let seeds=[...changed],walks=new Map;return(types)=>{let walk=walks.get(types);if(!walk)walk=affectedBy(graph,seeds,{...options,types}),walks.set(types,walk);return walk}}function importersOf(graph,node){return reverseIndex(graph).dependents.get(node)??[]}function fileKind(graph,dependent,node){if(dependent.includes("#"))return"export";let deps=graph.get(dependent);if(deps?.setup?.has(node))return"setup";if(deps?.types?.has(node))return"type";if(deps?.pages?.has(node))return"goto";if(node.includes("#"))return"name";return dependent.endsWith(".html")?"html":"import"}function affectedBy(graph,changed,{includeUnknown=!0,quiet=[],types=!0,layout,readers:seedReaders=!0,opaque,until,parents}={}){let index=reverseIndex(graph),{globbers,readers,listers,unknown}=index,dependents=types?index.dependents:runtimeDependents(graph,index),affected=new Set,queue=[],done=!1,visit=(path,via)=>{if(affected.has(path)||opaque?.(path))return;if(affected.add(path),queue.push(path),via&&parents)parents.set(path,via);if(until?.(path))done=!0},visitGroup=(group,from)=>{let{nodes,kinds}=group;for(let i=0;i<nodes.length;i++)visit(nodes[i],parents&&{from,kind:kinds[i]})},visitMatches=(groups,path)=>{for(let group of groups.literal.get(path)??[])visitGroup(group,path);for(let group of groups.wild)if(group.re.test(path))visitGroup(group,path)},changedPaths=[...changed];for(let path of changedPaths)visit(path);let first=queue[0];for(let path of quiet)visit(path),changedPaths.push(path);if(seedReaders){for(let path of changedPaths)visitMatches(readers,path);for(let path of changedPaths)if(!layout||layout.has(path))visitMatches(listers,path)}if(includeUnknown&&first!==void 0)for(let path of unknown)visit(path,{from:first,kind:"unknown"});let{literal}=globbers,active=globbers.wild,spent,spend=(group,from)=>{visitGroup(group,from),spent??=new Set,spent.add(group)};for(let at=0;at<queue.length&&!done;at++){let path=queue[at];for(let dependent of dependents.get(path)??[])visit(dependent,parents&&{from:path,kind:fileKind(graph,dependent,path)});let exact=literal.size>0?literal.get(path):void 0;if(exact){for(let group of exact)if(!spent?.has(group))spend(group,path)}let matched=!1;for(let group of active){if(!group.re.test(path))continue;spend(group,path),matched=!0}if(matched)active=active.filter((group)=>!spent?.has(group))}return affected}import{posix as posix3}from"node:path";var COMMENT=/\s+#.*$/,KEY_END=/:(?: |$)/,EMPTY_MAP=/^\{\s*\}(?:\s+#.*)?$/,EMPTY_LIST=/^\[\s*\](?:\s+#.*)?$/,UNSUPPORTED=/^[&*!|>%@`]/;class YamlError extends Error{}function fail2(line,message){throw new YamlError(`${message} at line ${line?.number??"end"}`)}function linesOf(text){let lines=[];for(let[i,raw]of text.split(`
|
|
7
|
+
`).entries()){let line=raw.endsWith("\r")?raw.slice(0,-1):raw,content=line.trimStart();if(content===""||content.startsWith("#"))continue;let indent=line.length-content.length;if(line.slice(0,indent).includes("\t"))fail2({indent,text:content,number:i+1},"a tab in indentation");lines.push({indent,text:content.trimEnd(),number:i+1})}return lines}function quoteEnd(text,start){let quote=text[start];for(let i=start+1;i<text.length;i++)if(quote==="'"&&text[i]==="'")if(text[i+1]==="'")i++;else return i+1;else if(quote==='"'&&text[i]==="\\")i++;else if(quote==='"'&&text[i]==='"')return i+1;return-1}function unquote(quoted){if(quoted.startsWith("'"))return quoted.slice(1,-1).replaceAll("''","'");let value=JSON.parse(quoted);if(typeof value!=="string")throw new YamlError("bad quoted scalar");return value}function flowEnd(text,line){let depth=0;for(let i=0;i<text.length;i++){let c=text[i];if(c==="'"||c==='"'){let end=quoteEnd(text,i);if(end===-1)fail2(line,"an unterminated string");i=end-1}else if(c==="{"||c==="[")depth++;else if(c==="}"||c==="]"){if(--depth===0)return i+1}}return fail2(line,"a flow collection over several lines")}function scalar(text,line){if(text.startsWith("'")||text.startsWith('"')){let end=quoteEnd(text,0);if(end===-1)fail2(line,"an unterminated string");if(text.slice(end).replace(COMMENT,"").trim()!=="")fail2(line,"text after a quoted scalar");return unquote(text.slice(0,end))}if(text.startsWith("{")||text.startsWith("[")){let end=flowEnd(text,line);if(text.slice(end).replace(COMMENT,"").trim()!=="")fail2(line,"text after a flow collection");return text.slice(0,end)}if(UNSUPPORTED.test(text))fail2(line,`unsupported syntax "${text[0]}"`);return text.replace(COMMENT,"")}function keyOf(text,line){if(text.startsWith("'")||text.startsWith('"')){let end=quoteEnd(text,0);if(end===-1)fail2(line,"an unterminated key");if(text[end]!==":")return;return{key:unquote(text.slice(0,end)),rest:text.slice(end+1)}}let colon=text.search(KEY_END);if(colon===-1)return;return{key:text.slice(0,colon),rest:text.slice(colon+1)}}class Parser{at=0;lines;constructor(lines){this.lines=lines}block(indent){let first=this.lines[this.at];if(!first||first.indent!==indent)return"";return first.text==="-"||first.text.startsWith("- ")?this.sequence(indent):this.mapping(indent,{})}value(rest,indent,line){let text=rest.trim();if(EMPTY_MAP.test(text))return{};if(EMPTY_LIST.test(text))return[];if(text!==""&&!text.startsWith("#"))return scalar(text,line);let next=this.lines[this.at];return next&&next.indent>indent?this.block(next.indent):""}mapping(indent,into){for(let line=this.lines[this.at];line;line=this.lines[this.at]){if(line.indent<indent)break;if(line.indent>indent)fail2(line,"unexpected indentation");let entry=keyOf(line.text,line);if(!entry)fail2(line,"a line that isn't a key");if(Object.hasOwn(into,entry.key))fail2(line,"a duplicate key");this.at++,into[entry.key]=this.value(entry.rest,indent,line)}return into}sequence(indent){let items=[];for(let line=this.lines[this.at];line;line=this.lines[this.at]){if(line.indent<indent)break;if(line.indent>indent)fail2(line,"unexpected indentation");if(line.text!=="-"&&!line.text.startsWith("- "))break;this.at++;let text=line.text.slice(1).trimStart(),inner={...line,indent:line.indent+2,text};if(text!==""&&keyOf(text,line))this.lines.splice(this.at,0,inner),items.push(this.mapping(inner.indent,{}));else items.push(this.value(text,indent,line))}return items}}function parseYaml(text){let parser=new Parser(linesOf(text)),value=parser.block(0),left=parser.lines[parser.at];if(left)fail2(left,"unexpected indentation");return value}var DEP_FIELDS2=["dependencies","devDependencies","peerDependencies","optionalDependencies"];function isRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isStringRecord3(value){return isRecord3(value)&&Object.values(value).every((item)=>typeof item==="string")}var STRING_OR_TRAILING_COMMA=/"(?:[^"\\]|\\.)*"|,(\s*[}\]])/g;function parseLenient(text){return JSON.parse(text.replace(STRING_OR_TRAILING_COMMA,(match,close)=>close??match))}function specsOf(value){let specs=new Map;for(let field of DEP_FIELDS2){let deps=value[field];if(deps===void 0)continue;if(!isStringRecord3(deps))return;specs.set(field,new Map(Object.entries(deps)))}return specs}function restOf(value,skip){return JSON.stringify(Object.entries(value).filter(([key])=>!skip.includes(key)))}function install(packages,name,entry,version,info){let installed=packages.get(name)??{entries:[],versions:[],dependencies:new Set,bin:!1};if(info?.bin!==void 0||info?.hasBin===!0||info?.hasBin==="true")installed.bin=!0;if(installed.entries.push(JSON.stringify(entry)),!installed.versions.includes(version))installed.versions.push(version);for(let field of["dependencies","optionalDependencies","peerDependencies"]){let deps=info?.[field];if(isRecord3(deps))for(let dep of Object.keys(deps))installed.dependencies.add(dep)}packages.set(name,installed)}function installedName(key){let parts=key.split("/"),last=parts.length-1;return last>0&&parts[last-1].startsWith("@")?`${parts[last-1]}/${parts[last]}`:parts[last]}function parseBunLock(text){let value=parseLenient(text);if(!isRecord3(value))return;let{packages,workspaces}=value;if(!isRecord3(packages)||!isRecord3(workspaces))return;let lockfile={packages:new Map,workspaces:new Map,rest:restOf(value,["packages","workspaces"])};for(let[key,entry]of Object.entries(packages)){if(!Array.isArray(entry)||typeof entry[0]!=="string")return;let ident=entry[0],at=ident.indexOf("@",1),version=at===-1?"":ident.slice(at+1);install(lockfile.packages,installedName(key),entry,version,entry.find(isRecord3))}for(let[dir,workspace]of Object.entries(workspaces)){let specs=isRecord3(workspace)?specsOf(workspace):void 0;if(!specs)return;lockfile.workspaces.set(dir===""?".":dir,specs)}return lockfile}var NODE_MODULES="node_modules/";function parsePackageLock(text){let value=JSON.parse(text);if(!isRecord3(value)||!isRecord3(value.packages))return;let{lockfileVersion}=value;if(lockfileVersion!==2&&lockfileVersion!==3)return;let lockfile={packages:new Map,workspaces:new Map,rest:restOf(value,["packages","dependencies","name","version"])};for(let[key,entry]of Object.entries(value.packages)){if(!isRecord3(entry))return;let at=key.lastIndexOf(NODE_MODULES);if(at!==-1&&(at===0||key[at-1]==="/")){let version=typeof entry.version==="string"?entry.version:"",name=key.slice(at+NODE_MODULES.length);install(lockfile.packages,name,entry,version,entry);continue}let specs=specsOf(entry);if(!specs)return;lockfile.workspaces.set(key===""?".":key,specs)}return lockfile}function pnpmKey(key){let bare=key.startsWith("/")?key.slice(1):key,at=bare.indexOf("@",1);if(at===-1)return;return{name:bare.slice(0,at),version:withoutPeers(bare.slice(at+1))}}function withoutPeers(version){let paren=version.indexOf("(");return paren===-1?version:version.slice(0,paren)}var YAML_DOCUMENT=/^---[ \t]*$/m,PNPM_VERSION=/^[69]\./,PNPM_DEP_FIELDS=["dependencies","devDependencies","optionalDependencies"];function parsePnpmLock(text){let docs=text.split(YAML_DOCUMENT).filter((doc)=>doc.trim()!=="").map(parseYaml),main=docs.findLast((doc)=>isRecord3(doc)&&typeof doc.lockfileVersion==="string");if(!isRecord3(main))return;let{lockfileVersion,packages={},snapshots={}}=main;if(typeof lockfileVersion!=="string")return;if(!PNPM_VERSION.test(lockfileVersion))return;if(!isRecord3(packages)||!isRecord3(snapshots))return;let workspaces=isRecord3(main.importers),importers=isRecord3(main.importers)?main.importers:{".":main},lockfile={packages:new Map,workspaces:new Map,rest:JSON.stringify([restOf(main,["importers","packages","snapshots",...PNPM_DEP_FIELDS]),...docs.filter((doc)=>doc!==main)])},restOfImporters=[];for(let[dir,importer]of Object.entries(importers)){if(!isRecord3(importer))return;let specs=new Map;for(let field of PNPM_DEP_FIELDS){let deps=importer[field];if(deps===void 0)continue;if(!isRecord3(deps))return;let declared=new Map;for(let[name,dep]of Object.entries(deps)){if(!isRecord3(dep)||typeof dep.specifier!=="string")return;declared.set(name,dep.specifier);let version=typeof dep.version==="string"?dep.version:"";install(lockfile.packages,name,[dir,field,version],withoutPeers(version),{})}specs.set(field,declared)}if(lockfile.workspaces.set(dir,specs),workspaces){let settings=restOf(importer,PNPM_DEP_FIELDS);if(settings!=="[]")restOfImporters.push([dir,settings])}}lockfile.rest+=JSON.stringify(restOfImporters);for(let section of[packages,snapshots])for(let[key,entry]of Object.entries(section)){let parsed=pnpmKey(key);if(!parsed)return;let info=isRecord3(entry)?entry:void 0;install(lockfile.packages,parsed.name,[key,entry],parsed.version,info)}return lockfile}var FORMATS=new Map([["bun.lock",parseBunLock],["package-lock.json",parsePackageLock],["pnpm-lock.yaml",parsePnpmLock]]),UNREAD=["bun.lockb","npm-shrinkwrap.json","yarn.lock"];function parse(file,text){let format=FORMATS.get(file);if(text===void 0||!format)return;try{return format(text)}catch{return}}function describe(name,before,after){if(before===void 0)return`${name} ${after} added`;if(after===void 0)return`${name} ${before} removed`;return before===after?`${name} ${after}, entry changed`:`${name} ${before} → ${after}`}function versions(installed){return installed&&sorted(installed.versions).join(", ")}function specChanges(before,after){let changed=new Map;for(let field of DEP_FIELDS2){let a=before?.get(field),b=after?.get(field);for(let name of new Set([...a?.keys()??[],...b?.keys()??[]]))if(a?.get(name)!==b?.get(name)&&!changed.has(name))changed.set(name,[a?.get(name),b?.get(name)])}return changed}function lockfileChanges(file,base,head){let changes=[],names=new Set([...base.packages.keys(),...head.packages.keys()]);for(let name of names){let before=base.packages.get(name),after=head.packages.get(name);if(before!==void 0&&after!==void 0&&sorted(before.entries).join(`
|
|
8
|
+
`)===sorted(after.entries).join(`
|
|
9
|
+
`))continue;changes.push({name,detail:`${file}: ${describe(name,versions(before),versions(after))}`,file})}let resolved=new Set(changes.map((change)=>change.name)),dirs=new Set([...base.workspaces.keys(),...head.workspaces.keys()]);for(let dir of dirs){let declared=specChanges(base.workspaces.get(dir),head.workspaces.get(dir));for(let[name,[before,after]]of declared){if(resolved.has(name))continue;resolved.add(name),changes.push({name,detail:`${file}: ${describe(`${name} range`,before,after)}`,file})}}return changes}var MANIFEST=/(?:^|\/)package\.json$/;function parseManifest(text){if(text===void 0)return;try{let value=JSON.parse(text);return isRecord3(value)?value:void 0}catch{return}}async function readPackageDiff(changed,listed,base,head){let lockfiles=changed.filter((file)=>FORMATS.has(file)),manifests=changed.filter((file)=>MANIFEST.test(file));if(lockfiles.length===0&&manifests.length===0)return;let read=(path)=>Promise.all([base(path),head(path)]),known=[...FORMATS.keys()],[lockTexts,manifestTexts]=await Promise.all([Promise.all(known.map((file)=>lockfiles.includes(file)?read(file):head(file).then((text)=>[text,text]))),Promise.all(manifests.map(read))]),diff={files:new Map,changes:[],dependents:new Map,declared:new Set,bins:new Set},present=new Map;for(let[i,file]of known.entries()){let[baseText,headText]=lockTexts[i],after=parse(file,headText);if(headText!==void 0)present.set(file,after);let before=parse(file,baseText);for(let lockfile of[before,after]){if(!lockfile)continue;for(let[name,installed]of lockfile.packages){if(installed.bin)diff.bins.add(name);for(let dependency of installed.dependencies){let set=diff.dependents.get(dependency)??new Set;set.add(name),diff.dependents.set(dependency,set)}}for(let specs of lockfile.workspaces.values())for(let deps of specs.values())for(let name of deps.keys())diff.declared.add(name)}if(!lockfiles.includes(file))continue;if(baseText===void 0||headText===void 0)diff.files.set(file,baseText===void 0?"added":"deleted");else if(!(before&&after))diff.files.set(file,"can't parse it");else if(before.rest===after.rest)diff.files.set(file,void 0),diff.changes.push(...lockfileChanges(file,before,after));else diff.files.set(file,"a setting other than the packages changed")}let unread=UNREAD.some((file)=>listed.includes(file));for(let[i,file]of manifests.entries()){let[before,after]=manifestTexts[i].map(parseManifest);if(!(before&&after)||unread||present.size===0)continue;let others=(record)=>restOf(record,DEP_FIELDS2),specsBefore=specsOf(before),specsAfter=specsOf(after);if(others(before)!==others(after)||!specsBefore||!specsAfter)continue;let dir=posix3.dirname(file),declared=specChanges(specsBefore,specsAfter);if(![...present.values()].every((lockfile)=>{let specs=lockfile?.workspaces.get(dir);if(!specs)return!1;return[...declared.keys()].every((name)=>DEP_FIELDS2.every((field)=>specs.get(field)?.get(name)===specsAfter.get(field)?.get(name)))}))continue;diff.files.set(file,void 0);for(let[name,[from,to]]of declared)diff.declared.add(name),diff.changes.push({name,detail:`${file}: ${describe(`${name} range`,from,to)}`,file})}return diff}function packageSeeds(graph,config,diff,files){let result={seeds:new Map,notes:[],reasons:[]},{isLoadedByName}=config,loadedOtherwise=(name)=>isLoadedByName===void 0||diff.bins.has(name)||isLoadedByName(name),tested=new Map,reachesTest=(name)=>{let found=tested.get(name);if(found===void 0){let node=`pkg:${name}`;found=graph.has(node)&&config.suites.some((suite)=>reaches(graph,[node],suite.isTest,{includeUnknown:!1,types:suite.types})),tested.set(name,found)}return found},changes=diff.changes.filter((change)=>files.includes(change.file)).sort((a,b)=>byCodeUnit(a.name,b.name)),unused=new Map,seen=new Set;for(let change of changes){let{name,detail}=change;if(seen.has(name))continue;seen.add(name);let closure=new Set([name]),queue=[name];for(let at=0;at<queue.length;at++)for(let dependent of diff.dependents.get(queue[at])??[]){if(closure.has(dependent))continue;closure.add(dependent),queue.push(dependent)}let through=[],covered=!0,importOnly=!1;for(let user of closure){let node=`pkg:${user}`,imported=graph.has(node);if(imported){if(through.push(user),!result.seeds.has(node))result.seeds.set(node,user===name?detail:`${detail}, which ${user} depends on`)}if(!(imported||diff.declared.has(user)||!diff.dependents.has(user))||reachesTest(user)||config.isInert(user))continue;if(loadedOtherwise(user)){covered=!1;let list=unused.get(user)??[];if(user===name)list.unshift(change);else list.push(change);unused.set(user,list)}else importOnly=!0}if(!covered)continue;if(through.length===0){result.notes.push(`${detail}, ${importOnly?"imported by no test":"inert"}`);continue}let others=through.filter((user)=>user!==name),shown=others.slice(0,3).join(", "),rest=others.length>3?` and ${others.length-3} more`:"";result.notes.push(others.length===0?detail:`${detail}, through ${shown}${rest}`)}for(let user of sorted(unused.keys())){let[first,...more]=unused.get(user)??[];if(!first)continue;let own=first.name===user,also=more.length===0?"":` (and ${more.length} more ${more.length===1?"package":"packages"} ${user} depends on)`;result.reasons.push({package:user,file:first.file,message:own?`${first.detail}${also}, and no test imports it`:`${first.detail}, which ${user} depends on${also}, and no test imports ${user}`})}return result}function formatSelection(selection){return selection.mode==="some"?selection.files.join(" "):selection.mode}function select(affected,tests){let files=tests.filter((file)=>affected.has(file));if(files.length===0)return{mode:"none"};if(files.length===tests.length)return{mode:"all"};return{mode:"some",files}}function classify(graph,changed,config,packages,settings){let causes=[],all=config.suites.map((suite)=>suite.name),runAll=(cause)=>causes.push({...cause,suites:all}),relevant=[],quiet=[],packageFiles=[],settingFiles=[];for(let file of changed){let read=graph.has(file),ignored=config.isIgnored(file);if(!read&&ignored)continue;let wired=config.suites.filter((suite)=>suite.isWiring(file)),diffed=packages?.files.has(file)??!1;if(config.isSelf(file)){runAll({kind:"self",file,message:`${file}: test selector changed`});continue}for(let suite of wired)causes.push({kind:"wiring",suites:[suite.name],file,message:`${file}: wires the ${suite.name} suite`});if(wired.length>0&&!diffed)continue;if(diffed){let reason=packages?.files.get(file);if(reason===void 0)packageFiles.push(file);else runAll({kind:"lockfile",file,message:`${file}: ${reason}`})}else if(read||config.roots.some((root)=>inRoot(file,root)))if(ignored)quiet.push(file);else((settings?.has(file))?settingFiles:relevant).push(file);else runAll({kind:"outside",file,message:`${file}: outside the dependency graph`})}return{relevant,quiet,packageFiles,settingFiles,causes}}function narrowedWalk(graph,seeds,{quiet,layout,types},coarse,narrowings){let matched=new Set(narrowings.flatMap((narrowing)=>narrowing.matched)),fine=affectedBy(graph,seeds.filter((seed)=>!matched.has(seed)),{quiet,layout,types});for(let narrowing of narrowings){let walk=affectedBy(graph,[...narrowing.matched,...narrowing.seeds],{opaque:narrowing.narrower.opaque,layout,types});for(let node of walk)fine.add(node)}return new Set([...fine].filter((node)=>coarse.has(node)))}function orphanOf(graph,config,suite,file){if(!suite.roots.some((root)=>inRoot(file,root)))return;if(reaches(graph,[file],(path)=>suite.isTest(path)||suite.isPage(path),{includeUnknown:!1,types:suite.types||DECLARATION.test(file)}))return;let deleted=!graph.has(file);if(deleted&&suite.isTest(file))return;if(deleted&&config.isImportOnly(file))return;if(suite.isNonInput(file))return;return{typed:!suite.types&&reaches(graph,[file],suite.isTest,{includeUnknown:!1})}}function planTests(graph,changed,config,{barrelNames=[],layout=new Set,narrowed=[],packages,settings}={}){let{relevant,quiet,packageFiles,settingFiles,causes}=classify(graph,changed,config,packages,settings),settingCauses=new Map,settingNotes=[];for(let file of settingFiles){let change=settings?.get(file);if(!change)continue;settingNotes.push(change.note);for(let seed of change.seeds)if(!settingCauses.has(seed))settingCauses.set(seed,`governed by ${file}, which changed`)}let bumped=packages&&packageFiles.length>0?packageSeeds(graph,config,packages,packageFiles):{seeds:new Map,notes:[],reasons:[]},all=config.suites.map((suite)=>suite.name);for(let unused of bumped.reasons)causes.push({kind:"package",suites:all,...unused});let seeds=[...relevant,...settingFiles,...settingCauses.keys(),...barrelNames,...packageFiles,...bumped.seeds.keys()],affected=walksByTypes(graph,seeds,{quiet,layout}),nodes=[...graph.keys()],tests=new Map(config.suites.map((suite)=>[suite.name,nodes.filter(suite.isTest)]));for(let suite of config.suites)for(let file of relevant){let orphan=orphanOf(graph,config,suite,file);if(!orphan)continue;let{typed}=orphan;causes.push({kind:"orphan",suites:[suite.name],file,message:`${file}: no ${suite.name} test imports it${typed?" (only type imports reach it: list it in the suite's `nonInputs` if nothing loads it at runtime)":""}`})}let narrowings=new Map;for(let{narrower,result}of narrowed){let matched=relevant.filter(narrower.match);if(matched.length===0)continue;if("all"in result){causes.push({kind:"narrower",suites:narrower.suites,narrower:narrower.name,message:`${narrower.name}: ${result.all}`});continue}for(let name of narrower.suites){let list=narrowings.get(name)??[];list.push({matched,narrower,seeds:result.seeds}),narrowings.set(name,list)}}let full=new Set(causes.flatMap((cause)=>cause.suites)),suites={};for(let suite of config.suites){if(full.has(suite.name)){suites[suite.name]={mode:"all"};continue}let coarse=affected(suite.types),narrowing=narrowings.get(suite.name);suites[suite.name]=select(narrowing?narrowedWalk(graph,seeds,{quiet,layout,types:suite.types},coarse,narrowing):coarse,tests.get(suite.name)??[])}return{suites,reasons:causes.map((cause)=>cause.message),causes,totals:Object.fromEntries(config.suites.map((suite)=>[suite.name,tests.get(suite.name)?.length??0])),full:[...full],packages:bumped.notes,settings:settingNotes,settingCauses,seeds,quiet,layout,packageCauses:bumped.seeds,narrowings}}import{posix as posix5}from"node:path";function plural(count,one,many=`${one}s`){return`${count} ${count===1?one:many}`}import{posix as posix4}from"node:path";var COMMENT2=/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,TRAILING_COMMA=/("(?:[^"\\]|\\.)*")|,(?=\s*[}\]])/g,BOM=/^/,RELATIVE2=/^\.\.?(?:\/|$)/;function parseJsonc(text){return JSON.parse(text.replace(BOM,"").replace(COMMENT2,(_,string)=>string??" ").replace(TRAILING_COMMA,(_,string)=>string??""))}function isStrings2(value){return Array.isArray(value)&&value.every((item)=>typeof item==="string")}function parse2(file,text){let value;try{value=parseJsonc(text)}catch(error){return{error:error instanceof Error?error.message:String(error)}}if(!isRecord2(value))return{error:"not an object"};let dir=posix4.dirname(file),{extends:extended}=value,read={extends:typeof extended==="string"?[extended]:[]};if(isStrings2(extended))read.extends=extended;let options=value.compilerOptions;if(isRecord2(options)){if(typeof options.baseUrl==="string")read.baseUrl=posix4.join(dir,options.baseUrl);if(isRecord2(options.paths)){let map={};for(let[key,targets]of Object.entries(options.paths))if(isStrings2(targets))map[key]=targets;read.paths={map,dir}}}return{read}}function extendsPath(file,target){if(!RELATIVE2.test(target))return;let path=posix4.join(posix4.dirname(file),target);return path.startsWith("../")||path===".."?void 0:path}async function readTsconfigs(files,read){let parsed=new Map,load=async(file,extended)=>{if(parsed.has(file))return;parsed.set(file,void 0);let text=await read(file,extended);if(text===void 0){if(!file.endsWith(".json"))await load(`${file}.json`,!0);return}let result=parse2(file,text);if(parsed.set(file,result),!("read"in result))return;await Promise.all(result.read.extends.map((target)=>{let path=extendsPath(file,target);return path===void 0?void 0:load(path,!0)}))};await Promise.all(files.map((file)=>load(file,!1)));let found=(path)=>{let at=parsed.get(path);if(at!==void 0||path.endsWith(".json"))return at;return parsed.get(`${path}.json`)},effective=(file,seen)=>{let at=found(file);if(at===void 0)return{extends:[]};if(!("read"in at)||seen.has(file))return;let chain=new Set([...seen,file]),merged={extends:[]};for(let target of at.read.extends){let path=extendsPath(file,target);if(path===void 0)continue;let base=effective(path,chain);if(base===void 0)return;if(base.baseUrl!==void 0)merged.baseUrl=base.baseUrl;if(base.paths!==void 0)merged.paths=base.paths}if(at.read.baseUrl!==void 0)merged.baseUrl=at.read.baseUrl;if(at.read.paths!==void 0)merged.paths=at.read.paths;return merged},chain=(file,into)=>{if(into.has(file))return;into.add(file);let at=found(file);if(at===void 0&&!file.endsWith(".json"))into.add(`${file}.json`);if(at===void 0||!("read"in at))return;for(let target of at.read.extends){let path=extendsPath(file,target);if(path!==void 0)chain(path,into)}},tsconfigs=new Map,sources=new Map;for(let file of files){if(parsed.get(file)===void 0)continue;let chained=new Set;chain(file,chained),sources.set(posix4.dirname(file),[...chained]);let options=effective(file,new Set),resolved={paths:{}};if(options?.baseUrl!==void 0)resolved.baseUrl=options.baseUrl;let{paths}=options??{};if(paths){let base=options?.baseUrl??paths.dir;for(let[key,targets]of Object.entries(paths.map))resolved.paths[key]=targets.map((target)=>posix4.join(base,target))}tsconfigs.set(posix4.dirname(file),resolved)}let unparsed=[];for(let file of sorted(parsed.keys())){let at=parsed.get(file);if(at&&"error"in at)unparsed.push({file,reason:at.error})}return{tsconfigs,sources,unparsed}}var METADATA=new Set(["author","bugs","contributors","description","engines","files","funding","homepage","keywords","license","maintainers","private","publishConfig","repository","version"]),MANIFEST2=/(?:^|\/)package\.json$/,TSCONFIG=/(?:^|\/)tsconfig\.json$/;function within(file,dir){return dir==="."||file.startsWith(`${dir}/`)}function governed(files,dirs,dir){let deeper=dirs.filter((other)=>other!==dir&&within(other,dir));return files.filter((file)=>within(file,dir)&&!deeper.some((other)=>within(file,other)))}function parsed(text,jsonc){if(text===void 0)return;try{return jsonc?parseJsonc(text):JSON.parse(text)}catch{return null}}function changedKeys(before,after){if(!(isRecord2(before)&&isRecord2(after)))return;return[...new Set([...Object.keys(before),...Object.keys(after)])].filter((key)=>JSON.stringify(before[key])!==JSON.stringify(after[key]))}async function settingChanges({changed,files,tsconfigs,packages,accounted,base,head}){let tsDirs=[...tsconfigs.keys()],packageDirs=[...packages],candidates=changed.filter((file)=>TSCONFIG.test(file)||MANIFEST2.test(file)&&!accounted.has(file)||tsDirs.some((dir)=>tsconfigs.get(dir)?.includes(file))),texts=await Promise.all(candidates.map((file)=>Promise.all([base(file),head(file)]))),result=new Map;for(let[i,file]of candidates.entries()){let[before,after]=texts[i],manifest=MANIFEST2.test(file),keys=changedKeys(parsed(before,!manifest),parsed(after,!manifest)),counted=keys?.filter((key)=>!(manifest&&METADATA.has(key))),own=posix5.dirname(file),dirs=manifest?[own]:tsDirs.filter((dir)=>tsconfigs.get(dir)?.includes(file));if(TSCONFIG.test(file)&&!dirs.includes(own))dirs.push(own);let all=[...new Set([...manifest?packageDirs:tsDirs,...dirs])];if(keys!==void 0&&counted?.length===0){let what=keys.length===0?"only formatting or comments":`only ${keys.join(", ")}`;result.set(file,{seeds:[],note:`${file}: ${what} changed, so no file resolves or runs differently`});continue}let seeds=[...new Set(dirs.flatMap((dir)=>governed(files,all,dir)))],what=manifest?"resolve or run":"resolve or compile";result.set(file,{seeds,note:`${file}: changes how the ${plural(seeds.length,"file")} it governs ${what}`})}return result}function hasCode(error,codes){return error instanceof Error&&"code"in error&&typeof error.code==="string"&&codes.includes(error.code)}async function readIfFile(path){try{return await readFile3(path,"utf-8")}catch(error){if(hasCode(error,["ENOENT","EISDIR"]))return;throw error}}function collectPackages(rootJson,sources){let packages=new Map,parse=(text)=>{try{return toPackageJson(JSON.parse(text))}catch{return{}}};if(rootJson!==void 0)packages.set(".",parse(rootJson));for(let[path,text]of sources){if(path==="package.json"||!path.endsWith("/package.json"))continue;packages.set(posix6.dirname(path),parse(text))}return packages}var READS_IN_FLIGHT=64;async function inParallel(tasks,limit){let next=0,worker=()=>next<tasks.length?tasks[next++]().then(worker):Promise.resolve();await Promise.all(Array.from({length:Math.min(limit,tasks.length)},worker))}async function isFile(path){try{return(await stat(path)).isFile()}catch(error){if(hasCode(error,["ENOENT","ENOTDIR"]))return!1;throw error}}async function extractRevision(root,revision,cache){let extractions=new Map,texts=new Map,missing=new Set,tasks=[],cached=0,read=async(file)=>{let text=await readIfFile(join4(root,file));if(text===void 0)missing.add(file);return text};for(let file of revision.files)if(SCANNED.test(file)){let format=formatOf(file),oid=revision.blobs.get(file),hit=oid===void 0?void 0:cache.get(oid,format);if(hit){extractions.set(file,hit),cached++;continue}tasks.push(()=>read(file).then((source)=>{if(source===void 0)return;let extraction=extract(format,source);if(extractions.set(file,extraction),oid!==void 0)cache.set(oid,format,extraction)}))}else if(file.endsWith("/package.json"))tasks.push(()=>read(file).then((source)=>{if(source!==void 0)texts.set(file,source)}));else if(!revision.present.has(file))tasks.push(()=>isFile(join4(root,file)).then((found)=>{if(!found)missing.add(file)}));await inParallel(tasks,READS_IN_FLIGHT);let files=revision.files.filter((file)=>!missing.has(file)),manifests=new Map;for(let file of files){let text=texts.get(file);if(text!==void 0)manifests.set(file,text)}return{files,extractions,manifests,extracted:{cached,read:extractions.size-cached}}}function graphView(graph,config){let nodes=[...graph.keys()];return{nodes:()=>nodes,importers:(node)=>importersOf(graph,node),dependents:(from)=>affectedBy(graph,from,{includeUnknown:!1}),tests:(name)=>{let suite=config.suites.find((candidate)=>candidate.name===name);if(!suite)throw Error(`bivium: no suite "${name}"`);return nodes.filter(suite.isTest)}}}function messageOf(error){return error instanceof Error?error.message:String(error)}async function runNarrowers(root,revision,graph,config,suites,packages,settings){let{relevant}=classify(graph,revision.changed,config,packages,settings),wanted=config.narrowers.filter((narrower)=>relevant.some(narrower.match)&&(suites===void 0||narrower.suites.some((name)=>suites.includes(name))));if(wanted.length===0)return[];let view=graphView(graph,config),base={commit:await revision.mergeBase(),read:revision.readBase},head={commit:void 0,read:(path)=>readIfFile(join4(root,path))};return Promise.all(wanted.map(async(narrower)=>{let changed=relevant.filter(narrower.match);try{let result=await narrower.narrow({root,base,head,changed,graph:view});return{narrower,result}}catch(error){return{narrower,result:{all:`failed: ${messageOf(error)}`}}}}))}async function computePlan(root,base,config,{cache:cacheOption=config.cache,suites,mergeBase=!1}={}){let dir=cacheDir(root,cacheOption),[revision,rootJson,cache]=await Promise.all([readRevision(root,base,config.roots,{blobs:dir!==void 0,mergeBase}),readFile3(join4(root,"package.json"),"utf-8").catch(()=>{return}),ExtractionCache.open(dir)]);if(revision.changed.some((file)=>config.narrowers.some((narrower)=>narrower.match(file))))revision.mergeBase();let listed,readTsconfig=async(file,extended)=>{if(extended){if(listed??=new Set(revision.listed),!listed.has(file))return}return readIfFile(join4(root,file))},[{files,extractions,manifests,extracted},ts,packageDiff]=await Promise.all([extractRevision(root,revision,cache),readTsconfigs(["tsconfig.json",...revision.files.filter((file)=>file.endsWith("/tsconfig.json"))],readTsconfig),readPackageDiff(revision.changed,revision.listed,revision.readBase,(path)=>readIfFile(join4(root,path)))]),{tsconfigs}=ts,basePending=new Map(revision.changed.filter((file)=>config.isBarrel(file)&&extractions.get(file)?.barrel).map((file)=>[file,revision.readBase(file)])),packages=collectPackages(rootJson,manifests),graph=graphFrom(files,extractions,{config,packages,tsconfigs}),saved=cache.save(),settings=await settingChanges({changed:revision.changed,files,tsconfigs:ts.sources,packages:packages.keys(),accounted:new Set(packageDiff?.files.keys()),base:revision.readBase,head:(path)=>readIfFile(join4(root,path))}),barrelNames=(await Promise.all([...basePending].map(async([file,pending])=>{let head=graph.get(file)?.barrel;if(!head)return[];let before=baseBarrelNames(file,await pending,{config,packages,tsconfigs},graph);return(before?changedBarrelNames(before,head):[...head.keys()]).map((name)=>`${file}#${name}`)}))).flat(),narrowed=await runNarrowers(root,revision,graph,config,suites,packageDiff,settings),planned=planTests(graph,revision.changed,config,{barrelNames,layout:revision.layout,narrowed,packages:packageDiff,settings});return await saved,{plan:planned,graph,changed:revision.changed,mergeBase:revision.mergeBase,barrelNames,narrowed,packages,tsconfigs,unparsedTsconfigs:ts.unparsed,extractions,listed:revision.listed,fallbacks:new Map([...extractions].flatMap(([file,extraction])=>extraction.fallback===void 0?[]:[[file,extraction.fallback]])),extracted}}async function prepare({cwd=process.cwd(),base,config,configFile}){let root=resolve2(cwd),resolved;if(config)resolved=resolveConfig(checkConfig(config));else{let loaded=await loadConfig(root,configFile),isSelf=loaded.config.isSelf;resolved={...loaded.config,file:loaded.file,isSelf:(path)=>path===loaded.file||isSelf(path)}}return{root,base:base??resolved.base??await defaultBase(root),config:resolved}}async function plan2(options={}){let{root,base,config}=await prepare(options),computed=await computePlan(root,base,config,{...options.cache!==void 0&&{cache:options.cache},mergeBase:!0});return{suites:computed.plan.suites,reasons:computed.plan.reasons,causes:computed.plan.causes,totals:computed.plan.totals,packages:computed.plan.packages,base,mergeBase:await computed.mergeBase(),changed:computed.changed,narrowed:computed.narrowed.map(({narrower,result})=>({name:narrower.name,result}))}}
|
|
10
|
+
export{version,globToRegExp,defineConfig2,inRoot,sorted,QUERY,UNDECLARED_READS,RELATIVE,aliasPath,createResolver,SCANNED,formatOf,extract,stringsOf,finish,gotoPage,walksByTypes,importersOf,affectedBy,formatSelection,orphanOf,plural,computePlan,prepare,plan2};
|
package/shared-8v4dra0r.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{readFile as readFile3,stat as stat2}from"node:fs/promises";import{join as join4,posix as posix6,resolve as resolve2}from"node:path";import{existsSync}from"node:fs";import{mkdir,readFile,rename,unlink,writeFile}from"node:fs/promises";import{isAbsolute,join}from"node:path";var version="0.3.2";var SCANNER_VERSION=6,MAGIC="bivium-extractions",FILE="extractions.json";function isHeader(value){return typeof value==="object"&&value!==null&&"magic"in value&&value.magic===MAGIC&&"bivium"in value&&value.bivium===version&&"scanner"in value&&value.scanner===SCANNER_VERSION&&"rows"in value&&typeof value.rows==="number"&&"strings"in value&&typeof value.strings==="number"}function cacheDir(root,cache){if(cache===!1)return;if(typeof cache==="string")return isAbsolute(cache)?cache:join(root,cache);let modules=join(root,"node_modules");return existsSync(modules)?join(modules,".cache","bivium"):join(root,".bivium","cache")}class ExtractionCache{#rows=new Map;#strings=[];#used=new Map;#dirty=!1;dir;constructor(dir){this.dir=dir}static async open(dir){let cache=new ExtractionCache(dir);if(!dir)return cache;let text=await readFile(join(dir,FILE),"utf-8").catch(()=>"");if(text)cache.#load(text);return cache}#load(text){try{let parsed=JSON.parse(text);if(!Array.isArray(parsed))return;let[header,strings,rows]=parsed;if(!isHeader(header)||!Array.isArray(strings)||!Array.isArray(rows)||header.strings!==strings.length||header.rows!==rows.length)return;this.#strings=strings;for(let row of rows)if(Array.isArray(row)&&typeof row[0]==="string")this.#rows.set(row[0],row)}catch{}}get size(){return this.#rows.size}get(oid,format){let key=`${format}:${oid}`,used=this.#used.get(key);if(used)return used;let row=this.#rows.get(key);if(!row)return;let extraction;try{extraction=decode(row,this.#strings)}catch{this.#rows.delete(key);return}return this.#used.set(key,extraction),extraction}set(oid,format,extraction){let key=`${format}:${oid}`;this.#used.set(key,extraction),this.#dirty=!0}async save(){if(!this.dir||!this.#dirty)return;let table=new Strings,rows=[];for(let[key,extraction]of this.#used)rows.push(encode(key,extraction,table));let stale=Math.floor(this.#used.size/2);for(let[key,row]of this.#rows){if(stale===0)break;if(this.#used.has(key))continue;try{rows.push(encode(key,decode(row,this.#strings),table)),stale--}catch{}}let header={magic:MAGIC,bivium:version,scanner:SCANNER_VERSION,rows:rows.length,strings:table.list.length},file=join(this.dir,FILE),temp=`${file}.${process.pid}.${Date.now()}.tmp`;try{await mkdir(this.dir,{recursive:!0});let ignore=join(this.dir,".gitignore");if(!existsSync(ignore))await writeFile(ignore,`*
|
|
2
|
-
`);await writeFile(temp,JSON.stringify([header,table.list,rows])),await rename(temp,file),this.#dirty=!1}catch{await unlink(temp).catch(()=>{return})}}}class Strings{list=[];#ids=new Map;id(value){let id=this.#ids.get(value);if(id===void 0)id=this.list.length,this.list.push(value),this.#ids.set(value,id);return id}ids(values){return values.length===0?0:values.map((value)=>this.id(value))}}function typeIndexes(imports){let indexes=[];for(let[i,ref]of imports.entries())if(ref.type)indexes.push(i);return indexes.length===0?0:indexes}function encode(key,e,table){let imports=e.imports.map(({specifier,names})=>names?[table.id(specifier),...names.map((n)=>table.id(n))]:table.id(specifier)),barrel=e.barrel&&[[...e.barrel.names].flatMap(([name,from])=>[table.id(name),table.id(from)]),table.ids(e.barrel.stars)];return[key,imports.length===0?0:imports,table.ids(e.globs),table.ids(e.gotos),table.ids(e.dependsOn),table.ids(e.reads),table.ids(e.unknown),e.fallback===void 0?0:table.id(e.fallback),barrel??0,typeIndexes(e.imports),table.ids(e.lists)]}function decode(row,strings){let str=(id)=>{let value=typeof id==="number"?strings[id]:void 0;if(typeof value!=="string")throw Error("bad string id");return value},list=(ids)=>{if(ids===0)return[];if(!Array.isArray(ids))throw Error("bad list");return ids.map(str)},refs=row[1]===0?[]:row[1];if(!Array.isArray(refs))throw Error("bad imports");let imports=refs.map((item)=>Array.isArray(item)?{specifier:str(item[0]),names:item.slice(1).map(str)}:{specifier:str(item)});if(row[9]!==0){if(!Array.isArray(row[9]))throw Error("bad types");for(let i of row[9]){let ref=typeof i==="number"?imports[i]:void 0;if(!ref)throw Error("bad type index");ref.type=!0}}let extraction={imports,globs:list(row[2]),gotos:list(row[3]),dependsOn:list(row[4]),reads:list(row[5]),lists:list(row[10]),unknown:list(row[6])};if(row[7]!==0)extraction.fallback=str(row[7]);if(row[8]!==0){if(!Array.isArray(row[8]))throw Error("bad barrel");let[pairs,stars]=row[8];if(!Array.isArray(pairs))throw Error("bad barrel names");let names=new Map;for(let i=0;i<pairs.length;i+=2)names.set(str(pairs[i]),str(pairs[i+1]));extraction.barrel={names,stars:list(stars)}}return extraction}import{existsSync as existsSync2,readFileSync}from"node:fs";import{isAbsolute as isAbsolute2,join as join2,relative,resolve}from"node:path";import{pathToFileURL}from"node:url";var GLOB_LITERAL=/[.+^$()|[\]\\]/g,REGEX_SPECIAL=/[.*+?^${}()|[\]\\]/g,DIGIT=/[0-9]/,CAPTURE_REFERENCE=/\$(\d+)/g;function compile(glob,{capture=!1,captures}={}){let source="",wildcards=0,group=(body)=>(wildcards++,capture?`(${body})`:body);for(let i=0;i<glob.length;i++){let char=glob[i];if(captures&&char==="$"&&DIGIT.test(glob[i+1]??"")){let end=i+1;while(DIGIT.test(glob[end]??""))end++;let text=captures[Number(glob.slice(i+1,end))-1];source+=text===void 0?".*":text.replace(REGEX_SPECIAL,"\\$&"),i=end-1}else if(char==="*"&&glob[i+1]==="*"){let slash=glob[i+2]==="/";source+=group(slash?"(?:.*/)?":".*"),i+=slash?2:1}else if(char==="*")source+=group("[^/]*");else if(char==="?")source+=group("[^/]");else if(char==="{")wildcards++,source+=capture?"(":"(?:";else if(char==="}")source+=")";else if(char===",")source+="|";else source+=char.replace(GLOB_LITERAL,"\\$&")}return{source:`^${source}$`,wildcards}}function globToRegExp(glob){return new RegExp(compile(glob).source)}function captureGlob(glob){let{source,wildcards}=compile(glob,{capture:!0});return{pattern:new RegExp(source),wildcards}}function captureReferences(glob){return[...glob.matchAll(CAPTURE_REFERENCE)].map((match)=>Number(match[1]))}function expandGlob(glob,captures){return new RegExp(compile(glob,{captures}).source)}function matcher(globs=[]){let list=typeof globs==="string"?[globs]:globs;if(list.length===0)return()=>!1;let res=list.map(globToRegExp);return(path)=>res.some((re)=>re.test(path))}function defineConfig2(config){return config}var DEFAULT_EXTENSIONS=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".d.ts",".svelte",".vue",".json"];function list(value,fallback){if(value===void 0)return[...fallback];return typeof value==="string"?[value]:[...value]}var LEADING_DOT_SLASH=/^\.\//,TRAILING_SLASHES=/\/+$/;function normalizeRoot(root){return root.replace(LEADING_DOT_SLASH,"").replace(TRAILING_SLASHES,"")||"."}function pathMaps(record={}){return Object.entries(record).map(([key,globs])=>{let{pattern,wildcards}=captureGlob(key),values=list(globs,[]),fixed=values.map((value)=>captureReferences(value).length===0?globToRegExp(value):void 0);return{key,exact:wildcards===0,pattern,values,targets:(path)=>{let match=pattern.exec(path);if(!match)return;let captures=match.slice(1);return values.map((value,i)=>fixed[i]??expandGlob(value,captures))}}})}function resolveConfig(config){let names=Object.keys(config.suites);if(names.length===0)throw Error("bivium config: no suites");let suites=Object.entries(config.suites).map(([name,suite])=>({name,isTest:matcher(suite.tests),run:suite.run,roots:list(suite.root,["."]).map(normalizeRoot),urls:Object.entries(suite.urls??{}).map(([key,targets])=>({key,targets:list(targets,[])})),isPage:matcher(suite.pages),isWiring:matcher(suite.wiring),isSetup:matcher(suite.setup),setup:list(suite.setup,[]),isNonInput:matcher(suite.nonInputs),output:suite.output??`${name}-tests`,types:suite.types??!0})),narrowers=(config.narrowers??[]).map((narrower)=>{let unknown=narrower.suites?.find((name)=>!names.includes(name));if(unknown!==void 0)throw Error(`bivium config: narrower ${narrower.name} names no suite ${unknown}`);return{name:narrower.name,match:matcher(narrower.match),opaque:matcher(narrower.opaque),suites:[...narrower.suites??names],narrow:async(context)=>checkResult(await narrower.narrow(context))}});return{suites,narrowers,roots:list(config.roots,["."]).map(normalizeRoot),isIgnored:matcher(config.ignore),alias:Object.entries(config.alias??{}).map(([key,path])=>[key.replace(TRAILING_SLASHES,"")||key,normalizeRoot(path)]).sort(([a],[b])=>b.length-a.length),generated:pathMaps(config.edges),reads:pathMaps(config.reads),isSelf:matcher(config.self),isImportOnly:matcher(config.importOnly),isHermetic:matcher(config.hermetic),isBarrel:config.barrels?matcher(config.barrels):()=>!0,external:new Set(config.external),isInert:matcher(config.inert),...config.loadedByName!==void 0&&{isLoadedByName:matcher(config.loadedByName)},extensions:config.extensions??DEFAULT_EXTENSIONS,deadGlobs:config.deadGlobs??[],...config.knownUnknowns&&{knownUnknowns:config.knownUnknowns},base:config.base,cache:config.cache}}function inRoot(file,root){return root==="."||file===root||file.startsWith(`${root}/`)}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isStrings(value){return Array.isArray(value)&&value.every((item)=>typeof item==="string")}function isGlobs(value){return typeof value==="string"||isStrings(value)}function isStringRecord(value){return isRecord(value)&&Object.values(value).every((item)=>typeof item==="string")}function isGlobsRecord(value){return isRecord(value)&&Object.values(value).every(isGlobs)}function isBoolean(value){return typeof value==="boolean"}function isString(value){return typeof value==="string"}function isCache(value){return typeof value==="boolean"||typeof value==="string"}function field(record,key,is,path,expected){let value=record[key];if(value===void 0||is(value))return value;throw Error(`bivium config: ${path}${key} must be ${expected}`)}var SUITE_KEYS=new Set(["tests","run","root","urls","pages","wiring","setup","nonInputs","output","types"]),NARROWER_KEYS=new Set(["name","match","opaque","suites","narrow"]),DEAD_GLOB_KEYS=new Set(["file","glob","reason"]),KNOWN_UNKNOWN_KEYS=new Set(["file","reason"]),CONFIG_KEYS=new Set(["suites","narrowers","roots","ignore","alias","edges","reads","self","importOnly","hermetic","barrels","external","inert","loadedByName","extensions","deadGlobs","knownUnknowns","base","cache"]);function checkKeys(record,known,path){for(let key of Object.keys(record))if(!known.has(key))throw Error(`bivium config: unknown key ${path}${key}`)}function checkSuite(name,value){if(!isRecord(value))throw Error(`bivium config: suites.${name} must be an object`);let at=`suites.${name}.`;checkKeys(value,SUITE_KEYS,at);let tests=field(value,"tests",isGlobs,at,"a glob or a list of globs");if(tests===void 0||tests.length===0)throw Error(`bivium config: suite ${name} has no tests`);let globs="a glob or a list of globs";return{tests,run:field(value,"run",isString,at,"a command"),root:paths(value,"root",at),urls:field(value,"urls",isGlobsRecord,at,"a map of URL patterns"),pages:field(value,"pages",isGlobs,at,globs),wiring:field(value,"wiring",isGlobs,at,globs),setup:field(value,"setup",isGlobs,at,globs),nonInputs:field(value,"nonInputs",isGlobs,at,globs),output:field(value,"output",isString,at,"an output name"),types:field(value,"types",isBoolean,at,"a boolean")}}var WILDCARD=/[*?{}[\]]/;function paths(record,key,at){let value=field(record,key,isGlobs,at,"a path or a list of paths");for(let path of typeof value==="string"?[value]:value??[]){let wildcard=WILDCARD.exec(path);if(!wildcard)continue;let prefix=normalizeRoot(path.slice(0,wildcard.index));throw Error(`bivium config: ${at}${key} takes paths, not globs: "${path}" (the directory is "${prefix}")`)}return value}function isResult(value){if(!isRecord(value))return!1;if("all"in value)return typeof value.all==="string";return"seeds"in value&&isStrings(value.seeds)&&(!("note"in value)||typeof value.note==="string")}function checkResult(value){if(isResult(value))return value;throw Error("returned neither { seeds: string[] } nor { all: string }")}function checkNarrower(value,at){if(!isRecord(value))throw Error(`bivium config: ${at} must be an object`);checkKeys(value,NARROWER_KEYS,`${at}.`);let name=field(value,"name",isString,`${at}.`,"a string"),match=field(value,"match",isGlobs,`${at}.`,"globs"),opaque=field(value,"opaque",isGlobs,`${at}.`,"globs"),suites=field(value,"suites",isStrings,`${at}.`,"suite names"),{narrow}=value;if(name===void 0||match===void 0||opaque===void 0)throw Error(`bivium config: ${at} needs a name, match and opaque`);if(typeof narrow!=="function")throw Error(`bivium config: ${at}.narrow must be a function`);return{name,match,opaque,suites,narrow:async(context)=>{let result=await Reflect.apply(narrow,value,[context]);return checkResult(result)}}}function checkDeadGlob(value,at){if(!isRecord(value))throw Error(`bivium config: ${at} must be an object`);checkKeys(value,DEAD_GLOB_KEYS,`${at}.`);let file=field(value,"file",isString,`${at}.`,"a path"),glob=field(value,"glob",isString,`${at}.`,"a glob"),reason=field(value,"reason",isString,`${at}.`,"a string");if(!(file&&glob&&reason))throw Error(`bivium config: ${at} needs a file, glob and reason`);return{file,glob,reason}}function checkKnownUnknown(value,at){if(!isRecord(value))throw Error(`bivium config: ${at} must be an object`);checkKeys(value,KNOWN_UNKNOWN_KEYS,`${at}.`);let file=field(value,"file",isString,`${at}.`,"a path"),reason=field(value,"reason",isString,`${at}.`,"a string");if(!(file&&reason))throw Error(`bivium config: ${at} needs a file and reason`);return{file,reason}}function checkCaptures(name,record){for(let[key,globs]of Object.entries(record??{})){let{wildcards}=captureGlob(key);for(let value of list(globs,[])){let bad=captureReferences(value).find((n)=>n<1||n>wildcards);if(bad===void 0)continue;let has=`${wildcards} ${wildcards===1?"wildcard":"wildcards"}`,why=bad<1?"captures count from $1":`its key has ${has}`;throw Error(`bivium config: ${name}["${key}"] refers to $${bad} in ${value}, but ${why}`)}}}function checkConfig(value){if(!isRecord(value))throw Error("bivium config: not an object");if(!isRecord(value.suites))throw Error("bivium config: suites must be an object");checkKeys(value,CONFIG_KEYS,"");let{narrowers,deadGlobs,knownUnknowns}=value;if(narrowers!==void 0&&!Array.isArray(narrowers))throw Error("bivium config: narrowers must be a list");if(deadGlobs!==void 0&&!Array.isArray(deadGlobs))throw Error("bivium config: deadGlobs must be a list");if(knownUnknowns!==void 0&&!Array.isArray(knownUnknowns))throw Error("bivium config: knownUnknowns must be a list");let suites={};for(let[name,suite]of Object.entries(value.suites))suites[name]=checkSuite(name,suite);let globs="a glob or a list of globs",edges=field(value,"edges",isGlobsRecord,"","a map of globs"),reads=field(value,"reads",isGlobsRecord,"","a map of globs");return checkCaptures("edges",edges),checkCaptures("reads",reads),{suites,narrowers:narrowers?.map((narrower,i)=>checkNarrower(narrower,`narrowers[${i}]`)),roots:paths(value,"roots",""),ignore:field(value,"ignore",isGlobs,"",globs),alias:field(value,"alias",isStringRecord,"","a map of paths"),edges,reads,self:field(value,"self",isGlobs,"",globs),importOnly:field(value,"importOnly",isGlobs,"",globs),hermetic:field(value,"hermetic",isGlobs,"",globs),barrels:field(value,"barrels",isGlobs,"",globs),external:field(value,"external",isStrings,"","a list of packages"),inert:field(value,"inert",isGlobs,"",globs),loadedByName:field(value,"loadedByName",isGlobs,"",globs),extensions:field(value,"extensions",isStrings,"","a list"),deadGlobs:deadGlobs?.map((entry,i)=>checkDeadGlob(entry,`deadGlobs[${i}]`)),knownUnknowns:knownUnknowns?.map((entry,i)=>checkKnownUnknown(entry,`knownUnknowns[${i}]`)),base:field(value,"base",isString,"","a ref"),cache:field(value,"cache",isCache,"","a directory or a boolean")}}var CONFIG_FILES=["bivium.config.ts","bivium.config.mts","bivium.config.mjs","bivium.config.js","bivium.config.json"];async function readConfig(file){if(file.endsWith(".json"))return JSON.parse(readFileSync(file,"utf-8"));let module=await import(pathToFileURL(file).href);return isRecord(module)?module.default:void 0}async function loadConfig(root,path){let file=path===void 0?CONFIG_FILES.map((name)=>join2(root,name)).find((f)=>existsSync2(f)):resolve(process.cwd(),path);if(!file||!existsSync2(file))throw Error(`bivium: no config found${path?` at ${path}`:` in ${root}`}`);let inside=relative(root,file);return{config:resolveConfig(checkConfig(await readConfig(file))),file:inside.startsWith("..")||isAbsolute2(inside)?file:inside}}import{spawn}from"node:child_process";import{readFile as readFile2,stat}from"node:fs/promises";import{resolve as absolute,dirname,join as join3}from"node:path";function byCodeUnit(a,b){if(a===b)return 0;return a<b?-1:1}function sorted(values){return[...values].sort(byCodeUnit)}function git(cwd,...args){return new Promise((resolve,reject)=>{let child=spawn("git",args,{cwd}),chunks=[];child.stdout.on("data",(chunk)=>chunks.push(chunk)),child.on("error",reject),child.on("close",(status)=>{resolve({status:status??1,stdout:Buffer.concat(chunks).toString("utf-8")})})})}async function gitOrThrow(cwd,...args){let result=await git(cwd,...args);if(result.status!==0)throw Error(`git ${args.join(" ")} failed`);return result.stdout}function lines(output){return output.split(`
|
|
3
|
-
`).filter(Boolean)}var INDEX_ENTRY=/^(\S) (\d{6}) ([0-9a-f]+) (\d)\t(.*)$/,RAW_ENTRY=/^:(\d{6}) \d{6} ([0-9a-f]+) [0-9a-f]+ ([A-Z])\d*\t(.*)$/;function mergeBaseOf(cwd,base){let pending;return()=>{if(pending===void 0)pending=gitOrThrow(cwd,"merge-base",base,"HEAD").then((out)=>out.trim()),pending.catch(()=>{return});return pending}}async function readRevision(cwd,base,roots,{blobs=!1,mergeBase:eager=!1}={}){let mergeBase=mergeBaseOf(cwd,base);if(eager)mergeBase();let diffArgs=["--no-renames","--merge-base",base],promisor=promisorRemote(cwd).catch(()=>{return}),[listing,diff,staged]=await Promise.all([gitOrThrow(cwd,"ls-files","-s","-v","-o","--exclude-standard"),gitOrThrow(cwd,"diff","--raw","--no-abbrev",...diffArgs),gitOrThrow(cwd,"diff","--cached","--name-only",...diffArgs)]),entries=lines(listing),untracked=[];for(let line of entries)if(line.startsWith("? "))untracked.push(line.slice(2));let before=new Map,diffed=[],layout=new Set(untracked);for(let line of lines(diff)){let entry=RAW_ENTRY.exec(line);if(!entry)throw Error(`git diff: unexpected line ${line}`);let[,mode,oid,status,path]=entry;if(diffed.push(path),status==="A"||status==="D")layout.add(path);if(status==="A")before.set(path,void 0);else if("MTD".includes(status)&&mode!=="160000")before.set(path,oid)}let blob=blobReader(cwd,promisor),reads=new Map,readBase=(path)=>{let read=reads.get(path);if(read===void 0)read=readBaseOnce(path),reads.set(path,read);return read},readBaseOnce=(path)=>{if(!before.has(path)){if(present.has(path))return readFile2(join3(cwd,path),"utf-8").catch(()=>mergeBase().then((commit)=>show(cwd,`${commit}:${path}`)));return mergeBase().then((commit)=>show(cwd,`${commit}:${path}`))}let oid=before.get(path);return oid===void 0?Promise.resolve(void 0):blob(oid)},changed=[...new Set([...diffed,...untracked])],dirty=new Set([...changed,...lines(staged)]),underRoots=(path)=>roots.some((root)=>inRoot(path,root)),files=new Set,tracked=new Set,present=new Set,oids=new Map;for(let line of entries){let entry=INDEX_ENTRY.exec(line);if(!entry){if(line.startsWith("? ")&&underRoots(line.slice(2)))files.add(line.slice(2));continue}let[,tag,mode,oid,stage,path]=entry;if(tracked.add(path),mode==="160000"||!underRoots(path))continue;if(files.add(path),dirty.has(path)||stage!=="0"||tag!=="H")continue;if(mode!=="100644"&&mode!=="100755")continue;if(present.add(path),blobs)oids.set(path,oid)}return{files:sorted(files),listed:[...tracked,...untracked],changed,layout,mergeBase,readBase,blobs:oids,present}}var SECTION=/^\s*\[\s*([^\s\]"]+)(?:\s+"([^"]*)")?\s*\]/,ENTRY=/^\s*([\w.-]+)\s*=\s*(.*?)\s*$/;async function gitDir(cwd){for(let dir=absolute(cwd);;dir=dirname(dir)){let dotGit=join3(dir,".git"),found=await stat(dotGit).catch(()=>{return});if(found?.isDirectory())return dotGit;if(found?.isFile()){let text=await readFile2(dotGit,"utf-8").catch(()=>""),named=GITDIR.exec(text)?.[1];if(named===void 0)return;let worktree=absolute(dir,named);return readFile2(join3(worktree,"commondir"),"utf-8").then((common)=>absolute(worktree,common.trim())).catch(()=>worktree)}if(dirname(dir)===dir)return}}var GITDIR=/^gitdir:\s*(.+?)\s*$/m;async function promisorRemote(cwd){let dir=await gitDir(cwd);if(dir===void 0)return;let text=await readFile2(join3(dir,"config"),"utf-8").catch(()=>{return});if(text===void 0)return;let section="",name="";for(let line of text.split(`
|
|
4
|
-
`)){let header=SECTION.exec(line);if(header){section=header[1].toLowerCase(),name=header[2]??"";continue}let entry=ENTRY.exec(line);if(!entry)continue;let key=entry[1].toLowerCase(),value=entry[2];if(section==="extensions"&&key==="partialclone")return value;if(section==="remote"&&key==="promisor"&&value==="true")return name}return}function blobReader(cwd,remote){let queue=[],batch,prefetch=async(oids)=>{let name=await remote;if(name===void 0)return;let listed=await git(cwd,"rev-list","--objects","--no-walk","--missing=print",...oids),missing=lines(listed.stdout).filter((line)=>line.startsWith("?")).map((line)=>line.slice(1));if(missing.length===0)return;await git(cwd,"-c","fetch.negotiationAlgorithm=noop","fetch","--quiet","--no-tags","--no-write-fetch-head","--recurse-submodules=no","--filter=blob:none",name,...missing)};return(oid)=>(queue.push(oid),batch??=Promise.resolve().then(()=>{let oids=queue;return queue=[],batch=void 0,prefetch([...new Set(oids)]).catch(()=>{return})}),batch.then(()=>show(cwd,oid)))}async function show(cwd,object){let result=await git(cwd,"show",object);return result.status===0?result.stdout:void 0}async function defaultBase(cwd){let head=await git(cwd,"symbolic-ref","--short","refs/remotes/origin/HEAD");if(head.status===0&&head.stdout.trim())return head.stdout.trim();let refs=["origin/main","origin/master","main","master"],found=await Promise.all(refs.map((ref)=>git(cwd,"rev-parse","--verify","--quiet",ref))),branch=refs.find((_,i)=>found[i].status===0);if(branch)return branch;throw Error("bivium: no base given and no default branch found")}var COMMENTS=/\/\/.*$|\/\*[\s\S]*?\*\//gm,AS=/\s+as\s+/,TYPE_PREFIX=/^type\s+/,NAMED_EXPORT=/export\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']\s*;?/g,STAR_EXPORT=/export\s+(?:type\s+)?\*(?:\s+as\s+([\w$]+))?\s+from\s*["']([^"']+)["']\s*;?/g,BARREL_FILE=/\.[cm]?[jt]sx?$/,ONLY_SEPARATORS=/^[\s;]*$/,STARTS_WITH_EXPORT=/^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*export\b/;function parseBarrel(path,source){return BARREL_FILE.test(path)?parseReExports(source):void 0}function parseReExports(source){if(!STARTS_WITH_EXPORT.test(source))return;let code=source.replace(COMMENTS,""),barrel={names:new Map,stars:[]},rest=code.replace(NAMED_EXPORT,(_,list,from)=>{for(let part of list.split(",")){let name=part.trim().replace(TYPE_PREFIX,"").split(AS).pop();if(name)barrel.names.set(name,from)}return""});if(rest=rest.replace(STAR_EXPORT,(_,name,from)=>{if(name)barrel.names.set(name,from);else barrel.stars.push(from);return""}),barrel.names.size+barrel.stars.length===0)return;return ONLY_SEPARATORS.test(rest)?barrel:void 0}import{builtinModules}from"node:module";import{posix}from"node:path";var QUERY=/[?#].*$/,UNDECLARED_READS="reads the disk without @depends-on",RELATIVE=/^\.\.?(?:\/|$)/,URL_REF=/^[a-z]+:|^\/\//,LIST_SEPARATOR=/[\s,]+(?![^{]*\})/,DEPENDS_ON=/^\s*(?:\/\/|\/?\*+)\s*@depends-on\s+(.+?)\s*(?:\*\/)?\s*$/gm,READS=/^\s*(?:\/\/|\/?\*+)\s*@reads\s+(.+?)\s*(?:\*\/)?\s*$/gm,LISTS=/^\s*(?:\/\/|\/?\*+)\s*@lists\s+(.+?)\s*(?:\*\/)?\s*$/gm,GLOB_REGISTRY=/^\s*(?:\/\/|\/?\*+)\s*@glob-registry\b/m,AS2=/\s+as\s+/,TYPE_PREFIX2=/^type\s+/,NAMED_CLAUSE=/\{([^}]*)\}/,DEFAULT_OR_NAMESPACE=/^\s*[\w$*]/;function namedBindings(clause){let named=NAMED_CLAUSE.exec(clause);if(!named||DEFAULT_OR_NAMESPACE.test(clause.replace(NAMED_CLAUSE,"")))return;return named[1].split(",").map((part)=>part.trim().replace(TYPE_PREFIX2,"").split(AS2)[0].trim()).filter(Boolean)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isStringRecord2(value){return isRecord2(value)&&Object.values(value).every((item)=>typeof item==="string")}function toPackageJson(value){if(!isRecord2(value))return{};let json={};if(typeof value.name==="string")json.name=value.name;if(value.exports!==void 0)json.exports=value.exports;if(isRecord2(value.imports))json.imports=value.imports;if(typeof value.main==="string")json.main=value.main;let{sideEffects}=value;if(typeof sideEffects==="boolean"||Array.isArray(sideEffects)&&sideEffects.every((glob)=>typeof glob==="string"))json.sideEffects=sideEffects;for(let field of DEP_FIELDS){let deps=value[field];if(isStringRecord2(deps))json[field]=deps}return json}var BUILTINS=new Set(builtinModules),RUNTIME_BUILTIN=/^(?:node:|bun(?:$|:))/,JS_EXTENSION=/\.(?:js|jsx|mjs|cjs)$/,TS_SOURCES={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]},NODE_PREFIX=/^node:/,INVALID_IMPORT_TARGET=/^[./#]/,SVELTEKIT_ASSETS="./%sveltekit.assets%/",INDEX="/index",SVELTE_CONFIGS=["js","mjs","cjs","ts","mts"].map((ext)=>`svelte.config.${ext}`),DEP_FIELDS=["dependencies","devDependencies","peerDependencies","optionalDependencies"];function packageName(specifier){let parts=specifier.split("/");return specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0]}function builtin(specifier){if(RUNTIME_BUILTIN.test(specifier)){let name=specifier.replace(NODE_PREFIX,"");return specifier.startsWith("bun")?specifier:`node:${name.split("/")[0]}`}let name=specifier.split("/")[0];return BUILTINS.has(specifier)||BUILTINS.has(name)?`node:${name}`:void 0}function targets(value,out=[]){if(typeof value==="string")out.push(value);else if(Array.isArray(value))for(let item of value)targets(item,out);else if(value&&typeof value==="object")for(let item of Object.values(value))targets(item,out);return out}function subpathMap(exports){if(typeof exports==="string"||Array.isArray(exports))return{".":exports};if(!isRecord2(exports))return;return Object.keys(exports).some((key)=>key.startsWith("."))?exports:{".":exports}}function mapTargets(map,subpath){if(subpath in map&&!subpath.includes("*"))return targets(map[subpath]);let best;for(let key of Object.keys(map)){let star=key.indexOf("*");if(star===-1)continue;let prefix=key.slice(0,star),suffix=key.slice(star+1);if(subpath.length>=key.length-1&&subpath.startsWith(prefix)&&subpath.endsWith(suffix)&&(!best||prefix.length>best.key.indexOf("*")||prefix.length===best.key.indexOf("*")&&key.length>best.key.length))best={key,match:subpath.slice(prefix.length,subpath.length-suffix.length)}}if(!best)return;let{match}=best;return targets(map[best.key]).map((target)=>target.replaceAll("*",match))}function exportTargets(exports,subpath){let map=subpathMap(exports);return map&&mapTargets(map,subpath)}function byDepth(packages){return[...packages].sort(([a],[b])=>b.length-a.length)}function owner(packages,file){return byDepth(packages).find(([dir])=>dir==="."||file.startsWith(`${dir}/`))}function aliasPath([key,target],specifier){if(specifier!==key&&!specifier.startsWith(`${key}/`))return;let rest=specifier.slice(key.length+1);if(target===".")return posix.normalize(rest||".");return posix.normalize(rest?`${target}/${rest}`:target)}function createResolver({files,config,packages,tsconfigs=new Map}){let generated=(path)=>config.generated.some(({pattern})=>pattern.test(path)),{extensions}=config,exists=(path)=>files.has(path),suffixed=new Map,indexes=new Map,byTail=[],undotted=[];for(let i=0;i<extensions.length;i++){let ext=extensions[i],dot=ext.lastIndexOf(".");if(dot===-1)undotted.push(i);else{let list=byTail[ext.length-dot];if(list)list.push(i);else byTail[ext.length-dot]=[i]}}let addSuffixed=(i,file)=>{let ext=extensions[i];if(!file.endsWith(ext))return;let base=file.slice(0,file.length-ext.length),list=suffixed.get(base);if(list)list.push([i,file]);else{let created=[[i,file]];if(suffixed.set(base,created),base.endsWith(INDEX))indexes.set(base.slice(0,-INDEX.length),created)}};for(let file of files){let dot=file.lastIndexOf(".");if(dot!==-1)for(let i of byTail[file.length-dot]??[])addSuffixed(i,file);for(let i of undotted)addSuffixed(i,file)}for(let list of suffixed.values())if(list.length>1)list.sort(([a],[b])=>a-b);let deepestFirst=byDepth(packages),local=new Map;for(let[dir,json]of deepestFirst)if(json.name&&!local.has(json.name))local.set(json.name,dir);let declaredIn=(dir)=>{let names=new Set;for(let[pkgDir,json]of deepestFirst){if(pkgDir!=="."&&dir!==pkgDir&&!dir.startsWith(`${pkgDir}/`))continue;for(let field of DEP_FIELDS)for(let name of Object.keys(json[field]??{}))names.add(name)}return names},tsSources=(path)=>{let js=JS_EXTENSION.exec(path);if(!js)return[];let stem=path.slice(0,js.index);return(TS_SOURCES[js[0]]??[]).map((ext)=>stem+ext).filter((file)=>generated(file)||exists(file))},exact=(path)=>generated(path)||exists(path)?[path]:tsSources(path),probe=(base,guess=!1)=>{if(generated(base))return[base];let found=[];if(exists(base))found.push(base);for(let[,file]of suffixed.get(base)??[])found.push(file);if(found.length===0)found.push(...tsSources(base));for(let[,file]of indexes.get(base)??[])found.push(file);if(found.length===0&&!guess&&config.generated.length>0){for(let ext of extensions)if(generated(base+ext))found.push(base+ext);for(let ext of extensions)if(generated(`${base}/index${ext}`))found.push(`${base}/index${ext}`)}return found},tsDeepestFirst=[...tsconfigs].sort(([a],[b])=>b.length-a.length),scopes=new Map,scopeOf=(from)=>{let contains=([dir])=>dir==="."||from.startsWith(`${dir}/`),pkg=deepestFirst.findIndex(contains),ts=tsDeepestFirst.findIndex(contains),key=`${pkg} ${ts}`,scope=scopes.get(key);if(!scope){let owning=pkg===-1?void 0:deepestFirst[pkg];scope={owning,ts:ts===-1?void 0:tsDeepestFirst[ts][1],declared:declaredIn(owning?.[0]??"."),resolved:new Map},scopes.set(key,scope)}return scope},svelteKitRoot=(dir)=>{for(let at=dir;;at=posix.dirname(at)){if(at==="."||packages.has(at))return at;if(SVELTE_CONFIGS.some((name)=>exists(`${at}/${name}`)))return at}},inPackage=(dir,path)=>dir==="."?path:posix.join(dir,path),resolveLocal=(dir,json,subpath)=>{if(json.exports!==void 0){let list=exportTargets(json.exports,subpath);return[...new Set((list??[]).flatMap((target)=>exact(inPackage(dir,posix.normalize(target)))))]}if(subpath===".")return probe(inPackage(dir,posix.normalize(json.main??"index")));return probe(inPackage(dir,subpath.slice(2)))},resolveImport=(scope,bare)=>{let{owning}=scope,imports=owning?.[1].imports,list=owning&&imports&&mapTargets(imports,bare);if(!list)return;let found=[],pkg;for(let target of list){if(target.startsWith("./")){for(let path of exact(inPackage(owning[0],posix.normalize(target))))if(!found.includes(path))found.push(path);continue}if(INVALID_IMPORT_TARGET.test(target))continue;let specifier=target.replace(QUERY,""),resolved=specifier===""?void 0:resolveBare(scope,specifier);if(resolved===void 0)return;if("pkg"in resolved)pkg??=resolved.pkg;else for(let file of resolved.files)if(!found.includes(file))found.push(file)}if(found.length>0)return{files:found};return pkg===void 0?void 0:{pkg}},resolveRelative=(fromDir,bare)=>{if(bare.startsWith(SVELTEKIT_ASSETS)){let rest=bare.slice(SVELTEKIT_ASSETS.length),found=probe(posix.join(svelteKitRoot(fromDir),"static",rest));return found.length>0?{files:found}:void 0}let found=probe(posix.join(fromDir,bare));return found.length>0?{files:found}:void 0},resolveBare=(scope,bare)=>{for(let alias of config.alias){let path=aliasPath(alias,bare);if(path===void 0)continue;let found=probe(path);if(found.length>0)return{files:found}}let{ts}=scope,mapped=ts&&mapTargets(ts.paths,bare);if(mapped){let found=[...new Set(mapped.flatMap((path)=>probe(posix.normalize(path))))];if(found.length>0)return{files:found}}if(bare.startsWith("#"))return resolveImport(scope,bare);let name=packageName(bare),dir=local.get(name);if(dir!==void 0){let subpath=`.${bare.slice(name.length)}`,found=resolveLocal(dir,packages.get(dir)??{},subpath);return found.length>0?{files:found}:void 0}if(ts?.baseUrl!==void 0){let found=probe(posix.join(ts.baseUrl,bare),!0);if(found.length>0)return{files:found}}let node=builtin(bare);if(node)return{pkg:node};if(scope.declared.has(name)||config.external.has(name))return{pkg:name};return},dirs=new Map,directoryOf=(from)=>{let dir=posix.dirname(from),found=dirs.get(dir);if(!found)found={dir,relative:new Map,scope:scopeOf(from)},dirs.set(dir,found);return found},lastFrom,last;return(from,specifier)=>{if(from!==lastFrom||!last)lastFrom=from,last=directoryOf(from);let{dir,relative,scope}=last,hash=specifier.startsWith("#")?"#":"",isRelative=RELATIVE.test(specifier),memo=isRelative?relative:scope.resolved;if(memo.has(specifier))return memo.get(specifier);let bare=hash+specifier.slice(hash.length).replace(QUERY,""),resolved;if(bare!==""&&bare!=="#")resolved=isRelative?resolveRelative(dir,bare):resolveBare(scope,bare);return memo.set(specifier,resolved),resolved}}import{posix as posix2}from"node:path";function createLexed(){return{imports:[],globs:[],gotos:[],dependsOn:[],reads:[],lists:[],registry:!1,nonLiteralImport:!1,nonLiteralGlob:!1,readsDisk:!1}}class LexError extends Error{}var TS={jsx:!1,tsx:!1},JS={jsx:!0,tsx:!1},TSX={jsx:!0,tsx:!0},JS_FILE=/\.[cm]?jsx?$/;function dialectOf(path){if(path.endsWith(".tsx"))return TSX;if(JS_FILE.test(path))return JS;return TS}var T_START=0,T_PUNCT=1,T_OPERAND=2,T_IDENT=3,T_DOT=4,T_CLOSE_PAREN=5,T_CLOSE_KW=6,T_CLOSE_BLOCK=7,T_ARROW=8,T_SEMI=9,T_LBRACE=10,M_PAREN=0,M_PAREN_KW=1,M_BRACKET=2,M_BLOCK=3,M_EXPR=4,M_TEMPLATE=5,DISK=new Set(["fs","node:fs","fs/promises","node:fs/promises","child_process","node:child_process"]),VI_CALLS=new Set(["mock","doMock","unmock","importActual","importMock"]),CALL_IMPORT=0,CALL_PROPERTY=1,CALL_MOCK=2,CALL_ACTUAL=3,src="",end=0,out=createLexed(),dialect=TS,nextAt=-1,nextImport=-1,LS=String.fromCharCode(8232),PS=String.fromCharCode(8233),oddLines=!1,templateOpen=!1;function fail(message,at){throw new LexError(`${message} at ${at}`)}function openFile(source,sink){src=source,out=sink,nextAt=-1,nextImport=-1,oddLines=source.includes("\r")||source.includes(LS)||source.includes(PS)}function lexRange(start,stop,language=TS){dialect=language,end=stop;let i=start;if(src.charCodeAt(i)===65279)i++;if(src.charCodeAt(i)===35&&src.charCodeAt(i+1)===33)i=lineEnd(i);code(i,!1)}function lexExpression(start,stop){return dialect=TS,end=stop,code(start,!0)}function isUnicodeSpace(c){return c===160||c===65279||c===5760||c>=8192&&c<=8202||c===8232||c===8233||c===8239||c===8287||c===12288}var IDENT=new Uint8Array(128);for(let c=0;c<128;c++)if(c>=97&&c<=122||c>=65&&c<=90||c===36||c===95)IDENT[c]=3;else if(c>=48&&c<=57)IDENT[c]=2;function isIdentStart(c){return c<128?(IDENT[c]&1)!==0:c>=128&&!isUnicodeSpace(c)}function isIdentPart(c){return c<128?IDENT[c]!==0:c>=128&&!isUnicodeSpace(c)}function identEnd(start){let i=start,s=src,n=end;while(i<n){let c=s.charCodeAt(i);if(c<128?IDENT[c]===0:isUnicodeSpace(c))break;i++}return i}function isWord(i,word){return i+word.length<=end&&src.startsWith(word,i)&&!isIdentPart(src.charCodeAt(i+word.length))}function lineEnd(start){let i=start;if(oddLines){while(i<end){let c=src.charCodeAt(i);if(c===10||c===13||c===8232||c===8233)return i;i++}return end}let e=src.indexOf(`
|
|
5
|
-
`,i);return e===-1||e>end?end:e}function skipTrivia(start){let i=start;while(i<end){let c=src.charCodeAt(i);if(c===32||c>=9&&c<=13||c>=128&&isUnicodeSpace(c))i++;else if(c===47&&src.charCodeAt(i+1)===47)i=lineEnd(i+2);else if(c===47&&src.charCodeAt(i+1)===42){let e=src.indexOf("*/",i+2);if(e===-1||e+2>end)return end;i=e+2}else break}return i}function stringEnd(i){let quote=src.charCodeAt(i),j=i+1;while(j<end){let c=src.charCodeAt(j);if(c===quote)return j+1;if(c===92){j+=src.charCodeAt(j+1)===13&&src.charCodeAt(j+2)===10?3:2;continue}if(c===10||c===13)return-1;j++}return-1}function template(start){let j=start;while(j<end){let c=src.charCodeAt(j);if(c===96)return templateOpen=!1,j+1;if(c===92){j+=2;continue}if(c===36&&src.charCodeAt(j+1)===123)return templateOpen=!0,j+2;j++}return fail("unterminated template",j)}function regex(i){let j=i+1,inClass=!1;for(;;){if(j>=end)fail("unterminated regex",i);let c=src.charCodeAt(j);if(c===92){j+=2;continue}if(c===10||c===13)fail("unterminated regex",i);if(inClass){if(c===93)inClass=!1}else if(c===47)break;else if(c===91)inClass=!0;j++}return identEnd(j+1)}function isOneOf(start,stop,words){if(stop-start!==words[0].length)return!1;let c=src.charCodeAt(start);for(let word of words)if(word.charCodeAt(0)===c&&src.startsWith(word,start))return!0;return!1}var EXPRESSION_KEYWORDS=[],PAREN_KEYWORDS=[],BLOCK_KEYWORDS=[];function byLength(table,words){for(let word of words)table[word.length]=[...table[word.length]??[],word]}byLength(EXPRESSION_KEYWORDS,["in","do","new","case","else","void","throw","yield","await","return","typeof","delete","default","instanceof"]);byLength(PAREN_KEYWORDS,["if","for","with","while"]);byLength(BLOCK_KEYWORDS,["do","try","else","finally"]);function isKeyword(table,start,stop){let words=table[stop-start];return words!==void 0&&isOneOf(start,stop,words)}function isExpressionKeyword(start,stop){return isKeyword(EXPRESSION_KEYWORDS,start,stop)}function valueEnded(last,wordStart,wordEnd,wordIsProperty){return last===T_OPERAND||last===T_CLOSE_PAREN||last===T_IDENT&&(wordIsProperty||!isExpressionKeyword(wordStart,wordEnd))}function isParenKeyword(start,stop){return isKeyword(PAREN_KEYWORDS,start,stop)}function isBlockKeyword(start,stop){return isKeyword(BLOCK_KEYWORDS,start,stop)}function isWordAt(start,stop,word){return stop-start===word.length&&src.startsWith(word,start)}var KEYWORD_SHAPE=new Uint8Array(1024);for(let word of["vi","Bun","goto","import","export","require"])KEYWORD_SHAPE[word.length<<7|word.charCodeAt(0)]=1;function keyword(c,i,j,property){switch(j-i){case 2:if(src.charCodeAt(i+1)===105)vi(j);break;case 3:if(src.startsWith("Bun",i))bun(j);break;case 4:if(property&&src.startsWith("goto",i))goto(j);break;case 6:if(!property){if(c===105&&src.startsWith("import",i))importAt(j);else if(c===101&&src.startsWith("export",i))exportAt(j)}break;case 7:if(src.startsWith("require",i))requireAt(j,property);break}}function code(start,brace){let i=start,s=src,n=end,stack=[],last=T_START,wordStart=0,wordEnd=0,wordIsProperty=!1;while(i<n){let c=s.charCodeAt(i);if(c<128?(IDENT[c]&1)!==0:!isUnicodeSpace(c)){let j=i+1;while(j<n){let d=s.charCodeAt(j);if(d<128?IDENT[d]===0:isUnicodeSpace(d))break;j++}let property=last===T_DOT;if(c<128&&j-i<8&&KEYWORD_SHAPE[j-i<<7|c]!==0)keyword(c,i,j,property);last=T_IDENT,wordStart=i,wordEnd=j,wordIsProperty=property,i=j;continue}switch(c){case 32:case 9:case 10:case 11:case 12:case 13:i++;continue;case 47:{let next=src.charCodeAt(i+1);if(next===47){let e=lineEnd(i+2);comment(i,e,!1),i=e}else if(next===42){let e=src.indexOf("*/",i+2);if(e===-1||e+2>end)fail("unterminated comment",i);comment(i,e+2,!0),i=e+2}else if(valueEnded(last,wordStart,wordEnd,wordIsProperty))i++,last=T_PUNCT;else i=regex(i),last=T_OPERAND;continue}case 39:case 34:{let e=stringEnd(i);if(e===-1)fail("unterminated string",i);i=e,last=T_OPERAND;continue}case 96:if(i=template(i+1),templateOpen)stack.push(M_TEMPLATE),last=T_PUNCT;else last=T_OPERAND;continue;case 123:{let block=last===T_START||last===T_SEMI||last===T_LBRACE||last===T_CLOSE_PAREN||last===T_CLOSE_KW||last===T_CLOSE_BLOCK||last===T_ARROW||last===T_IDENT&&!wordIsProperty&&isBlockKeyword(wordStart,wordEnd);stack.push(block?M_BLOCK:M_EXPR),last=T_LBRACE,i++;continue}case 125:{if(stack.length===0){if(brace)return i+1;fail("unbalanced }",i)}let open=stack.pop();if(open===M_TEMPLATE){if(i=template(i+1),templateOpen)stack.push(M_TEMPLATE),last=T_PUNCT;else last=T_OPERAND;continue}if(open===M_BLOCK)last=T_CLOSE_BLOCK;else if(open===M_EXPR)last=T_OPERAND;else fail("unbalanced }",i);i++;continue}case 40:stack.push(last===T_IDENT&&!wordIsProperty&&isParenKeyword(wordStart,wordEnd)?M_PAREN_KW:M_PAREN),last=T_PUNCT,i++;continue;case 41:{let open=stack.pop();if(open===M_PAREN)last=T_CLOSE_PAREN;else if(open===M_PAREN_KW)last=T_CLOSE_KW;else fail("unbalanced )",i);i++;continue}case 91:stack.push(M_BRACKET),last=T_PUNCT,i++;continue;case 93:if(stack.pop()!==M_BRACKET)fail("unbalanced ]",i);last=T_OPERAND,i++;continue;case 59:last=T_SEMI,i++;continue;case 46:if(src.charCodeAt(i+1)===46&&src.charCodeAt(i+2)===46)last=T_PUNCT,i+=3;else if(isDigit(src.charCodeAt(i+1)))i=numberEnd(i+1),last=T_OPERAND;else last=T_DOT,i++;continue;case 61:if(src.charCodeAt(i+1)===62)last=T_ARROW,i+=2;else last=T_PUNCT,i++;continue;case 43:case 45:if(src.charCodeAt(i+1)===c)last=last===T_OPERAND||last===T_IDENT||last===T_CLOSE_PAREN?T_OPERAND:T_PUNCT,i+=2;else last=T_PUNCT,i++;continue;case 33:last=valueEnded(last,wordStart,wordEnd,wordIsProperty)&&src.charCodeAt(i+1)!==61?T_OPERAND:T_PUNCT,i++;continue;case 60:if(src.charCodeAt(i+1)===60||src.charCodeAt(i+1)===61)last=T_PUNCT,i+=2;else if(!valueEnded(last,wordStart,wordEnd,wordIsProperty)&&dialect.jsx&&isJsxStart(i))i=jsxElement(i),last=T_OPERAND;else last=T_PUNCT,i++;continue;case 35:if(isIdentStart(src.charCodeAt(i+1)))i=identEnd(i+1),last=T_OPERAND;else last=T_PUNCT,i++;continue;default:if(isDigit(c)){i=numberEnd(i+1),last=T_OPERAND;continue}if(c<128)last=T_PUNCT;i++;continue}}if(brace)fail("unterminated expression",i);if(stack.length>0)fail(stack[stack.length-1]===M_TEMPLATE?"unterminated template":"unbalanced brackets",i);return i}function isDigit(c){return c>=48&&c<=57}function numberEnd(start){let i=start;while(i<end){let c=src.charCodeAt(i);if(isIdentPart(c)||c===46)i++;else break}return i}function comment(start,stop,block){if(nextAt<start)nextAt=indexOrEnd("@",start);while(nextAt<stop){if(src.startsWith("@depends-on",nextAt)||src.startsWith("@reads",nextAt)||src.startsWith("@lists",nextAt)||src.startsWith("@glob-registry",nextAt)){annotations(start,stop),nextAt=indexOrEnd("@",stop);break}nextAt=indexOrEnd("@",nextAt+1)}if(block&&src.charCodeAt(start+2)===42){if(nextImport<start)nextImport=indexOrEnd("import",start);while(nextImport<stop)jsdocImport(start,nextImport,stop),nextImport=indexOrEnd("import",nextImport+6)}}function indexOrEnd(text,from){let at=src.indexOf(text,from);return at===-1?src.length:at}var BLANK=/^[ \t]*$/;function annotations(start,stop){let lineStart=src.lastIndexOf(`
|
|
6
|
-
`,start-1)+1,prefix=src.slice(lineStart,start),text=(BLANK.test(prefix)?prefix:"x")+src.slice(start,stop);for(let[,list]of text.matchAll(DEPENDS_ON))out.dependsOn.push(...list.split(LIST_SEPARATOR).filter(Boolean));for(let[,list]of text.matchAll(READS))out.reads.push(...list.split(LIST_SEPARATOR).filter(Boolean));for(let[,list]of text.matchAll(LISTS))out.lists.push(...list.split(LIST_SEPARATOR).filter(Boolean));if(GLOB_REGISTRY.test(text))out.registry=!0}var JSDOC_IMPORT_TYPE=/import\s*\(\s*(["'`])([^"'`\n]+)\1\s*\)/y,JSDOC_IMPORT_TAG=/@import\s+([^;"'`]*?)\s*from\s*(["'])([^"'\n]+)\2/y,JSDOC_LINE_STAR=/\n\s*\*/g;function inTagType(start,at){let depth=0,outer=-1;for(let i=start;i<at;i++){let c=src.charCodeAt(i);if(c===123){if(depth++===0)outer=i}else if(c===125&&depth>0)depth--}if(depth===0)return!1;let p=outer-1;while(p>start&&isSpace(src.charCodeAt(p)))p--;while(p>start&&isIdentPart(src.charCodeAt(p)))p--;return src.charCodeAt(p)===64&&p+1<outer}function jsdocImport(start,at,stop){if(src.charCodeAt(at-1)===64){JSDOC_IMPORT_TAG.lastIndex=at-1;let tag=JSDOC_IMPORT_TAG.exec(src);if(tag&&JSDOC_IMPORT_TAG.lastIndex<=stop){let clause=tag[1].replace(JSDOC_LINE_STAR,`
|
|
7
|
-
`),names=clause.includes("{")?namedBindings(clause):void 0;out.imports.push(names?{specifier:tag[3],names,type:!0}:{specifier:tag[3],type:!0})}return}if(isIdentPart(src.charCodeAt(at-1))||src.charCodeAt(at-1)===46)return;if(!inTagType(start,at))return;JSDOC_IMPORT_TYPE.lastIndex=at;let type=JSDOC_IMPORT_TYPE.exec(src);if(type&&JSDOC_IMPORT_TYPE.lastIndex<=stop)out.imports.push({specifier:type[2],type:!0})}function record(specifier,names,disk,type=!1){if(specifier==="")return;let ref=names?{specifier,names}:{specifier};if(type)ref.type=!0;if(out.imports.push(ref),disk&&!type&&DISK.has(specifier))out.readsDisk=!0}function isSpace(c){return c===32||c>=9&&c<=13}function isQuote(c){return c===39||c===34}function importAt(j){let k=skipTrivia(j),c=src.charCodeAt(k);if(c===40)call(k,CALL_IMPORT);else if(c===46)meta(k);else if(isQuote(c)){let e=stringEnd(k);if(e!==-1)record(src.slice(k+1,e-1),void 0,!0)}else declaration(k)}function declaration(k){let clauseStart=k,type=!1;if(src.startsWith("type",k)&&isSpace(src.charCodeAt(k+4))){clauseStart=k+5;while(clauseStart<end&&isSpace(src.charCodeAt(clauseStart)))clauseStart++;let next=skipTrivia(k+4);type=!(isWord(next,"from")&&isQuote(src.charCodeAt(skipTrivia(next+4))))}let p=k;for(let steps=0;steps<256;steps++){if(p=skipTrivia(p),p>=end)return;let c=src.charCodeAt(p);if(isIdentStart(c)){let q=identEnd(p+1);if(q-p===4&&src.startsWith("from",p)){let r=skipTrivia(q);if(isQuote(src.charCodeAt(r))){let e=stringEnd(r);if(e!==-1)record(src.slice(r+1,e-1),clauseNames(clauseStart,p),!0,type);return}}p=q}else if(c===123){if(p=braceEnd(p),p===-1)return}else if(c===42||c===44)p++;else return}}function clauseNames(start,stop){let clause=src.slice(start,stop);if(!clause.includes("{"))return;return namedBindings(clause.replace(COMMENTS2,""))}var COMMENTS2=/\/\/.*$|\/\*[\s\S]*?\*\//gm;function braceEnd(open){let p=open,depth=0;while(p<end){let c=src.charCodeAt(p);if(c===123)depth++,p++;else if(c===125){if(p++,--depth===0)return p}else if(isQuote(c)){if(p=stringEnd(p),p===-1)return-1}else if(c===47&&src.charCodeAt(p+1)===47)p=lineEnd(p+2);else if(c===47&&src.charCodeAt(p+1)===42){let e=src.indexOf("*/",p+2);if(e===-1)return-1;p=e+2}else if(c===59||c===40||c===96)return-1;else p++}return-1}function exportAt(j){let p=skipTrivia(j),type=!1;if(isWord(p,"type")){let q=skipTrivia(p+4),c=src.charCodeAt(q);if(c===123||c===42)p=q,type=!0}let clauseStart=p,c=src.charCodeAt(p),q;if(c===123){if(q=braceEnd(p),q===-1)return}else if(c===42){if(q=skipTrivia(p+1),isWord(q,"as")){q=skipTrivia(q+2);let n=src.charCodeAt(q);if(isQuote(n))q=stringEnd(q);else if(isIdentStart(n))q=identEnd(q+1);else return;if(q===-1)return}}else return;if(q=skipTrivia(q),!isWord(q,"from"))return;let r=skipTrivia(q+4);if(!isQuote(src.charCodeAt(r)))return;let e=stringEnd(r);if(e===-1)return;record(src.slice(r+1,e-1),clauseNames(clauseStart,q),!0,type)}function call(k,kind){let a=skipTrivia(k+1),c=src.charCodeAt(a);if(c===41)return;let e;if(isQuote(c))e=stringEnd(a);else if(c===96){if(e=template(a+1),templateOpen)e=-1}else e=-1;let next=e===-1?-1:src.charCodeAt(skipTrivia(e));if(next===44||next===41)record(src.slice(a+1,e-1),void 0,kind===CALL_IMPORT||kind===CALL_PROPERTY||kind===CALL_ACTUAL);else if(kind!==CALL_PROPERTY&&!isSignature(k,a))out.nonLiteralImport=!0}function isSignature(k,a){if(isIdentStart(src.charCodeAt(a))){let p=skipTrivia(identEnd(a+1)),c=src.charCodeAt(p);if(c===58||c===63&&src.charCodeAt(skipTrivia(p+1))===58)return!0}let close=parenEnd(k);return close!==-1&&src.charCodeAt(skipTrivia(close))===123}function parenEnd(k){let depth=0,p=k;while(p<end){let c=src.charCodeAt(p);if(c===40||c===91||c===123)depth++;else if(c===41||c===93||c===125){if(--depth===0)return p+1}else if(isQuote(c)||c===96){if(p=c===96?templateEnd(p):stringEnd(p),p===-1)return-1;continue}else if(c===47&&(src.charCodeAt(p+1)===47||src.charCodeAt(p+1)===42)){p=skipTrivia(p);continue}p++}return-1}function requireAt(j,property){let k=skipTrivia(j);if(src.charCodeAt(k)===40)call(k,property?CALL_PROPERTY:CALL_IMPORT)}function vi(j){let p=skipTrivia(j);if(src.charCodeAt(p)!==46)return;let q=skipTrivia(p+1),r=identEnd(q),name=src.slice(q,r);if(!VI_CALLS.has(name))return;let s=skipTrivia(r);if(src.charCodeAt(s)===60){if(s=genericEnd(s),s===-1){out.nonLiteralImport=!0;return}s=skipTrivia(s)}if(src.charCodeAt(s)===40)call(s,name==="importActual"?CALL_ACTUAL:CALL_MOCK)}function meta(k){let m=skipTrivia(k+1);if(!isWord(m,"meta"))return;let p=skipTrivia(m+4);if(src.charCodeAt(p)!==46)return;let q=skipTrivia(p+1),r=identEnd(q);if(!isWordAt(q,r,"glob")&&!isWordAt(q,r,"globEager"))return;let s=skipTrivia(r);if(src.charCodeAt(s)===60){if(s=genericEnd(s),s===-1){out.nonLiteralGlob=!0;return}s=skipTrivia(s)}if(src.charCodeAt(s)===40)globArgument(s)}function genericEnd(start){let p=start,depth=0;while(p<end&&p-start<4096){let c=src.charCodeAt(p);if(c===60)depth++;else if(c===62&&src.charCodeAt(p-1)!==61){if(--depth===0)return p+1}else if(isQuote(c)){if(p=stringEnd(p),p===-1)return-1;continue}else if(c===96){if(p=template(p+1),templateOpen)return-1;continue}else if(c===59&&depth===0)return-1;p++}return-1}function literalEnd(a){let c=src.charCodeAt(a);if(isQuote(c))return stringEnd(a);if(c===96){let e=template(a+1);return templateOpen?-1:e}return-1}function globArgument(k){let a=skipTrivia(k+1),patterns=[],e;if(src.charCodeAt(a)===91){a=skipTrivia(a+1);for(;;){if(src.charCodeAt(a)===93){e=a+1;break}let f=literalEnd(a);if(f===-1){e=-1;break}patterns.push(src.slice(a+1,f-1)),a=skipTrivia(f);let c=src.charCodeAt(a);if(c===44)a=skipTrivia(a+1);else if(c!==93){e=-1;break}}}else if(e=literalEnd(a),e!==-1)patterns.push(src.slice(a+1,e-1));let next=e===-1?-1:src.charCodeAt(skipTrivia(e));if(next===44||next===41)out.globs.push(...patterns);else out.nonLiteralGlob=!0}function goto(j){let k=skipTrivia(j);if(src.charCodeAt(k)!==40)return;let a=skipTrivia(k+1),p=a,depth=0;while(p<end){let c=src.charCodeAt(p);if((c===44||c===41)&&depth===0)break;if(c===40||c===91||c===123)depth++;else if(c===41||c===93||c===125)depth--;else if(isQuote(c)||c===96){let e=c===96?templateEnd(p):stringEnd(p);if(e===-1)return;p=e;continue}p++}out.gotos.push(src.slice(a,p).trim())}function templateEnd(p){let q=template(p+1);while(templateOpen){let depth=1;while(q<end&&depth>0){let c=src.charCodeAt(q);if(c===123)depth++;else if(c===125)depth--;else if(isQuote(c)){if(q=stringEnd(q),q===-1)return-1;continue}else if(c===96){if(q=templateEnd(q),q===-1)return-1;continue}q++}if(depth>0)return-1;q=template(q)}return q}function bun(j){if(src.charCodeAt(j)!==46)return;if(src.startsWith("file",j+1)||src.startsWith("Glob",j+1)||src.startsWith("spawn",j+1))out.readsDisk=!0}function isJsxStart(i){let c=src.charCodeAt(i+1);if(c===62)return!0;if(!isIdentStart(c))return!1;if(!dialect.tsx)return!0;let p=skipTrivia(identEnd(i+2));return src.charCodeAt(p)!==44&&!isWord(p,"extends")}function jsxNameEnd(start){let p=start;while(p<end){let c=src.charCodeAt(p);if(isIdentPart(c)||c===45||c===46||c===58)p++;else break}return p}function jsxElement(i){let p=i+1;if(src.charCodeAt(p)===62)return jsxChildren(p+1);if(p=jsxNameEnd(p),dialect.tsx){let q=skipTrivia(p);if(src.charCodeAt(q)===60){if(p=genericEnd(q),p===-1)fail("unterminated JSX type arguments",q)}}for(;;){if(p=skipTrivia(p),p>=end)fail("unterminated JSX",i);let c=src.charCodeAt(p);if(c===47&&src.charCodeAt(p+1)===62)return p+2;if(c===62)return jsxChildren(p+1);if(c===123){p=code(p+1,!0);continue}if(!isIdentStart(c))fail(`bad JSX attribute in <> at ${i}:`,p);if(p=skipTrivia(jsxNameEnd(p)),src.charCodeAt(p)!==61)continue;p=skipTrivia(p+1);let v=src.charCodeAt(p);if(isQuote(v)){let e=src.indexOf(src[p],p+1);if(e===-1||e>=end)fail("unterminated JSX attribute",p);p=e+1}else if(v===123)p=code(p+1,!0);else if(v===60)p=jsxElement(p);else fail("bad JSX attribute",p)}}function jsxChildren(start){let p=start;while(p<end){let c=src.charCodeAt(p);if(c===60){if(src.charCodeAt(p+1)===47){let e=src.indexOf(">",p);if(e===-1||e>=end)break;return e+1}p=jsxElement(p)}else if(c===123)p=code(p+1,!0);else p++}return fail("unterminated JSX",p)}function hostOf(path){let dot=path.lastIndexOf("."),ext=path.slice(dot+1);return ext==="svelte"||ext==="vue"||ext==="astro"||ext==="html"?ext:void 0}var TAG_REF=/^<(?:script|link|iframe)\b[^>]*\b(?:src|href)=(?:"([^"]+)"|'([^']+)'|([^\s"'=<>`]+))/,GENERICS=/\sgenerics=(["'])/,LANG_JSX=/\slang=["']?(?:jsx|tsx)\b/,LOWERCASE=/[a-z]/,FENCE_OPEN=/^\s*---[ \t]*\r?\n/,FENCE_CLOSE=/^---[ \t]*$/m;function isTag(src,i,name){for(let k=0;k<name.length;k++)if((src.charCodeAt(i+1+k)|32)!==name.charCodeAt(k))return!1;let c=src.charCodeAt(i+1+name.length);return c===62||c===47||c===32||c>=9&&c<=13}function tagEnd(src,i){let j=i+1;while(j<src.length){let c=src.charCodeAt(j);if(c===62)return j+1;if(c===34||c===39){let e=src.indexOf(src[j],j+1);if(e===-1)break;j=e+1}else j++}throw new LexError(`unterminated tag at ${i}`)}function closeTag(src,from,name){let lower=src.indexOf(`</${name}`,from);if(lower!==-1)return lower;let any=src.slice(from).search(new RegExp(`</${name}`,"i"));if(any===-1)throw new LexError(`unterminated <${name}> at ${from}`);return from+any}function indexOrEnd2(src,text,from){let at=src.indexOf(text,from);return at===-1?src.length:at}function lexHost(src,out,host){let n=src.length,i=0;if(host==="astro")i=frontmatter(src);let nextTag=-1,nextBrace=host==="svelte"?-1:n;while(i<n){if(nextTag<i)nextTag=indexOrEnd2(src,"<",i);if(nextBrace<i)nextBrace=indexOrEnd2(src,"{",i);if(i=Math.min(nextTag,nextBrace),i>=n)break;if(src.charCodeAt(i)===123){let j=i+1,sigil=src.charCodeAt(j);if(sigil===35||sigil===58||sigil===64||sigil===47&&LOWERCASE.test(src[j+1]??""))j++;i=lexExpression(j,n);continue}if(src.startsWith("<!--",i)){let e=src.indexOf("-->",i+4);if(e===-1)throw new LexError(`unterminated comment at ${i}`);i=e+3}else if(isTag(src,i,"script")){let open=tagEnd(src,i),tag=src.slice(i,open);if(host==="html"||host==="vue")ref(tag,out);let generics=tag.match(GENERICS);if(generics?.index!==void 0){let start=i+generics.index+generics[0].length,stop=src.indexOf(generics[1],start);if(stop!==-1&&stop<open)lexRange(start,stop,TS)}let close=closeTag(src,open,"script"),dialect=LANG_JSX.test(tag)?TSX:TS;lexRange(open,close,dialect),i=close+8}else if(isTag(src,i,"style"))i=closeTag(src,tagEnd(src,i),"style")+7;else if(host==="html"&&(isTag(src,i,"link")||isTag(src,i,"iframe"))){let open=tagEnd(src,i);ref(src.slice(i,open),out),i=open}else i++}}function ref(tag,out){let match=TAG_REF.exec(tag),value=match&&(match[1]??match[2]??match[3]);if(value&&!URL_REF.test(value))out.imports.push({specifier:RELATIVE.test(value)?value:`./${value}`})}function frontmatter(src){let start=FENCE_OPEN.exec(src);if(!start)return 0;let from=start[0].length,close=src.slice(from).search(FENCE_CLOSE);if(close===-1)throw new LexError("unterminated frontmatter");return lexRange(from,from+close,TS),from+close+3}var COMMENTS3=/\/\/.*$|\/\*[\s\S]*?\*\//gm,QUOTED=/["']([^"']+)["']/g,STATIC_IMPORT=/(?:^|[\n;>])\s*(?:import|export)\s+(?:type\s+)?([^;"'`]*?)\s*from\s*["']([^"'\n]+)["']/g,SIDE_EFFECT_IMPORT=/(?:^|[\n;>])\s*import\s*["']([^"'\n]+)["']/g,CALL_WITH_LITERAL=/\b(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\(\s*(["'`])([^"'`$\n]+)\1\s*[,)]/g,NON_LITERAL_CALL=/(?<![.\w])(?:import|require)\(\s*(?!["'`])[^)\s]/,TEMPLATE_CALL=/(?<![.\w])(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\(\s*`[^`]*\$\{/,GLOB_CALL=/\bimport\.meta\.glob(?:<(?:[^<>]|<[^<>]*>)*>)?\(\s*(\[[^\]]*\]|["'][^"']*["'])/g,GLOB_CALL_ANY=/\bimport\.meta\.glob[<(]/g,GOTO=/\.goto\(\s*([^,)]*)/g,HTML_REF=/<(?:script|link|iframe)\b[^>]*\b(?:src|href)=["']([^"']+)["']/g,READS_DISK=/\b(?:from|import|require|importActual)\s*\(?\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\bBun\.(?:file|Glob|spawn)/;function extractRegex(source,html){let result={imports:[],globs:[],gotos:[],dependsOn:[],reads:[],lists:[],unknown:[]};if(html){for(let[,ref]of source.matchAll(HTML_REF))if(!URL_REF.test(ref))result.imports.push({specifier:RELATIVE.test(ref)?ref:`./${ref}`})}for(let[,clause,specifier]of source.matchAll(STATIC_IMPORT)){let names=namedBindings(clause.replace(COMMENTS3,""));result.imports.push(names?{specifier,names}:{specifier})}for(let[,specifier]of source.matchAll(SIDE_EFFECT_IMPORT))result.imports.push({specifier});let calls=source.includes("import(")||source.includes("require(")||source.includes("vi.");for(let[,,specifier]of calls?source.matchAll(CALL_WITH_LITERAL):[])result.imports.push({specifier});if(calls&&(NON_LITERAL_CALL.test(source)||TEMPLATE_CALL.test(source)))result.unknown.push("non-literal dynamic import");let globbing=source.includes("import.meta.glob"),globs=globbing?[...source.matchAll(GLOB_CALL)]:[];if(globbing&&globs.length!==[...source.matchAll(GLOB_CALL_ANY)].length)result.unknown.push("non-literal glob import");for(let[,argument]of GLOB_REGISTRY.test(source)?[]:globs)for(let[,glob]of argument.matchAll(QUOTED)){if(glob.startsWith("!"))continue;result.globs.push(glob.replace(QUERY,""))}if(source.includes(".goto("))for(let[,argument]of source.matchAll(GOTO))result.gotos.push(argument.trim());if(result.dependsOn=[...source.includes("@depends-on")?source.matchAll(DEPENDS_ON):[]].flatMap(([,list])=>list.split(LIST_SEPARATOR).filter(Boolean)),result.reads=[...source.includes("@reads")?source.matchAll(READS):[]].flatMap(([,list])=>list.split(LIST_SEPARATOR).filter(Boolean)),result.lists=[...source.includes("@lists")?source.matchAll(LISTS):[]].flatMap(([,list])=>list.split(LIST_SEPARATOR).filter(Boolean)),(source.includes("fs")||source.includes("child_process")||source.includes("Bun."))&&READS_DISK.test(source)&&result.dependsOn.length+result.reads.length+result.lists.length===0)result.unknown.push(UNDECLARED_READS);return result}var SCANNED=/\.(?:svelte|vue|astro|html|[cm]?[jt]sx?)$/;function formatOf(path){let host=hostOf(path);if(host)return host;let dialect=dialectOf(path);if(dialect===TSX)return"tsx";return dialect===JS?"js":"ts"}function extract(format,source){let lexed=createLexed(),extraction;try{if(openFile(source,lexed),isHost(format))lexHost(source,lexed,format);else lexRange(0,source.length,DIALECTS[format]);extraction=fromLexed(lexed)}catch(error){let fallback=error instanceof LexError?error.message:`lexer error: ${error}`;extraction={...extractRegex(source,format==="html"),fallback}}if(!isHost(format)){let barrel=parseReExports(source);if(barrel)extraction.barrel=barrel}return detach(extraction)}function own(text){return JSON.parse(JSON.stringify(text))}function detach(extraction){let list=(texts)=>texts.map(own),{imports,barrel,fallback}=extraction,detached={imports:imports.map(({specifier,names,type})=>{let ref=names?{specifier:own(specifier),names:list(names)}:{specifier:own(specifier)};if(type)ref.type=!0;return ref}),globs:list(extraction.globs),gotos:list(extraction.gotos),dependsOn:list(extraction.dependsOn),reads:list(extraction.reads),lists:list(extraction.lists),unknown:extraction.unknown};if(fallback!==void 0)detached.fallback=fallback;if(barrel)detached.barrel={names:new Map([...barrel.names].map(([name,from])=>[own(name),own(from)])),stars:list(barrel.stars)};return detached}function finish(path,extraction,{gotos=!1}={}){let{globs}=extraction,dir=globs.length>0?posix2.dirname(path):"",result={imports:extraction.imports,globs:globs.map((glob)=>posix2.join(dir,glob)),gotos:gotos?extraction.gotos:[],dependsOn:extraction.dependsOn,reads:extraction.reads,lists:extraction.lists,unknown:extraction.unknown};if(extraction.fallback!==void 0)result.fallback=extraction.fallback;return result}var DIALECTS={ts:TS,tsx:TSX,js:JS},isHost=(format)=>format!=="ts"&&format!=="tsx"&&format!=="js";function fromLexed(lexed){let unknown=[];if(lexed.nonLiteralImport)unknown.push("non-literal dynamic import");if(lexed.nonLiteralGlob)unknown.push("non-literal glob import");let globs=[];for(let glob of lexed.registry?[]:lexed.globs){if(glob.startsWith("!"))continue;globs.push(glob.replace(QUERY,""))}let declared=lexed.dependsOn.length+lexed.reads.length+lexed.lists.length;if(lexed.readsDisk&&declared===0)unknown.push(UNDECLARED_READS);return{imports:lexed.imports,globs,gotos:lexed.gotos,dependsOn:lexed.dependsOn,reads:lexed.reads,lists:lexed.lists,unknown}}var STRING_LITERAL=/^["'`]([^"'`$]*)["'`]$/,STATIC_PATH_TEMPLATE=/^`([^`$?#]*)[?#][^`]*`$/;function gotoUrl(argument){return STRING_LITERAL.exec(argument)?.[1]??STATIC_PATH_TEMPLATE.exec(argument)?.[1]}var leaf=()=>({files:new Set,patterns:[],reads:[],unknown:[]}),LEADING_DOT_SLASH2=/^\.\//,JS_SPECIFIER=/\.[cm]?jsx?$/,DECLARATION=/\.d(?:\.[^/.]+)?\.[cm]?ts$/;function addPattern(deps,pattern,kind){if(deps.patterns.push(pattern),kind==="glob")return;deps.patternKinds??=new Map,deps.patternKinds.set(pattern,kind)}var NON_LITERAL_GOTO="non-literal goto(",HERMETIC_CAUSES=new Set([UNDECLARED_READS,"non-literal dynamic import"]);function sideEffectful(owning){let sideEffects=owning?.[1].sideEffects;if(sideEffects===!1)return()=>!1;if(!Array.isArray(sideEffects))return()=>!0;let dir=owning?.[0]??".";return matcher(sideEffects.map((glob)=>{if(!glob.includes("/"))return`**/${glob}`;let path=glob.replace(LEADING_DOT_SLASH2,"");return dir==="."?path:`${dir}/${path}`}))}function gotoSuite(config,path){return config.suites.find((suite)=>suite.urls.length>0&&suite.roots.some((root)=>inRoot(path,root)))}function mapUrl(suite,url){for(let{key,targets}of suite.urls){let star=key.indexOf("*");if(star===-1){if(url===key)return targets;continue}let prefix=key.slice(0,star),suffix=key.slice(star+1);if(url.startsWith(prefix)&&url.endsWith(suffix)){let match=url.slice(prefix.length,url.length-suffix.length);return targets.map((target)=>target.replaceAll("*",match))}}return}function gotoPage(config,path,argument){let suite=gotoSuite(config,path),url=gotoUrl(argument);return suite===void 0||url===void 0?void 0:mapUrl(suite,url.replace(QUERY,""))}function graphFrom(files,extractions,{config,packages,tsconfigs}){let graph=new Map,paths=[...files],exists=new Set(paths),resolve=createResolver({files:exists,config,packages,tsconfigs}),scans=new Map,barrels=new Map;for(let path of paths){let extraction=extractions.get(path);if(!extraction)continue;let gotos=gotoSuite(config,path)!==void 0;if(scans.set(path,finish(path,extraction,{gotos})),extraction.barrel&&config.isBarrel(path))barrels.set(path,extraction.barrel)}let named=new Map,effects=new Map,nameUnknown=new Map;for(let[path,barrel]of barrels){let effectful=sideEffectful(owner(packages,path));if(effectful(path))continue;let resolveTarget=(specifier)=>{let resolved=resolve(path,specifier);return resolved&&"files"in resolved?resolved.files:void 0},always=[];for(let specifier of[...barrel.names.values(),...barrel.stars])for(let file of resolveTarget(specifier)??[])if(effectful(file)&&!always.includes(file))always.push(file);let names=new Map;for(let[name,specifier]of barrel.names){let targets=resolveTarget(specifier);if(!targets)nameUnknown.set(`${path}#${name}`,[`unresolved "${specifier}"`]);names.set(name,targets??[])}named.set(path,names),effects.set(path,always)}let external=new Set;for(let path of paths){let found=scans.get(path);if(!found){graph.set(path,leaf());continue}let deps=leaf(),valued=new Set,typed=new Set,declaration=DECLARATION.test(path);for(let{specifier,names,type}of found.imports){let resolved=resolve(path,specifier),add=(node)=>{deps.files.add(node),(type===!0||declaration||DECLARATION.test(node)?typed:valued).add(node)};if(resolved===void 0){let cause=`unresolved "${specifier}"`;if(!deps.unknown.includes(cause))deps.unknown.push(cause)}else if("pkg"in resolved)add(`pkg:${resolved.pkg}`),external.add(`pkg:${resolved.pkg}`);else{if(type!==!0&&!declaration&&JS_SPECIFIER.test(specifier.replace(QUERY,""))&&resolved.files.every((file)=>DECLARATION.test(file))){let cause=`only declarations for "${specifier}"`;if(!deps.unknown.includes(cause))deps.unknown.push(cause)}for(let file of resolved.files){let barrel=names&&named.get(file);if(!barrel||!names){add(file);continue}for(let name of names)add(barrel.has(name)?`${file}#${name}`:file)}}}for(let node of typed){if(valued.has(node))continue;deps.types??=new Set,deps.types.add(node)}deps.unknown.push(...config.isHermetic(path)?found.unknown.filter((cause)=>!HERMETIC_CAUSES.has(cause)):found.unknown);for(let glob of found.globs)addPattern(deps,globToRegExp(glob),"glob");let suite=found.gotos.length>0?gotoSuite(config,path):void 0;if(suite)for(let argument of found.gotos){let url=gotoUrl(argument);if(url===void 0){if(found.dependsOn.length===0)deps.unknown.push(`${NON_LITERAL_GOTO}${argument})`)}else if(url!=="about:blank"){let mapped=mapUrl(suite,url.replace(QUERY,""));if(mapped===void 0)deps.unknown.push(`goto("${url}")`);else if(exists.has(mapped[0]??""))for(let page of mapped.filter((file)=>exists.has(file))){if(!deps.files.has(page))deps.pages??=new Set,deps.pages.add(page);deps.files.add(page)}else deps.unknown.push(`missing fixture "${url}"`)}}for(let glob of found.dependsOn)addPattern(deps,globToRegExp(glob),"depends-on");for(let glob of found.reads)deps.reads.push(globToRegExp(glob));if(found.lists.length>0)deps.lists=found.lists.map(globToRegExp);let names=named.get(path);if(names)deps.barrel=names;graph.set(path,deps)}for(let[path,names]of named)for(let[name,targets]of names){let id=`${path}#${name}`;graph.set(id,{...leaf(),files:new Set([...targets,...effects.get(path)??[]]),unknown:nameUnknown.get(id)??[]})}for(let id of external)graph.set(id,leaf());for(let suite of config.suites){let setup=paths.filter(suite.isSetup);if(setup.length===0)continue;for(let path of paths){let deps=suite.isTest(path)?graph.get(path):void 0;if(!deps)continue;for(let file of setup){if(file===path)continue;deps.types?.delete(file),deps.files.add(file),deps.setup??=new Set,deps.setup.add(file)}}}for(let deps of[...graph.values()])for(let file of deps.files)if(!graph.has(file)&&isGenerated(config,file))graph.set(file,leaf());for(let[path,deps]of graph){let depends=!1,declared=!1;for(let edge of config.generated){let inputs=edge.targets(path);if(!inputs)continue;depends||=edge.exact;for(let input of inputs)addPattern(deps,input,"edges")}for(let read of config.reads){let globs=read.targets(path);if(!globs)continue;declared||=read.exact,deps.reads.push(...globs)}if(depends||declared)deps.unknown=deps.unknown.filter((cause)=>cause!==UNDECLARED_READS&&!(depends&&cause.startsWith(NON_LITERAL_GOTO)))}return graph}function isGenerated(config,path){return config.generated.some(({pattern})=>pattern.test(path))}function changedBarrelNames(before,after){let names=new Set([...before.keys(),...after.keys()]),key=(files)=>files?.join("\x00");return[...names].filter((name)=>key(before.get(name))!==key(after.get(name)))}function baseBarrelNames(path,source,{config,packages,tsconfigs},graph){let barrel=source===void 0?void 0:parseBarrel(path,source);if(!barrel)return;let resolve=createResolver({files:new Set(graph.keys()),config,packages,tsconfigs}),names=new Map;for(let[name,specifier]of barrel.names){let resolved=resolve(path,specifier);names.set(name,resolved&&"files"in resolved?resolved.files:[])}return names}var indexes=new WeakMap,REGEX_SYNTAX="[](){}|*+?.^$";function literalOf(re){let{source}=re;if(!source.startsWith("^")||!source.endsWith("$"))return;let path="";for(let i=1;i<source.length-1;i++){let char=source[i];if(char==="\\")path+=source[++i];else if(REGEX_SYNTAX.includes(char))return;else path+=char}return path}function patterns(){let literal=new Map,wild=[],bySource=new Map;return{literal,wild,add:(re,node,kind)=>{let group=bySource.get(re.source);if(!group){group={re,nodes:[],kinds:[]},bySource.set(re.source,group);let path=literalOf(re);if(path===void 0)wild.push(group);else{let list=literal.get(path);list?list.push(group):literal.set(path,[group])}}if(group.nodes.at(-1)===node)return;group.nodes.push(node),group.kinds.push(kind)}}}function reverseIndex(graph){let cached=indexes.get(graph);if(cached)return cached;let dependents=new Map,globbers=patterns(),readers=patterns(),listers=patterns(),unknown=[];for(let[path,deps]of graph){for(let file of deps.files){let list=dependents.get(file);list?list.push(path):dependents.set(file,[path])}for(let re of deps.patterns)globbers.add(re,path,deps.patternKinds?.get(re)??"glob");for(let re of deps.reads)readers.add(re,path,"reads");for(let re of deps.lists??[])listers.add(re,path,"lists");if(deps.unknown.length>0)unknown.push(path)}let index={dependents,globbers,readers,listers,unknown};return indexes.set(graph,index),index}function runtimeDependents(graph,index){if(index.runtime)return index.runtime;let runtime=new Map;for(let[path,deps]of graph)for(let file of deps.files){if(deps.types?.has(file))continue;let list=runtime.get(file);list?list.push(path):runtime.set(file,[path])}return index.runtime=runtime,runtime}function reaches(graph,changed,match,options={}){let reached=affectedBy(graph,changed,{...options,until:match});for(let path of reached)if(match(path))return!0;return!1}function walksByTypes(graph,changed,options={}){let seeds=[...changed],walks=new Map;return(types)=>{let walk=walks.get(types);if(!walk)walk=affectedBy(graph,seeds,{...options,types}),walks.set(types,walk);return walk}}function importersOf(graph,node){return reverseIndex(graph).dependents.get(node)??[]}function fileKind(graph,dependent,node){if(dependent.includes("#"))return"export";let deps=graph.get(dependent);if(deps?.setup?.has(node))return"setup";if(deps?.types?.has(node))return"type";if(deps?.pages?.has(node))return"goto";if(node.includes("#"))return"name";return dependent.endsWith(".html")?"html":"import"}function affectedBy(graph,changed,{includeUnknown=!0,quiet=[],types=!0,layout,readers:seedReaders=!0,opaque,until,parents}={}){let index=reverseIndex(graph),{globbers,readers,listers,unknown}=index,dependents=types?index.dependents:runtimeDependents(graph,index),affected=new Set,queue=[],done=!1,visit=(path,via)=>{if(affected.has(path)||opaque?.(path))return;if(affected.add(path),queue.push(path),via&&parents)parents.set(path,via);if(until?.(path))done=!0},visitGroup=(group,from)=>{let{nodes,kinds}=group;for(let i=0;i<nodes.length;i++)visit(nodes[i],parents&&{from,kind:kinds[i]})},visitMatches=(groups,path)=>{for(let group of groups.literal.get(path)??[])visitGroup(group,path);for(let group of groups.wild)if(group.re.test(path))visitGroup(group,path)},changedPaths=[...changed];for(let path of changedPaths)visit(path);let first=queue[0];for(let path of quiet)visit(path),changedPaths.push(path);if(seedReaders){for(let path of changedPaths)visitMatches(readers,path);for(let path of changedPaths)if(!layout||layout.has(path))visitMatches(listers,path)}if(includeUnknown&&first!==void 0)for(let path of unknown)visit(path,{from:first,kind:"unknown"});let{literal}=globbers,active=globbers.wild,spent,spend=(group,from)=>{visitGroup(group,from),spent??=new Set,spent.add(group)};for(let at=0;at<queue.length&&!done;at++){let path=queue[at];for(let dependent of dependents.get(path)??[])visit(dependent,parents&&{from:path,kind:fileKind(graph,dependent,path)});let exact=literal.size>0?literal.get(path):void 0;if(exact){for(let group of exact)if(!spent?.has(group))spend(group,path)}let matched=!1;for(let group of active){if(!group.re.test(path))continue;spend(group,path),matched=!0}if(matched)active=active.filter((group)=>!spent?.has(group))}return affected}import{posix as posix3}from"node:path";var COMMENT=/\s+#.*$/,KEY_END=/:(?: |$)/,EMPTY_MAP=/^\{\s*\}(?:\s+#.*)?$/,EMPTY_LIST=/^\[\s*\](?:\s+#.*)?$/,UNSUPPORTED=/^[&*!|>%@`]/;class YamlError extends Error{}function fail2(line,message){throw new YamlError(`${message} at line ${line?.number??"end"}`)}function linesOf(text){let lines=[];for(let[i,raw]of text.split(`
|
|
8
|
-
`).entries()){let line=raw.endsWith("\r")?raw.slice(0,-1):raw,content=line.trimStart();if(content===""||content.startsWith("#"))continue;let indent=line.length-content.length;if(line.slice(0,indent).includes("\t"))fail2({indent,text:content,number:i+1},"a tab in indentation");lines.push({indent,text:content.trimEnd(),number:i+1})}return lines}function quoteEnd(text,start){let quote=text[start];for(let i=start+1;i<text.length;i++)if(quote==="'"&&text[i]==="'")if(text[i+1]==="'")i++;else return i+1;else if(quote==='"'&&text[i]==="\\")i++;else if(quote==='"'&&text[i]==='"')return i+1;return-1}function unquote(quoted){if(quoted.startsWith("'"))return quoted.slice(1,-1).replaceAll("''","'");let value=JSON.parse(quoted);if(typeof value!=="string")throw new YamlError("bad quoted scalar");return value}function flowEnd(text,line){let depth=0;for(let i=0;i<text.length;i++){let c=text[i];if(c==="'"||c==='"'){let end=quoteEnd(text,i);if(end===-1)fail2(line,"an unterminated string");i=end-1}else if(c==="{"||c==="[")depth++;else if(c==="}"||c==="]"){if(--depth===0)return i+1}}return fail2(line,"a flow collection over several lines")}function scalar(text,line){if(text.startsWith("'")||text.startsWith('"')){let end=quoteEnd(text,0);if(end===-1)fail2(line,"an unterminated string");if(text.slice(end).replace(COMMENT,"").trim()!=="")fail2(line,"text after a quoted scalar");return unquote(text.slice(0,end))}if(text.startsWith("{")||text.startsWith("[")){let end=flowEnd(text,line);if(text.slice(end).replace(COMMENT,"").trim()!=="")fail2(line,"text after a flow collection");return text.slice(0,end)}if(UNSUPPORTED.test(text))fail2(line,`unsupported syntax "${text[0]}"`);return text.replace(COMMENT,"")}function keyOf(text,line){if(text.startsWith("'")||text.startsWith('"')){let end=quoteEnd(text,0);if(end===-1)fail2(line,"an unterminated key");if(text[end]!==":")return;return{key:unquote(text.slice(0,end)),rest:text.slice(end+1)}}let colon=text.search(KEY_END);if(colon===-1)return;return{key:text.slice(0,colon),rest:text.slice(colon+1)}}class Parser{at=0;lines;constructor(lines){this.lines=lines}block(indent){let first=this.lines[this.at];if(!first||first.indent!==indent)return"";return first.text==="-"||first.text.startsWith("- ")?this.sequence(indent):this.mapping(indent,{})}value(rest,indent,line){let text=rest.trim();if(EMPTY_MAP.test(text))return{};if(EMPTY_LIST.test(text))return[];if(text!==""&&!text.startsWith("#"))return scalar(text,line);let next=this.lines[this.at];return next&&next.indent>indent?this.block(next.indent):""}mapping(indent,into){for(let line=this.lines[this.at];line;line=this.lines[this.at]){if(line.indent<indent)break;if(line.indent>indent)fail2(line,"unexpected indentation");let entry=keyOf(line.text,line);if(!entry)fail2(line,"a line that isn't a key");if(Object.hasOwn(into,entry.key))fail2(line,"a duplicate key");this.at++,into[entry.key]=this.value(entry.rest,indent,line)}return into}sequence(indent){let items=[];for(let line=this.lines[this.at];line;line=this.lines[this.at]){if(line.indent<indent)break;if(line.indent>indent)fail2(line,"unexpected indentation");if(line.text!=="-"&&!line.text.startsWith("- "))break;this.at++;let text=line.text.slice(1).trimStart(),inner={...line,indent:line.indent+2,text};if(text!==""&&keyOf(text,line))this.lines.splice(this.at,0,inner),items.push(this.mapping(inner.indent,{}));else items.push(this.value(text,indent,line))}return items}}function parseYaml(text){let parser=new Parser(linesOf(text)),value=parser.block(0),left=parser.lines[parser.at];if(left)fail2(left,"unexpected indentation");return value}var DEP_FIELDS2=["dependencies","devDependencies","peerDependencies","optionalDependencies"];function isRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isStringRecord3(value){return isRecord3(value)&&Object.values(value).every((item)=>typeof item==="string")}var STRING_OR_TRAILING_COMMA=/"(?:[^"\\]|\\.)*"|,(\s*[}\]])/g;function parseLenient(text){return JSON.parse(text.replace(STRING_OR_TRAILING_COMMA,(match,close)=>close??match))}function specsOf(value){let specs=new Map;for(let field of DEP_FIELDS2){let deps=value[field];if(deps===void 0)continue;if(!isStringRecord3(deps))return;specs.set(field,new Map(Object.entries(deps)))}return specs}function restOf(value,skip){return JSON.stringify(Object.entries(value).filter(([key])=>!skip.includes(key)))}function install(packages,name,entry,version,info){let installed=packages.get(name)??{entries:[],versions:[],dependencies:new Set,bin:!1};if(info?.bin!==void 0||info?.hasBin===!0||info?.hasBin==="true")installed.bin=!0;if(installed.entries.push(JSON.stringify(entry)),!installed.versions.includes(version))installed.versions.push(version);for(let field of["dependencies","optionalDependencies","peerDependencies"]){let deps=info?.[field];if(isRecord3(deps))for(let dep of Object.keys(deps))installed.dependencies.add(dep)}packages.set(name,installed)}function installedName(key){let parts=key.split("/"),last=parts.length-1;return last>0&&parts[last-1].startsWith("@")?`${parts[last-1]}/${parts[last]}`:parts[last]}function parseBunLock(text){let value=parseLenient(text);if(!isRecord3(value))return;let{packages,workspaces}=value;if(!isRecord3(packages)||!isRecord3(workspaces))return;let lockfile={packages:new Map,workspaces:new Map,rest:restOf(value,["packages","workspaces"])};for(let[key,entry]of Object.entries(packages)){if(!Array.isArray(entry)||typeof entry[0]!=="string")return;let ident=entry[0],at=ident.indexOf("@",1),version=at===-1?"":ident.slice(at+1);install(lockfile.packages,installedName(key),entry,version,entry.find(isRecord3))}for(let[dir,workspace]of Object.entries(workspaces)){let specs=isRecord3(workspace)?specsOf(workspace):void 0;if(!specs)return;lockfile.workspaces.set(dir===""?".":dir,specs)}return lockfile}var NODE_MODULES="node_modules/";function parsePackageLock(text){let value=JSON.parse(text);if(!isRecord3(value)||!isRecord3(value.packages))return;let{lockfileVersion}=value;if(lockfileVersion!==2&&lockfileVersion!==3)return;let lockfile={packages:new Map,workspaces:new Map,rest:restOf(value,["packages","dependencies","name","version"])};for(let[key,entry]of Object.entries(value.packages)){if(!isRecord3(entry))return;let at=key.lastIndexOf(NODE_MODULES);if(at!==-1&&(at===0||key[at-1]==="/")){let version=typeof entry.version==="string"?entry.version:"",name=key.slice(at+NODE_MODULES.length);install(lockfile.packages,name,entry,version,entry);continue}let specs=specsOf(entry);if(!specs)return;lockfile.workspaces.set(key===""?".":key,specs)}return lockfile}function pnpmKey(key){let bare=key.startsWith("/")?key.slice(1):key,at=bare.indexOf("@",1);if(at===-1)return;return{name:bare.slice(0,at),version:withoutPeers(bare.slice(at+1))}}function withoutPeers(version){let paren=version.indexOf("(");return paren===-1?version:version.slice(0,paren)}var YAML_DOCUMENT=/^---[ \t]*$/m,PNPM_VERSION=/^[69]\./,PNPM_DEP_FIELDS=["dependencies","devDependencies","optionalDependencies"];function parsePnpmLock(text){let docs=text.split(YAML_DOCUMENT).filter((doc)=>doc.trim()!=="").map(parseYaml),main=docs.findLast((doc)=>isRecord3(doc)&&typeof doc.lockfileVersion==="string");if(!isRecord3(main))return;let{lockfileVersion,packages={},snapshots={}}=main;if(typeof lockfileVersion!=="string")return;if(!PNPM_VERSION.test(lockfileVersion))return;if(!isRecord3(packages)||!isRecord3(snapshots))return;let workspaces=isRecord3(main.importers),importers=isRecord3(main.importers)?main.importers:{".":main},lockfile={packages:new Map,workspaces:new Map,rest:JSON.stringify([restOf(main,["importers","packages","snapshots",...PNPM_DEP_FIELDS]),...docs.filter((doc)=>doc!==main)])},restOfImporters=[];for(let[dir,importer]of Object.entries(importers)){if(!isRecord3(importer))return;let specs=new Map;for(let field of PNPM_DEP_FIELDS){let deps=importer[field];if(deps===void 0)continue;if(!isRecord3(deps))return;let declared=new Map;for(let[name,dep]of Object.entries(deps)){if(!isRecord3(dep)||typeof dep.specifier!=="string")return;declared.set(name,dep.specifier);let version=typeof dep.version==="string"?dep.version:"";install(lockfile.packages,name,[dir,field,version],withoutPeers(version),{})}specs.set(field,declared)}if(lockfile.workspaces.set(dir,specs),workspaces){let settings=restOf(importer,PNPM_DEP_FIELDS);if(settings!=="[]")restOfImporters.push([dir,settings])}}lockfile.rest+=JSON.stringify(restOfImporters);for(let section of[packages,snapshots])for(let[key,entry]of Object.entries(section)){let parsed=pnpmKey(key);if(!parsed)return;let info=isRecord3(entry)?entry:void 0;install(lockfile.packages,parsed.name,[key,entry],parsed.version,info)}return lockfile}var FORMATS=new Map([["bun.lock",parseBunLock],["package-lock.json",parsePackageLock],["pnpm-lock.yaml",parsePnpmLock]]),UNREAD=["bun.lockb","npm-shrinkwrap.json","yarn.lock"];function parse(file,text){let format=FORMATS.get(file);if(text===void 0||!format)return;try{return format(text)}catch{return}}function describe(name,before,after){if(before===void 0)return`${name} ${after} added`;if(after===void 0)return`${name} ${before} removed`;return before===after?`${name} ${after}, entry changed`:`${name} ${before} → ${after}`}function versions(installed){return installed&&sorted(installed.versions).join(", ")}function specChanges(before,after){let changed=new Map;for(let field of DEP_FIELDS2){let a=before?.get(field),b=after?.get(field);for(let name of new Set([...a?.keys()??[],...b?.keys()??[]]))if(a?.get(name)!==b?.get(name)&&!changed.has(name))changed.set(name,[a?.get(name),b?.get(name)])}return changed}function lockfileChanges(file,base,head){let changes=[],names=new Set([...base.packages.keys(),...head.packages.keys()]);for(let name of names){let before=base.packages.get(name),after=head.packages.get(name);if(before!==void 0&&after!==void 0&&sorted(before.entries).join(`
|
|
9
|
-
`)===sorted(after.entries).join(`
|
|
10
|
-
`))continue;changes.push({name,detail:`${file}: ${describe(name,versions(before),versions(after))}`,file})}let resolved=new Set(changes.map((change)=>change.name)),dirs=new Set([...base.workspaces.keys(),...head.workspaces.keys()]);for(let dir of dirs){let declared=specChanges(base.workspaces.get(dir),head.workspaces.get(dir));for(let[name,[before,after]]of declared){if(resolved.has(name))continue;resolved.add(name),changes.push({name,detail:`${file}: ${describe(`${name} range`,before,after)}`,file})}}return changes}var MANIFEST=/(?:^|\/)package\.json$/;function parseManifest(text){if(text===void 0)return;try{let value=JSON.parse(text);return isRecord3(value)?value:void 0}catch{return}}async function readPackageDiff(changed,listed,base,head){let lockfiles=changed.filter((file)=>FORMATS.has(file)),manifests=changed.filter((file)=>MANIFEST.test(file));if(lockfiles.length===0&&manifests.length===0)return;let read=(path)=>Promise.all([base(path),head(path)]),known=[...FORMATS.keys()],[lockTexts,manifestTexts]=await Promise.all([Promise.all(known.map((file)=>lockfiles.includes(file)?read(file):head(file).then((text)=>[text,text]))),Promise.all(manifests.map(read))]),diff={files:new Map,changes:[],dependents:new Map,declared:new Set,bins:new Set},present=new Map;for(let[i,file]of known.entries()){let[baseText,headText]=lockTexts[i],after=parse(file,headText);if(headText!==void 0)present.set(file,after);let before=parse(file,baseText);for(let lockfile of[before,after]){if(!lockfile)continue;for(let[name,installed]of lockfile.packages){if(installed.bin)diff.bins.add(name);for(let dependency of installed.dependencies){let set=diff.dependents.get(dependency)??new Set;set.add(name),diff.dependents.set(dependency,set)}}for(let specs of lockfile.workspaces.values())for(let deps of specs.values())for(let name of deps.keys())diff.declared.add(name)}if(!lockfiles.includes(file))continue;if(baseText===void 0||headText===void 0)diff.files.set(file,baseText===void 0?"added":"deleted");else if(!(before&&after))diff.files.set(file,"can't parse it");else if(before.rest===after.rest)diff.files.set(file,void 0),diff.changes.push(...lockfileChanges(file,before,after));else diff.files.set(file,"a setting other than the packages changed")}let unread=UNREAD.some((file)=>listed.includes(file));for(let[i,file]of manifests.entries()){let[before,after]=manifestTexts[i].map(parseManifest);if(!(before&&after)||unread||present.size===0)continue;let others=(record)=>restOf(record,DEP_FIELDS2),specsBefore=specsOf(before),specsAfter=specsOf(after);if(others(before)!==others(after)||!specsBefore||!specsAfter)continue;let dir=posix3.dirname(file),declared=specChanges(specsBefore,specsAfter);if(![...present.values()].every((lockfile)=>{let specs=lockfile?.workspaces.get(dir);if(!specs)return!1;return[...declared.keys()].every((name)=>DEP_FIELDS2.every((field)=>specs.get(field)?.get(name)===specsAfter.get(field)?.get(name)))}))continue;diff.files.set(file,void 0);for(let[name,[from,to]]of declared)diff.declared.add(name),diff.changes.push({name,detail:`${file}: ${describe(`${name} range`,from,to)}`,file})}return diff}function packageSeeds(graph,config,diff,files){let result={seeds:new Map,notes:[],reasons:[]},{isLoadedByName}=config,loadedOtherwise=(name)=>isLoadedByName===void 0||diff.bins.has(name)||isLoadedByName(name),tested=new Map,reachesTest=(name)=>{let found=tested.get(name);if(found===void 0){let node=`pkg:${name}`;found=graph.has(node)&&config.suites.some((suite)=>reaches(graph,[node],suite.isTest,{includeUnknown:!1,types:suite.types})),tested.set(name,found)}return found},changes=diff.changes.filter((change)=>files.includes(change.file)).sort((a,b)=>byCodeUnit(a.name,b.name)),unused=new Map,seen=new Set;for(let change of changes){let{name,detail}=change;if(seen.has(name))continue;seen.add(name);let closure=new Set([name]),queue=[name];for(let at=0;at<queue.length;at++)for(let dependent of diff.dependents.get(queue[at])??[]){if(closure.has(dependent))continue;closure.add(dependent),queue.push(dependent)}let through=[],covered=!0,importOnly=!1;for(let user of closure){let node=`pkg:${user}`,imported=graph.has(node);if(imported){if(through.push(user),!result.seeds.has(node))result.seeds.set(node,user===name?detail:`${detail}, which ${user} depends on`)}if(!(imported||diff.declared.has(user)||!diff.dependents.has(user))||reachesTest(user)||config.isInert(user))continue;if(loadedOtherwise(user)){covered=!1;let list=unused.get(user)??[];if(user===name)list.unshift(change);else list.push(change);unused.set(user,list)}else importOnly=!0}if(!covered)continue;if(through.length===0){result.notes.push(`${detail}, ${importOnly?"imported by no test":"inert"}`);continue}let others=through.filter((user)=>user!==name),shown=others.slice(0,3).join(", "),rest=others.length>3?` and ${others.length-3} more`:"";result.notes.push(others.length===0?detail:`${detail}, through ${shown}${rest}`)}for(let user of sorted(unused.keys())){let[first,...more]=unused.get(user)??[];if(!first)continue;let own=first.name===user,also=more.length===0?"":` (and ${more.length} more ${more.length===1?"package":"packages"} ${user} depends on)`;result.reasons.push({package:user,file:first.file,message:own?`${first.detail}${also}, and no test imports it`:`${first.detail}, which ${user} depends on${also}, and no test imports ${user}`})}return result}function formatSelection(selection){return selection.mode==="some"?selection.files.join(" "):selection.mode}function select(affected,tests){let files=tests.filter((file)=>affected.has(file));if(files.length===0)return{mode:"none"};if(files.length===tests.length)return{mode:"all"};return{mode:"some",files}}function classify(graph,changed,config,packages,settings){let causes=[],all=config.suites.map((suite)=>suite.name),runAll=(cause)=>causes.push({...cause,suites:all}),relevant=[],quiet=[],packageFiles=[],settingFiles=[];for(let file of changed){let read=graph.has(file),ignored=config.isIgnored(file);if(!read&&ignored)continue;let wired=config.suites.filter((suite)=>suite.isWiring(file)),diffed=packages?.files.has(file)??!1;if(config.isSelf(file)){runAll({kind:"self",file,message:`${file}: test selector changed`});continue}for(let suite of wired)causes.push({kind:"wiring",suites:[suite.name],file,message:`${file}: wires the ${suite.name} suite`});if(wired.length>0&&!diffed)continue;if(diffed){let reason=packages?.files.get(file);if(reason===void 0)packageFiles.push(file);else runAll({kind:"lockfile",file,message:`${file}: ${reason}`})}else if(read||config.roots.some((root)=>inRoot(file,root)))if(ignored)quiet.push(file);else((settings?.has(file))?settingFiles:relevant).push(file);else runAll({kind:"outside",file,message:`${file}: outside the dependency graph`})}return{relevant,quiet,packageFiles,settingFiles,causes}}function narrowedWalk(graph,seeds,{quiet,layout,types},coarse,narrowings){let matched=new Set(narrowings.flatMap((narrowing)=>narrowing.matched)),fine=affectedBy(graph,seeds.filter((seed)=>!matched.has(seed)),{quiet,layout,types});for(let narrowing of narrowings){let walk=affectedBy(graph,[...narrowing.matched,...narrowing.seeds],{opaque:narrowing.narrower.opaque,layout,types});for(let node of walk)fine.add(node)}return new Set([...fine].filter((node)=>coarse.has(node)))}function orphanOf(graph,config,suite,file){if(!suite.roots.some((root)=>inRoot(file,root)))return;if(reaches(graph,[file],(path)=>suite.isTest(path)||suite.isPage(path),{includeUnknown:!1,types:suite.types||DECLARATION.test(file)}))return;let deleted=!graph.has(file);if(deleted&&suite.isTest(file))return;if(deleted&&config.isImportOnly(file))return;if(suite.isNonInput(file))return;return{typed:!suite.types&&reaches(graph,[file],suite.isTest,{includeUnknown:!1})}}function planTests(graph,changed,config,{barrelNames=[],layout=new Set,narrowed=[],packages,settings}={}){let{relevant,quiet,packageFiles,settingFiles,causes}=classify(graph,changed,config,packages,settings),settingCauses=new Map,settingNotes=[];for(let file of settingFiles){let change=settings?.get(file);if(!change)continue;settingNotes.push(change.note);for(let seed of change.seeds)if(!settingCauses.has(seed))settingCauses.set(seed,`governed by ${file}, which changed`)}let bumped=packages&&packageFiles.length>0?packageSeeds(graph,config,packages,packageFiles):{seeds:new Map,notes:[],reasons:[]},all=config.suites.map((suite)=>suite.name);for(let unused of bumped.reasons)causes.push({kind:"package",suites:all,...unused});let seeds=[...relevant,...settingFiles,...settingCauses.keys(),...barrelNames,...packageFiles,...bumped.seeds.keys()],affected=walksByTypes(graph,seeds,{quiet,layout}),nodes=[...graph.keys()],tests=new Map(config.suites.map((suite)=>[suite.name,nodes.filter(suite.isTest)]));for(let suite of config.suites)for(let file of relevant){let orphan=orphanOf(graph,config,suite,file);if(!orphan)continue;let{typed}=orphan;causes.push({kind:"orphan",suites:[suite.name],file,message:`${file}: no ${suite.name} test imports it${typed?" (only type imports reach it: list it in the suite's `nonInputs` if nothing loads it at runtime)":""}`})}let narrowings=new Map;for(let{narrower,result}of narrowed){let matched=relevant.filter(narrower.match);if(matched.length===0)continue;if("all"in result){causes.push({kind:"narrower",suites:narrower.suites,narrower:narrower.name,message:`${narrower.name}: ${result.all}`});continue}for(let name of narrower.suites){let list=narrowings.get(name)??[];list.push({matched,narrower,seeds:result.seeds}),narrowings.set(name,list)}}let full=new Set(causes.flatMap((cause)=>cause.suites)),suites={};for(let suite of config.suites){if(full.has(suite.name)){suites[suite.name]={mode:"all"};continue}let coarse=affected(suite.types),narrowing=narrowings.get(suite.name);suites[suite.name]=select(narrowing?narrowedWalk(graph,seeds,{quiet,layout,types:suite.types},coarse,narrowing):coarse,tests.get(suite.name)??[])}return{suites,reasons:causes.map((cause)=>cause.message),causes,totals:Object.fromEntries(config.suites.map((suite)=>[suite.name,tests.get(suite.name)?.length??0])),full:[...full],packages:bumped.notes,settings:settingNotes,settingCauses,seeds,quiet,layout,packageCauses:bumped.seeds,narrowings}}import{posix as posix5}from"node:path";function plural(count,one,many=`${one}s`){return`${count} ${count===1?one:many}`}import{posix as posix4}from"node:path";var COMMENT2=/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,TRAILING_COMMA=/("(?:[^"\\]|\\.)*")|,(?=\s*[}\]])/g,BOM=/^/,RELATIVE2=/^\.\.?(?:\/|$)/;function parseJsonc(text){return JSON.parse(text.replace(BOM,"").replace(COMMENT2,(_,string)=>string??" ").replace(TRAILING_COMMA,(_,string)=>string??""))}function isStrings2(value){return Array.isArray(value)&&value.every((item)=>typeof item==="string")}function parse2(file,text){let value;try{value=parseJsonc(text)}catch(error){return{error:error instanceof Error?error.message:String(error)}}if(!isRecord2(value))return{error:"not an object"};let dir=posix4.dirname(file),{extends:extended}=value,read={extends:typeof extended==="string"?[extended]:[]};if(isStrings2(extended))read.extends=extended;let options=value.compilerOptions;if(isRecord2(options)){if(typeof options.baseUrl==="string")read.baseUrl=posix4.join(dir,options.baseUrl);if(isRecord2(options.paths)){let map={};for(let[key,targets]of Object.entries(options.paths))if(isStrings2(targets))map[key]=targets;read.paths={map,dir}}}return{read}}function extendsPath(file,target){if(!RELATIVE2.test(target))return;let path=posix4.join(posix4.dirname(file),target);return path.startsWith("../")||path===".."?void 0:path}async function readTsconfigs(files,read){let parsed=new Map,load=async(file,extended)=>{if(parsed.has(file))return;parsed.set(file,void 0);let text=await read(file,extended);if(text===void 0){if(!file.endsWith(".json"))await load(`${file}.json`,!0);return}let result=parse2(file,text);if(parsed.set(file,result),!("read"in result))return;await Promise.all(result.read.extends.map((target)=>{let path=extendsPath(file,target);return path===void 0?void 0:load(path,!0)}))};await Promise.all(files.map((file)=>load(file,!1)));let found=(path)=>{let at=parsed.get(path);if(at!==void 0||path.endsWith(".json"))return at;return parsed.get(`${path}.json`)},effective=(file,seen)=>{let at=found(file);if(at===void 0)return{extends:[]};if(!("read"in at)||seen.has(file))return;let chain=new Set([...seen,file]),merged={extends:[]};for(let target of at.read.extends){let path=extendsPath(file,target);if(path===void 0)continue;let base=effective(path,chain);if(base===void 0)return;if(base.baseUrl!==void 0)merged.baseUrl=base.baseUrl;if(base.paths!==void 0)merged.paths=base.paths}if(at.read.baseUrl!==void 0)merged.baseUrl=at.read.baseUrl;if(at.read.paths!==void 0)merged.paths=at.read.paths;return merged},chain=(file,into)=>{if(into.has(file))return;into.add(file);let at=found(file);if(at===void 0&&!file.endsWith(".json"))into.add(`${file}.json`);if(at===void 0||!("read"in at))return;for(let target of at.read.extends){let path=extendsPath(file,target);if(path!==void 0)chain(path,into)}},tsconfigs=new Map,sources=new Map;for(let file of files){if(parsed.get(file)===void 0)continue;let chained=new Set;chain(file,chained),sources.set(posix4.dirname(file),[...chained]);let options=effective(file,new Set),resolved={paths:{}};if(options?.baseUrl!==void 0)resolved.baseUrl=options.baseUrl;let{paths}=options??{};if(paths){let base=options?.baseUrl??paths.dir;for(let[key,targets]of Object.entries(paths.map))resolved.paths[key]=targets.map((target)=>posix4.join(base,target))}tsconfigs.set(posix4.dirname(file),resolved)}let unparsed=[];for(let file of sorted(parsed.keys())){let at=parsed.get(file);if(at&&"error"in at)unparsed.push({file,reason:at.error})}return{tsconfigs,sources,unparsed}}var METADATA=new Set(["author","bugs","contributors","description","engines","files","funding","homepage","keywords","license","maintainers","private","publishConfig","repository","version"]),MANIFEST2=/(?:^|\/)package\.json$/,TSCONFIG=/(?:^|\/)tsconfig\.json$/;function within(file,dir){return dir==="."||file.startsWith(`${dir}/`)}function governed(files,dirs,dir){let deeper=dirs.filter((other)=>other!==dir&&within(other,dir));return files.filter((file)=>within(file,dir)&&!deeper.some((other)=>within(file,other)))}function parsed(text,jsonc){if(text===void 0)return;try{return jsonc?parseJsonc(text):JSON.parse(text)}catch{return null}}function changedKeys(before,after){if(!(isRecord2(before)&&isRecord2(after)))return;return[...new Set([...Object.keys(before),...Object.keys(after)])].filter((key)=>JSON.stringify(before[key])!==JSON.stringify(after[key]))}async function settingChanges({changed,files,tsconfigs,packages,accounted,base,head}){let tsDirs=[...tsconfigs.keys()],packageDirs=[...packages],candidates=changed.filter((file)=>TSCONFIG.test(file)||MANIFEST2.test(file)&&!accounted.has(file)||tsDirs.some((dir)=>tsconfigs.get(dir)?.includes(file))),texts=await Promise.all(candidates.map((file)=>Promise.all([base(file),head(file)]))),result=new Map;for(let[i,file]of candidates.entries()){let[before,after]=texts[i],manifest=MANIFEST2.test(file),keys=changedKeys(parsed(before,!manifest),parsed(after,!manifest)),counted=keys?.filter((key)=>!(manifest&&METADATA.has(key))),own=posix5.dirname(file),dirs=manifest?[own]:tsDirs.filter((dir)=>tsconfigs.get(dir)?.includes(file));if(TSCONFIG.test(file)&&!dirs.includes(own))dirs.push(own);let all=[...new Set([...manifest?packageDirs:tsDirs,...dirs])];if(keys!==void 0&&counted?.length===0){let what=keys.length===0?"only formatting or comments":`only ${keys.join(", ")}`;result.set(file,{seeds:[],note:`${file}: ${what} changed, which no file resolves or runs by`});continue}let seeds=[...new Set(dirs.flatMap((dir)=>governed(files,all,dir)))],what=manifest?"resolve or run":"resolve or compile";result.set(file,{seeds,note:`${file}: changes how the ${plural(seeds.length,"file")} it governs ${what}`})}return result}function hasCode(error,codes){return error instanceof Error&&"code"in error&&typeof error.code==="string"&&codes.includes(error.code)}async function readIfFile(path){try{return await readFile3(path,"utf-8")}catch(error){if(hasCode(error,["ENOENT","EISDIR"]))return;throw error}}function collectPackages(rootJson,sources){let packages=new Map,parse=(text)=>{try{return toPackageJson(JSON.parse(text))}catch{return{}}};if(rootJson!==void 0)packages.set(".",parse(rootJson));for(let[path,text]of sources){if(path==="package.json"||!path.endsWith("/package.json"))continue;packages.set(posix6.dirname(path),parse(text))}return packages}var READS_IN_FLIGHT=64;async function inParallel(tasks,limit){let next=0,worker=()=>next<tasks.length?tasks[next++]().then(worker):Promise.resolve();await Promise.all(Array.from({length:Math.min(limit,tasks.length)},worker))}async function isFile(path){try{return(await stat2(path)).isFile()}catch(error){if(hasCode(error,["ENOENT","ENOTDIR"]))return!1;throw error}}async function extractRevision(root,revision,cache){let extractions=new Map,texts=new Map,missing=new Set,tasks=[],cached=0,read=async(file)=>{let text=await readIfFile(join4(root,file));if(text===void 0)missing.add(file);return text};for(let file of revision.files)if(SCANNED.test(file)){let format=formatOf(file),oid=revision.blobs.get(file),hit=oid===void 0?void 0:cache.get(oid,format);if(hit){extractions.set(file,hit),cached++;continue}tasks.push(()=>read(file).then((source)=>{if(source===void 0)return;let extraction=extract(format,source);if(extractions.set(file,extraction),oid!==void 0)cache.set(oid,format,extraction)}))}else if(file.endsWith("/package.json"))tasks.push(()=>read(file).then((source)=>{if(source!==void 0)texts.set(file,source)}));else if(!revision.present.has(file))tasks.push(()=>isFile(join4(root,file)).then((found)=>{if(!found)missing.add(file)}));await inParallel(tasks,READS_IN_FLIGHT);let files=revision.files.filter((file)=>!missing.has(file)),manifests=new Map;for(let file of files){let text=texts.get(file);if(text!==void 0)manifests.set(file,text)}return{files,extractions,manifests,extracted:{cached,read:extractions.size-cached}}}function graphView(graph,config){let nodes=[...graph.keys()];return{nodes:()=>nodes,importers:(node)=>importersOf(graph,node),dependents:(from)=>affectedBy(graph,from,{includeUnknown:!1}),tests:(name)=>{let suite=config.suites.find((candidate)=>candidate.name===name);if(!suite)throw Error(`bivium: no suite "${name}"`);return nodes.filter(suite.isTest)}}}function messageOf(error){return error instanceof Error?error.message:String(error)}async function runNarrowers(root,revision,graph,config,suites,packages,settings){let{relevant}=classify(graph,revision.changed,config,packages,settings),wanted=config.narrowers.filter((narrower)=>relevant.some(narrower.match)&&(suites===void 0||narrower.suites.some((name)=>suites.includes(name))));if(wanted.length===0)return[];let view=graphView(graph,config),base={commit:await revision.mergeBase(),read:revision.readBase},head={commit:void 0,read:(path)=>readIfFile(join4(root,path))};return Promise.all(wanted.map(async(narrower)=>{let changed=relevant.filter(narrower.match);try{let result=await narrower.narrow({root,base,head,changed,graph:view});return{narrower,result}}catch(error){return{narrower,result:{all:`failed: ${messageOf(error)}`}}}}))}async function computePlan(root,base,config,{cache:cacheOption=config.cache,suites,mergeBase=!1}={}){let dir=cacheDir(root,cacheOption),[revision,rootJson,cache]=await Promise.all([readRevision(root,base,config.roots,{blobs:dir!==void 0,mergeBase}),readFile3(join4(root,"package.json"),"utf-8").catch(()=>{return}),ExtractionCache.open(dir)]);if(revision.changed.some((file)=>config.narrowers.some((narrower)=>narrower.match(file))))revision.mergeBase();let listed,readTsconfig=async(file,extended)=>{if(extended){if(listed??=new Set(revision.listed),!listed.has(file))return}return readIfFile(join4(root,file))},[{files,extractions,manifests,extracted},ts,packageDiff]=await Promise.all([extractRevision(root,revision,cache),readTsconfigs(["tsconfig.json",...revision.files.filter((file)=>file.endsWith("/tsconfig.json"))],readTsconfig),readPackageDiff(revision.changed,revision.listed,revision.readBase,(path)=>readIfFile(join4(root,path)))]),{tsconfigs}=ts,basePending=new Map(revision.changed.filter((file)=>config.isBarrel(file)&&extractions.get(file)?.barrel).map((file)=>[file,revision.readBase(file)])),packages=collectPackages(rootJson,manifests),graph=graphFrom(files,extractions,{config,packages,tsconfigs}),saved=cache.save(),settings=await settingChanges({changed:revision.changed,files,tsconfigs:ts.sources,packages:packages.keys(),accounted:new Set(packageDiff?.files.keys()),base:revision.readBase,head:(path)=>readIfFile(join4(root,path))}),barrelNames=(await Promise.all([...basePending].map(async([file,pending])=>{let head=graph.get(file)?.barrel;if(!head)return[];let before=baseBarrelNames(file,await pending,{config,packages,tsconfigs},graph);return(before?changedBarrelNames(before,head):[...head.keys()]).map((name)=>`${file}#${name}`)}))).flat(),narrowed=await runNarrowers(root,revision,graph,config,suites,packageDiff,settings),planned=planTests(graph,revision.changed,config,{barrelNames,layout:revision.layout,narrowed,packages:packageDiff,settings});return await saved,{plan:planned,graph,changed:revision.changed,mergeBase:revision.mergeBase,barrelNames,narrowed,packages,tsconfigs,unparsedTsconfigs:ts.unparsed,extractions,listed:revision.listed,fallbacks:new Map([...extractions].flatMap(([file,extraction])=>extraction.fallback===void 0?[]:[[file,extraction.fallback]])),extracted}}async function prepare({cwd=process.cwd(),base,config,configFile}){let root=resolve2(cwd),resolved;if(config)resolved=resolveConfig(checkConfig(config));else{let loaded=await loadConfig(root,configFile),isSelf=loaded.config.isSelf;resolved={...loaded.config,file:loaded.file,isSelf:(path)=>path===loaded.file||isSelf(path)}}return{root,base:base??resolved.base??await defaultBase(root),config:resolved}}async function plan2(options={}){let{root,base,config}=await prepare(options),computed=await computePlan(root,base,config,{...options.cache!==void 0&&{cache:options.cache},mergeBase:!0});return{suites:computed.plan.suites,reasons:computed.plan.reasons,causes:computed.plan.causes,totals:computed.plan.totals,packages:computed.plan.packages,base,mergeBase:await computed.mergeBase(),changed:computed.changed,narrowed:computed.narrowed.map(({narrower,result})=>({name:narrower.name,result}))}}
|
|
11
|
-
export{version,globToRegExp,defineConfig2,sorted,QUERY,UNDECLARED_READS,RELATIVE,aliasPath,createResolver,SCANNED,formatOf,extract,finish,gotoPage,walksByTypes,importersOf,affectedBy,formatSelection,orphanOf,plural,computePlan,prepare,plan2};
|