bivium 0.9.0 → 0.11.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.
@@ -0,0 +1,1047 @@
1
+ import {
2
+ SEPARATOR2,
3
+ branch2,
4
+ NOTE_INDENT2,
5
+ closingLine2,
6
+ failLine2,
7
+ truncateWords2,
8
+ truncatePath2,
9
+ textWidth2,
10
+ MEASURE2,
11
+ plural2
12
+ } from "./shared-mpjk8met.js";
13
+ import {
14
+ globToRegExp,
15
+ inRoot2
16
+ } from "./shared-qaqjsxsk.js";
17
+ import {
18
+ fanIn2
19
+ } from "./shared-8kbmg99n.js";
20
+ import {
21
+ duration,
22
+ wrapped
23
+ } from "./shared-b9dpffxv.js";
24
+ import {
25
+ QUERY,
26
+ UNDECLARED_READS,
27
+ RELATIVE,
28
+ aliasPath,
29
+ SCANNED,
30
+ formatOf,
31
+ stringsOf,
32
+ finish,
33
+ walksByTypes,
34
+ affectedBy,
35
+ sorted,
36
+ isPackageFile,
37
+ orphanOf
38
+ } from "./shared-wxem8d5w.js";
39
+
40
+ // src/check.ts
41
+ import { statSync } from "node:fs";
42
+ import { join as join2, posix as posix2 } from "node:path";
43
+
44
+ // src/locate.ts
45
+ import { readFile } from "node:fs/promises";
46
+ import { isAbsolute, join } from "node:path";
47
+ var DISK_READ = /\bfrom\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\brequire\s*\(\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\bBun\.(?:file|Glob|spawn)/;
48
+ var NON_LITERAL_IMPORT = /\b(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\s*(?:<[^>]*>)?\(\s*(?!["'][^"'`$]*["']\s*[,)])/;
49
+ var GLOB_CALL = /\bimport\.meta\.glob/;
50
+ var QUOTED_CAUSE = /"([^"]+)"/;
51
+ var LOADS = /\b(?:import|export|from|require|mock|doMock|unmock|importActual|importMock)\b|\b(?:src|href)\s*=/;
52
+ var GOTO_CALL = /\bgoto\s*\(/;
53
+ function lineAt(source, index) {
54
+ let line = 1;
55
+ for (let i = source.indexOf(`
56
+ `);i !== -1 && i < index; i = source.indexOf(`
57
+ `, i + 1)) {
58
+ line++;
59
+ }
60
+ return line;
61
+ }
62
+ function lineOf(source, needle) {
63
+ const index = typeof needle === "string" ? source.indexOf(needle) : source.search(needle);
64
+ return index === -1 ? undefined : lineAt(source, index);
65
+ }
66
+ function commentRanges(source) {
67
+ const ranges = [];
68
+ for (let i = 0;i < source.length; i++) {
69
+ const c = source[i];
70
+ if (c === '"' || c === "'") {
71
+ while (++i < source.length && source[i] !== c && source[i] !== `
72
+ `) {
73
+ if (source[i] === "\\")
74
+ i++;
75
+ }
76
+ } else if (c === "`") {
77
+ while (++i < source.length && source[i] !== "`") {
78
+ if (source[i] === "\\")
79
+ i++;
80
+ }
81
+ } else if (source.startsWith("//", i)) {
82
+ const end = source.indexOf(`
83
+ `, i);
84
+ ranges.push([i, end === -1 ? source.length : end]);
85
+ i = end === -1 ? source.length : end;
86
+ } else if (source.startsWith("/*", i) || source.startsWith("<!--", i)) {
87
+ const close = c === "/" ? "*/" : "-->";
88
+ const end = source.indexOf(close, i + 2);
89
+ const stop = end === -1 ? source.length : end + close.length;
90
+ ranges.push([i, stop]);
91
+ i = stop - 1;
92
+ }
93
+ }
94
+ return ranges;
95
+ }
96
+ function lineTextAt(source, index) {
97
+ const start = source.lastIndexOf(`
98
+ `, index - 1) + 1;
99
+ const end = source.indexOf(`
100
+ `, index);
101
+ return source.slice(start, end === -1 ? source.length : end);
102
+ }
103
+ function bestLine(source, needles, near) {
104
+ let comments;
105
+ const inComment = (index) => {
106
+ comments ??= commentRanges(source);
107
+ return comments.some(([start, end]) => index >= start && index < end);
108
+ };
109
+ let code;
110
+ let any;
111
+ for (const needle of needles) {
112
+ for (let index = source.indexOf(needle);index !== -1; index = source.indexOf(needle, index + 1)) {
113
+ any ??= index;
114
+ if (inComment(index))
115
+ continue;
116
+ if (near === undefined || near.test(lineTextAt(source, index))) {
117
+ return lineAt(source, index);
118
+ }
119
+ code ??= index;
120
+ }
121
+ }
122
+ const found = code ?? any;
123
+ return found === undefined ? undefined : lineAt(source, found);
124
+ }
125
+ function specifierLine(source, specifier) {
126
+ const quoted = ['"', "'", "`"].map((quote) => `${quote}${specifier}${quote}`);
127
+ return bestLine(source, quoted, LOADS) ?? bestLine(source, [specifier]);
128
+ }
129
+ function gotoLine(source, argument, page) {
130
+ return (argument === undefined ? undefined : bestLine(source, [argument], GOTO_CALL)) ?? bestLine(source, [page.slice(page.lastIndexOf("/") + 1)], GOTO_CALL);
131
+ }
132
+ function callLine(source, call) {
133
+ return bestLine(source, [call]);
134
+ }
135
+ function causeLine(source, cause) {
136
+ if (cause.startsWith("unresolved ")) {
137
+ const specifier = QUOTED_CAUSE.exec(cause)?.[1];
138
+ return specifier === undefined ? undefined : specifierLine(source, specifier);
139
+ }
140
+ if (cause === "non-literal dynamic import")
141
+ return lineOf(source, NON_LITERAL_IMPORT);
142
+ if (cause === "non-literal glob import")
143
+ return lineOf(source, GLOB_CALL);
144
+ if (cause === UNDECLARED_READS) {
145
+ return lineOf(source, DISK_READ);
146
+ }
147
+ if (cause.startsWith("non-literal goto(")) {
148
+ return lineOf(source, cause.slice("non-literal ".length, -1));
149
+ }
150
+ const url = QUOTED_CAUSE.exec(cause)?.[1];
151
+ return url === undefined ? undefined : lineOf(source, url);
152
+ }
153
+ function textLine(source, text) {
154
+ return lineOf(source, text);
155
+ }
156
+ function annotationLine(source, tag, glob) {
157
+ const index = source.split(`
158
+ `).findIndex((line) => line.includes(tag) && line.includes(glob));
159
+ return index === -1 ? undefined : index + 1;
160
+ }
161
+ function lineText(source, line) {
162
+ let start = 0;
163
+ for (let n = 1;n < line; n++) {
164
+ const next = source.indexOf(`
165
+ `, start);
166
+ if (next === -1)
167
+ return "";
168
+ start = next + 1;
169
+ }
170
+ const end = source.indexOf(`
171
+ `, start);
172
+ return source.slice(start, end === -1 ? source.length : end).trim();
173
+ }
174
+ async function sourceOf(root, file) {
175
+ try {
176
+ return await readFile(isAbsolute(file) ? file : join(root, file), "utf-8");
177
+ } catch {
178
+ return;
179
+ }
180
+ }
181
+ function fileOf(node) {
182
+ const hash = node.indexOf("#");
183
+ return hash === -1 ? node : node.slice(0, hash);
184
+ }
185
+ async function causesOf(root, computed, node) {
186
+ const file = fileOf(node);
187
+ const source = await sourceOf(root, file);
188
+ return (computed.graph.get(node)?.unknown ?? []).map((cause) => {
189
+ if (source === undefined)
190
+ return { cause };
191
+ const line = causeLine(source, cause);
192
+ return line === undefined ? { cause } : { cause, at: `${file}:${line}`, text: lineText(source, line) };
193
+ });
194
+ }
195
+
196
+ // src/spelled.ts
197
+ import { posix } from "node:path";
198
+ var PATH_LIKE = /^[\w@.+~()[\]-]+(?:\/[\w@.+~()[\]-]+)*$/;
199
+ var LETTER = /[a-z]/i;
200
+ var LEADING_SLASHES = /^\/+/;
201
+ var TRAILING_SLASHES = /\/+$/;
202
+ var DOT_RELATIVE = /^\.\.?\//;
203
+ function candidates(file, text) {
204
+ let path = text.replace(TRAILING_SLASHES, "");
205
+ const rooted = path.startsWith("/");
206
+ if (rooted)
207
+ path = path.replace(LEADING_SLASHES, "");
208
+ if (!PATH_LIKE.test(path) || !LETTER.test(path))
209
+ return [];
210
+ const dir = posix.dirname(file);
211
+ let found;
212
+ if (rooted)
213
+ found = path.includes("/") ? [posix.normalize(path)] : [];
214
+ else if (DOT_RELATIVE.test(path))
215
+ found = [posix.join(dir, path)];
216
+ else if (path.includes("/")) {
217
+ found = [posix.normalize(path), posix.join(dir, path)];
218
+ } else
219
+ found = [posix.join(dir, path)];
220
+ return found.filter((p) => p !== "." && !p.startsWith("../"));
221
+ }
222
+ function fixFor(file, path, dir) {
223
+ if (dir) {
224
+ return `if it reads them, add \`reads: { "${file}": "${path}/**" }\` (or \`// @reads ${path}/**\`), \`@depends-on\` if it runs them, \`@lists\` if it only names them`;
225
+ }
226
+ if (SCANNED.test(path)) {
227
+ 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`;
228
+ }
229
+ return `if it reads it, add \`reads: { "${file}": "${path}" }\` (or \`// @reads ${path}\`), \`@lists\` if it only names it`;
230
+ }
231
+ function spellers(config, { graph }) {
232
+ const found = new Map;
233
+ for (const suite of config.suites) {
234
+ const reached = fanIn2(graph, suite);
235
+ for (const [node, deps] of graph) {
236
+ if (deps.unknown.length > 0 || !SCANNED.test(node))
237
+ continue;
238
+ if (node.startsWith("pkg:") || node.includes("#"))
239
+ continue;
240
+ if (suite.isTest(node) || (reached.get(node) ?? 0) > 0 && suite.roots.some((root) => inRoot2(node, root))) {
241
+ const suites = found.get(node);
242
+ suites ? suites.push(suite) : found.set(node, [suite]);
243
+ }
244
+ }
245
+ }
246
+ return new Map(sorted(found.keys()).map((node) => [node, found.get(node) ?? []]));
247
+ }
248
+ function runsAnyway(config, { graph }, suites, targets) {
249
+ if (targets.some((file) => config.isSelf(file) || suites.some((suite) => suite.isWiring(file)))) {
250
+ return "wiring";
251
+ }
252
+ const orphan = targets.some((file) => !config.isIgnored(file) && suites.some((suite) => orphanOf(graph, config, suite, file)));
253
+ return orphan ? "orphan" : undefined;
254
+ }
255
+ function withNames(graph, targets) {
256
+ return targets.flatMap((file) => [
257
+ file,
258
+ ...[...graph.get(file)?.barrel?.keys() ?? []].map((name) => `${file}#${name}`)
259
+ ]);
260
+ }
261
+ async function spelledPaths(root, config, computed, done = () => {}) {
262
+ const { graph } = computed;
263
+ const files = new Set;
264
+ const dirs = new Map;
265
+ for (const node of graph.keys()) {
266
+ if (node.startsWith("pkg:") || node.includes("#"))
267
+ continue;
268
+ files.add(node);
269
+ for (let dir = posix.dirname(node);dir !== "."; ) {
270
+ const list = dirs.get(dir);
271
+ list ? list.push(node) : dirs.set(dir, [node]);
272
+ dir = posix.dirname(dir);
273
+ }
274
+ }
275
+ const found = { undeclared: [], orphaned: [] };
276
+ const spelling = spellers(config, computed);
277
+ const nodes = [...spelling.keys()];
278
+ const sources = await Promise.all(nodes.map((node) => sourceOf(root, node)));
279
+ const every = Math.max(1, Math.ceil(nodes.length / 20));
280
+ for (const [i, node] of nodes.entries()) {
281
+ if (i % every === 0)
282
+ done(i / nodes.length);
283
+ const source = sources[i];
284
+ const suites = spelling.get(node) ?? [];
285
+ const through = [
286
+ ...affectedBy(graph, [node], { includeUnknown: false, readers: false })
287
+ ].filter((path) => suites.some((suite) => suite.isTest(path)));
288
+ if (source === undefined)
289
+ continue;
290
+ const seen = new Set;
291
+ for (const text of stringsOf(formatOf(node), source) ?? []) {
292
+ for (const path of candidates(node, text)) {
293
+ if (seen.has(path) || path === node)
294
+ continue;
295
+ seen.add(path);
296
+ const dir = !files.has(path);
297
+ if (dir && node.startsWith(`${path}/`))
298
+ continue;
299
+ const targets = dir ? dirs.get(path) : [path];
300
+ if (!targets)
301
+ continue;
302
+ const selected = affectedBy(graph, withNames(graph, targets));
303
+ if (through.every((test) => selected.has(test)))
304
+ continue;
305
+ const anyway = runsAnyway(config, computed, suites, targets);
306
+ if (anyway === "wiring")
307
+ continue;
308
+ const line = specifierLine(source, text);
309
+ const entry = {
310
+ file: node,
311
+ path,
312
+ dir,
313
+ fix: fixFor(node, path, dir)
314
+ };
315
+ if (line !== undefined)
316
+ entry.at = `${node}:${line}`;
317
+ found[anyway === "orphan" ? "orphaned" : "undeclared"].push(entry);
318
+ }
319
+ }
320
+ }
321
+ return found;
322
+ }
323
+
324
+ // src/check.ts
325
+ var EXAMPLES = 3;
326
+ var TAGS = {
327
+ "depends-on": "@depends-on",
328
+ reads: "@reads",
329
+ lists: "@lists",
330
+ glob: "import.meta.glob",
331
+ edges: "edges",
332
+ setup: "setup"
333
+ };
334
+ var QUOTED = /"([^"]+)"/;
335
+ function fixFor2(cause) {
336
+ if (cause.startsWith("unresolved ")) {
337
+ const specifier = QUOTED.exec(cause)?.[1] ?? "";
338
+ if (specifier.startsWith("./%sveltekit.assets%/")) {
339
+ 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";
340
+ }
341
+ if (RELATIVE.test(specifier)) {
342
+ return "no file at that path: fix the import, or add an `edges` entry if a build generates it";
343
+ }
344
+ if (specifier.startsWith("#")) {
345
+ return "map it in the `imports` of the file's package.json, or with `alias`";
346
+ }
347
+ 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`";
348
+ }
349
+ if (cause.startsWith("only declarations for ")) {
350
+ 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";
351
+ }
352
+ if (cause === "non-literal dynamic import") {
353
+ 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";
354
+ }
355
+ if (cause === "non-literal glob import") {
356
+ return "pass `import.meta.glob` literal patterns";
357
+ }
358
+ if (cause === UNDECLARED_READS) {
359
+ 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";
360
+ }
361
+ if (cause.startsWith("non-literal goto(")) {
362
+ 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>`";
363
+ }
364
+ if (cause.startsWith("missing fixture ")) {
365
+ return "no page at that URL: fix the URL, or the suite's `urls`";
366
+ }
367
+ if (cause.startsWith("goto(")) {
368
+ return "map the URL to a file with the suite's `urls`";
369
+ }
370
+ return "see the cause";
371
+ }
372
+ function isFile(path) {
373
+ return statSync(path, { throwIfNoEntry: false })?.isFile() ?? false;
374
+ }
375
+ function stemOf(path) {
376
+ const slash = path.lastIndexOf("/");
377
+ const dot = path.indexOf(".", slash + 2);
378
+ return dot === -1 ? path : path.slice(0, dot);
379
+ }
380
+ function nearMisses(root, config, { graph, listed }) {
381
+ let stems;
382
+ const listedSet = new Set(listed);
383
+ const siblings = (path) => {
384
+ if (!stems) {
385
+ stems = new Map;
386
+ for (const file of listed) {
387
+ const stem = stemOf(file);
388
+ const list = stems.get(stem);
389
+ list ? list.push(file) : stems.set(stem, [file]);
390
+ }
391
+ }
392
+ return stems.get(stemOf(path)) ?? [];
393
+ };
394
+ const candidates = (base) => [
395
+ base,
396
+ ...config.extensions.map((ext) => base + ext),
397
+ ...config.extensions.map((ext) => `${base}/index${ext}`)
398
+ ];
399
+ return (node, cause) => {
400
+ if (!cause.startsWith("unresolved "))
401
+ return;
402
+ const specifier = (QUOTED.exec(cause)?.[1] ?? "").replace(QUERY, "");
403
+ const base = RELATIVE.test(specifier) ? posix2.join(posix2.dirname(fileOf(node)), specifier) : config.alias.map((alias) => aliasPath(alias, specifier)).find((path) => path !== undefined);
404
+ if (base === undefined || base.startsWith("../"))
405
+ return;
406
+ const tried = candidates(base);
407
+ const outside = tried.find((path) => listedSet.has(path) && !graph.has(path));
408
+ if (outside !== undefined) {
409
+ return `${outside} exists, but outside \`roots\`: add it to \`roots\``;
410
+ }
411
+ const unlisted = tried.find((path) => isFile(join2(root, path)));
412
+ if (unlisted !== undefined && !listedSet.has(unlisted)) {
413
+ return `${unlisted} exists, but git doesn't list it (ignored?): if a build writes it, name it in \`edges\` with its inputs`;
414
+ }
415
+ const sibling = siblings(base).find((file) => graph.has(file));
416
+ if (sibling !== undefined) {
417
+ return `${sibling} exists: import it by that name, or add its extension to \`extensions\``;
418
+ }
419
+ return;
420
+ };
421
+ }
422
+ function declaredGlobs(node, extraction) {
423
+ const relative = finish(node, extraction).globs;
424
+ return [
425
+ ...extraction.dependsOn.map((glob) => ({
426
+ kind: "depends-on",
427
+ glob,
428
+ pattern: globToRegExp(glob)
429
+ })),
430
+ ...extraction.reads.map((glob) => ({
431
+ kind: "reads",
432
+ glob,
433
+ pattern: globToRegExp(glob)
434
+ })),
435
+ ...extraction.lists.map((glob) => ({
436
+ kind: "lists",
437
+ glob,
438
+ pattern: globToRegExp(glob)
439
+ })),
440
+ ...extraction.globs.map((glob, i) => {
441
+ const path = relative[i];
442
+ if (path === undefined) {
443
+ throw new Error(`bivium: check: no resolved path for glob ${glob}.`);
444
+ }
445
+ return { kind: "glob", glob, pattern: globToRegExp(path) };
446
+ })
447
+ ];
448
+ }
449
+ function problemOf(matches, ignored) {
450
+ if (matches === 0)
451
+ return "matches nothing";
452
+ if (ignored === 0)
453
+ return;
454
+ return ignored === matches ? "matches only ignored files" : "partly ignored";
455
+ }
456
+ function matchesOf(patterns, listed) {
457
+ return listed.filter((file) => patterns.some((re) => re.test(file)));
458
+ }
459
+ function deadOf(node, kind, glob, matches, skipped) {
460
+ const ignored = sorted(matches.filter(skipped));
461
+ const problem = problemOf(matches.length, ignored.length);
462
+ if (problem === undefined)
463
+ return;
464
+ return {
465
+ node,
466
+ kind,
467
+ glob,
468
+ problem,
469
+ matches: matches.length,
470
+ ignored: ignored.length,
471
+ examples: ignored.slice(0, EXAMPLES),
472
+ fix: problem === "matches nothing" ? "fix the path" : "point it at files the selector reads, or allowlist it in `deadGlobs` with a reason"
473
+ };
474
+ }
475
+ function rootsFor(files) {
476
+ const dirs = files.map((file) => posix2.dirname(file));
477
+ let common = dirs[0] ?? ".";
478
+ for (const dir of dirs) {
479
+ while (common !== "." && dir !== common && !dir.startsWith(`${common}/`)) {
480
+ common = posix2.dirname(common);
481
+ }
482
+ }
483
+ if (common !== ".")
484
+ return [common];
485
+ return sorted(new Set(files.map((file) => file.split("/")[0] ?? file)));
486
+ }
487
+ function listOf(names) {
488
+ const quoted = names.map((name) => `\`${name}\``);
489
+ const last = quoted.pop() ?? "";
490
+ return quoted.length === 0 ? last : `${quoted.join(", ")} and ${last}`;
491
+ }
492
+ function outsideOf(node, kind, glob, matches, isOutside) {
493
+ const outside = sorted(matches.filter(isOutside));
494
+ if (outside.length === 0)
495
+ return;
496
+ const roots = rootsFor(outside);
497
+ return {
498
+ node,
499
+ kind,
500
+ glob,
501
+ matches: matches.length,
502
+ outside: outside.length,
503
+ examples: outside.slice(0, EXAMPLES),
504
+ roots,
505
+ fix: `add ${listOf(roots)} to \`roots\`: a change outside them runs everything`
506
+ };
507
+ }
508
+ function problemsOf(node, kind, glob, matches, { skipped, isOutside }, found) {
509
+ const dead = deadOf(node, kind, glob, matches, skipped);
510
+ if (dead)
511
+ found.dead.push(dead);
512
+ const outside = outsideOf(node, kind, glob, matches, isOutside);
513
+ if (outside)
514
+ found.outside.push(outside);
515
+ }
516
+ function configProblems(config, { graph, listed }, filters) {
517
+ const file = config.file ?? "the config";
518
+ const found = { dead: [], outside: [] };
519
+ const entries = [
520
+ ...config.generated.map((map) => ["edges", map]),
521
+ ...config.reads.map((map) => ["reads", map])
522
+ ];
523
+ for (const [kind, map] of entries) {
524
+ const patterns = map.values.map(() => new Map);
525
+ let matched = false;
526
+ for (const node of graph.keys()) {
527
+ const targets = map.targets(node);
528
+ if (!targets)
529
+ continue;
530
+ matched = true;
531
+ for (const [i, re] of targets.entries())
532
+ patterns[i]?.set(re.source, re);
533
+ }
534
+ if (!matched) {
535
+ found.dead.push({
536
+ node: file,
537
+ kind,
538
+ glob: map.key,
539
+ problem: "matches nothing",
540
+ matches: 0,
541
+ ignored: 0,
542
+ examples: [],
543
+ fix: "fix the path: no file the graph reads matches it"
544
+ });
545
+ continue;
546
+ }
547
+ for (const [i, glob] of map.values.entries()) {
548
+ const expanded = [...patterns[i]?.values() ?? []];
549
+ const matches = matchesOf(expanded, listed);
550
+ problemsOf(file, kind, glob, matches, filters, found);
551
+ }
552
+ }
553
+ for (const suite of config.suites) {
554
+ for (const glob of suite.setup) {
555
+ const matches = matchesOf([globToRegExp(glob)], listed);
556
+ problemsOf(file, "setup", glob, matches, filters, found);
557
+ }
558
+ }
559
+ return found;
560
+ }
561
+ async function findGlobProblems(root, config, computed) {
562
+ const { graph, extractions, listed } = computed;
563
+ const filters = {
564
+ skipped: (file) => config.isIgnored(file) && !graph.has(file),
565
+ isOutside: (file) => !graph.has(file) && !config.roots.some((path) => inRoot2(file, path)) && !config.isIgnored(file) && !config.isSelf(file) && !config.suites.some((suite) => suite.isWiring(file)) && !isPackageFile(file)
566
+ };
567
+ const found = { dead: [], outside: [] };
568
+ for (const node of graph.keys()) {
569
+ const extraction = extractions.get(node);
570
+ if (!extraction)
571
+ continue;
572
+ for (const { kind, glob, pattern } of declaredGlobs(node, extraction)) {
573
+ const matches = matchesOf([pattern], listed);
574
+ problemsOf(node, kind, glob, matches, filters, found);
575
+ }
576
+ }
577
+ const configured = configProblems(config, computed, filters);
578
+ const nodes = [
579
+ ...new Set([found, configured].flatMap(({ dead, outside }) => [...dead, ...outside].map(({ node }) => node)))
580
+ ];
581
+ const texts = await Promise.all(nodes.map((node) => sourceOf(root, node)));
582
+ const sources = new Map(nodes.map((node, i) => [node, texts[i]]));
583
+ const locate = (annotated) => (entry) => {
584
+ const source = sources.get(entry.node);
585
+ if (source === undefined)
586
+ return entry;
587
+ const at = annotated && entry.kind !== "glob" ? annotationLine(source, TAGS[entry.kind], entry.glob) : specifierLine(source, entry.glob);
588
+ return at === undefined ? entry : { ...entry, at: `${entry.node}:${at}` };
589
+ };
590
+ return {
591
+ dead: [
592
+ ...found.dead.map(locate(true)),
593
+ ...configured.dead.map(locate(false))
594
+ ],
595
+ outside: [
596
+ ...found.outside.map(locate(true)),
597
+ ...configured.outside.map(locate(false))
598
+ ]
599
+ };
600
+ }
601
+ var CONFIG_FILE = /(?:^|[./_-])(?:config|setup|teardown|harness)(?:[./_-]|$)|^tsconfig[^/]*\.json$|^\.[^/]*rc(?:\.[^/]+)?$/;
602
+ function unreachedFix(file, tests, spelled) {
603
+ const named = spelled.find(({ path }) => file === path || file.startsWith(`${path}/`));
604
+ if (named !== undefined) {
605
+ return `${named.at ?? named.file} names ${named.path}: ${named.fix}`;
606
+ }
607
+ const name = posix2.basename(file);
608
+ const owner = tests.find((test) => name.startsWith(`${posix2.basename(test)}.`));
609
+ if (owner !== undefined) {
610
+ return `if ${owner} reads it, add \`reads: { "${owner}": "${file}" }\` (or \`// @reads ${file}\` in the test)`;
611
+ }
612
+ if (CONFIG_FILE.test(name)) {
613
+ 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";
614
+ }
615
+ 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";
616
+ }
617
+ function unreachedFiles(config, { graph }, spelled) {
618
+ const found = [];
619
+ const files = [...graph.keys()].filter((node) => !node.startsWith("pkg:") && !node.includes("#"));
620
+ for (const suite of config.suites) {
621
+ const reached = fanIn2(graph, suite);
622
+ const tests = files.filter(suite.isTest);
623
+ for (const file of files) {
624
+ if ((reached.get(file) ?? 0) > 0)
625
+ continue;
626
+ if (config.isIgnored(file) || config.isSelf(file))
627
+ continue;
628
+ if (suite.isWiring(file))
629
+ continue;
630
+ if (!orphanOf(graph, config, suite, file))
631
+ continue;
632
+ found.push({
633
+ suite: suite.name,
634
+ file,
635
+ fix: unreachedFix(file, tests, spelled)
636
+ });
637
+ }
638
+ }
639
+ return found;
640
+ }
641
+ async function check2(root, config, computed, step = () => {}) {
642
+ step("finding what the graph can't read", 0.05);
643
+ const nodes = [...computed.graph].filter(([, deps]) => deps.unknown.length > 0).map(([node]) => node);
644
+ const testsOf = (node) => {
645
+ const reach = walksByTypes(computed.graph, [node], {
646
+ includeUnknown: false,
647
+ readers: false
648
+ });
649
+ const found = new Set;
650
+ for (const suite of config.suites) {
651
+ for (const test of reach(suite.types)) {
652
+ if (suite.isTest(test))
653
+ found.add(test);
654
+ }
655
+ }
656
+ return sorted(found);
657
+ };
658
+ const nearMiss = nearMisses(root, config, computed);
659
+ const known = new Map((config.knownUnknowns ?? []).map((entry) => [entry.file, entry.reason]));
660
+ const unknown = await Promise.all(nodes.map(async (node) => {
661
+ const causes = (await causesOf(root, computed, node)).map(({ cause, at }) => {
662
+ const fix = nearMiss(node, cause) ?? fixFor2(cause);
663
+ return at === undefined ? { cause, fix } : { cause, at, fix };
664
+ });
665
+ const reason = known.get(node);
666
+ const entry = { node, causes, tests: testsOf(node) };
667
+ if (reason !== undefined)
668
+ entry.known = reason;
669
+ return entry;
670
+ }));
671
+ const fallbacks = [...computed.fallbacks].map(([file, reason]) => ({
672
+ file,
673
+ reason
674
+ }));
675
+ step("finding dead globs", 0.1);
676
+ const globs = await findGlobProblems(root, config, computed);
677
+ const { dead } = globs;
678
+ const spelling = "finding paths nothing declares";
679
+ const spelled = await spelledPaths(root, config, computed, (ratio) => step(spelling, 0.15 + 0.8 * ratio));
680
+ step("finding files no test reaches", 0.95);
681
+ const unreached = unreachedFiles(config, computed, [
682
+ ...spelled.undeclared,
683
+ ...spelled.orphaned
684
+ ]);
685
+ const allows = (entry, found) => entry.file === found.node && entry.glob === found.glob;
686
+ return {
687
+ unknown,
688
+ fallbacks,
689
+ unparsedTsconfigs: computed.unparsedTsconfigs,
690
+ deadGlobs: dead.filter((found) => !config.deadGlobs.some((entry) => allows(entry, found))),
691
+ outsideRoots: globs.outside,
692
+ unlistedUnknowns: config.knownUnknowns ? unknown.filter((entry) => entry.tests.length > 0 && entry.known === undefined).map((entry) => entry.node) : [],
693
+ staleKnownUnknowns: (config.knownUnknowns ?? []).filter((entry) => !nodes.includes(entry.file)).map((entry) => ({
694
+ ...entry,
695
+ fix: "remove the entry: its dependencies are known now"
696
+ })),
697
+ unreached,
698
+ undeclaredPaths: spelled.undeclared,
699
+ staleDeadGlobs: config.deadGlobs.filter((entry) => !dead.some((found) => allows(entry, found))).map((entry) => ({
700
+ ...entry,
701
+ fix: "remove the entry: its glob is no longer dead"
702
+ }))
703
+ };
704
+ }
705
+ function summary({ problem, matches, ignored, examples }) {
706
+ if (problem === "matches nothing")
707
+ return problem;
708
+ const shown = [...examples, ...ignored > examples.length ? ["…"] : []];
709
+ const count = problem === "partly ignored" ? `${ignored} of ${matches}` : `${ignored}`;
710
+ return `${problem} (${count}: ${shown.join(", ")})`;
711
+ }
712
+ function outsideSummary({ matches, outside, examples }) {
713
+ const shown = [...examples, ...outside > examples.length ? ["…"] : []];
714
+ const count = outside === matches ? plural2(outside, "match", "matches") : `${outside} of ${matches} matches`;
715
+ return `${count} outside (${shown.join(", ")})`;
716
+ }
717
+ function widening(report) {
718
+ return report.unknown.filter((node) => node.tests.length > 0);
719
+ }
720
+ function failed2(report, max) {
721
+ return max !== undefined && widening(report).length > max || report.unlistedUnknowns.length > 0 || report.staleKnownUnknowns.length > 0 || report.deadGlobs.length > 0 || report.outsideRoots.length > 0 || report.staleDeadGlobs.length > 0 || report.undeclaredPaths.length > 0;
722
+ }
723
+ function categoryOf(cause) {
724
+ if (cause.startsWith("unresolved ")) {
725
+ const specifier = QUOTED.exec(cause)?.[1] ?? "";
726
+ if (RELATIVE.test(specifier))
727
+ return "unresolved relative import";
728
+ if (specifier.startsWith("#"))
729
+ return "unresolved # import";
730
+ return "unresolved bare import (a package, alias or path)";
731
+ }
732
+ if (cause.startsWith("only declarations for ")) {
733
+ return "a .js import with only its declarations there";
734
+ }
735
+ if (cause.startsWith("non-literal goto("))
736
+ return "non-literal goto()";
737
+ if (cause.startsWith("goto("))
738
+ return "goto() URL no `urls` pattern maps";
739
+ if (cause.startsWith("missing fixture "))
740
+ return "goto() of a missing page";
741
+ return cause;
742
+ }
743
+ var POSITION = /(?: in <>)? at \d+.*$/;
744
+ function byCount(counts) {
745
+ return Object.fromEntries([...counts].sort(([a, x], [b, y]) => y - x || (a < b ? -1 : 1)));
746
+ }
747
+ function summarize2(report) {
748
+ const widen = widening(report);
749
+ const causes = new Map;
750
+ for (const node of widen) {
751
+ for (const category of new Set(node.causes.map(({ cause }) => categoryOf(cause)))) {
752
+ causes.set(category, (causes.get(category) ?? 0) + 1);
753
+ }
754
+ }
755
+ const reasons = new Map;
756
+ for (const { reason } of report.fallbacks) {
757
+ const what = reason.replace(POSITION, "");
758
+ reasons.set(what, (reasons.get(what) ?? 0) + 1);
759
+ }
760
+ return {
761
+ unknown: widen.length,
762
+ testsOnAnyChange: new Set(widen.flatMap((node) => node.tests)).size,
763
+ unknownByCause: byCount(causes),
764
+ unknownNoTestReaches: report.unknown.length - widen.length,
765
+ fallbacks: report.fallbacks.length,
766
+ fallbackReasons: byCount(reasons),
767
+ unparsedTsconfigs: report.unparsedTsconfigs.length,
768
+ deadGlobs: report.deadGlobs.length,
769
+ outsideRoots: report.outsideRoots.length,
770
+ staleDeadGlobs: report.staleDeadGlobs.length,
771
+ unlistedUnknowns: report.unlistedUnknowns.length,
772
+ staleKnownUnknowns: report.staleKnownUnknowns.length,
773
+ undeclaredPaths: report.undeclaredPaths.length,
774
+ unreached: report.unreached.length
775
+ };
776
+ }
777
+ var SHOWN = 3;
778
+ var BRANCH_WIDTH = " ├ ".length;
779
+ function sharedFix(examples) {
780
+ const counts = new Map;
781
+ for (const { fix } of examples) {
782
+ if (fix !== undefined)
783
+ counts.set(fix, (counts.get(fix) ?? 0) + 1);
784
+ }
785
+ const [top] = [...counts].sort(([, a], [, b]) => b - a);
786
+ if (top === undefined)
787
+ return;
788
+ return top[1] > 1 || examples.length === 1 ? top[0] : undefined;
789
+ }
790
+ function fixLines({ paint, all }, first, fix) {
791
+ const label = `${first}${paint.good("fix")} `;
792
+ if (all) {
793
+ return {
794
+ lines: wrapped(fix, label, " ".repeat(textWidth2(label))),
795
+ cut: false
796
+ };
797
+ }
798
+ const shown = truncateWords2(fix, MEASURE2 - textWidth2(label));
799
+ return { lines: [`${label}${shown}`], cut: shown !== fix };
800
+ }
801
+ function renderSection(view, { title, count, examples }) {
802
+ const { paint, all } = view;
803
+ const lines = [`${paint.bold(title)}${paint.dim(`${SEPARATOR2}${count}`)}`];
804
+ const shared = sharedFix(examples);
805
+ const shown = all ? examples : examples.slice(0, SHOWN);
806
+ const hidden = examples.length - shown.length;
807
+ let cut = hidden > 0;
808
+ const detailWidth = Math.min(40, Math.max(0, ...shown.map(({ detail }) => textWidth2(detail ?? ""))));
809
+ const placeMax = Math.max(30, MEASURE2 - BRANCH_WIDTH - (detailWidth > 0 ? detailWidth + 2 : 0));
810
+ const places = shown.map(({ place }) => {
811
+ const fitted = all ? place : truncatePath2(place, placeMax);
812
+ cut ||= fitted !== place;
813
+ return fitted;
814
+ });
815
+ const placeWidth = Math.max(0, ...places.map(textWidth2));
816
+ for (const [i, example] of shown.entries()) {
817
+ const glyph = paint.dim(branch2(i, hidden > 0 ? shown.length + 1 : shown.length));
818
+ const place = places[i] ?? "";
819
+ let detail = example.detail ?? "";
820
+ if (detail !== "" && !all) {
821
+ const room = MEASURE2 - BRANCH_WIDTH - placeWidth - 2;
822
+ const fitted = truncateWords2(detail, room);
823
+ cut ||= fitted !== detail;
824
+ detail = fitted;
825
+ }
826
+ lines.push(detail === "" ? ` ${glyph}${place}` : ` ${glyph}${place.padEnd(placeWidth)} ${paint.dim(detail)}`);
827
+ if (example.fix !== undefined && example.fix !== shared) {
828
+ const note = fixLines(view, NOTE_INDENT2, example.fix);
829
+ lines.push(...note.lines);
830
+ cut ||= note.cut;
831
+ }
832
+ }
833
+ if (hidden > 0) {
834
+ lines.push(` ${paint.dim(`└ ${hidden} more`)}`);
835
+ }
836
+ if (shared !== undefined) {
837
+ const line = fixLines(view, " ", shared);
838
+ lines.push(...line.lines);
839
+ cut ||= line.cut;
840
+ }
841
+ return { lines, cut };
842
+ }
843
+ var UNRESOLVED = "unresolved ";
844
+ function countOf(hits, files, noun) {
845
+ return hits === files && noun !== "import" ? plural2(files, "file") : `${plural2(hits, noun)} in ${plural2(files, "file")}`;
846
+ }
847
+ function causeSections(widen) {
848
+ const byCategory = new Map;
849
+ for (const { node, causes, known } of widen) {
850
+ for (const { cause, at, fix } of causes) {
851
+ const category = categoryOf(cause);
852
+ const named = cause.startsWith(UNRESOLVED) ? cause.slice(UNRESOLVED.length) : cause === category ? "" : cause;
853
+ const detail = [named, known === undefined ? "" : `known: ${known}`].filter((part) => part !== "").join(SEPARATOR2);
854
+ const example = { place: at ?? node, fix };
855
+ if (detail !== "")
856
+ example.detail = detail;
857
+ const hits = byCategory.get(category) ?? [];
858
+ hits.push({ node, example });
859
+ byCategory.set(category, hits);
860
+ }
861
+ }
862
+ return [...byCategory].map(([category, hits]) => {
863
+ const files = new Set(hits.map(({ node }) => node)).size;
864
+ const noun = category.includes("import") ? "import" : "place";
865
+ return {
866
+ files,
867
+ section: {
868
+ title: category,
869
+ count: countOf(hits.length, files, noun),
870
+ examples: hits.map(({ example }) => example)
871
+ }
872
+ };
873
+ }).sort((a, b) => b.files - a.files || (a.section.title < b.section.title ? -1 : 1)).map(({ section }) => section);
874
+ }
875
+ var filesIn = (entries) => new Set(entries.map(({ file }) => file)).size;
876
+ function otherSections(report) {
877
+ const sections = [];
878
+ const add = (section) => {
879
+ if (section.examples.length > 0)
880
+ sections.push(section);
881
+ };
882
+ const spelled = report.undeclaredPaths;
883
+ add({
884
+ title: "path spelled in code that nothing declares",
885
+ count: `${plural2(spelled.length, "path")} in ${plural2(filesIn(spelled), "file")}`,
886
+ examples: spelled.map(({ file, path, dir, at, fix }) => ({
887
+ place: at ?? file,
888
+ detail: dir ? `${path}/` : path,
889
+ fix
890
+ }))
891
+ });
892
+ const dead = report.deadGlobs;
893
+ add({
894
+ title: "dead glob: a change to what it matches selects nothing",
895
+ count: `${plural2(dead.length, "glob")} in ${plural2(new Set(dead.map(({ node }) => node)).size, "file")}`,
896
+ examples: dead.map((found) => ({
897
+ place: found.at ?? found.node,
898
+ detail: `${found.kind} ${found.glob}: ${summary(found)}`,
899
+ fix: found.fix
900
+ }))
901
+ });
902
+ const outside = report.outsideRoots;
903
+ add({
904
+ title: "glob outside `roots`: a change to a match runs everything",
905
+ count: `${plural2(outside.length, "glob")} in ${plural2(new Set(outside.map(({ node }) => node)).size, "file")}`,
906
+ examples: outside.map((found) => ({
907
+ place: found.at ?? found.node,
908
+ detail: `${found.kind} ${found.glob}: ${outsideSummary(found)}`,
909
+ fix: found.fix
910
+ }))
911
+ });
912
+ add({
913
+ title: "`deadGlobs` entry that matches no dead glob",
914
+ count: plural2(report.staleDeadGlobs.length, "entry", "entries"),
915
+ examples: report.staleDeadGlobs.map(({ file, glob, fix }) => ({
916
+ place: file,
917
+ detail: glob,
918
+ fix
919
+ }))
920
+ });
921
+ add({
922
+ title: "unknown not in `knownUnknowns`",
923
+ count: plural2(report.unlistedUnknowns.length, "file"),
924
+ examples: report.unlistedUnknowns.map((node) => ({
925
+ place: node,
926
+ fix: "make its dependencies known, or list it in `knownUnknowns` with a reason"
927
+ }))
928
+ });
929
+ add({
930
+ title: "`knownUnknowns` entry whose dependencies are known",
931
+ count: plural2(report.staleKnownUnknowns.length, "entry", "entries"),
932
+ examples: report.staleKnownUnknowns.map(({ file, reason, fix }) => ({
933
+ place: file,
934
+ detail: reason,
935
+ fix
936
+ }))
937
+ });
938
+ for (const suite of new Set(report.unreached.map(({ suite }) => suite))) {
939
+ const entries = report.unreached.filter((entry) => entry.suite === suite);
940
+ add({
941
+ title: "no test reaches: a change runs the whole suite",
942
+ count: `${plural2(entries.length, "file")} in suite ${suite}`,
943
+ examples: entries.map(({ file, fix }) => ({ place: file, fix }))
944
+ });
945
+ }
946
+ add({
947
+ title: "tsconfig that doesn't parse, whose `paths` are ignored",
948
+ count: plural2(report.unparsedTsconfigs.length, "file"),
949
+ examples: report.unparsedTsconfigs.map(({ file, reason }) => ({
950
+ place: file,
951
+ detail: reason
952
+ }))
953
+ });
954
+ add({
955
+ title: "read by the regex extractor",
956
+ count: `${plural2(report.fallbacks.length, "file")} the lexer couldn't read`,
957
+ examples: report.fallbacks.map(({ file, reason }) => ({
958
+ place: file,
959
+ detail: reason
960
+ }))
961
+ });
962
+ const idle = report.unknown.filter((node) => node.tests.length === 0);
963
+ add({
964
+ title: "unknown, but no test reaches it, so it widens nothing",
965
+ count: plural2(idle.length, "file"),
966
+ examples: idle.flatMap(({ node, causes, known }) => causes.map(({ cause, at }) => ({
967
+ place: at ?? node,
968
+ detail: known === undefined ? cause : `${cause}${SEPARATOR2}known: ${known}`
969
+ })))
970
+ });
971
+ return sections;
972
+ }
973
+ function verdict(paint, counts) {
974
+ const { unknown, testsOnAnyChange: tests } = counts;
975
+ if (unknown === 0) {
976
+ return paint.good("bivium can follow every file a test reaches");
977
+ }
978
+ return `${paint.bad(`${plural2(unknown, "file")} bivium can't follow`)} ${unknown === 1 ? "sends" : "send"} ${paint.bold(String(tests))} ${tests === 1 ? "test" : "tests"} to every change`;
979
+ }
980
+ function context(counts, max) {
981
+ const parts = [
982
+ max === undefined ? "" : `at most ${max} allowed`,
983
+ counts.undeclaredPaths > 0 ? plural2(counts.undeclaredPaths, "undeclared path") : "",
984
+ counts.deadGlobs > 0 ? plural2(counts.deadGlobs, "dead glob") : "",
985
+ counts.outsideRoots > 0 ? plural2(counts.outsideRoots, "glob outside roots", "globs outside roots") : "",
986
+ counts.staleDeadGlobs > 0 ? plural2(counts.staleDeadGlobs, "stale `deadGlobs` entry", "stale `deadGlobs` entries") : "",
987
+ counts.unlistedUnknowns > 0 ? `${counts.unlistedUnknowns} not in \`knownUnknowns\`` : "",
988
+ counts.staleKnownUnknowns > 0 ? plural2(counts.staleKnownUnknowns, "stale `knownUnknowns` entry", "stale `knownUnknowns` entries") : "",
989
+ counts.unreached > 0 ? `${plural2(counts.unreached, "file")} no test reaches` : "",
990
+ counts.unparsedTsconfigs > 0 ? plural2(counts.unparsedTsconfigs, "tsconfig that doesn't parse", "tsconfigs that don't parse") : "",
991
+ counts.fallbacks > 0 ? `${plural2(counts.fallbacks, "file")} the lexer couldn't read` : "",
992
+ counts.unknownNoTestReaches > 0 ? `${counts.unknownNoTestReaches} more unknown no test reaches` : ""
993
+ ].filter((part) => part !== "");
994
+ const lines = [];
995
+ for (const part of parts) {
996
+ const last = lines.at(-1);
997
+ if (last !== undefined && textWidth2(last) + SEPARATOR2.length + textWidth2(part) <= MEASURE2) {
998
+ lines[lines.length - 1] = `${last}${SEPARATOR2}${part}`;
999
+ } else
1000
+ lines.push(part);
1001
+ }
1002
+ return lines;
1003
+ }
1004
+ function failures(counts, max) {
1005
+ const parts = [
1006
+ [
1007
+ max !== undefined && counts.unknown > max ? counts.unknown : 0,
1008
+ `unknown, over --max-unknown ${max}`,
1009
+ `unknown, over --max-unknown ${max}`
1010
+ ],
1011
+ [counts.unlistedUnknowns, "unlisted unknown", "unlisted unknowns"],
1012
+ [counts.undeclaredPaths, "undeclared path", "undeclared paths"],
1013
+ [counts.deadGlobs, "dead glob", "dead globs"],
1014
+ [counts.outsideRoots, "glob outside roots", "globs outside roots"],
1015
+ [
1016
+ counts.staleKnownUnknowns + counts.staleDeadGlobs,
1017
+ "stale entry",
1018
+ "stale entries"
1019
+ ]
1020
+ ];
1021
+ return parts.flatMap(([count, one, many]) => count > 0 ? [plural2(count, one, many)] : []);
1022
+ }
1023
+ function formatReport2(report, max, view) {
1024
+ const { paint } = view;
1025
+ const counts = summarize2(report);
1026
+ const lines = [
1027
+ verdict(paint, counts),
1028
+ ...context(counts, max).map((line) => paint.dim(line)),
1029
+ ""
1030
+ ];
1031
+ let cut = false;
1032
+ for (const section of [
1033
+ ...causeSections(widening(report)),
1034
+ ...otherSections(report)
1035
+ ]) {
1036
+ const rendered = renderSection(view, section);
1037
+ lines.push(...rendered.lines, "");
1038
+ cut ||= rendered.cut;
1039
+ }
1040
+ const detail = `checked in ${duration(view.elapsedMs)}${cut ? `${SEPARATOR2}--all for every file` : ""}`;
1041
+ const failed = failures(counts, max);
1042
+ lines.push(failed.length > 0 ? failLine2(paint, failed.join(SEPARATOR2), detail) : closingLine2(paint, "Check passes", detail));
1043
+ return lines.join(`
1044
+ `);
1045
+ }
1046
+
1047
+ export { specifierLine, gotoLine, callLine, textLine, annotationLine, lineText, sourceOf, fileOf, causesOf, fixFor2, check2, failed2, summarize2, formatReport2 };