bivium 0.7.0 → 0.8.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.
@@ -1,14 +1,14 @@
1
- // src/compute.ts
2
- import { readFile as readFile3, stat } from "node:fs/promises";
3
- import { join as join4, posix as posix6, resolve as resolve2 } from "node:path";
4
-
5
- // src/cache.ts
6
- import { existsSync } from "node:fs";
7
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
8
- import { isAbsolute, join } from "node:path";
9
-
10
- // package.json
11
- var version = "0.7.0";
1
+ import {
2
+ BiviumError2
3
+ } from "./shared-211m8fjt.js";
4
+ import {
5
+ globToRegExp,
6
+ matcher,
7
+ resolveConfig2,
8
+ inRoot2,
9
+ checkConfig2,
10
+ loadConfig2
11
+ } from "./shared-550cvwt2.js";
12
12
 
13
13
  // src/env.ts
14
14
  function githubOutputPath() {
@@ -34,1236 +34,264 @@ function agentVariable(env) {
34
34
  });
35
35
  }
36
36
 
37
- // src/cache.ts
38
- var SCANNER_VERSION = 9;
39
- var MAGIC = "bivium-extractions";
40
- var FILE = "extractions.json";
41
- function isHeader(value) {
42
- 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";
37
+ // package.json
38
+ var version = "0.8.0";
39
+
40
+ // src/barrel.ts
41
+ var COMMENTS = /\/\/.*$|\/\*[\s\S]*?\*\//gm;
42
+ var AS = /\s+as\s+/;
43
+ var TYPE_PREFIX = /^type\s+/;
44
+ var NAMED_EXPORT = /export\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']\s*;?/g;
45
+ var STAR_EXPORT = /export\s+(?:type\s+)?\*(?:\s+as\s+([\w$]+))?\s+from\s*["']([^"']+)["']\s*;?/g;
46
+ var BARREL_FILE = /\.[cm]?[jt]sx?$/;
47
+ var ONLY_SEPARATORS = /^[\s;]*$/;
48
+ var STARTS_WITH_EXPORT = /^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*export\b/;
49
+ function parseBarrel(path, source) {
50
+ return BARREL_FILE.test(path) ? parseReExports(source) : undefined;
43
51
  }
44
- function cacheDir(root, cache) {
45
- if (cache === false)
52
+ function parseReExports(source) {
53
+ if (!STARTS_WITH_EXPORT.test(source))
46
54
  return;
47
- if (typeof cache === "string") {
48
- return isAbsolute(cache) ? cache : join(root, cache);
49
- }
50
- const modules = join(root, "node_modules");
51
- return existsSync(modules) ? join(modules, ".cache", "bivium") : join(root, ".bivium", "cache");
55
+ const code = source.replace(COMMENTS, "");
56
+ const barrel = { names: new Map, stars: [] };
57
+ let rest = code.replace(NAMED_EXPORT, (_, list, from) => {
58
+ for (const part of list.split(",")) {
59
+ const name = part.trim().replace(TYPE_PREFIX, "").split(AS).pop();
60
+ if (name)
61
+ barrel.names.set(name, from);
62
+ }
63
+ return "";
64
+ });
65
+ rest = rest.replace(STAR_EXPORT, (_, name, from) => {
66
+ if (name)
67
+ barrel.names.set(name, from);
68
+ else
69
+ barrel.stars.push(from);
70
+ return "";
71
+ });
72
+ if (barrel.names.size + barrel.stars.length === 0)
73
+ return;
74
+ return ONLY_SEPARATORS.test(rest) ? barrel : undefined;
52
75
  }
53
76
 
54
- class ExtractionCache {
55
- #rows = new Map;
56
- #strings = [];
57
- #used = new Map;
58
- #dirty = false;
59
- dir;
60
- constructor(dir) {
61
- this.dir = dir;
62
- }
63
- static async open(dir) {
64
- const cache = new ExtractionCache(dir);
65
- if (!dir)
66
- return cache;
67
- const text = await readFile(join(dir, FILE), "utf-8").catch(() => "");
68
- if (text)
69
- cache.#load(text);
70
- return cache;
77
+ // src/resolve.ts
78
+ import { builtinModules } from "node:module";
79
+ import { posix } from "node:path";
80
+
81
+ // src/syntax.ts
82
+ var QUERY = /[?#].*$/;
83
+ var UNDECLARED_READS = "reads the disk without @depends-on";
84
+ var RELATIVE = /^\.\.?(?:\/|$)/;
85
+ var URL_REF = /^[a-z]+:|^\/\//;
86
+ var LIST_SEPARATOR = /[\s,]+(?![^{]*\})/;
87
+ var DEPENDS_ON = /^\s*(?:\/\/|\/?\*+)\s*@depends-on\s+(.+?)\s*(?:\*\/)?\s*$/gm;
88
+ var READS = /^\s*(?:\/\/|\/?\*+)\s*@reads\s+(.+?)\s*(?:\*\/)?\s*$/gm;
89
+ var LISTS = /^\s*(?:\/\/|\/?\*+)\s*@lists\s+(.+?)\s*(?:\*\/)?\s*$/gm;
90
+ var GLOB_REGISTRY = /^\s*(?:\/\/|\/?\*+)\s*@glob-registry\b/m;
91
+ var AS2 = /\s+as\s+/;
92
+ var TYPE_PREFIX2 = /^type\s+/;
93
+ var NAMED_CLAUSE = /\{([^}]*)\}/;
94
+ var DEFAULT_OR_NAMESPACE = /^\s*[\w$*]/;
95
+ function namedBindings(clause) {
96
+ const named = NAMED_CLAUSE.exec(clause);
97
+ if (!named || DEFAULT_OR_NAMESPACE.test(clause.replace(NAMED_CLAUSE, ""))) {
98
+ return;
71
99
  }
72
- #load(text) {
73
- try {
74
- const parsed = JSON.parse(text);
75
- if (!Array.isArray(parsed))
76
- return;
77
- const fields = parsed;
78
- const [header, strings, rows] = fields;
79
- if (!isHeader(header) || !Array.isArray(strings) || !Array.isArray(rows) || header.strings !== strings.length || header.rows !== rows.length) {
80
- return;
81
- }
82
- this.#strings = strings;
83
- for (const row of rows) {
84
- if (Array.isArray(row) && typeof row[0] === "string") {
85
- this.#rows.set(row[0], row);
86
- }
87
- }
88
- } catch {}
100
+ return captured(named, 1).split(",").map((part) => (part.trim().replace(TYPE_PREFIX2, "").split(AS2)[0] ?? "").trim()).filter(Boolean);
101
+ }
102
+ function captured(match, index) {
103
+ const value = match[index];
104
+ if (value === undefined) {
105
+ throw new Error(`bivium: scan: group ${index} of ${match[0]} is unset.`);
89
106
  }
90
- get size() {
91
- return this.#rows.size;
107
+ return value;
108
+ }
109
+
110
+ // src/resolve.ts
111
+ function isRecord(value) {
112
+ return typeof value === "object" && value !== null && !Array.isArray(value);
113
+ }
114
+ function isStringRecord(value) {
115
+ return isRecord(value) && Object.values(value).every((item) => typeof item === "string");
116
+ }
117
+ function toPackageJson(value) {
118
+ if (!isRecord(value))
119
+ return {};
120
+ const json = {};
121
+ if (typeof value.name === "string")
122
+ json.name = value.name;
123
+ if (value.exports !== undefined)
124
+ json.exports = value.exports;
125
+ if (isRecord(value.imports))
126
+ json.imports = value.imports;
127
+ if (typeof value.main === "string")
128
+ json.main = value.main;
129
+ const { sideEffects } = value;
130
+ if (typeof sideEffects === "boolean" || Array.isArray(sideEffects) && sideEffects.every((glob) => typeof glob === "string")) {
131
+ json.sideEffects = sideEffects;
92
132
  }
93
- get(oid, format) {
94
- const key = `${format}:${oid}`;
95
- const used = this.#used.get(key);
96
- if (used)
97
- return used;
98
- const row = this.#rows.get(key);
99
- if (!row)
100
- return;
101
- let extraction;
102
- try {
103
- extraction = decode(row, this.#strings);
104
- } catch {
105
- this.#rows.delete(key);
106
- return;
107
- }
108
- this.#used.set(key, extraction);
109
- return extraction;
133
+ for (const field of DEP_FIELDS) {
134
+ const deps = value[field];
135
+ if (isStringRecord(deps))
136
+ json[field] = deps;
110
137
  }
111
- set(oid, format, extraction) {
112
- const key = `${format}:${oid}`;
113
- this.#used.set(key, extraction);
114
- this.#dirty = true;
138
+ return json;
139
+ }
140
+ var BUILTINS = new Set(builtinModules);
141
+ var RUNTIME_BUILTIN = /^(?:node:|bun(?:$|:))/;
142
+ var JS_EXTENSION = /\.(?:js|jsx|mjs|cjs)$/;
143
+ var TS_SOURCES = {
144
+ ".js": [".ts", ".tsx", ".d.ts"],
145
+ ".jsx": [".tsx", ".ts", ".d.ts"],
146
+ ".mjs": [".mts", ".d.mts"],
147
+ ".cjs": [".cts", ".d.cts"]
148
+ };
149
+ var NODE_PREFIX = /^node:/;
150
+ var INVALID_IMPORT_TARGET = /^[./#]/;
151
+ var SVELTEKIT_ASSETS = "./%sveltekit.assets%/";
152
+ var INDEX = "/index";
153
+ var SVELTE_CONFIGS = ["js", "mjs", "cjs", "ts", "mts"].map((ext) => `svelte.config.${ext}`);
154
+ var DEP_FIELDS = [
155
+ "dependencies",
156
+ "devDependencies",
157
+ "peerDependencies",
158
+ "optionalDependencies"
159
+ ];
160
+ function packageName(specifier) {
161
+ const parts = specifier.split("/");
162
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? "";
163
+ }
164
+ function builtin(specifier) {
165
+ if (RUNTIME_BUILTIN.test(specifier)) {
166
+ const name = specifier.replace(NODE_PREFIX, "");
167
+ return specifier.startsWith("bun") ? specifier : `node:${name.split("/")[0]}`;
115
168
  }
116
- async save() {
117
- if (!this.dir || !this.#dirty)
118
- return;
119
- const table = createStrings();
120
- const rows = [];
121
- for (const [key, extraction] of this.#used) {
122
- rows.push(encode(key, extraction, table));
123
- }
124
- let stale = Math.floor(this.#used.size / 2);
125
- for (const [key, row] of this.#rows) {
126
- if (stale === 0)
127
- break;
128
- if (this.#used.has(key))
129
- continue;
130
- try {
131
- rows.push(encode(key, decode(row, this.#strings), table));
132
- stale--;
133
- } catch {}
134
- }
135
- const header = {
136
- magic: MAGIC,
137
- bivium: version,
138
- scanner: SCANNER_VERSION,
139
- rows: rows.length,
140
- strings: table.list.length
141
- };
142
- const file = join(this.dir, FILE);
143
- const temp = `${file}.${process.pid}.${nowMs()}.tmp`;
144
- try {
145
- await mkdir(this.dir, { recursive: true });
146
- const ignore = join(this.dir, ".gitignore");
147
- if (!existsSync(ignore))
148
- await writeFile(ignore, `*
149
- `);
150
- await writeFile(temp, JSON.stringify([header, table.list, rows]));
151
- await rename(temp, file);
152
- this.#dirty = false;
153
- } catch {
154
- await unlink(temp).catch(() => {
155
- return;
156
- });
157
- }
169
+ const name = specifier.split("/")[0] ?? "";
170
+ return BUILTINS.has(specifier) || BUILTINS.has(name) ? `node:${name}` : undefined;
171
+ }
172
+ function targets(value, out = []) {
173
+ if (typeof value === "string")
174
+ out.push(value);
175
+ else if (Array.isArray(value))
176
+ for (const item of value)
177
+ targets(item, out);
178
+ else if (value && typeof value === "object") {
179
+ for (const item of Object.values(value))
180
+ targets(item, out);
158
181
  }
182
+ return out;
159
183
  }
160
- function createStrings() {
161
- const list = [];
162
- const idsByValue = new Map;
163
- const id = (value) => {
164
- let found = idsByValue.get(value);
165
- if (found === undefined) {
166
- found = list.length;
167
- list.push(value);
168
- idsByValue.set(value, found);
169
- }
170
- return found;
171
- };
172
- const ids = (values) => values.length === 0 ? 0 : values.map(id);
173
- return { list, id, ids };
174
- }
175
- function typeIndexes(imports) {
176
- const indexes = [];
177
- for (const [i, ref] of imports.entries())
178
- if (ref.type)
179
- indexes.push(i);
180
- return indexes.length === 0 ? 0 : indexes;
181
- }
182
- function encode(key, e, table) {
183
- const imports = e.imports.map(({ specifier, names }) => names ? [table.id(specifier), ...names.map((n) => table.id(n))] : table.id(specifier));
184
- const barrel = e.barrel && [
185
- [...e.barrel.names].flatMap(([name, from]) => [
186
- table.id(name),
187
- table.id(from)
188
- ]),
189
- table.ids(e.barrel.stars)
190
- ];
191
- return [
192
- key,
193
- imports.length === 0 ? 0 : imports,
194
- table.ids(e.globs),
195
- table.ids(e.gotos),
196
- table.ids(e.dependsOn),
197
- table.ids(e.reads),
198
- table.ids(e.unknown),
199
- e.fallback === undefined ? 0 : table.id(e.fallback),
200
- barrel ?? 0,
201
- typeIndexes(e.imports),
202
- table.ids(e.lists)
203
- ];
204
- }
205
- function decode(row, strings) {
206
- const str = (id) => {
207
- const value = typeof id === "number" ? strings[id] : undefined;
208
- if (typeof value !== "string")
209
- throw new Error("bad string id");
210
- return value;
211
- };
212
- const list = (ids) => {
213
- if (ids === 0)
214
- return [];
215
- if (!Array.isArray(ids))
216
- throw new Error("bad list");
217
- return ids.map(str);
218
- };
219
- const refs = row[1] === 0 ? [] : row[1];
220
- if (!Array.isArray(refs))
221
- throw new Error("bad imports");
222
- const imports = refs.map((item) => Array.isArray(item) ? { specifier: str(item[0]), names: item.slice(1).map(str) } : { specifier: str(item) });
223
- if (row[9] !== 0) {
224
- if (!Array.isArray(row[9]))
225
- throw new Error("bad types");
226
- for (const i of row[9]) {
227
- const ref = typeof i === "number" ? imports[i] : undefined;
228
- if (!ref)
229
- throw new Error("bad type index");
230
- ref.type = true;
231
- }
232
- }
233
- const extraction = {
234
- imports,
235
- globs: list(row[2]),
236
- gotos: list(row[3]),
237
- dependsOn: list(row[4]),
238
- reads: list(row[5]),
239
- lists: list(row[10]),
240
- unknown: list(row[6])
241
- };
242
- if (row[7] !== 0)
243
- extraction.fallback = str(row[7]);
244
- if (row[8] !== 0) {
245
- if (!Array.isArray(row[8]))
246
- throw new Error("bad barrel");
247
- const barrel = row[8];
248
- const [pairs, stars] = barrel;
249
- if (!Array.isArray(pairs))
250
- throw new Error("bad barrel names");
251
- const names = new Map;
252
- for (let i = 0;i < pairs.length; i += 2) {
253
- names.set(str(pairs[i]), str(pairs[i + 1]));
254
- }
255
- extraction.barrel = { names, stars: list(stars) };
256
- }
257
- return extraction;
258
- }
259
-
260
- // src/config.ts
261
- import { existsSync as existsSync2, readFileSync } from "node:fs";
262
- import { isAbsolute as isAbsolute2, join as join2, relative, resolve } from "node:path";
263
- import { pathToFileURL } from "node:url";
264
-
265
- // src/errors.ts
266
- var KINDS = {
267
- BV_MISSING_ARGUMENT: "usage",
268
- BV_UNKNOWN_COMMAND: "usage",
269
- BV_UNKNOWN_OPTION: "usage",
270
- BV_BAD_OPTION_VALUE: "usage",
271
- BV_UNEXPECTED_ARGUMENT: "usage",
272
- BV_UNKNOWN_SUITE: "usage",
273
- BV_UNKNOWN_TEST: "usage",
274
- BV_UNKNOWN_FILE: "usage",
275
- BV_NO_RUN_COMMAND: "usage",
276
- BV_NO_GITHUB_OUTPUT: "usage",
277
- BV_CONFIG_NOT_FOUND: "config",
278
- BV_CONFIG_UNREADABLE: "config",
279
- BV_CONFIG_INVALID: "config",
280
- BV_GIT_NO_BASE: "git",
281
- BV_GIT_NO_MERGE_BASE: "git",
282
- BV_GIT_FAILED: "git",
283
- BV_INTERNAL: "other"
284
- };
285
-
286
- class BiviumError2 extends Error {
287
- code;
288
- kind;
289
- constructor(code, message, options) {
290
- super(message, options);
291
- this.code = code;
292
- this.kind = KINDS[code];
293
- }
294
- }
295
- function distance(a, b) {
296
- const width = b.length + 1;
297
- const cells = new Uint32Array((a.length + 1) * width);
298
- const d = (i, j) => cells[i * width + j] ?? 0;
299
- for (let i = 0;i <= a.length; i++)
300
- cells[i * width] = i;
301
- for (let j = 0;j <= b.length; j++)
302
- cells[j] = j;
303
- for (let i = 1;i <= a.length; i++) {
304
- for (let j = 1;j <= b.length; j++) {
305
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
306
- let best = Math.min(d(i - 1, j) + 1, d(i, j - 1) + 1, d(i - 1, j - 1) + cost);
307
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
308
- best = Math.min(best, d(i - 2, j - 2) + 1);
309
- }
310
- cells[i * width + j] = best;
311
- }
184
+ function subpathMap(exports) {
185
+ if (typeof exports === "string" || Array.isArray(exports)) {
186
+ return { ".": exports };
312
187
  }
313
- return d(a.length, b.length);
188
+ if (!isRecord(exports))
189
+ return;
190
+ const bySubpath = Object.keys(exports).some((key) => key.startsWith("."));
191
+ return bySubpath ? exports : { ".": exports };
314
192
  }
315
- function closest(input, candidates) {
316
- const most = Math.max(1, Math.floor(input.length / 3));
193
+ function mapTargets(map, subpath) {
194
+ if (subpath in map && !subpath.includes("*"))
195
+ return targets(map[subpath]);
317
196
  let best;
318
- let bestDistance = most + 1;
319
- for (const candidate of candidates) {
320
- const d = distance(input, candidate);
321
- if (d < bestDistance) {
322
- best = candidate;
323
- bestDistance = d;
197
+ for (const key of Object.keys(map)) {
198
+ const star = key.indexOf("*");
199
+ if (star === -1)
200
+ continue;
201
+ const prefix = key.slice(0, star);
202
+ const suffix = key.slice(star + 1);
203
+ 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)) {
204
+ best = {
205
+ key,
206
+ match: subpath.slice(prefix.length, subpath.length - suffix.length)
207
+ };
324
208
  }
325
209
  }
326
- return best;
327
- }
328
- function didYouMean(input, candidates) {
329
- const match = closest(input, candidates);
330
- return match === undefined ? "" : ` (did you mean ${match}?)`;
331
- }
332
-
333
- // src/glob.ts
334
- var GLOB_LITERAL = /[.+^$()|[\]\\]/g;
335
- var REGEX_SPECIAL = /[.*+?^${}()|[\]\\]/g;
336
- var DIGIT = /[0-9]/;
337
- var CAPTURE_REFERENCE = /\$(\d+)/g;
338
- function compile(glob, {
339
- capture = false,
340
- captures
341
- } = {}) {
342
- let source = "";
343
- let wildcards = 0;
344
- const group = (body) => {
345
- wildcards++;
346
- return capture ? `(${body})` : body;
347
- };
348
- for (let i = 0;i < glob.length; i++) {
349
- const char = glob.charAt(i);
350
- if (captures && char === "$" && DIGIT.test(glob[i + 1] ?? "")) {
351
- let end = i + 1;
352
- while (DIGIT.test(glob[end] ?? ""))
353
- end++;
354
- const text = captures[Number(glob.slice(i + 1, end)) - 1];
355
- source += text === undefined ? ".*" : text.replace(REGEX_SPECIAL, "\\$&");
356
- i = end - 1;
357
- } else if (char === "*" && glob[i + 1] === "*") {
358
- const slash = glob[i + 2] === "/";
359
- source += group(slash ? "(?:.*/)?" : ".*");
360
- i += slash ? 2 : 1;
361
- } else if (char === "*")
362
- source += group("[^/]*");
363
- else if (char === "?")
364
- source += group("[^/]");
365
- else if (char === "{") {
366
- wildcards++;
367
- source += capture ? "(" : "(?:";
368
- } else if (char === "}")
369
- source += ")";
370
- else if (char === ",")
371
- source += "|";
372
- else
373
- source += char.replace(GLOB_LITERAL, "\\$&");
374
- }
375
- return { source: `^${source}$`, wildcards };
376
- }
377
- function globToRegExp(glob) {
378
- return new RegExp(compile(glob).source);
379
- }
380
- function captureGlob(glob) {
381
- const { source, wildcards } = compile(glob, { capture: true });
382
- return { pattern: new RegExp(source), wildcards };
383
- }
384
- function captureReferences(glob) {
385
- return [...glob.matchAll(CAPTURE_REFERENCE)].map((match) => Number(match[1]));
386
- }
387
- function expandGlob(glob, captures) {
388
- return new RegExp(compile(glob, { captures }).source);
389
- }
390
- function matcher(globs = []) {
391
- const list = typeof globs === "string" ? [globs] : globs;
392
- if (list.length === 0)
393
- return () => false;
394
- const res = list.map(globToRegExp);
395
- return (path) => res.some((re) => re.test(path));
210
+ if (!best)
211
+ return;
212
+ const { match } = best;
213
+ return targets(map[best.key]).map((target) => target.replaceAll("*", match));
396
214
  }
397
-
398
- // src/config.ts
399
- function defineConfig2(config) {
400
- return config;
401
- }
402
- var DEFAULT_EXTENSIONS = [
403
- ".ts",
404
- ".tsx",
405
- ".mts",
406
- ".cts",
407
- ".js",
408
- ".jsx",
409
- ".mjs",
410
- ".cjs",
411
- ".d.ts",
412
- ".svelte",
413
- ".vue",
414
- ".json"
415
- ];
416
- function list(value, fallback) {
417
- if (value === undefined)
418
- return [...fallback];
419
- return typeof value === "string" ? [value] : [...value];
215
+ function exportTargets(exports, subpath) {
216
+ const map = subpathMap(exports);
217
+ return map && mapTargets(map, subpath);
420
218
  }
421
- var LEADING_DOT_SLASH = /^\.\//;
422
- var TRAILING_SLASHES = /\/+$/;
423
- function normalizeRoot(root) {
424
- return root.replace(LEADING_DOT_SLASH, "").replace(TRAILING_SLASHES, "") || ".";
425
- }
426
- function pathMaps(record = {}) {
427
- return Object.entries(record).map(([key, globs]) => {
428
- const { pattern, wildcards } = captureGlob(key);
429
- const values = list(globs, []);
430
- const fixed = values.map((value) => captureReferences(value).length === 0 ? globToRegExp(value) : undefined);
431
- return {
432
- key,
433
- exact: wildcards === 0,
434
- pattern,
435
- values,
436
- targets: (path) => {
437
- const match = pattern.exec(path);
438
- if (!match)
439
- return;
440
- const captures = match.slice(1);
441
- return values.map((value, i) => fixed[i] ?? expandGlob(value, captures));
442
- }
443
- };
444
- });
219
+ function byDepth(packages) {
220
+ return [...packages].sort(([a], [b]) => b.length - a.length);
445
221
  }
446
- function isInertOf(inert) {
447
- const listed = matcher(inert);
448
- return (name) => name === "bivium" || listed(name);
222
+ function owner(packages, file) {
223
+ return byDepth(packages).find(([dir]) => dir === "." || file.startsWith(`${dir}/`));
449
224
  }
450
- function optional(key, value) {
451
- const out = {};
452
- if (value !== undefined)
453
- out[key] = value;
454
- return out;
225
+ function aliasPath([key, target], specifier) {
226
+ if (specifier !== key && !specifier.startsWith(`${key}/`))
227
+ return;
228
+ const rest = specifier.slice(key.length + 1);
229
+ if (target === ".")
230
+ return posix.normalize(rest || ".");
231
+ return posix.normalize(rest ? `${target}/${rest}` : target);
455
232
  }
456
- function resolveConfig(config) {
457
- const names = Object.keys(config.suites);
458
- if (names.length === 0)
459
- throw new Error("bivium config: no suites");
460
- const suites = Object.entries(config.suites).map(([name, suite]) => ({
461
- name,
462
- isTest: matcher(suite.tests),
463
- ...optional("run", suite.run),
464
- roots: list(suite.root, ["."]).map(normalizeRoot),
465
- urls: Object.entries(suite.urls ?? {}).map(([key, targets]) => ({
466
- key,
467
- targets: list(targets, [])
468
- })),
469
- isPage: matcher(suite.pages),
470
- isWiring: matcher(suite.wiring),
471
- isSetup: matcher(suite.setup),
472
- setup: list(suite.setup, []),
473
- isNonInput: matcher(suite.nonInputs),
474
- output: suite.output ?? `${name}-tests`,
475
- types: suite.types ?? true
476
- }));
477
- const narrowers = (config.narrowers ?? []).map((narrower) => {
478
- const unknown = narrower.suites?.find((name) => !names.includes(name));
479
- if (unknown !== undefined) {
480
- throw new Error(`bivium config: narrower ${narrower.name} names no suite ${unknown}`);
233
+ function createResolver({
234
+ files,
235
+ config,
236
+ packages,
237
+ tsconfigs = new Map
238
+ }) {
239
+ const generated = (path) => config.generated.some(({ pattern }) => pattern.test(path));
240
+ const { extensions } = config;
241
+ const exists = (path) => files.has(path);
242
+ const suffixed = new Map;
243
+ const indexes = new Map;
244
+ const byTail = [];
245
+ const undotted = [];
246
+ for (const [i, ext] of extensions.entries()) {
247
+ const dot = ext.lastIndexOf(".");
248
+ if (dot === -1)
249
+ undotted.push(i);
250
+ else {
251
+ const list = byTail[ext.length - dot];
252
+ if (list)
253
+ list.push(i);
254
+ else
255
+ byTail[ext.length - dot] = [i];
481
256
  }
482
- return {
483
- name: narrower.name,
484
- match: matcher(narrower.match),
485
- opaque: matcher(narrower.opaque),
486
- suites: [...narrower.suites ?? names],
487
- narrow: async (context) => checkResult(await narrower.narrow(context))
488
- };
489
- });
490
- return {
491
- suites,
492
- narrowers,
493
- roots: list(config.roots, ["."]).map(normalizeRoot),
494
- isIgnored: matcher(config.ignore),
495
- alias: Object.entries(config.alias ?? {}).map(([key, path]) => [
496
- key.replace(TRAILING_SLASHES, "") || key,
497
- normalizeRoot(path)
498
- ]).sort(([a], [b]) => b.length - a.length),
499
- generated: pathMaps(config.edges),
500
- reads: pathMaps(config.reads),
501
- isSelf: matcher(config.self),
502
- isImportOnly: matcher(config.importOnly),
503
- isHermetic: matcher(config.hermetic),
504
- isBarrel: config.barrels ? matcher(config.barrels) : () => true,
505
- external: new Set(config.external),
506
- isInert: isInertOf(config.inert),
507
- ...config.loadedByName !== undefined && {
508
- isLoadedByName: matcher(config.loadedByName)
509
- },
510
- extensions: config.extensions ?? DEFAULT_EXTENSIONS,
511
- deadGlobs: config.deadGlobs ?? [],
512
- ...config.knownUnknowns && { knownUnknowns: config.knownUnknowns },
513
- ...optional("base", config.base),
514
- ...optional("cache", config.cache)
515
- };
516
- }
517
- function inRoot(file, root) {
518
- return root === "." || file === root || file.startsWith(`${root}/`);
519
- }
520
- function isRecord(value) {
521
- return typeof value === "object" && value !== null && !Array.isArray(value);
522
- }
523
- function isStrings(value) {
524
- return Array.isArray(value) && value.every((item) => typeof item === "string");
525
- }
526
- function isGlobs(value) {
527
- return typeof value === "string" || isStrings(value);
528
- }
529
- function isStringRecord(value) {
530
- return isRecord(value) && Object.values(value).every((item) => typeof item === "string");
531
- }
532
- function isGlobsRecord(value) {
533
- return isRecord(value) && Object.values(value).every(isGlobs);
534
- }
535
- function isBoolean(value) {
536
- return typeof value === "boolean";
537
- }
538
- function isString(value) {
539
- return typeof value === "string";
540
- }
541
- function isCache(value) {
542
- return typeof value === "boolean" || typeof value === "string";
543
- }
544
- function field(record, key, is, path, expected) {
545
- const value = record[key];
546
- if (value === undefined || is(value))
547
- return value;
548
- throw new Error(`bivium config: ${path}${key} must be ${expected}`);
549
- }
550
- var SUITE_KEYS = new Set([
551
- "tests",
552
- "run",
553
- "root",
554
- "urls",
555
- "pages",
556
- "wiring",
557
- "setup",
558
- "nonInputs",
559
- "output",
560
- "types"
561
- ]);
562
- var NARROWER_KEYS = new Set(["name", "match", "opaque", "suites", "narrow"]);
563
- var DEAD_GLOB_KEYS = new Set(["file", "glob", "reason"]);
564
- var KNOWN_UNKNOWN_KEYS = new Set(["file", "reason"]);
565
- var CONFIG_KEYS = new Set([
566
- "suites",
567
- "narrowers",
568
- "roots",
569
- "ignore",
570
- "alias",
571
- "edges",
572
- "reads",
573
- "self",
574
- "importOnly",
575
- "hermetic",
576
- "barrels",
577
- "external",
578
- "inert",
579
- "loadedByName",
580
- "extensions",
581
- "deadGlobs",
582
- "knownUnknowns",
583
- "base",
584
- "cache"
585
- ]);
586
- function unknownKeys(value) {
587
- const found = [];
588
- const visit = (record, known, path) => {
589
- if (!isRecord(record))
257
+ }
258
+ const addSuffixed = (i, file) => {
259
+ const ext = extensions[i];
260
+ if (ext === undefined) {
261
+ throw new Error(`bivium: resolve: no extension at index ${i}.`);
262
+ }
263
+ if (!file.endsWith(ext))
590
264
  return;
591
- for (const key of Object.keys(record)) {
592
- if (!known.has(key))
593
- found.push(`${path}${key}${didYouMean(key, known)}`);
265
+ const base = file.slice(0, file.length - ext.length);
266
+ const list = suffixed.get(base);
267
+ if (list)
268
+ list.push([i, file]);
269
+ else {
270
+ const created = [[i, file]];
271
+ suffixed.set(base, created);
272
+ if (base.endsWith(INDEX)) {
273
+ indexes.set(base.slice(0, -INDEX.length), created);
274
+ }
594
275
  }
595
276
  };
596
- visit(value, CONFIG_KEYS, "");
597
- if (isRecord(value.suites)) {
598
- for (const [name, suite] of Object.entries(value.suites)) {
599
- visit(suite, SUITE_KEYS, `suites.${name}.`);
600
- }
601
- }
602
- const lists = [
603
- ["narrowers", NARROWER_KEYS],
604
- ["deadGlobs", DEAD_GLOB_KEYS],
605
- ["knownUnknowns", KNOWN_UNKNOWN_KEYS]
606
- ];
607
- for (const [key, known] of lists) {
608
- const entries = value[key];
609
- if (!Array.isArray(entries))
610
- continue;
611
- for (const [i, entry] of entries.entries()) {
612
- visit(entry, known, `${key}[${i}].`);
277
+ for (const file of files) {
278
+ const dot = file.lastIndexOf(".");
279
+ if (dot !== -1) {
280
+ for (const i of byTail[file.length - dot] ?? [])
281
+ addSuffixed(i, file);
613
282
  }
283
+ for (const i of undotted)
284
+ addSuffixed(i, file);
614
285
  }
615
- return found;
616
- }
617
- function checkSuite(name, value) {
618
- if (!isRecord(value)) {
619
- throw new Error(`bivium config: suites.${name} must be an object`);
620
- }
621
- const at = `suites.${name}.`;
622
- const tests = field(value, "tests", isGlobs, at, "a glob or a list of globs");
623
- if (tests === undefined || tests.length === 0) {
624
- throw new Error(`bivium config: suite ${name} has no tests`);
286
+ for (const list of suffixed.values()) {
287
+ if (list.length > 1)
288
+ list.sort(([a], [b]) => a - b);
625
289
  }
626
- const globs = "a glob or a list of globs";
627
- return {
628
- tests,
629
- ...optional("run", field(value, "run", isString, at, "a command")),
630
- ...optional("root", paths(value, "root", at)),
631
- ...optional("urls", field(value, "urls", isGlobsRecord, at, "a map of URL patterns")),
632
- ...optional("pages", field(value, "pages", isGlobs, at, globs)),
633
- ...optional("wiring", field(value, "wiring", isGlobs, at, globs)),
634
- ...optional("setup", field(value, "setup", isGlobs, at, globs)),
635
- ...optional("nonInputs", field(value, "nonInputs", isGlobs, at, globs)),
636
- ...optional("output", field(value, "output", isString, at, "an output name")),
637
- ...optional("types", field(value, "types", isBoolean, at, "a boolean"))
638
- };
639
- }
640
- var WILDCARD = /[*?{}[\]]/;
641
- function paths(record, key, at) {
642
- const value = field(record, key, isGlobs, at, "a path or a list of paths");
643
- for (const path of typeof value === "string" ? [value] : value ?? []) {
644
- const wildcard = WILDCARD.exec(path);
645
- if (!wildcard)
646
- continue;
647
- const prefix = normalizeRoot(path.slice(0, wildcard.index));
648
- throw new Error(`bivium config: ${at}${key} takes paths, not globs: "${path}" (the directory is "${prefix}")`);
649
- }
650
- return value;
651
- }
652
- function isResult(value) {
653
- if (!isRecord(value))
654
- return false;
655
- if ("all" in value)
656
- return typeof value.all === "string";
657
- return "seeds" in value && isStrings(value.seeds) && (!("note" in value) || typeof value.note === "string");
658
- }
659
- function checkResult(value) {
660
- if (isResult(value))
661
- return value;
662
- throw new Error("returned neither { seeds: string[] } nor { all: string }");
663
- }
664
- function checkNarrower(value, at) {
665
- if (!isRecord(value)) {
666
- throw new Error(`bivium config: ${at} must be an object`);
667
- }
668
- const name = field(value, "name", isString, `${at}.`, "a string");
669
- const match = field(value, "match", isGlobs, `${at}.`, "globs");
670
- const opaque = field(value, "opaque", isGlobs, `${at}.`, "globs");
671
- const suites = field(value, "suites", isStrings, `${at}.`, "suite names");
672
- const { narrow } = value;
673
- if (name === undefined || match === undefined || opaque === undefined) {
674
- throw new Error(`bivium config: ${at} needs a name, match and opaque`);
675
- }
676
- if (typeof narrow !== "function") {
677
- throw new Error(`bivium config: ${at}.narrow must be a function`);
678
- }
679
- return {
680
- name,
681
- match,
682
- opaque,
683
- ...optional("suites", suites),
684
- narrow: async (context) => {
685
- const result = await Reflect.apply(narrow, value, [context]);
686
- return checkResult(result);
687
- }
688
- };
689
- }
690
- function checkDeadGlob(value, at) {
691
- if (!isRecord(value)) {
692
- throw new Error(`bivium config: ${at} must be an object`);
693
- }
694
- const file = field(value, "file", isString, `${at}.`, "a path");
695
- const glob = field(value, "glob", isString, `${at}.`, "a glob");
696
- const reason = field(value, "reason", isString, `${at}.`, "a string");
697
- if (!(file && glob && reason)) {
698
- throw new Error(`bivium config: ${at} needs a file, glob and reason`);
699
- }
700
- return { file, glob, reason };
701
- }
702
- function checkKnownUnknown(value, at) {
703
- if (!isRecord(value)) {
704
- throw new Error(`bivium config: ${at} must be an object`);
705
- }
706
- const file = field(value, "file", isString, `${at}.`, "a path");
707
- const reason = field(value, "reason", isString, `${at}.`, "a string");
708
- if (!(file && reason)) {
709
- throw new Error(`bivium config: ${at} needs a file and reason`);
710
- }
711
- return { file, reason };
712
- }
713
- function checkCaptures(name, record) {
714
- for (const [key, globs] of Object.entries(record ?? {})) {
715
- const { wildcards } = captureGlob(key);
716
- for (const value of list(globs, [])) {
717
- const bad = captureReferences(value).find((n) => n < 1 || n > wildcards);
718
- if (bad === undefined)
719
- continue;
720
- const has = `${wildcards} ${wildcards === 1 ? "wildcard" : "wildcards"}`;
721
- const why = bad < 1 ? "captures count from $1" : `its key has ${has}`;
722
- throw new Error(`bivium config: ${name}["${key}"] refers to $${bad} in ${value}, but ${why}`);
723
- }
724
- }
725
- }
726
- function checkConfig(value) {
727
- if (!isRecord(value))
728
- throw new Error("bivium config: not an object");
729
- if (!isRecord(value.suites)) {
730
- throw new Error("bivium config: suites must be an object");
731
- }
732
- const unknown = unknownKeys(value);
733
- if (unknown.length === 1) {
734
- throw new Error(`bivium config: unknown key ${unknown[0]}`);
735
- }
736
- if (unknown.length > 1) {
737
- throw new Error(`bivium config: unknown keys:
738
- ${unknown.map((key) => ` ${key}`).join(`
739
- `)}`);
740
- }
741
- const { narrowers, deadGlobs, knownUnknowns } = value;
742
- if (narrowers !== undefined && !Array.isArray(narrowers)) {
743
- throw new Error("bivium config: narrowers must be a list");
744
- }
745
- if (deadGlobs !== undefined && !Array.isArray(deadGlobs)) {
746
- throw new Error("bivium config: deadGlobs must be a list");
747
- }
748
- if (knownUnknowns !== undefined && !Array.isArray(knownUnknowns)) {
749
- throw new Error("bivium config: knownUnknowns must be a list");
750
- }
751
- const suites = {};
752
- for (const [name, suite] of Object.entries(value.suites)) {
753
- suites[name] = checkSuite(name, suite);
754
- }
755
- const globs = "a glob or a list of globs";
756
- const edges = field(value, "edges", isGlobsRecord, "", "a map of globs");
757
- const reads = field(value, "reads", isGlobsRecord, "", "a map of globs");
758
- checkCaptures("edges", edges);
759
- checkCaptures("reads", reads);
760
- return {
761
- suites,
762
- ...optional("narrowers", narrowers?.map((narrower, i) => checkNarrower(narrower, `narrowers[${i}]`))),
763
- ...optional("roots", paths(value, "roots", "")),
764
- ...optional("ignore", field(value, "ignore", isGlobs, "", globs)),
765
- ...optional("alias", field(value, "alias", isStringRecord, "", "a map of paths")),
766
- ...optional("edges", edges),
767
- ...optional("reads", reads),
768
- ...optional("self", field(value, "self", isGlobs, "", globs)),
769
- ...optional("importOnly", field(value, "importOnly", isGlobs, "", globs)),
770
- ...optional("hermetic", field(value, "hermetic", isGlobs, "", globs)),
771
- ...optional("barrels", field(value, "barrels", isGlobs, "", globs)),
772
- ...optional("external", field(value, "external", isStrings, "", "a list of packages")),
773
- ...optional("inert", field(value, "inert", isGlobs, "", globs)),
774
- ...optional("loadedByName", field(value, "loadedByName", isGlobs, "", globs)),
775
- ...optional("extensions", field(value, "extensions", isStrings, "", "a list")),
776
- ...optional("deadGlobs", deadGlobs?.map((entry, i) => checkDeadGlob(entry, `deadGlobs[${i}]`))),
777
- ...optional("knownUnknowns", knownUnknowns?.map((entry, i) => checkKnownUnknown(entry, `knownUnknowns[${i}]`))),
778
- ...optional("base", field(value, "base", isString, "", "a ref")),
779
- ...optional("cache", field(value, "cache", isCache, "", "a directory or a boolean"))
780
- };
781
- }
782
- var CONFIG_FILES = [
783
- "bivium.config.ts",
784
- "bivium.config.mts",
785
- "bivium.config.mjs",
786
- "bivium.config.js",
787
- "bivium.config.json"
788
- ];
789
- async function readConfig(file) {
790
- if (file.endsWith(".json"))
791
- return JSON.parse(readFileSync(file, "utf-8"));
792
- const module = await import(pathToFileURL(file).href);
793
- return isRecord(module) ? module.default : undefined;
794
- }
795
- var CONFIG_PREFIX = /^bivium config: /;
796
- async function loadConfig(root, path) {
797
- const file = path === undefined ? CONFIG_FILES.map((name) => join2(root, name)).find((f) => existsSync2(f)) : resolve(process.cwd(), path);
798
- if (!file || !existsSync2(file)) {
799
- throw new BiviumError2("BV_CONFIG_NOT_FOUND", path ? `bivium: no config found at ${path}` : `bivium: no config found in ${root}: looked for ${CONFIG_FILES.join(", ")} (--config names another file, --cwd another repository)`);
800
- }
801
- const inside = relative(root, file);
802
- const shown = inside.startsWith("..") || isAbsolute2(inside) ? file : inside;
803
- const named = (code, error) => {
804
- const message = error instanceof Error ? error.message : String(error);
805
- return new BiviumError2(code, `bivium config: ${shown}: ${message.replace(CONFIG_PREFIX, "")}`, { cause: error });
806
- };
807
- let raw;
808
- try {
809
- raw = await readConfig(file);
810
- } catch (error) {
811
- throw named("BV_CONFIG_UNREADABLE", error);
812
- }
813
- let config;
814
- try {
815
- config = resolveConfig(checkConfig(raw));
816
- } catch (error) {
817
- throw named("BV_CONFIG_INVALID", error);
818
- }
819
- return { config, file: shown };
820
- }
821
-
822
- // src/git.ts
823
- import { spawn } from "node:child_process";
824
- import { readFile as readFile2 } from "node:fs/promises";
825
- import { join as join3 } from "node:path";
826
-
827
- // src/sorted.ts
828
- function byCodeUnit(a, b) {
829
- if (a === b)
830
- return 0;
831
- return a < b ? -1 : 1;
832
- }
833
- function sorted(values) {
834
- return [...values].sort(byCodeUnit);
835
- }
836
-
837
- // src/git.ts
838
- function git(cwd, ...args) {
839
- return new Promise((resolve, reject) => {
840
- const child = spawn("git", args, { cwd });
841
- const chunks = [];
842
- const errors = [];
843
- child.stdout.on("data", (chunk) => chunks.push(chunk));
844
- child.stderr.on("data", (chunk) => errors.push(chunk));
845
- child.on("error", reject);
846
- child.on("close", (status) => {
847
- resolve({
848
- status: status ?? 1,
849
- stdout: Buffer.concat(chunks).toString("utf-8"),
850
- stderr: Buffer.concat(errors).toString("utf-8")
851
- });
852
- });
853
- });
854
- }
855
- async function gitOrThrow(cwd, ...args) {
856
- const result = await git(cwd, ...args);
857
- if (result.status !== 0) {
858
- const said = result.stderr.trim().split(`
859
- `)[0];
860
- throw new BiviumError2("BV_GIT_FAILED", `bivium: git ${args.join(" ")} failed${said ? `: ${said}` : ""}`);
861
- }
862
- return result.stdout;
863
- }
864
- function lines(output) {
865
- return output.split(`
866
- `).filter(Boolean);
867
- }
868
- var INDEX_ENTRY = /^(\S) (\d{6}) ([0-9a-f]+) (\d)\t(.*)$/;
869
- var RAW_ENTRY = /^:(\d{6}) \d{6} ([0-9a-f]+) [0-9a-f]+ ([A-Z])\d*\t(.*)$/;
870
- async function missingHistory(cwd, base) {
871
- const [known, forked, shallow] = await Promise.all([
872
- git(cwd, "rev-parse", "--verify", "--quiet", `${base}^{commit}`),
873
- git(cwd, "merge-base", base, "HEAD"),
874
- git(cwd, "rev-parse", "--is-shallow-repository")
875
- ]);
876
- const fix = shallow.stdout.trim() === "true" ? " The clone is shallow: fetch the history (actions/checkout: `fetch-depth: 0`)." : "";
877
- if (known.status !== 0) {
878
- return new BiviumError2("BV_GIT_NO_BASE", `bivium: no commit ${base} here to diff against: fetch it.${fix}`);
879
- }
880
- if (forked.status !== 0) {
881
- return new BiviumError2("BV_GIT_NO_MERGE_BASE", `bivium: ${base} and HEAD share no commit here, so there's no merge base to diff against.${fix}`);
882
- }
883
- return;
884
- }
885
- function mergeBaseOf(cwd, base) {
886
- let pending;
887
- return () => {
888
- if (pending === undefined) {
889
- pending = gitOrThrow(cwd, "merge-base", base, "HEAD").then((out) => out.trim());
890
- pending.catch(() => {
891
- return;
892
- });
893
- }
894
- return pending;
895
- };
896
- }
897
- async function readRevision(cwd, base, roots, {
898
- blobs = false,
899
- mergeBase: eager = false
900
- } = {}) {
901
- const mergeBase = mergeBaseOf(cwd, base);
902
- if (eager)
903
- mergeBase();
904
- const diffArgs = ["--no-renames", "--merge-base", base];
905
- const [listing, diff, staged] = await Promise.all([
906
- gitOrThrow(cwd, "ls-files", "-s", "-v", "-o", "--exclude-standard"),
907
- gitOrThrow(cwd, "diff", "--raw", "--no-abbrev", ...diffArgs),
908
- gitOrThrow(cwd, "diff", "--cached", "--name-only", ...diffArgs)
909
- ]).catch(async (error) => {
910
- throw await missingHistory(cwd, base) ?? error;
911
- });
912
- const entries = lines(listing);
913
- const untracked = [];
914
- for (const line of entries) {
915
- if (line.startsWith("? "))
916
- untracked.push(line.slice(2));
917
- }
918
- const before = new Map;
919
- const diffed = [];
920
- const layout = new Set(untracked);
921
- for (const line of lines(diff)) {
922
- const [, mode, oid, status, path] = RAW_ENTRY.exec(line) ?? [];
923
- if (mode === undefined || oid === undefined || status === undefined || path === undefined) {
924
- throw new Error(`git diff: unexpected line ${line}`);
925
- }
926
- diffed.push(path);
927
- if (status === "A" || status === "D")
928
- layout.add(path);
929
- if (status === "A")
930
- before.set(path, undefined);
931
- else if ("MTD".includes(status) && mode !== "160000") {
932
- before.set(path, oid);
933
- }
934
- }
935
- const reads = new Map;
936
- const readBase = (path) => {
937
- let read = reads.get(path);
938
- if (read === undefined) {
939
- read = readBaseOnce(path);
940
- reads.set(path, read);
941
- }
942
- return read;
943
- };
944
- const readBaseOnce = (path) => {
945
- if (!before.has(path)) {
946
- if (present.has(path)) {
947
- return readFile2(join3(cwd, path), "utf-8").catch(() => mergeBase().then((commit) => show(cwd, `${commit}:${path}`)));
948
- }
949
- return mergeBase().then((commit) => show(cwd, `${commit}:${path}`));
950
- }
951
- const oid = before.get(path);
952
- return oid === undefined ? Promise.resolve(undefined) : show(cwd, oid);
953
- };
954
- const changed = [...new Set([...diffed, ...untracked])];
955
- const dirty = new Set([...changed, ...lines(staged)]);
956
- const underRoots = (path) => roots.some((root) => inRoot(path, root));
957
- const files = new Set;
958
- const tracked = new Set;
959
- const present = new Set;
960
- const oids = new Map;
961
- for (const line of entries) {
962
- const entry = INDEX_ENTRY.exec(line);
963
- if (!entry) {
964
- if (line.startsWith("? ") && underRoots(line.slice(2))) {
965
- files.add(line.slice(2));
966
- }
967
- continue;
968
- }
969
- const [, tag, mode, oid, stage, path] = entry;
970
- if (tag === undefined || mode === undefined || oid === undefined || stage === undefined || path === undefined) {
971
- throw new Error(`bivium: git: unexpected ls-files line ${line}.`);
972
- }
973
- tracked.add(path);
974
- if (mode === "160000" || !underRoots(path))
975
- continue;
976
- files.add(path);
977
- if (dirty.has(path) || stage !== "0" || tag !== "H")
978
- continue;
979
- if (mode !== "100644" && mode !== "100755")
980
- continue;
981
- present.add(path);
982
- if (blobs)
983
- oids.set(path, oid);
984
- }
985
- return {
986
- files: sorted(files),
987
- listed: [...tracked, ...untracked],
988
- changed,
989
- layout,
990
- mergeBase,
991
- readBase,
992
- blobs: oids,
993
- present
994
- };
995
- }
996
- async function show(cwd, object) {
997
- const result = await git(cwd, "show", object);
998
- return result.status === 0 ? result.stdout : undefined;
999
- }
1000
- async function defaultBase(cwd) {
1001
- const head = await git(cwd, "symbolic-ref", "--short", "refs/remotes/origin/HEAD");
1002
- if (head.status === 0 && head.stdout.trim())
1003
- return head.stdout.trim();
1004
- const refs = ["origin/main", "origin/master", "main", "master"];
1005
- const found = await Promise.all(refs.map((ref) => git(cwd, "rev-parse", "--verify", "--quiet", ref)));
1006
- const branch = refs[found.findIndex((result) => result.status === 0)];
1007
- if (branch)
1008
- return branch;
1009
- throw new BiviumError2("BV_GIT_NO_BASE", `bivium: no base given and no default branch found (tried origin/HEAD, ${refs.join(", ")}): pass one, as in \`bivium plan origin/main\`, or set base in the config`);
1010
- }
1011
-
1012
- // src/barrel.ts
1013
- var COMMENTS = /\/\/.*$|\/\*[\s\S]*?\*\//gm;
1014
- var AS = /\s+as\s+/;
1015
- var TYPE_PREFIX = /^type\s+/;
1016
- var NAMED_EXPORT = /export\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']\s*;?/g;
1017
- var STAR_EXPORT = /export\s+(?:type\s+)?\*(?:\s+as\s+([\w$]+))?\s+from\s*["']([^"']+)["']\s*;?/g;
1018
- var BARREL_FILE = /\.[cm]?[jt]sx?$/;
1019
- var ONLY_SEPARATORS = /^[\s;]*$/;
1020
- var STARTS_WITH_EXPORT = /^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*export\b/;
1021
- function parseBarrel(path, source) {
1022
- return BARREL_FILE.test(path) ? parseReExports(source) : undefined;
1023
- }
1024
- function parseReExports(source) {
1025
- if (!STARTS_WITH_EXPORT.test(source))
1026
- return;
1027
- const code = source.replace(COMMENTS, "");
1028
- const barrel = { names: new Map, stars: [] };
1029
- let rest = code.replace(NAMED_EXPORT, (_, list, from) => {
1030
- for (const part of list.split(",")) {
1031
- const name = part.trim().replace(TYPE_PREFIX, "").split(AS).pop();
1032
- if (name)
1033
- barrel.names.set(name, from);
1034
- }
1035
- return "";
1036
- });
1037
- rest = rest.replace(STAR_EXPORT, (_, name, from) => {
1038
- if (name)
1039
- barrel.names.set(name, from);
1040
- else
1041
- barrel.stars.push(from);
1042
- return "";
1043
- });
1044
- if (barrel.names.size + barrel.stars.length === 0)
1045
- return;
1046
- return ONLY_SEPARATORS.test(rest) ? barrel : undefined;
1047
- }
1048
-
1049
- // src/resolve.ts
1050
- import { builtinModules } from "node:module";
1051
- import { posix } from "node:path";
1052
-
1053
- // src/syntax.ts
1054
- var QUERY = /[?#].*$/;
1055
- var UNDECLARED_READS = "reads the disk without @depends-on";
1056
- var RELATIVE = /^\.\.?(?:\/|$)/;
1057
- var URL_REF = /^[a-z]+:|^\/\//;
1058
- var LIST_SEPARATOR = /[\s,]+(?![^{]*\})/;
1059
- var DEPENDS_ON = /^\s*(?:\/\/|\/?\*+)\s*@depends-on\s+(.+?)\s*(?:\*\/)?\s*$/gm;
1060
- var READS = /^\s*(?:\/\/|\/?\*+)\s*@reads\s+(.+?)\s*(?:\*\/)?\s*$/gm;
1061
- var LISTS = /^\s*(?:\/\/|\/?\*+)\s*@lists\s+(.+?)\s*(?:\*\/)?\s*$/gm;
1062
- var GLOB_REGISTRY = /^\s*(?:\/\/|\/?\*+)\s*@glob-registry\b/m;
1063
- var AS2 = /\s+as\s+/;
1064
- var TYPE_PREFIX2 = /^type\s+/;
1065
- var NAMED_CLAUSE = /\{([^}]*)\}/;
1066
- var DEFAULT_OR_NAMESPACE = /^\s*[\w$*]/;
1067
- function namedBindings(clause) {
1068
- const named = NAMED_CLAUSE.exec(clause);
1069
- if (!named || DEFAULT_OR_NAMESPACE.test(clause.replace(NAMED_CLAUSE, ""))) {
1070
- return;
1071
- }
1072
- return captured(named, 1).split(",").map((part) => (part.trim().replace(TYPE_PREFIX2, "").split(AS2)[0] ?? "").trim()).filter(Boolean);
1073
- }
1074
- function captured(match, index) {
1075
- const value = match[index];
1076
- if (value === undefined) {
1077
- throw new Error(`bivium: scan: group ${index} of ${match[0]} is unset.`);
1078
- }
1079
- return value;
1080
- }
1081
-
1082
- // src/resolve.ts
1083
- function isRecord2(value) {
1084
- return typeof value === "object" && value !== null && !Array.isArray(value);
1085
- }
1086
- function isStringRecord2(value) {
1087
- return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
1088
- }
1089
- function toPackageJson(value) {
1090
- if (!isRecord2(value))
1091
- return {};
1092
- const json = {};
1093
- if (typeof value.name === "string")
1094
- json.name = value.name;
1095
- if (value.exports !== undefined)
1096
- json.exports = value.exports;
1097
- if (isRecord2(value.imports))
1098
- json.imports = value.imports;
1099
- if (typeof value.main === "string")
1100
- json.main = value.main;
1101
- const { sideEffects } = value;
1102
- if (typeof sideEffects === "boolean" || Array.isArray(sideEffects) && sideEffects.every((glob) => typeof glob === "string")) {
1103
- json.sideEffects = sideEffects;
1104
- }
1105
- for (const field of DEP_FIELDS) {
1106
- const deps = value[field];
1107
- if (isStringRecord2(deps))
1108
- json[field] = deps;
1109
- }
1110
- return json;
1111
- }
1112
- var BUILTINS = new Set(builtinModules);
1113
- var RUNTIME_BUILTIN = /^(?:node:|bun(?:$|:))/;
1114
- var JS_EXTENSION = /\.(?:js|jsx|mjs|cjs)$/;
1115
- var TS_SOURCES = {
1116
- ".js": [".ts", ".tsx", ".d.ts"],
1117
- ".jsx": [".tsx", ".ts", ".d.ts"],
1118
- ".mjs": [".mts", ".d.mts"],
1119
- ".cjs": [".cts", ".d.cts"]
1120
- };
1121
- var NODE_PREFIX = /^node:/;
1122
- var INVALID_IMPORT_TARGET = /^[./#]/;
1123
- var SVELTEKIT_ASSETS = "./%sveltekit.assets%/";
1124
- var INDEX = "/index";
1125
- var SVELTE_CONFIGS = ["js", "mjs", "cjs", "ts", "mts"].map((ext) => `svelte.config.${ext}`);
1126
- var DEP_FIELDS = [
1127
- "dependencies",
1128
- "devDependencies",
1129
- "peerDependencies",
1130
- "optionalDependencies"
1131
- ];
1132
- function packageName(specifier) {
1133
- const parts = specifier.split("/");
1134
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? "";
1135
- }
1136
- function builtin(specifier) {
1137
- if (RUNTIME_BUILTIN.test(specifier)) {
1138
- const name = specifier.replace(NODE_PREFIX, "");
1139
- return specifier.startsWith("bun") ? specifier : `node:${name.split("/")[0]}`;
1140
- }
1141
- const name = specifier.split("/")[0] ?? "";
1142
- return BUILTINS.has(specifier) || BUILTINS.has(name) ? `node:${name}` : undefined;
1143
- }
1144
- function targets(value, out = []) {
1145
- if (typeof value === "string")
1146
- out.push(value);
1147
- else if (Array.isArray(value))
1148
- for (const item of value)
1149
- targets(item, out);
1150
- else if (value && typeof value === "object") {
1151
- for (const item of Object.values(value))
1152
- targets(item, out);
1153
- }
1154
- return out;
1155
- }
1156
- function subpathMap(exports) {
1157
- if (typeof exports === "string" || Array.isArray(exports)) {
1158
- return { ".": exports };
1159
- }
1160
- if (!isRecord2(exports))
1161
- return;
1162
- const bySubpath = Object.keys(exports).some((key) => key.startsWith("."));
1163
- return bySubpath ? exports : { ".": exports };
1164
- }
1165
- function mapTargets(map, subpath) {
1166
- if (subpath in map && !subpath.includes("*"))
1167
- return targets(map[subpath]);
1168
- let best;
1169
- for (const key of Object.keys(map)) {
1170
- const star = key.indexOf("*");
1171
- if (star === -1)
1172
- continue;
1173
- const prefix = key.slice(0, star);
1174
- const suffix = key.slice(star + 1);
1175
- 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)) {
1176
- best = {
1177
- key,
1178
- match: subpath.slice(prefix.length, subpath.length - suffix.length)
1179
- };
1180
- }
1181
- }
1182
- if (!best)
1183
- return;
1184
- const { match } = best;
1185
- return targets(map[best.key]).map((target) => target.replaceAll("*", match));
1186
- }
1187
- function exportTargets(exports, subpath) {
1188
- const map = subpathMap(exports);
1189
- return map && mapTargets(map, subpath);
1190
- }
1191
- function byDepth(packages) {
1192
- return [...packages].sort(([a], [b]) => b.length - a.length);
1193
- }
1194
- function owner(packages, file) {
1195
- return byDepth(packages).find(([dir]) => dir === "." || file.startsWith(`${dir}/`));
1196
- }
1197
- function aliasPath([key, target], specifier) {
1198
- if (specifier !== key && !specifier.startsWith(`${key}/`))
1199
- return;
1200
- const rest = specifier.slice(key.length + 1);
1201
- if (target === ".")
1202
- return posix.normalize(rest || ".");
1203
- return posix.normalize(rest ? `${target}/${rest}` : target);
1204
- }
1205
- function createResolver({
1206
- files,
1207
- config,
1208
- packages,
1209
- tsconfigs = new Map
1210
- }) {
1211
- const generated = (path) => config.generated.some(({ pattern }) => pattern.test(path));
1212
- const { extensions } = config;
1213
- const exists = (path) => files.has(path);
1214
- const suffixed = new Map;
1215
- const indexes = new Map;
1216
- const byTail = [];
1217
- const undotted = [];
1218
- for (const [i, ext] of extensions.entries()) {
1219
- const dot = ext.lastIndexOf(".");
1220
- if (dot === -1)
1221
- undotted.push(i);
1222
- else {
1223
- const list = byTail[ext.length - dot];
1224
- if (list)
1225
- list.push(i);
1226
- else
1227
- byTail[ext.length - dot] = [i];
1228
- }
1229
- }
1230
- const addSuffixed = (i, file) => {
1231
- const ext = extensions[i];
1232
- if (ext === undefined) {
1233
- throw new Error(`bivium: resolve: no extension at index ${i}.`);
1234
- }
1235
- if (!file.endsWith(ext))
1236
- return;
1237
- const base = file.slice(0, file.length - ext.length);
1238
- const list = suffixed.get(base);
1239
- if (list)
1240
- list.push([i, file]);
1241
- else {
1242
- const created = [[i, file]];
1243
- suffixed.set(base, created);
1244
- if (base.endsWith(INDEX)) {
1245
- indexes.set(base.slice(0, -INDEX.length), created);
1246
- }
1247
- }
1248
- };
1249
- for (const file of files) {
1250
- const dot = file.lastIndexOf(".");
1251
- if (dot !== -1) {
1252
- for (const i of byTail[file.length - dot] ?? [])
1253
- addSuffixed(i, file);
1254
- }
1255
- for (const i of undotted)
1256
- addSuffixed(i, file);
1257
- }
1258
- for (const list of suffixed.values()) {
1259
- if (list.length > 1)
1260
- list.sort(([a], [b]) => a - b);
1261
- }
1262
- const deepestFirst = byDepth(packages);
1263
- const local = new Map;
1264
- for (const [dir, json] of deepestFirst) {
1265
- if (json.name && !local.has(json.name))
1266
- local.set(json.name, dir);
290
+ const deepestFirst = byDepth(packages);
291
+ const local = new Map;
292
+ for (const [dir, json] of deepestFirst) {
293
+ if (json.name && !local.has(json.name))
294
+ local.set(json.name, dir);
1267
295
  }
1268
296
  const declaredIn = (dir) => {
1269
297
  const names = new Set;
@@ -2939,7 +1967,7 @@ var leaf = () => ({
2939
1967
  reads: [],
2940
1968
  unknown: []
2941
1969
  });
2942
- var LEADING_DOT_SLASH2 = /^\.\//;
1970
+ var LEADING_DOT_SLASH = /^\.\//;
2943
1971
  var JS_SPECIFIER = /\.[cm]?jsx?$/;
2944
1972
  var DECLARATION = /\.d(?:\.[^/.]+)?\.[cm]?ts$/;
2945
1973
  function addPattern(deps, pattern, kind) {
@@ -2977,12 +2005,12 @@ function sideEffectful(owning) {
2977
2005
  return matcher(sideEffects.map((glob) => {
2978
2006
  if (!glob.includes("/"))
2979
2007
  return `**/${glob}`;
2980
- const path = glob.replace(LEADING_DOT_SLASH2, "");
2008
+ const path = glob.replace(LEADING_DOT_SLASH, "");
2981
2009
  return dir === "." ? path : `${dir}/${path}`;
2982
2010
  }));
2983
2011
  }
2984
2012
  function gotoSuite(config, path) {
2985
- return config.suites.find((suite) => suite.urls.length > 0 && suite.roots.some((root) => inRoot(path, root)));
2013
+ return config.suites.find((suite) => suite.urls.length > 0 && suite.roots.some((root) => inRoot2(path, root)));
2986
2014
  }
2987
2015
  function mapUrl(suite, url) {
2988
2016
  for (const { key, targets } of suite.urls) {
@@ -3394,61 +2422,210 @@ function affectedBy(graph, changed, {
3394
2422
  if (group.re.test(path))
3395
2423
  visitGroup(group, path);
3396
2424
  }
3397
- };
3398
- const changedPaths = [...changed];
3399
- for (const path of changedPaths)
3400
- visit(path);
3401
- const first = queue[0];
3402
- for (const path of quiet) {
3403
- visit(path);
3404
- changedPaths.push(path);
2425
+ };
2426
+ const changedPaths = [...changed];
2427
+ for (const path of changedPaths)
2428
+ visit(path);
2429
+ const first = queue[0];
2430
+ for (const path of quiet) {
2431
+ visit(path);
2432
+ changedPaths.push(path);
2433
+ }
2434
+ if (seedReaders) {
2435
+ for (const path of changedPaths)
2436
+ visitMatches(readers, path);
2437
+ for (const path of changedPaths) {
2438
+ if (!layout || layout.has(path))
2439
+ visitMatches(listers, path);
2440
+ }
2441
+ }
2442
+ if (includeUnknown && first !== undefined) {
2443
+ for (const path of unknown)
2444
+ visit(path, { from: first, kind: "unknown" });
2445
+ }
2446
+ const { literal } = globbers;
2447
+ let active = globbers.wild;
2448
+ let spent;
2449
+ const spend = (group, from) => {
2450
+ visitGroup(group, from);
2451
+ spent ??= new Set;
2452
+ spent.add(group);
2453
+ };
2454
+ for (let at = 0;at < queue.length && !done; at++) {
2455
+ const path = queue[at];
2456
+ if (path === undefined) {
2457
+ throw new Error("bivium: graph: walked off the queue.");
2458
+ }
2459
+ for (const dependent of dependents.get(path) ?? []) {
2460
+ visit(dependent, parents && { from: path, kind: fileKind(graph, dependent, path) });
2461
+ }
2462
+ const exact = literal.size > 0 ? literal.get(path) : undefined;
2463
+ if (exact) {
2464
+ for (const group of exact) {
2465
+ if (!spent?.has(group))
2466
+ spend(group, path);
2467
+ }
2468
+ }
2469
+ let matched = false;
2470
+ for (const group of active) {
2471
+ if (!group.re.test(path))
2472
+ continue;
2473
+ spend(group, path);
2474
+ matched = true;
2475
+ }
2476
+ if (matched)
2477
+ active = active.filter((group) => !spent?.has(group));
2478
+ }
2479
+ return affected;
2480
+ }
2481
+
2482
+ // src/sorted.ts
2483
+ function byCodeUnit(a, b) {
2484
+ if (a === b)
2485
+ return 0;
2486
+ return a < b ? -1 : 1;
2487
+ }
2488
+ function sorted(values) {
2489
+ return [...values].sort(byCodeUnit);
2490
+ }
2491
+
2492
+ // src/terminal.ts
2493
+ var asIs = (text) => text;
2494
+ var PLAIN = {
2495
+ good: asIs,
2496
+ warn: asIs,
2497
+ bad: asIs,
2498
+ dim: asIs,
2499
+ bold: asIs,
2500
+ faint: asIs
2501
+ };
2502
+ function createPaint() {
2503
+ const wrap = (code) => (text) => text === "" ? text : `\x1B[${code}m${text}\x1B[39m`;
2504
+ return {
2505
+ good: wrap(32),
2506
+ warn: wrap(33),
2507
+ bad: wrap(31),
2508
+ dim: wrap(90),
2509
+ bold: (text) => text === "" ? text : `\x1B[1m${text}\x1B[22m`,
2510
+ faint: (text) => text === "" ? text : `\x1B[2m${text}\x1B[22m`
2511
+ };
2512
+ }
2513
+ function wantsColor(forced, terminal, env, agent) {
2514
+ if (forced !== undefined)
2515
+ return forced;
2516
+ if ((env.NO_COLOR ?? "") !== "")
2517
+ return false;
2518
+ const force = env.FORCE_COLOR;
2519
+ if (force !== undefined && force !== "")
2520
+ return force !== "0";
2521
+ return terminal && !agent && !isDumb(env);
2522
+ }
2523
+ var isDumb = (env) => env.TERM === "dumb";
2524
+ var SEPARATOR = " · ";
2525
+ var branch = (index, count) => index === count - 1 ? "└ " : "├ ";
2526
+ var NOTE_INDENT = " ";
2527
+ function closingLine(paint, what, detail) {
2528
+ return `${paint.good("✓")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
2529
+ }
2530
+ function failLine(paint, what, detail) {
2531
+ return `${paint.bad("✗")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
2532
+ }
2533
+ function truncateWords(text, max) {
2534
+ if ([...text].length <= max)
2535
+ return text;
2536
+ const cut = [...text].slice(0, max - 1).join("");
2537
+ const space = cut.lastIndexOf(" ");
2538
+ return `${(space > max / 2 ? cut.slice(0, space) : cut).replace(/[\s,;:]+$/, "")}…`;
2539
+ }
2540
+ var HASH_TAIL = /[-.][^-./]+\.\w+$/;
2541
+ var WORD_END = /(?<=[-_.])/;
2542
+ var width = (text) => [...text].length;
2543
+ function truncatePath(path, max) {
2544
+ if (width(path) <= max)
2545
+ return path;
2546
+ const parts = path.split("/");
2547
+ const name = parts.pop() ?? path;
2548
+ for (let keep = parts.length - 1;keep >= 0; keep--) {
2549
+ const candidate = `…/${[...parts.slice(parts.length - keep), name].join("/")}`;
2550
+ if (width(candidate) <= max)
2551
+ return candidate;
2552
+ }
2553
+ const prefix = parts.length > 0 ? "…/" : "";
2554
+ const tail = HASH_TAIL.exec(name)?.[0] ?? "";
2555
+ const stem = name.slice(0, name.length - tail.length);
2556
+ const room = max - width(prefix) - width(tail) - 1;
2557
+ if (room < 4)
2558
+ return `${prefix}…${[...name].slice(-(max - width(prefix) - 1)).join("")}`;
2559
+ const words = stem.split(WORD_END);
2560
+ const first = words[0] ?? "";
2561
+ let end = "";
2562
+ for (let i = words.length - 1;i > 0; i--) {
2563
+ const word = words[i] ?? "";
2564
+ if (width(first) + 1 + width(word + end) > room)
2565
+ break;
2566
+ end = word + end;
2567
+ }
2568
+ return end === "" ? `${prefix}${[...stem].slice(0, room).join("")}…${tail}` : `${prefix}${first}…${end}${tail}`;
2569
+ }
2570
+ var ESCAPE = /\x1b\[[0-9;]*m/g;
2571
+ var textWidth = (text) => typeof Bun === "undefined" ? [...text.replace(ESCAPE, "")].length : Bun.stringWidth(text);
2572
+ var MEASURE = 80;
2573
+ var RULE = "\x00rule";
2574
+ function aligned(table, rightColumns = [], paintRule = asIs, indent = " ") {
2575
+ const blank = (cell) => cell === "" || cell === RULE;
2576
+ const used = new Set(table.flatMap((row) => row.flatMap((cell, i) => blank(cell) ? [] : [i])));
2577
+ const keep = (row) => row.filter((_, i) => used.has(i));
2578
+ const rows = table.map(keep);
2579
+ const right = [...used].sort((a, b) => a - b).flatMap((column, i) => rightColumns.includes(column) ? [i] : []);
2580
+ const cellWidth = (cell) => cell === RULE ? 0 : textWidth(cell);
2581
+ const widths = [];
2582
+ for (const row of rows) {
2583
+ for (const [i, cell] of row.entries()) {
2584
+ if (i === row.length - 1 && !right.includes(i))
2585
+ continue;
2586
+ widths[i] = Math.max(widths[i] ?? 0, cellWidth(cell));
2587
+ }
3405
2588
  }
3406
- if (seedReaders) {
3407
- for (const path of changedPaths)
3408
- visitMatches(readers, path);
3409
- for (const path of changedPaths) {
3410
- if (!layout || layout.has(path))
3411
- visitMatches(listers, path);
2589
+ const pad = (cell, i) => " ".repeat(Math.max(0, (widths[i] ?? 0) - cellWidth(cell)));
2590
+ const columnsWidth = (from, to) => widths.slice(from, to).reduce((sum, w) => sum + w + 2, 0);
2591
+ return rows.map((row) => {
2592
+ const first = row.indexOf(RULE);
2593
+ if (first !== -1) {
2594
+ const last = row.lastIndexOf(RULE);
2595
+ const line = "─".repeat(columnsWidth(first, last + 1) - 2);
2596
+ return `${indent}${" ".repeat(columnsWidth(0, first))}${paintRule(line)}`;
3412
2597
  }
3413
- }
3414
- if (includeUnknown && first !== undefined) {
3415
- for (const path of unknown)
3416
- visit(path, { from: first, kind: "unknown" });
3417
- }
3418
- const { literal } = globbers;
3419
- let active = globbers.wild;
3420
- let spent;
3421
- const spend = (group, from) => {
3422
- visitGroup(group, from);
3423
- spent ??= new Set;
3424
- spent.add(group);
2598
+ return `${indent}${row.map((cell, i) => right.includes(i) ? pad(cell, i) + cell : i === row.length - 1 ? cell : cell + pad(cell, i)).join(" ")}`.trimEnd();
2599
+ });
2600
+ }
2601
+ var headerRow = (paint, cells) => cells.map((cell) => paint.faint(cell));
2602
+ var plural = (count, one, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
2603
+ var SILENT = { step: () => {}, clear: () => {} };
2604
+ var BAR_WIDTH = 20;
2605
+ var CLEAR_LINE = "\r\x1B[2K";
2606
+ function createProgress(write, paint, nowMs) {
2607
+ const startMs = nowMs();
2608
+ let text = "";
2609
+ let doneRatio = 0;
2610
+ const render = () => {
2611
+ const done = Math.round(Math.min(1, Math.max(0, doneRatio)) * BAR_WIDTH);
2612
+ const bar = paint.good("━".repeat(done)) + paint.dim("─".repeat(BAR_WIDTH - done));
2613
+ const seconds = Math.floor((nowMs() - startMs) / 1000);
2614
+ write(`${CLEAR_LINE}${bar} ${text}${paint.dim(` · ${seconds} s`)}`);
3425
2615
  };
3426
- for (let at = 0;at < queue.length && !done; at++) {
3427
- const path = queue[at];
3428
- if (path === undefined) {
3429
- throw new Error("bivium: graph: walked off the queue.");
3430
- }
3431
- for (const dependent of dependents.get(path) ?? []) {
3432
- visit(dependent, parents && { from: path, kind: fileKind(graph, dependent, path) });
3433
- }
3434
- const exact = literal.size > 0 ? literal.get(path) : undefined;
3435
- if (exact) {
3436
- for (const group of exact) {
3437
- if (!spent?.has(group))
3438
- spend(group, path);
3439
- }
3440
- }
3441
- let matched = false;
3442
- for (const group of active) {
3443
- if (!group.re.test(path))
3444
- continue;
3445
- spend(group, path);
3446
- matched = true;
2616
+ const timer = setInterval(render, 1000);
2617
+ timer.unref();
2618
+ return {
2619
+ step(next, ratio) {
2620
+ text = next;
2621
+ doneRatio = ratio;
2622
+ render();
2623
+ },
2624
+ clear() {
2625
+ clearInterval(timer);
2626
+ write(CLEAR_LINE);
3447
2627
  }
3448
- if (matched)
3449
- active = active.filter((group) => !spent?.has(group));
3450
- }
3451
- return affected;
2628
+ };
3452
2629
  }
3453
2630
 
3454
2631
  // src/lockfile.ts
@@ -3613,831 +2790,1101 @@ function parseYaml(text) {
3613
2790
  items.push(value(text, indent, line));
3614
2791
  }
3615
2792
  }
3616
- return items;
2793
+ return items;
2794
+ }
2795
+ const document = block(0);
2796
+ const left = lines[at];
2797
+ if (left)
2798
+ fail2(left, "unexpected indentation");
2799
+ return document;
2800
+ }
2801
+
2802
+ // src/lockfile.ts
2803
+ var DEP_FIELDS2 = [
2804
+ "dependencies",
2805
+ "devDependencies",
2806
+ "peerDependencies",
2807
+ "optionalDependencies"
2808
+ ];
2809
+ function isRecord2(value) {
2810
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2811
+ }
2812
+ function isStringRecord2(value) {
2813
+ return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
2814
+ }
2815
+ var STRING_OR_TRAILING_COMMA = /"(?:[^"\\]|\\.)*"|,(\s*[}\]])/g;
2816
+ function parseLenient(text) {
2817
+ return JSON.parse(text.replace(STRING_OR_TRAILING_COMMA, (match, close) => close ?? match));
2818
+ }
2819
+ function specsOf(value) {
2820
+ const specs = new Map;
2821
+ for (const field of DEP_FIELDS2) {
2822
+ const deps = value[field];
2823
+ if (deps === undefined)
2824
+ continue;
2825
+ if (!isStringRecord2(deps))
2826
+ return;
2827
+ specs.set(field, new Map(Object.entries(deps)));
2828
+ }
2829
+ return specs;
2830
+ }
2831
+ function restOf(value, skip) {
2832
+ return JSON.stringify(Object.entries(value).filter(([key]) => !skip.includes(key)));
2833
+ }
2834
+ function install(packages, name, entry, version, info) {
2835
+ const installed = packages.get(name) ?? {
2836
+ entries: [],
2837
+ versions: [],
2838
+ dependencies: new Set,
2839
+ bin: false
2840
+ };
2841
+ if (info?.bin !== undefined || info?.hasBin === true || info?.hasBin === "true") {
2842
+ installed.bin = true;
2843
+ }
2844
+ installed.entries.push(JSON.stringify(entry));
2845
+ if (!installed.versions.includes(version))
2846
+ installed.versions.push(version);
2847
+ for (const field of [
2848
+ "dependencies",
2849
+ "optionalDependencies",
2850
+ "peerDependencies"
2851
+ ]) {
2852
+ const deps = info?.[field];
2853
+ if (isRecord2(deps)) {
2854
+ for (const dep of Object.keys(deps))
2855
+ installed.dependencies.add(dep);
2856
+ }
2857
+ }
2858
+ packages.set(name, installed);
2859
+ }
2860
+ function installedName(key) {
2861
+ const [name = key, scope] = key.split("/").reverse();
2862
+ return scope?.startsWith("@") ? `${scope}/${name}` : name;
2863
+ }
2864
+ function parseBunLock(text) {
2865
+ const value = parseLenient(text);
2866
+ if (!isRecord2(value))
2867
+ return;
2868
+ const { packages, workspaces } = value;
2869
+ if (!isRecord2(packages) || !isRecord2(workspaces))
2870
+ return;
2871
+ const lockfile = {
2872
+ packages: new Map,
2873
+ workspaces: new Map,
2874
+ rest: restOf(value, ["packages", "workspaces"])
2875
+ };
2876
+ for (const [key, entry] of Object.entries(packages)) {
2877
+ if (!Array.isArray(entry) || typeof entry[0] !== "string")
2878
+ return;
2879
+ const ident = entry[0];
2880
+ const at = ident.indexOf("@", 1);
2881
+ const version = at === -1 ? "" : ident.slice(at + 1);
2882
+ install(lockfile.packages, installedName(key), entry, version, entry.find(isRecord2));
2883
+ }
2884
+ for (const [dir, workspace] of Object.entries(workspaces)) {
2885
+ const specs = isRecord2(workspace) ? specsOf(workspace) : undefined;
2886
+ if (!specs)
2887
+ return;
2888
+ lockfile.workspaces.set(dir === "" ? "." : dir, specs);
2889
+ }
2890
+ return lockfile;
2891
+ }
2892
+ var NODE_MODULES = "node_modules/";
2893
+ function parsePackageLock(text) {
2894
+ const value = JSON.parse(text);
2895
+ if (!isRecord2(value) || !isRecord2(value.packages))
2896
+ return;
2897
+ const { lockfileVersion } = value;
2898
+ if (lockfileVersion !== 2 && lockfileVersion !== 3)
2899
+ return;
2900
+ const lockfile = {
2901
+ packages: new Map,
2902
+ workspaces: new Map,
2903
+ rest: restOf(value, ["packages", "dependencies", "name", "version"])
2904
+ };
2905
+ for (const [key, entry] of Object.entries(value.packages)) {
2906
+ if (!isRecord2(entry))
2907
+ return;
2908
+ const at = key.lastIndexOf(NODE_MODULES);
2909
+ if (at !== -1 && (at === 0 || key[at - 1] === "/")) {
2910
+ const version = typeof entry.version === "string" ? entry.version : "";
2911
+ const name = key.slice(at + NODE_MODULES.length);
2912
+ install(lockfile.packages, name, entry, version, entry);
2913
+ continue;
2914
+ }
2915
+ const specs = specsOf(entry);
2916
+ if (!specs)
2917
+ return;
2918
+ lockfile.workspaces.set(key === "" ? "." : key, specs);
2919
+ }
2920
+ return lockfile;
2921
+ }
2922
+ function pnpmKey(key) {
2923
+ const bare = key.startsWith("/") ? key.slice(1) : key;
2924
+ const at = bare.indexOf("@", 1);
2925
+ if (at === -1)
2926
+ return;
2927
+ return { name: bare.slice(0, at), version: withoutPeers(bare.slice(at + 1)) };
2928
+ }
2929
+ function withoutPeers(version) {
2930
+ const paren = version.indexOf("(");
2931
+ return paren === -1 ? version : version.slice(0, paren);
2932
+ }
2933
+ var YAML_DOCUMENT = /^---[ \t]*$/m;
2934
+ var PNPM_VERSION = /^[69]\./;
2935
+ var PNPM_DEP_FIELDS = [
2936
+ "dependencies",
2937
+ "devDependencies",
2938
+ "optionalDependencies"
2939
+ ];
2940
+ function parsePnpmLock(text) {
2941
+ const docs = text.split(YAML_DOCUMENT).filter((doc) => doc.trim() !== "").map(parseYaml);
2942
+ const main = docs.findLast((doc) => isRecord2(doc) && typeof doc.lockfileVersion === "string");
2943
+ if (!isRecord2(main))
2944
+ return;
2945
+ const { lockfileVersion, packages = {}, snapshots = {} } = main;
2946
+ if (typeof lockfileVersion !== "string")
2947
+ return;
2948
+ if (!PNPM_VERSION.test(lockfileVersion))
2949
+ return;
2950
+ if (!isRecord2(packages) || !isRecord2(snapshots))
2951
+ return;
2952
+ const workspaces = isRecord2(main.importers);
2953
+ const importers = isRecord2(main.importers) ? main.importers : { ".": main };
2954
+ const lockfile = {
2955
+ packages: new Map,
2956
+ workspaces: new Map,
2957
+ rest: JSON.stringify([
2958
+ restOf(main, ["importers", "packages", "snapshots", ...PNPM_DEP_FIELDS]),
2959
+ ...docs.filter((doc) => doc !== main)
2960
+ ])
2961
+ };
2962
+ const restOfImporters = [];
2963
+ for (const [dir, importer] of Object.entries(importers)) {
2964
+ if (!isRecord2(importer))
2965
+ return;
2966
+ const specs = new Map;
2967
+ for (const field of PNPM_DEP_FIELDS) {
2968
+ const deps = importer[field];
2969
+ if (deps === undefined)
2970
+ continue;
2971
+ if (!isRecord2(deps))
2972
+ return;
2973
+ const declared = new Map;
2974
+ for (const [name, dep] of Object.entries(deps)) {
2975
+ if (!isRecord2(dep) || typeof dep.specifier !== "string") {
2976
+ return;
2977
+ }
2978
+ declared.set(name, dep.specifier);
2979
+ const version = typeof dep.version === "string" ? dep.version : "";
2980
+ install(lockfile.packages, name, [dir, field, version], withoutPeers(version), {});
2981
+ }
2982
+ specs.set(field, declared);
2983
+ }
2984
+ lockfile.workspaces.set(dir, specs);
2985
+ if (workspaces) {
2986
+ const settings = restOf(importer, PNPM_DEP_FIELDS);
2987
+ if (settings !== "[]")
2988
+ restOfImporters.push([dir, settings]);
2989
+ }
3617
2990
  }
3618
- const document = block(0);
3619
- const left = lines[at];
3620
- if (left)
3621
- fail2(left, "unexpected indentation");
3622
- return document;
2991
+ lockfile.rest += JSON.stringify(restOfImporters);
2992
+ for (const section of [packages, snapshots]) {
2993
+ for (const [key, entry] of Object.entries(section)) {
2994
+ const parsed = pnpmKey(key);
2995
+ if (!parsed)
2996
+ return;
2997
+ const info = isRecord2(entry) ? entry : undefined;
2998
+ install(lockfile.packages, parsed.name, [key, entry], parsed.version, info);
2999
+ }
3000
+ }
3001
+ return lockfile;
3623
3002
  }
3624
-
3625
- // src/lockfile.ts
3626
- var DEP_FIELDS2 = [
3627
- "dependencies",
3628
- "devDependencies",
3629
- "peerDependencies",
3630
- "optionalDependencies"
3631
- ];
3632
- function isRecord3(value) {
3633
- return typeof value === "object" && value !== null && !Array.isArray(value);
3003
+ var FORMATS = new Map([
3004
+ ["bun.lock", parseBunLock],
3005
+ ["package-lock.json", parsePackageLock],
3006
+ ["pnpm-lock.yaml", parsePnpmLock]
3007
+ ]);
3008
+ var UNREAD = ["bun.lockb", "npm-shrinkwrap.json", "yarn.lock"];
3009
+ function parse(file, text) {
3010
+ const format = FORMATS.get(file);
3011
+ if (text === undefined || !format)
3012
+ return;
3013
+ try {
3014
+ return format(text);
3015
+ } catch {
3016
+ return;
3017
+ }
3634
3018
  }
3635
- function isStringRecord3(value) {
3636
- return isRecord3(value) && Object.values(value).every((item) => typeof item === "string");
3019
+ function describe(name, before, after) {
3020
+ if (before === undefined)
3021
+ return `${name} ${after} added`;
3022
+ if (after === undefined)
3023
+ return `${name} ${before} removed`;
3024
+ return before === after ? `${name} ${after}, entry changed` : `${name} ${before} → ${after}`;
3637
3025
  }
3638
- var STRING_OR_TRAILING_COMMA = /"(?:[^"\\]|\\.)*"|,(\s*[}\]])/g;
3639
- function parseLenient(text) {
3640
- return JSON.parse(text.replace(STRING_OR_TRAILING_COMMA, (match, close) => close ?? match));
3026
+ function versions(installed) {
3027
+ return installed && sorted(installed.versions).join(", ");
3641
3028
  }
3642
- function specsOf(value) {
3643
- const specs = new Map;
3029
+ function specChanges(before, after) {
3030
+ const changed = new Map;
3644
3031
  for (const field of DEP_FIELDS2) {
3645
- const deps = value[field];
3646
- if (deps === undefined)
3647
- continue;
3648
- if (!isStringRecord3(deps))
3649
- return;
3650
- specs.set(field, new Map(Object.entries(deps)));
3032
+ const a = before?.get(field);
3033
+ const b = after?.get(field);
3034
+ for (const name of new Set([...a?.keys() ?? [], ...b?.keys() ?? []])) {
3035
+ if (a?.get(name) !== b?.get(name) && !changed.has(name)) {
3036
+ changed.set(name, [a?.get(name), b?.get(name)]);
3037
+ }
3038
+ }
3651
3039
  }
3652
- return specs;
3653
- }
3654
- function restOf(value, skip) {
3655
- return JSON.stringify(Object.entries(value).filter(([key]) => !skip.includes(key)));
3040
+ return changed;
3656
3041
  }
3657
- function install(packages, name, entry, version, info) {
3658
- const installed = packages.get(name) ?? {
3659
- entries: [],
3660
- versions: [],
3661
- dependencies: new Set,
3662
- bin: false
3663
- };
3664
- if (info?.bin !== undefined || info?.hasBin === true || info?.hasBin === "true") {
3665
- installed.bin = true;
3042
+ function lockfileChanges(file, base, head) {
3043
+ const changes = [];
3044
+ const names = new Set([...base.packages.keys(), ...head.packages.keys()]);
3045
+ for (const name of names) {
3046
+ const before = base.packages.get(name);
3047
+ const after = head.packages.get(name);
3048
+ const same = before !== undefined && after !== undefined && sorted(before.entries).join(`
3049
+ `) === sorted(after.entries).join(`
3050
+ `);
3051
+ if (same)
3052
+ continue;
3053
+ changes.push({
3054
+ name,
3055
+ detail: `${file}: ${describe(name, versions(before), versions(after))}`,
3056
+ file
3057
+ });
3666
3058
  }
3667
- installed.entries.push(JSON.stringify(entry));
3668
- if (!installed.versions.includes(version))
3669
- installed.versions.push(version);
3670
- for (const field of [
3671
- "dependencies",
3672
- "optionalDependencies",
3673
- "peerDependencies"
3674
- ]) {
3675
- const deps = info?.[field];
3676
- if (isRecord3(deps)) {
3677
- for (const dep of Object.keys(deps))
3678
- installed.dependencies.add(dep);
3059
+ const resolved = new Set(changes.map((change) => change.name));
3060
+ const dirs = new Set([...base.workspaces.keys(), ...head.workspaces.keys()]);
3061
+ for (const dir of dirs) {
3062
+ const declared = specChanges(base.workspaces.get(dir), head.workspaces.get(dir));
3063
+ for (const [name, [before, after]] of declared) {
3064
+ if (resolved.has(name))
3065
+ continue;
3066
+ resolved.add(name);
3067
+ changes.push({
3068
+ name,
3069
+ detail: `${file}: ${describe(`${name} range`, before, after)}`,
3070
+ file
3071
+ });
3679
3072
  }
3680
3073
  }
3681
- packages.set(name, installed);
3682
- }
3683
- function installedName(key) {
3684
- const [name = key, scope] = key.split("/").reverse();
3685
- return scope?.startsWith("@") ? `${scope}/${name}` : name;
3074
+ return changes;
3686
3075
  }
3687
- function parseBunLock(text) {
3688
- const value = parseLenient(text);
3689
- if (!isRecord3(value))
3076
+ var MANIFEST = /(?:^|\/)package\.json$/;
3077
+ function parseManifest(text) {
3078
+ if (text === undefined)
3690
3079
  return;
3691
- const { packages, workspaces } = value;
3692
- if (!isRecord3(packages) || !isRecord3(workspaces))
3080
+ try {
3081
+ const value = JSON.parse(text);
3082
+ return isRecord2(value) ? value : undefined;
3083
+ } catch {
3693
3084
  return;
3694
- const lockfile = {
3695
- packages: new Map,
3696
- workspaces: new Map,
3697
- rest: restOf(value, ["packages", "workspaces"])
3085
+ }
3086
+ }
3087
+ async function readPackageDiff(changed, listed, base, head) {
3088
+ const lockfiles = changed.filter((file) => FORMATS.has(file));
3089
+ const manifests = changed.filter((file) => MANIFEST.test(file));
3090
+ if (lockfiles.length === 0 && manifests.length === 0)
3091
+ return;
3092
+ const read = (path) => Promise.all([base(path), head(path)]);
3093
+ const known = [...FORMATS.keys()];
3094
+ const [lockTexts, manifestTexts] = await Promise.all([
3095
+ Promise.all(known.map(async (file) => {
3096
+ if (lockfiles.includes(file))
3097
+ return [file, ...await read(file)];
3098
+ const text = await head(file);
3099
+ return [file, text, text];
3100
+ })),
3101
+ Promise.all(manifests.map(async (file) => [file, ...await read(file)]))
3102
+ ]);
3103
+ const diff = {
3104
+ files: new Map,
3105
+ changes: [],
3106
+ dependents: new Map,
3107
+ declared: new Set,
3108
+ bins: new Set
3698
3109
  };
3699
- for (const [key, entry] of Object.entries(packages)) {
3700
- if (!Array.isArray(entry) || typeof entry[0] !== "string")
3701
- return;
3702
- const ident = entry[0];
3703
- const at = ident.indexOf("@", 1);
3704
- const version = at === -1 ? "" : ident.slice(at + 1);
3705
- install(lockfile.packages, installedName(key), entry, version, entry.find(isRecord3));
3110
+ const present = new Map;
3111
+ for (const [file, baseText, headText] of lockTexts) {
3112
+ const after = parse(file, headText);
3113
+ if (headText !== undefined)
3114
+ present.set(file, after);
3115
+ const before = parse(file, baseText);
3116
+ for (const lockfile of [before, after]) {
3117
+ if (!lockfile)
3118
+ continue;
3119
+ for (const [name, installed] of lockfile.packages) {
3120
+ if (installed.bin)
3121
+ diff.bins.add(name);
3122
+ for (const dependency of installed.dependencies) {
3123
+ const set = diff.dependents.get(dependency) ?? new Set;
3124
+ set.add(name);
3125
+ diff.dependents.set(dependency, set);
3126
+ }
3127
+ }
3128
+ for (const specs of lockfile.workspaces.values()) {
3129
+ for (const deps of specs.values()) {
3130
+ for (const name of deps.keys())
3131
+ diff.declared.add(name);
3132
+ }
3133
+ }
3134
+ }
3135
+ if (!lockfiles.includes(file))
3136
+ continue;
3137
+ if (baseText === undefined || headText === undefined) {
3138
+ diff.files.set(file, baseText === undefined ? "added" : "deleted");
3139
+ } else if (!(before && after)) {
3140
+ diff.files.set(file, "can't parse it");
3141
+ } else if (before.rest === after.rest) {
3142
+ diff.files.set(file, undefined);
3143
+ diff.changes.push(...lockfileChanges(file, before, after));
3144
+ } else {
3145
+ diff.files.set(file, "a setting other than the packages changed");
3146
+ }
3706
3147
  }
3707
- for (const [dir, workspace] of Object.entries(workspaces)) {
3708
- const specs = isRecord3(workspace) ? specsOf(workspace) : undefined;
3709
- if (!specs)
3710
- return;
3711
- lockfile.workspaces.set(dir === "" ? "." : dir, specs);
3148
+ const unread = UNREAD.some((file) => listed.includes(file));
3149
+ for (const [file, beforeText, afterText] of manifestTexts) {
3150
+ const before = parseManifest(beforeText);
3151
+ const after = parseManifest(afterText);
3152
+ if (!(before && after) || unread || present.size === 0)
3153
+ continue;
3154
+ const others = (record) => restOf(record, DEP_FIELDS2);
3155
+ const specsBefore = specsOf(before);
3156
+ const specsAfter = specsOf(after);
3157
+ if (others(before) !== others(after) || !specsBefore || !specsAfter) {
3158
+ continue;
3159
+ }
3160
+ const dir = posix3.dirname(file);
3161
+ const declared = specChanges(specsBefore, specsAfter);
3162
+ const recorded = [...present.values()].every((lockfile) => {
3163
+ const specs = lockfile?.workspaces.get(dir);
3164
+ if (!specs)
3165
+ return false;
3166
+ return [...declared.keys()].every((name) => DEP_FIELDS2.every((field) => specs.get(field)?.get(name) === specsAfter.get(field)?.get(name)));
3167
+ });
3168
+ if (!recorded)
3169
+ continue;
3170
+ diff.files.set(file, undefined);
3171
+ for (const [name, [from, to]] of declared) {
3172
+ diff.declared.add(name);
3173
+ diff.changes.push({
3174
+ name,
3175
+ detail: `${file}: ${describe(`${name} range`, from, to)}`,
3176
+ file
3177
+ });
3178
+ }
3712
3179
  }
3713
- return lockfile;
3180
+ return diff;
3714
3181
  }
3715
- var NODE_MODULES = "node_modules/";
3716
- function parsePackageLock(text) {
3717
- const value = JSON.parse(text);
3718
- if (!isRecord3(value) || !isRecord3(value.packages))
3719
- return;
3720
- const { lockfileVersion } = value;
3721
- if (lockfileVersion !== 2 && lockfileVersion !== 3)
3722
- return;
3723
- const lockfile = {
3724
- packages: new Map,
3725
- workspaces: new Map,
3726
- rest: restOf(value, ["packages", "dependencies", "name", "version"])
3182
+ function packageSeeds(graph, config, diff, files) {
3183
+ const result = { seeds: new Map, notes: [], reasons: [] };
3184
+ const { isLoadedByName } = config;
3185
+ const loadedOtherwise = (name) => isLoadedByName === undefined || diff.bins.has(name) || isLoadedByName(name);
3186
+ const tested = new Map;
3187
+ const reachesTest = (name) => {
3188
+ let found = tested.get(name);
3189
+ if (found === undefined) {
3190
+ const node = `pkg:${name}`;
3191
+ found = graph.has(node) && config.suites.some((suite) => reaches(graph, [node], suite.isTest, {
3192
+ includeUnknown: false,
3193
+ types: suite.types
3194
+ }));
3195
+ tested.set(name, found);
3196
+ }
3197
+ return found;
3727
3198
  };
3728
- for (const [key, entry] of Object.entries(value.packages)) {
3729
- if (!isRecord3(entry))
3730
- return;
3731
- const at = key.lastIndexOf(NODE_MODULES);
3732
- if (at !== -1 && (at === 0 || key[at - 1] === "/")) {
3733
- const version = typeof entry.version === "string" ? entry.version : "";
3734
- const name = key.slice(at + NODE_MODULES.length);
3735
- install(lockfile.packages, name, entry, version, entry);
3199
+ const changes = diff.changes.filter((change) => files.includes(change.file)).sort((a, b) => byCodeUnit(a.name, b.name));
3200
+ const unused = new Map;
3201
+ const seen = new Set;
3202
+ for (const change of changes) {
3203
+ const { name, detail } = change;
3204
+ if (seen.has(name))
3736
3205
  continue;
3206
+ seen.add(name);
3207
+ const closure = new Set([name]);
3208
+ const queue = [name];
3209
+ for (const queued of queue) {
3210
+ for (const dependent of diff.dependents.get(queued) ?? []) {
3211
+ if (closure.has(dependent))
3212
+ continue;
3213
+ closure.add(dependent);
3214
+ queue.push(dependent);
3215
+ }
3737
3216
  }
3738
- const specs = specsOf(entry);
3739
- if (!specs)
3740
- return;
3741
- lockfile.workspaces.set(key === "" ? "." : key, specs);
3217
+ const through = [];
3218
+ let covered = true;
3219
+ let importOnly = false;
3220
+ for (const user of closure) {
3221
+ const node = `pkg:${user}`;
3222
+ const imported = graph.has(node);
3223
+ if (imported) {
3224
+ through.push(user);
3225
+ if (!result.seeds.has(node)) {
3226
+ result.seeds.set(node, user === name ? detail : `${detail}, which ${user} depends on`);
3227
+ }
3228
+ }
3229
+ const entry = imported || diff.declared.has(user) || !diff.dependents.has(user);
3230
+ if (!entry || reachesTest(user) || config.isInert(user))
3231
+ continue;
3232
+ if (loadedOtherwise(user)) {
3233
+ covered = false;
3234
+ const list = unused.get(user) ?? [];
3235
+ if (user === name)
3236
+ list.unshift(change);
3237
+ else
3238
+ list.push(change);
3239
+ unused.set(user, list);
3240
+ } else {
3241
+ importOnly = true;
3242
+ }
3243
+ }
3244
+ if (!covered)
3245
+ continue;
3246
+ if (through.length === 0) {
3247
+ result.notes.push(`${detail}, ${importOnly ? "imported by no test" : "inert"}`);
3248
+ continue;
3249
+ }
3250
+ const others = through.filter((user) => user !== name);
3251
+ const shown = others.slice(0, 3).join(", ");
3252
+ const rest = others.length > 3 ? ` and ${others.length - 3} more` : "";
3253
+ result.notes.push(others.length === 0 ? detail : `${detail}, through ${shown}${rest}`);
3742
3254
  }
3743
- return lockfile;
3255
+ for (const user of sorted(unused.keys())) {
3256
+ const [first, ...more] = unused.get(user) ?? [];
3257
+ if (!first)
3258
+ continue;
3259
+ const own = first.name === user;
3260
+ const also = more.length === 0 ? "" : ` (and ${more.length} more ${more.length === 1 ? "package" : "packages"} ${user} depends on)`;
3261
+ result.reasons.push({
3262
+ package: user,
3263
+ file: first.file,
3264
+ message: own ? `${first.detail}${also}, and no test imports it` : `${first.detail}, which ${user} depends on${also}, and no test imports ${user}`
3265
+ });
3266
+ }
3267
+ return result;
3744
3268
  }
3745
- function pnpmKey(key) {
3746
- const bare = key.startsWith("/") ? key.slice(1) : key;
3747
- const at = bare.indexOf("@", 1);
3748
- if (at === -1)
3749
- return;
3750
- return { name: bare.slice(0, at), version: withoutPeers(bare.slice(at + 1)) };
3269
+
3270
+ // src/plan.ts
3271
+ function formatSelection(selection) {
3272
+ return selection.mode === "some" ? selection.files.join(" ") : selection.mode;
3751
3273
  }
3752
- function withoutPeers(version) {
3753
- const paren = version.indexOf("(");
3754
- return paren === -1 ? version : version.slice(0, paren);
3274
+ function select(affected, tests) {
3275
+ const files = tests.filter((file) => affected.has(file));
3276
+ if (files.length === 0)
3277
+ return { mode: "none" };
3278
+ if (files.length === tests.length)
3279
+ return { mode: "all" };
3280
+ return { mode: "some", files };
3755
3281
  }
3756
- var YAML_DOCUMENT = /^---[ \t]*$/m;
3757
- var PNPM_VERSION = /^[69]\./;
3758
- var PNPM_DEP_FIELDS = [
3759
- "dependencies",
3760
- "devDependencies",
3761
- "optionalDependencies"
3762
- ];
3763
- function parsePnpmLock(text) {
3764
- const docs = text.split(YAML_DOCUMENT).filter((doc) => doc.trim() !== "").map(parseYaml);
3765
- const main = docs.findLast((doc) => isRecord3(doc) && typeof doc.lockfileVersion === "string");
3766
- if (!isRecord3(main))
3767
- return;
3768
- const { lockfileVersion, packages = {}, snapshots = {} } = main;
3769
- if (typeof lockfileVersion !== "string")
3770
- return;
3771
- if (!PNPM_VERSION.test(lockfileVersion))
3772
- return;
3773
- if (!isRecord3(packages) || !isRecord3(snapshots))
3774
- return;
3775
- const workspaces = isRecord3(main.importers);
3776
- const importers = isRecord3(main.importers) ? main.importers : { ".": main };
3777
- const lockfile = {
3778
- packages: new Map,
3779
- workspaces: new Map,
3780
- rest: JSON.stringify([
3781
- restOf(main, ["importers", "packages", "snapshots", ...PNPM_DEP_FIELDS]),
3782
- ...docs.filter((doc) => doc !== main)
3783
- ])
3784
- };
3785
- const restOfImporters = [];
3786
- for (const [dir, importer] of Object.entries(importers)) {
3787
- if (!isRecord3(importer))
3788
- return;
3789
- const specs = new Map;
3790
- for (const field of PNPM_DEP_FIELDS) {
3791
- const deps = importer[field];
3792
- if (deps === undefined)
3793
- continue;
3794
- if (!isRecord3(deps))
3795
- return;
3796
- const declared = new Map;
3797
- for (const [name, dep] of Object.entries(deps)) {
3798
- if (!isRecord3(dep) || typeof dep.specifier !== "string") {
3799
- return;
3800
- }
3801
- declared.set(name, dep.specifier);
3802
- const version = typeof dep.version === "string" ? dep.version : "";
3803
- install(lockfile.packages, name, [dir, field, version], withoutPeers(version), {});
3804
- }
3805
- specs.set(field, declared);
3282
+ function classify(graph, changed, config, packages, settings) {
3283
+ const causes = [];
3284
+ const all = config.suites.map((suite) => suite.name);
3285
+ const runAll = (cause) => causes.push({ ...cause, suites: all });
3286
+ const relevant = [];
3287
+ const quiet = [];
3288
+ const packageFiles = [];
3289
+ const settingFiles = [];
3290
+ for (const file of changed) {
3291
+ const read = graph.has(file);
3292
+ const ignored = config.isIgnored(file);
3293
+ if (!read && ignored)
3294
+ continue;
3295
+ const wired = config.suites.filter((suite) => suite.isWiring(file));
3296
+ const diffed = packages?.files.has(file) ?? false;
3297
+ if (config.isSelf(file)) {
3298
+ runAll({
3299
+ kind: "self",
3300
+ file,
3301
+ message: `${file}: test selector changed`
3302
+ });
3303
+ continue;
3806
3304
  }
3807
- lockfile.workspaces.set(dir, specs);
3808
- if (workspaces) {
3809
- const settings = restOf(importer, PNPM_DEP_FIELDS);
3810
- if (settings !== "[]")
3811
- restOfImporters.push([dir, settings]);
3305
+ for (const suite of wired) {
3306
+ causes.push({
3307
+ kind: "wiring",
3308
+ suites: [suite.name],
3309
+ file,
3310
+ message: `${file}: wires the ${suite.name} suite`
3311
+ });
3812
3312
  }
3813
- }
3814
- lockfile.rest += JSON.stringify(restOfImporters);
3815
- for (const section of [packages, snapshots]) {
3816
- for (const [key, entry] of Object.entries(section)) {
3817
- const parsed = pnpmKey(key);
3818
- if (!parsed)
3819
- return;
3820
- const info = isRecord3(entry) ? entry : undefined;
3821
- install(lockfile.packages, parsed.name, [key, entry], parsed.version, info);
3313
+ if (wired.length > 0 && !diffed)
3314
+ continue;
3315
+ if (diffed) {
3316
+ const reason = packages?.files.get(file);
3317
+ if (reason === undefined) {
3318
+ packageFiles.push(file);
3319
+ } else {
3320
+ runAll({ kind: "lockfile", file, message: `${file}: ${reason}` });
3321
+ }
3322
+ } else if (read || config.roots.some((root) => inRoot2(file, root))) {
3323
+ if (ignored)
3324
+ quiet.push(file);
3325
+ else
3326
+ ((settings?.has(file)) ? settingFiles : relevant).push(file);
3327
+ } else {
3328
+ runAll({
3329
+ kind: "outside",
3330
+ file,
3331
+ message: `${file}: outside the dependency graph`
3332
+ });
3822
3333
  }
3823
3334
  }
3824
- return lockfile;
3335
+ return { relevant, quiet, packageFiles, settingFiles, causes };
3825
3336
  }
3826
- var FORMATS = new Map([
3827
- ["bun.lock", parseBunLock],
3828
- ["package-lock.json", parsePackageLock],
3829
- ["pnpm-lock.yaml", parsePnpmLock]
3830
- ]);
3831
- var UNREAD = ["bun.lockb", "npm-shrinkwrap.json", "yarn.lock"];
3832
- function parse(file, text) {
3833
- const format = FORMATS.get(file);
3834
- if (text === undefined || !format)
3337
+ function narrowedWalk(graph, seeds, {
3338
+ quiet,
3339
+ layout,
3340
+ types
3341
+ }, coarse, narrowings) {
3342
+ const matched = new Set(narrowings.flatMap((narrowing) => narrowing.matched));
3343
+ const fine = affectedBy(graph, seeds.filter((seed) => !matched.has(seed)), { quiet, layout, types });
3344
+ for (const narrowing of narrowings) {
3345
+ const walk = affectedBy(graph, [...narrowing.matched, ...narrowing.seeds], {
3346
+ opaque: narrowing.narrower.opaque,
3347
+ layout,
3348
+ types
3349
+ });
3350
+ for (const node of walk)
3351
+ fine.add(node);
3352
+ }
3353
+ return new Set([...fine].filter((node) => coarse.has(node)));
3354
+ }
3355
+ function orphanOf(graph, config, suite, file) {
3356
+ if (!suite.roots.some((root) => inRoot2(file, root)))
3835
3357
  return;
3836
- try {
3837
- return format(text);
3838
- } catch {
3358
+ const wired = (path) => suite.isTest(path) || suite.isPage(path);
3359
+ if (reaches(graph, [file], wired, {
3360
+ includeUnknown: false,
3361
+ types: suite.types || DECLARATION.test(file)
3362
+ })) {
3839
3363
  return;
3840
3364
  }
3365
+ const deleted = !graph.has(file);
3366
+ if (deleted && suite.isTest(file))
3367
+ return;
3368
+ if (deleted && config.isImportOnly(file))
3369
+ return;
3370
+ if (suite.isNonInput(file))
3371
+ return;
3372
+ const typed = !suite.types && reaches(graph, [file], suite.isTest, { includeUnknown: false });
3373
+ return { typed };
3841
3374
  }
3842
- function describe(name, before, after) {
3843
- if (before === undefined)
3844
- return `${name} ${after} added`;
3845
- if (after === undefined)
3846
- return `${name} ${before} removed`;
3847
- return before === after ? `${name} ${after}, entry changed` : `${name} ${before} → ${after}`;
3848
- }
3849
- function versions(installed) {
3850
- return installed && sorted(installed.versions).join(", ");
3851
- }
3852
- function specChanges(before, after) {
3853
- const changed = new Map;
3854
- for (const field of DEP_FIELDS2) {
3855
- const a = before?.get(field);
3856
- const b = after?.get(field);
3857
- for (const name of new Set([...a?.keys() ?? [], ...b?.keys() ?? []])) {
3858
- if (a?.get(name) !== b?.get(name) && !changed.has(name)) {
3859
- changed.set(name, [a?.get(name), b?.get(name)]);
3375
+ function planTests(graph, changed, config, {
3376
+ barrelNames = [],
3377
+ layout = new Set,
3378
+ narrowed = [],
3379
+ packages,
3380
+ settings
3381
+ } = {}) {
3382
+ const { relevant, quiet, packageFiles, settingFiles, causes } = classify(graph, changed, config, packages, settings);
3383
+ const settingCauses = new Map;
3384
+ const settingNotes = [];
3385
+ for (const file of settingFiles) {
3386
+ const change = settings?.get(file);
3387
+ if (!change)
3388
+ continue;
3389
+ settingNotes.push(change.note);
3390
+ for (const seed of change.seeds) {
3391
+ if (!settingCauses.has(seed)) {
3392
+ settingCauses.set(seed, `governed by ${file}, which changed`);
3860
3393
  }
3861
3394
  }
3862
3395
  }
3863
- return changed;
3864
- }
3865
- function lockfileChanges(file, base, head) {
3866
- const changes = [];
3867
- const names = new Set([...base.packages.keys(), ...head.packages.keys()]);
3868
- for (const name of names) {
3869
- const before = base.packages.get(name);
3870
- const after = head.packages.get(name);
3871
- const same = before !== undefined && after !== undefined && sorted(before.entries).join(`
3872
- `) === sorted(after.entries).join(`
3873
- `);
3874
- if (same)
3875
- continue;
3876
- changes.push({
3877
- name,
3878
- detail: `${file}: ${describe(name, versions(before), versions(after))}`,
3879
- file
3880
- });
3396
+ const bumped = packages && packageFiles.length > 0 ? packageSeeds(graph, config, packages, packageFiles) : { seeds: new Map, notes: [], reasons: [] };
3397
+ const all = config.suites.map((suite) => suite.name);
3398
+ for (const unused of bumped.reasons) {
3399
+ causes.push({ kind: "package", suites: all, ...unused });
3881
3400
  }
3882
- const resolved = new Set(changes.map((change) => change.name));
3883
- const dirs = new Set([...base.workspaces.keys(), ...head.workspaces.keys()]);
3884
- for (const dir of dirs) {
3885
- const declared = specChanges(base.workspaces.get(dir), head.workspaces.get(dir));
3886
- for (const [name, [before, after]] of declared) {
3887
- if (resolved.has(name))
3401
+ const seeds = [
3402
+ ...relevant,
3403
+ ...settingFiles,
3404
+ ...settingCauses.keys(),
3405
+ ...barrelNames,
3406
+ ...packageFiles,
3407
+ ...bumped.seeds.keys()
3408
+ ];
3409
+ const affected = walksByTypes(graph, seeds, { quiet, layout });
3410
+ const nodes = [...graph.keys()];
3411
+ const tests = new Map(config.suites.map((suite) => [suite.name, nodes.filter(suite.isTest)]));
3412
+ for (const suite of config.suites) {
3413
+ for (const file of relevant) {
3414
+ const orphan = orphanOf(graph, config, suite, file);
3415
+ if (!orphan)
3888
3416
  continue;
3889
- resolved.add(name);
3890
- changes.push({
3891
- name,
3892
- detail: `${file}: ${describe(`${name} range`, before, after)}`,
3893
- file
3417
+ const { typed } = orphan;
3418
+ causes.push({
3419
+ kind: "orphan",
3420
+ suites: [suite.name],
3421
+ file,
3422
+ 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)" : ""}`
3894
3423
  });
3895
3424
  }
3896
3425
  }
3897
- return changes;
3426
+ const narrowings = new Map;
3427
+ for (const { narrower, result } of narrowed) {
3428
+ const matched = relevant.filter(narrower.match);
3429
+ if (matched.length === 0)
3430
+ continue;
3431
+ if ("all" in result) {
3432
+ causes.push({
3433
+ kind: "narrower",
3434
+ suites: narrower.suites,
3435
+ narrower: narrower.name,
3436
+ message: `${narrower.name}: ${result.all}`
3437
+ });
3438
+ continue;
3439
+ }
3440
+ for (const name of narrower.suites) {
3441
+ const list = narrowings.get(name) ?? [];
3442
+ list.push({ matched, narrower, seeds: result.seeds });
3443
+ narrowings.set(name, list);
3444
+ }
3445
+ }
3446
+ const full = new Set(causes.flatMap((cause) => cause.suites));
3447
+ const suites = {};
3448
+ for (const suite of config.suites) {
3449
+ if (full.has(suite.name)) {
3450
+ suites[suite.name] = { mode: "all" };
3451
+ continue;
3452
+ }
3453
+ const coarse = affected(suite.types);
3454
+ const narrowing = narrowings.get(suite.name);
3455
+ suites[suite.name] = select(narrowing ? narrowedWalk(graph, seeds, { quiet, layout, types: suite.types }, coarse, narrowing) : coarse, tests.get(suite.name) ?? []);
3456
+ }
3457
+ return {
3458
+ suites,
3459
+ reasons: causes.map((cause) => cause.message),
3460
+ causes,
3461
+ totals: Object.fromEntries(config.suites.map((suite) => [
3462
+ suite.name,
3463
+ tests.get(suite.name)?.length ?? 0
3464
+ ])),
3465
+ full: [...full],
3466
+ packages: bumped.notes,
3467
+ settings: settingNotes,
3468
+ settingCauses,
3469
+ seeds,
3470
+ quiet,
3471
+ layout,
3472
+ packageCauses: bumped.seeds,
3473
+ narrowings
3474
+ };
3898
3475
  }
3899
- var MANIFEST = /(?:^|\/)package\.json$/;
3900
- function parseManifest(text) {
3901
- if (text === undefined)
3902
- return;
3903
- try {
3904
- const value = JSON.parse(text);
3905
- return isRecord3(value) ? value : undefined;
3906
- } catch {
3476
+
3477
+ // src/compute.ts
3478
+ import { readFile as readFile3, stat } from "node:fs/promises";
3479
+ import { join as join3, posix as posix6, resolve } from "node:path";
3480
+
3481
+ // src/cache.ts
3482
+ import { existsSync } from "node:fs";
3483
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3484
+ import { isAbsolute, join } from "node:path";
3485
+ var SCANNER_VERSION = 9;
3486
+ var MAGIC = "bivium-extractions";
3487
+ var FILE = "extractions.json";
3488
+ function isHeader(value) {
3489
+ 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";
3490
+ }
3491
+ function cacheDir(root, cache) {
3492
+ if (cache === false)
3907
3493
  return;
3494
+ if (typeof cache === "string") {
3495
+ return isAbsolute(cache) ? cache : join(root, cache);
3908
3496
  }
3497
+ const modules = join(root, "node_modules");
3498
+ return existsSync(modules) ? join(modules, ".cache", "bivium") : join(root, ".bivium", "cache");
3909
3499
  }
3910
- async function readPackageDiff(changed, listed, base, head) {
3911
- const lockfiles = changed.filter((file) => FORMATS.has(file));
3912
- const manifests = changed.filter((file) => MANIFEST.test(file));
3913
- if (lockfiles.length === 0 && manifests.length === 0)
3914
- return;
3915
- const read = (path) => Promise.all([base(path), head(path)]);
3916
- const known = [...FORMATS.keys()];
3917
- const [lockTexts, manifestTexts] = await Promise.all([
3918
- Promise.all(known.map(async (file) => {
3919
- if (lockfiles.includes(file))
3920
- return [file, ...await read(file)];
3921
- const text = await head(file);
3922
- return [file, text, text];
3923
- })),
3924
- Promise.all(manifests.map(async (file) => [file, ...await read(file)]))
3925
- ]);
3926
- const diff = {
3927
- files: new Map,
3928
- changes: [],
3929
- dependents: new Map,
3930
- declared: new Set,
3931
- bins: new Set
3932
- };
3933
- const present = new Map;
3934
- for (const [file, baseText, headText] of lockTexts) {
3935
- const after = parse(file, headText);
3936
- if (headText !== undefined)
3937
- present.set(file, after);
3938
- const before = parse(file, baseText);
3939
- for (const lockfile of [before, after]) {
3940
- if (!lockfile)
3941
- continue;
3942
- for (const [name, installed] of lockfile.packages) {
3943
- if (installed.bin)
3944
- diff.bins.add(name);
3945
- for (const dependency of installed.dependencies) {
3946
- const set = diff.dependents.get(dependency) ?? new Set;
3947
- set.add(name);
3948
- diff.dependents.set(dependency, set);
3949
- }
3500
+
3501
+ class ExtractionCache {
3502
+ #rows = new Map;
3503
+ #strings = [];
3504
+ #used = new Map;
3505
+ #dirty = false;
3506
+ dir;
3507
+ constructor(dir) {
3508
+ this.dir = dir;
3509
+ }
3510
+ static async open(dir) {
3511
+ const cache = new ExtractionCache(dir);
3512
+ if (!dir)
3513
+ return cache;
3514
+ const text = await readFile(join(dir, FILE), "utf-8").catch(() => "");
3515
+ if (text)
3516
+ cache.#load(text);
3517
+ return cache;
3518
+ }
3519
+ #load(text) {
3520
+ try {
3521
+ const parsed = JSON.parse(text);
3522
+ if (!Array.isArray(parsed))
3523
+ return;
3524
+ const fields = parsed;
3525
+ const [header, strings, rows] = fields;
3526
+ if (!isHeader(header) || !Array.isArray(strings) || !Array.isArray(rows) || header.strings !== strings.length || header.rows !== rows.length) {
3527
+ return;
3950
3528
  }
3951
- for (const specs of lockfile.workspaces.values()) {
3952
- for (const deps of specs.values()) {
3953
- for (const name of deps.keys())
3954
- diff.declared.add(name);
3529
+ this.#strings = strings;
3530
+ for (const row of rows) {
3531
+ if (Array.isArray(row) && typeof row[0] === "string") {
3532
+ this.#rows.set(row[0], row);
3955
3533
  }
3956
3534
  }
3535
+ } catch {}
3536
+ }
3537
+ get size() {
3538
+ return this.#rows.size;
3539
+ }
3540
+ get(oid, format) {
3541
+ const key = `${format}:${oid}`;
3542
+ const used = this.#used.get(key);
3543
+ if (used)
3544
+ return used;
3545
+ const row = this.#rows.get(key);
3546
+ if (!row)
3547
+ return;
3548
+ let extraction;
3549
+ try {
3550
+ extraction = decode(row, this.#strings);
3551
+ } catch {
3552
+ this.#rows.delete(key);
3553
+ return;
3957
3554
  }
3958
- if (!lockfiles.includes(file))
3959
- continue;
3960
- if (baseText === undefined || headText === undefined) {
3961
- diff.files.set(file, baseText === undefined ? "added" : "deleted");
3962
- } else if (!(before && after)) {
3963
- diff.files.set(file, "can't parse it");
3964
- } else if (before.rest === after.rest) {
3965
- diff.files.set(file, undefined);
3966
- diff.changes.push(...lockfileChanges(file, before, after));
3967
- } else {
3968
- diff.files.set(file, "a setting other than the packages changed");
3969
- }
3555
+ this.#used.set(key, extraction);
3556
+ return extraction;
3970
3557
  }
3971
- const unread = UNREAD.some((file) => listed.includes(file));
3972
- for (const [file, beforeText, afterText] of manifestTexts) {
3973
- const before = parseManifest(beforeText);
3974
- const after = parseManifest(afterText);
3975
- if (!(before && after) || unread || present.size === 0)
3976
- continue;
3977
- const others = (record) => restOf(record, DEP_FIELDS2);
3978
- const specsBefore = specsOf(before);
3979
- const specsAfter = specsOf(after);
3980
- if (others(before) !== others(after) || !specsBefore || !specsAfter) {
3981
- continue;
3558
+ set(oid, format, extraction) {
3559
+ const key = `${format}:${oid}`;
3560
+ this.#used.set(key, extraction);
3561
+ this.#dirty = true;
3562
+ }
3563
+ async save() {
3564
+ if (!this.dir || !this.#dirty)
3565
+ return;
3566
+ const table = createStrings();
3567
+ const rows = [];
3568
+ for (const [key, extraction] of this.#used) {
3569
+ rows.push(encode(key, extraction, table));
3982
3570
  }
3983
- const dir = posix3.dirname(file);
3984
- const declared = specChanges(specsBefore, specsAfter);
3985
- const recorded = [...present.values()].every((lockfile) => {
3986
- const specs = lockfile?.workspaces.get(dir);
3987
- if (!specs)
3988
- return false;
3989
- return [...declared.keys()].every((name) => DEP_FIELDS2.every((field) => specs.get(field)?.get(name) === specsAfter.get(field)?.get(name)));
3990
- });
3991
- if (!recorded)
3992
- continue;
3993
- diff.files.set(file, undefined);
3994
- for (const [name, [from, to]] of declared) {
3995
- diff.declared.add(name);
3996
- diff.changes.push({
3997
- name,
3998
- detail: `${file}: ${describe(`${name} range`, from, to)}`,
3999
- file
3571
+ let stale = Math.floor(this.#used.size / 2);
3572
+ for (const [key, row] of this.#rows) {
3573
+ if (stale === 0)
3574
+ break;
3575
+ if (this.#used.has(key))
3576
+ continue;
3577
+ try {
3578
+ rows.push(encode(key, decode(row, this.#strings), table));
3579
+ stale--;
3580
+ } catch {}
3581
+ }
3582
+ const header = {
3583
+ magic: MAGIC,
3584
+ bivium: version,
3585
+ scanner: SCANNER_VERSION,
3586
+ rows: rows.length,
3587
+ strings: table.list.length
3588
+ };
3589
+ const file = join(this.dir, FILE);
3590
+ const temp = `${file}.${process.pid}.${nowMs()}.tmp`;
3591
+ try {
3592
+ await mkdir(this.dir, { recursive: true });
3593
+ const ignore = join(this.dir, ".gitignore");
3594
+ if (!existsSync(ignore))
3595
+ await writeFile(ignore, `*
3596
+ `);
3597
+ await writeFile(temp, JSON.stringify([header, table.list, rows]));
3598
+ await rename(temp, file);
3599
+ this.#dirty = false;
3600
+ } catch {
3601
+ await unlink(temp).catch(() => {
3602
+ return;
4000
3603
  });
4001
3604
  }
4002
3605
  }
4003
- return diff;
4004
3606
  }
4005
- function packageSeeds(graph, config, diff, files) {
4006
- const result = { seeds: new Map, notes: [], reasons: [] };
4007
- const { isLoadedByName } = config;
4008
- const loadedOtherwise = (name) => isLoadedByName === undefined || diff.bins.has(name) || isLoadedByName(name);
4009
- const tested = new Map;
4010
- const reachesTest = (name) => {
4011
- let found = tested.get(name);
3607
+ function createStrings() {
3608
+ const list = [];
3609
+ const idsByValue = new Map;
3610
+ const id = (value) => {
3611
+ let found = idsByValue.get(value);
4012
3612
  if (found === undefined) {
4013
- const node = `pkg:${name}`;
4014
- found = graph.has(node) && config.suites.some((suite) => reaches(graph, [node], suite.isTest, {
4015
- includeUnknown: false,
4016
- types: suite.types
4017
- }));
4018
- tested.set(name, found);
3613
+ found = list.length;
3614
+ list.push(value);
3615
+ idsByValue.set(value, found);
4019
3616
  }
4020
3617
  return found;
4021
3618
  };
4022
- const changes = diff.changes.filter((change) => files.includes(change.file)).sort((a, b) => byCodeUnit(a.name, b.name));
4023
- const unused = new Map;
4024
- const seen = new Set;
4025
- for (const change of changes) {
4026
- const { name, detail } = change;
4027
- if (seen.has(name))
4028
- continue;
4029
- seen.add(name);
4030
- const closure = new Set([name]);
4031
- const queue = [name];
4032
- for (const queued of queue) {
4033
- for (const dependent of diff.dependents.get(queued) ?? []) {
4034
- if (closure.has(dependent))
4035
- continue;
4036
- closure.add(dependent);
4037
- queue.push(dependent);
4038
- }
4039
- }
4040
- const through = [];
4041
- let covered = true;
4042
- let importOnly = false;
4043
- for (const user of closure) {
4044
- const node = `pkg:${user}`;
4045
- const imported = graph.has(node);
4046
- if (imported) {
4047
- through.push(user);
4048
- if (!result.seeds.has(node)) {
4049
- result.seeds.set(node, user === name ? detail : `${detail}, which ${user} depends on`);
4050
- }
4051
- }
4052
- const entry = imported || diff.declared.has(user) || !diff.dependents.has(user);
4053
- if (!entry || reachesTest(user) || config.isInert(user))
4054
- continue;
4055
- if (loadedOtherwise(user)) {
4056
- covered = false;
4057
- const list = unused.get(user) ?? [];
4058
- if (user === name)
4059
- list.unshift(change);
4060
- else
4061
- list.push(change);
4062
- unused.set(user, list);
4063
- } else {
4064
- importOnly = true;
4065
- }
3619
+ const ids = (values) => values.length === 0 ? 0 : values.map(id);
3620
+ return { list, id, ids };
3621
+ }
3622
+ function typeIndexes(imports) {
3623
+ const indexes = [];
3624
+ for (const [i, ref] of imports.entries())
3625
+ if (ref.type)
3626
+ indexes.push(i);
3627
+ return indexes.length === 0 ? 0 : indexes;
3628
+ }
3629
+ function encode(key, e, table) {
3630
+ const imports = e.imports.map(({ specifier, names }) => names ? [table.id(specifier), ...names.map((n) => table.id(n))] : table.id(specifier));
3631
+ const barrel = e.barrel && [
3632
+ [...e.barrel.names].flatMap(([name, from]) => [
3633
+ table.id(name),
3634
+ table.id(from)
3635
+ ]),
3636
+ table.ids(e.barrel.stars)
3637
+ ];
3638
+ return [
3639
+ key,
3640
+ imports.length === 0 ? 0 : imports,
3641
+ table.ids(e.globs),
3642
+ table.ids(e.gotos),
3643
+ table.ids(e.dependsOn),
3644
+ table.ids(e.reads),
3645
+ table.ids(e.unknown),
3646
+ e.fallback === undefined ? 0 : table.id(e.fallback),
3647
+ barrel ?? 0,
3648
+ typeIndexes(e.imports),
3649
+ table.ids(e.lists)
3650
+ ];
3651
+ }
3652
+ function decode(row, strings) {
3653
+ const str = (id) => {
3654
+ const value = typeof id === "number" ? strings[id] : undefined;
3655
+ if (typeof value !== "string")
3656
+ throw new Error("bad string id");
3657
+ return value;
3658
+ };
3659
+ const list = (ids) => {
3660
+ if (ids === 0)
3661
+ return [];
3662
+ if (!Array.isArray(ids))
3663
+ throw new Error("bad list");
3664
+ return ids.map(str);
3665
+ };
3666
+ const refs = row[1] === 0 ? [] : row[1];
3667
+ if (!Array.isArray(refs))
3668
+ throw new Error("bad imports");
3669
+ const imports = refs.map((item) => Array.isArray(item) ? { specifier: str(item[0]), names: item.slice(1).map(str) } : { specifier: str(item) });
3670
+ if (row[9] !== 0) {
3671
+ if (!Array.isArray(row[9]))
3672
+ throw new Error("bad types");
3673
+ for (const i of row[9]) {
3674
+ const ref = typeof i === "number" ? imports[i] : undefined;
3675
+ if (!ref)
3676
+ throw new Error("bad type index");
3677
+ ref.type = true;
4066
3678
  }
4067
- if (!covered)
4068
- continue;
4069
- if (through.length === 0) {
4070
- result.notes.push(`${detail}, ${importOnly ? "imported by no test" : "inert"}`);
4071
- continue;
3679
+ }
3680
+ const extraction = {
3681
+ imports,
3682
+ globs: list(row[2]),
3683
+ gotos: list(row[3]),
3684
+ dependsOn: list(row[4]),
3685
+ reads: list(row[5]),
3686
+ lists: list(row[10]),
3687
+ unknown: list(row[6])
3688
+ };
3689
+ if (row[7] !== 0)
3690
+ extraction.fallback = str(row[7]);
3691
+ if (row[8] !== 0) {
3692
+ if (!Array.isArray(row[8]))
3693
+ throw new Error("bad barrel");
3694
+ const barrel = row[8];
3695
+ const [pairs, stars] = barrel;
3696
+ if (!Array.isArray(pairs))
3697
+ throw new Error("bad barrel names");
3698
+ const names = new Map;
3699
+ for (let i = 0;i < pairs.length; i += 2) {
3700
+ names.set(str(pairs[i]), str(pairs[i + 1]));
4072
3701
  }
4073
- const others = through.filter((user) => user !== name);
4074
- const shown = others.slice(0, 3).join(", ");
4075
- const rest = others.length > 3 ? ` and ${others.length - 3} more` : "";
4076
- result.notes.push(others.length === 0 ? detail : `${detail}, through ${shown}${rest}`);
4077
- }
4078
- for (const user of sorted(unused.keys())) {
4079
- const [first, ...more] = unused.get(user) ?? [];
4080
- if (!first)
4081
- continue;
4082
- const own = first.name === user;
4083
- const also = more.length === 0 ? "" : ` (and ${more.length} more ${more.length === 1 ? "package" : "packages"} ${user} depends on)`;
4084
- result.reasons.push({
4085
- package: user,
4086
- file: first.file,
4087
- message: own ? `${first.detail}${also}, and no test imports it` : `${first.detail}, which ${user} depends on${also}, and no test imports ${user}`
4088
- });
3702
+ extraction.barrel = { names, stars: list(stars) };
4089
3703
  }
4090
- return result;
3704
+ return extraction;
4091
3705
  }
4092
3706
 
4093
- // src/plan.ts
4094
- function formatSelection(selection) {
4095
- return selection.mode === "some" ? selection.files.join(" ") : selection.mode;
4096
- }
4097
- function select(affected, tests) {
4098
- const files = tests.filter((file) => affected.has(file));
4099
- if (files.length === 0)
4100
- return { mode: "none" };
4101
- if (files.length === tests.length)
4102
- return { mode: "all" };
4103
- return { mode: "some", files };
4104
- }
4105
- function classify(graph, changed, config, packages, settings) {
4106
- const causes = [];
4107
- const all = config.suites.map((suite) => suite.name);
4108
- const runAll = (cause) => causes.push({ ...cause, suites: all });
4109
- const relevant = [];
4110
- const quiet = [];
4111
- const packageFiles = [];
4112
- const settingFiles = [];
4113
- for (const file of changed) {
4114
- const read = graph.has(file);
4115
- const ignored = config.isIgnored(file);
4116
- if (!read && ignored)
4117
- continue;
4118
- const wired = config.suites.filter((suite) => suite.isWiring(file));
4119
- const diffed = packages?.files.has(file) ?? false;
4120
- if (config.isSelf(file)) {
4121
- runAll({
4122
- kind: "self",
4123
- file,
4124
- message: `${file}: test selector changed`
4125
- });
4126
- continue;
4127
- }
4128
- for (const suite of wired) {
4129
- causes.push({
4130
- kind: "wiring",
4131
- suites: [suite.name],
4132
- file,
4133
- message: `${file}: wires the ${suite.name} suite`
4134
- });
4135
- }
4136
- if (wired.length > 0 && !diffed)
4137
- continue;
4138
- if (diffed) {
4139
- const reason = packages?.files.get(file);
4140
- if (reason === undefined) {
4141
- packageFiles.push(file);
4142
- } else {
4143
- runAll({ kind: "lockfile", file, message: `${file}: ${reason}` });
4144
- }
4145
- } else if (read || config.roots.some((root) => inRoot(file, root))) {
4146
- if (ignored)
4147
- quiet.push(file);
4148
- else
4149
- ((settings?.has(file)) ? settingFiles : relevant).push(file);
4150
- } else {
4151
- runAll({
4152
- kind: "outside",
4153
- file,
4154
- message: `${file}: outside the dependency graph`
3707
+ // src/git.ts
3708
+ import { spawn } from "node:child_process";
3709
+ import { readFile as readFile2 } from "node:fs/promises";
3710
+ import { join as join2 } from "node:path";
3711
+ function git(cwd, ...args) {
3712
+ return new Promise((resolve, reject) => {
3713
+ const child = spawn("git", args, { cwd });
3714
+ const chunks = [];
3715
+ const errors = [];
3716
+ child.stdout.on("data", (chunk) => chunks.push(chunk));
3717
+ child.stderr.on("data", (chunk) => errors.push(chunk));
3718
+ child.on("error", reject);
3719
+ child.on("close", (status) => {
3720
+ resolve({
3721
+ status: status ?? 1,
3722
+ stdout: Buffer.concat(chunks).toString("utf-8"),
3723
+ stderr: Buffer.concat(errors).toString("utf-8")
4155
3724
  });
4156
- }
4157
- }
4158
- return { relevant, quiet, packageFiles, settingFiles, causes };
4159
- }
4160
- function narrowedWalk(graph, seeds, {
4161
- quiet,
4162
- layout,
4163
- types
4164
- }, coarse, narrowings) {
4165
- const matched = new Set(narrowings.flatMap((narrowing) => narrowing.matched));
4166
- const fine = affectedBy(graph, seeds.filter((seed) => !matched.has(seed)), { quiet, layout, types });
4167
- for (const narrowing of narrowings) {
4168
- const walk = affectedBy(graph, [...narrowing.matched, ...narrowing.seeds], {
4169
- opaque: narrowing.narrower.opaque,
4170
- layout,
4171
- types
4172
3725
  });
4173
- for (const node of walk)
4174
- fine.add(node);
4175
- }
4176
- return new Set([...fine].filter((node) => coarse.has(node)));
3726
+ });
4177
3727
  }
4178
- function orphanOf(graph, config, suite, file) {
4179
- if (!suite.roots.some((root) => inRoot(file, root)))
4180
- return;
4181
- const wired = (path) => suite.isTest(path) || suite.isPage(path);
4182
- if (reaches(graph, [file], wired, {
4183
- includeUnknown: false,
4184
- types: suite.types || DECLARATION.test(file)
4185
- })) {
4186
- return;
3728
+ async function gitOrThrow(cwd, ...args) {
3729
+ const result = await git(cwd, ...args);
3730
+ if (result.status !== 0) {
3731
+ const said = result.stderr.trim().split(`
3732
+ `)[0];
3733
+ throw new BiviumError2("BV_GIT_FAILED", `bivium: git ${args.join(" ")} failed${said ? `: ${said}` : ""}`);
4187
3734
  }
4188
- const deleted = !graph.has(file);
4189
- if (deleted && suite.isTest(file))
4190
- return;
4191
- if (deleted && config.isImportOnly(file))
4192
- return;
4193
- if (suite.isNonInput(file))
4194
- return;
4195
- const typed = !suite.types && reaches(graph, [file], suite.isTest, { includeUnknown: false });
4196
- return { typed };
3735
+ return result.stdout;
4197
3736
  }
4198
- function planTests(graph, changed, config, {
4199
- barrelNames = [],
4200
- layout = new Set,
4201
- narrowed = [],
4202
- packages,
4203
- settings
4204
- } = {}) {
4205
- const { relevant, quiet, packageFiles, settingFiles, causes } = classify(graph, changed, config, packages, settings);
4206
- const settingCauses = new Map;
4207
- const settingNotes = [];
4208
- for (const file of settingFiles) {
4209
- const change = settings?.get(file);
4210
- if (!change)
4211
- continue;
4212
- settingNotes.push(change.note);
4213
- for (const seed of change.seeds) {
4214
- if (!settingCauses.has(seed)) {
4215
- settingCauses.set(seed, `governed by ${file}, which changed`);
4216
- }
4217
- }
3737
+ function lines(output) {
3738
+ return output.split(`
3739
+ `).filter(Boolean);
3740
+ }
3741
+ var INDEX_ENTRY = /^(\S) (\d{6}) ([0-9a-f]+) (\d)\t(.*)$/;
3742
+ var RAW_ENTRY = /^:(\d{6}) \d{6} ([0-9a-f]+) [0-9a-f]+ ([A-Z])\d*\t(.*)$/;
3743
+ async function missingHistory(cwd, base) {
3744
+ const [known, forked, shallow] = await Promise.all([
3745
+ git(cwd, "rev-parse", "--verify", "--quiet", `${base}^{commit}`),
3746
+ git(cwd, "merge-base", base, "HEAD"),
3747
+ git(cwd, "rev-parse", "--is-shallow-repository")
3748
+ ]);
3749
+ const fix = shallow.stdout.trim() === "true" ? " The clone is shallow: fetch the history (actions/checkout: `fetch-depth: 0`)." : "";
3750
+ if (known.status !== 0) {
3751
+ return new BiviumError2("BV_GIT_NO_BASE", `bivium: no commit ${base} here to diff against: fetch it.${fix}`);
4218
3752
  }
4219
- const bumped = packages && packageFiles.length > 0 ? packageSeeds(graph, config, packages, packageFiles) : { seeds: new Map, notes: [], reasons: [] };
4220
- const all = config.suites.map((suite) => suite.name);
4221
- for (const unused of bumped.reasons) {
4222
- causes.push({ kind: "package", suites: all, ...unused });
3753
+ if (forked.status !== 0) {
3754
+ return new BiviumError2("BV_GIT_NO_MERGE_BASE", `bivium: ${base} and HEAD share no commit here, so there's no merge base to diff against.${fix}`);
4223
3755
  }
4224
- const seeds = [
4225
- ...relevant,
4226
- ...settingFiles,
4227
- ...settingCauses.keys(),
4228
- ...barrelNames,
4229
- ...packageFiles,
4230
- ...bumped.seeds.keys()
4231
- ];
4232
- const affected = walksByTypes(graph, seeds, { quiet, layout });
4233
- const nodes = [...graph.keys()];
4234
- const tests = new Map(config.suites.map((suite) => [suite.name, nodes.filter(suite.isTest)]));
4235
- for (const suite of config.suites) {
4236
- for (const file of relevant) {
4237
- const orphan = orphanOf(graph, config, suite, file);
4238
- if (!orphan)
4239
- continue;
4240
- const { typed } = orphan;
4241
- causes.push({
4242
- kind: "orphan",
4243
- suites: [suite.name],
4244
- file,
4245
- 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)" : ""}`
3756
+ return;
3757
+ }
3758
+ function mergeBaseOf(cwd, base) {
3759
+ let pending;
3760
+ return () => {
3761
+ if (pending === undefined) {
3762
+ pending = gitOrThrow(cwd, "merge-base", base, "HEAD").then((out) => out.trim());
3763
+ pending.catch(() => {
3764
+ return;
4246
3765
  });
4247
3766
  }
3767
+ return pending;
3768
+ };
3769
+ }
3770
+ async function readRevision(cwd, base, roots, {
3771
+ blobs = false,
3772
+ mergeBase: eager = false
3773
+ } = {}) {
3774
+ const mergeBase = mergeBaseOf(cwd, base);
3775
+ if (eager)
3776
+ mergeBase();
3777
+ const diffArgs = ["--no-renames", "--merge-base", base];
3778
+ const [listing, diff, staged] = await Promise.all([
3779
+ gitOrThrow(cwd, "ls-files", "-s", "-v", "-o", "--exclude-standard"),
3780
+ gitOrThrow(cwd, "diff", "--raw", "--no-abbrev", ...diffArgs),
3781
+ gitOrThrow(cwd, "diff", "--cached", "--name-only", ...diffArgs)
3782
+ ]).catch(async (error) => {
3783
+ throw await missingHistory(cwd, base) ?? error;
3784
+ });
3785
+ const entries = lines(listing);
3786
+ const untracked = [];
3787
+ for (const line of entries) {
3788
+ if (line.startsWith("? "))
3789
+ untracked.push(line.slice(2));
3790
+ }
3791
+ const before = new Map;
3792
+ const diffed = [];
3793
+ const layout = new Set(untracked);
3794
+ for (const line of lines(diff)) {
3795
+ const [, mode, oid, status, path] = RAW_ENTRY.exec(line) ?? [];
3796
+ if (mode === undefined || oid === undefined || status === undefined || path === undefined) {
3797
+ throw new Error(`git diff: unexpected line ${line}`);
3798
+ }
3799
+ diffed.push(path);
3800
+ if (status === "A" || status === "D")
3801
+ layout.add(path);
3802
+ if (status === "A")
3803
+ before.set(path, undefined);
3804
+ else if ("MTD".includes(status) && mode !== "160000") {
3805
+ before.set(path, oid);
3806
+ }
4248
3807
  }
4249
- const narrowings = new Map;
4250
- for (const { narrower, result } of narrowed) {
4251
- const matched = relevant.filter(narrower.match);
4252
- if (matched.length === 0)
4253
- continue;
4254
- if ("all" in result) {
4255
- causes.push({
4256
- kind: "narrower",
4257
- suites: narrower.suites,
4258
- narrower: narrower.name,
4259
- message: `${narrower.name}: ${result.all}`
4260
- });
4261
- continue;
3808
+ const reads = new Map;
3809
+ const readBase = (path) => {
3810
+ let read = reads.get(path);
3811
+ if (read === undefined) {
3812
+ read = readBaseOnce(path);
3813
+ reads.set(path, read);
4262
3814
  }
4263
- for (const name of narrower.suites) {
4264
- const list = narrowings.get(name) ?? [];
4265
- list.push({ matched, narrower, seeds: result.seeds });
4266
- narrowings.set(name, list);
3815
+ return read;
3816
+ };
3817
+ const readBaseOnce = (path) => {
3818
+ if (!before.has(path)) {
3819
+ if (present.has(path)) {
3820
+ return readFile2(join2(cwd, path), "utf-8").catch(() => mergeBase().then((commit) => show(cwd, `${commit}:${path}`)));
3821
+ }
3822
+ return mergeBase().then((commit) => show(cwd, `${commit}:${path}`));
4267
3823
  }
4268
- }
4269
- const full = new Set(causes.flatMap((cause) => cause.suites));
4270
- const suites = {};
4271
- for (const suite of config.suites) {
4272
- if (full.has(suite.name)) {
4273
- suites[suite.name] = { mode: "all" };
3824
+ const oid = before.get(path);
3825
+ return oid === undefined ? Promise.resolve(undefined) : show(cwd, oid);
3826
+ };
3827
+ const changed = [...new Set([...diffed, ...untracked])];
3828
+ const dirty = new Set([...changed, ...lines(staged)]);
3829
+ const underRoots = (path) => roots.some((root) => inRoot2(path, root));
3830
+ const files = new Set;
3831
+ const tracked = new Set;
3832
+ const present = new Set;
3833
+ const oids = new Map;
3834
+ for (const line of entries) {
3835
+ const entry = INDEX_ENTRY.exec(line);
3836
+ if (!entry) {
3837
+ if (line.startsWith("? ") && underRoots(line.slice(2))) {
3838
+ files.add(line.slice(2));
3839
+ }
4274
3840
  continue;
4275
3841
  }
4276
- const coarse = affected(suite.types);
4277
- const narrowing = narrowings.get(suite.name);
4278
- suites[suite.name] = select(narrowing ? narrowedWalk(graph, seeds, { quiet, layout, types: suite.types }, coarse, narrowing) : coarse, tests.get(suite.name) ?? []);
3842
+ const [, tag, mode, oid, stage, path] = entry;
3843
+ if (tag === undefined || mode === undefined || oid === undefined || stage === undefined || path === undefined) {
3844
+ throw new Error(`bivium: git: unexpected ls-files line ${line}.`);
3845
+ }
3846
+ tracked.add(path);
3847
+ if (mode === "160000" || !underRoots(path))
3848
+ continue;
3849
+ files.add(path);
3850
+ if (dirty.has(path) || stage !== "0" || tag !== "H")
3851
+ continue;
3852
+ if (mode !== "100644" && mode !== "100755")
3853
+ continue;
3854
+ present.add(path);
3855
+ if (blobs)
3856
+ oids.set(path, oid);
4279
3857
  }
4280
3858
  return {
4281
- suites,
4282
- reasons: causes.map((cause) => cause.message),
4283
- causes,
4284
- totals: Object.fromEntries(config.suites.map((suite) => [
4285
- suite.name,
4286
- tests.get(suite.name)?.length ?? 0
4287
- ])),
4288
- full: [...full],
4289
- packages: bumped.notes,
4290
- settings: settingNotes,
4291
- settingCauses,
4292
- seeds,
4293
- quiet,
3859
+ files: sorted(files),
3860
+ listed: [...tracked, ...untracked],
3861
+ changed,
4294
3862
  layout,
4295
- packageCauses: bumped.seeds,
4296
- narrowings
3863
+ mergeBase,
3864
+ readBase,
3865
+ blobs: oids,
3866
+ present
4297
3867
  };
4298
3868
  }
3869
+ async function show(cwd, object) {
3870
+ const result = await git(cwd, "show", object);
3871
+ return result.status === 0 ? result.stdout : undefined;
3872
+ }
3873
+ async function defaultBase(cwd) {
3874
+ const head = await git(cwd, "symbolic-ref", "--short", "refs/remotes/origin/HEAD");
3875
+ if (head.status === 0 && head.stdout.trim())
3876
+ return head.stdout.trim();
3877
+ const refs = ["origin/main", "origin/master", "main", "master"];
3878
+ const found = await Promise.all(refs.map((ref) => git(cwd, "rev-parse", "--verify", "--quiet", ref)));
3879
+ const branch = refs[found.findIndex((result) => result.status === 0)];
3880
+ if (branch)
3881
+ return branch;
3882
+ throw new BiviumError2("BV_GIT_NO_BASE", `bivium: no base given and no default branch found (tried origin/HEAD, ${refs.join(", ")}): pass one, as in \`bivium plan origin/main\`, or set base in the config`);
3883
+ }
4299
3884
 
4300
3885
  // src/settings.ts
4301
3886
  import { posix as posix5 } from "node:path";
4302
3887
 
4303
- // src/terminal.ts
4304
- var asIs = (text) => text;
4305
- var PLAIN = {
4306
- good: asIs,
4307
- warn: asIs,
4308
- bad: asIs,
4309
- dim: asIs,
4310
- bold: asIs,
4311
- faint: asIs
4312
- };
4313
- function createPaint() {
4314
- const wrap = (code) => (text) => text === "" ? text : `\x1B[${code}m${text}\x1B[39m`;
4315
- return {
4316
- good: wrap(32),
4317
- warn: wrap(33),
4318
- bad: wrap(31),
4319
- dim: wrap(90),
4320
- bold: (text) => text === "" ? text : `\x1B[1m${text}\x1B[22m`,
4321
- faint: (text) => text === "" ? text : `\x1B[2m${text}\x1B[22m`
4322
- };
4323
- }
4324
- function wantsColor(forced, terminal, env, agent) {
4325
- if (forced !== undefined)
4326
- return forced;
4327
- if ((env.NO_COLOR ?? "") !== "")
4328
- return false;
4329
- const force = env.FORCE_COLOR;
4330
- if (force !== undefined && force !== "")
4331
- return force !== "0";
4332
- return terminal && !agent;
4333
- }
4334
- var SEPARATOR = " · ";
4335
- var branch = (index, count) => index === count - 1 ? "└ " : "├ ";
4336
- var NOTE_INDENT = " ";
4337
- function closingLine(paint, what, detail) {
4338
- return `${paint.good("✓")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
4339
- }
4340
- function failLine(paint, what, detail) {
4341
- return `${paint.bad("✗")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
4342
- }
4343
- function truncateWords(text, max) {
4344
- if ([...text].length <= max)
4345
- return text;
4346
- const cut = [...text].slice(0, max - 1).join("");
4347
- const space = cut.lastIndexOf(" ");
4348
- return `${(space > max / 2 ? cut.slice(0, space) : cut).replace(/[\s,;:]+$/, "")}…`;
4349
- }
4350
- var HASH_TAIL = /[-.][^-./]+\.\w+$/;
4351
- var WORD_END = /(?<=[-_.])/;
4352
- var width = (text) => [...text].length;
4353
- function truncatePath(path, max) {
4354
- if (width(path) <= max)
4355
- return path;
4356
- const parts = path.split("/");
4357
- const name = parts.pop() ?? path;
4358
- for (let keep = parts.length - 1;keep >= 0; keep--) {
4359
- const candidate = `…/${[...parts.slice(parts.length - keep), name].join("/")}`;
4360
- if (width(candidate) <= max)
4361
- return candidate;
4362
- }
4363
- const prefix = parts.length > 0 ? "…/" : "";
4364
- const tail = HASH_TAIL.exec(name)?.[0] ?? "";
4365
- const stem = name.slice(0, name.length - tail.length);
4366
- const room = max - width(prefix) - width(tail) - 1;
4367
- if (room < 4)
4368
- return `${prefix}…${[...name].slice(-(max - width(prefix) - 1)).join("")}`;
4369
- const words = stem.split(WORD_END);
4370
- const first = words[0] ?? "";
4371
- let end = "";
4372
- for (let i = words.length - 1;i > 0; i--) {
4373
- const word = words[i] ?? "";
4374
- if (width(first) + 1 + width(word + end) > room)
4375
- break;
4376
- end = word + end;
4377
- }
4378
- return end === "" ? `${prefix}${[...stem].slice(0, room).join("")}…${tail}` : `${prefix}${first}…${end}${tail}`;
4379
- }
4380
- var ESCAPE = /\x1b\[[0-9;]*m/g;
4381
- var textWidth = (text) => typeof Bun === "undefined" ? [...text.replace(ESCAPE, "")].length : Bun.stringWidth(text);
4382
- var MEASURE = 80;
4383
- var RULE = "\x00rule";
4384
- function aligned(table, rightColumns = [], paintRule = asIs, indent = " ") {
4385
- const blank = (cell) => cell === "" || cell === RULE;
4386
- const used = new Set(table.flatMap((row) => row.flatMap((cell, i) => blank(cell) ? [] : [i])));
4387
- const keep = (row) => row.filter((_, i) => used.has(i));
4388
- const rows = table.map(keep);
4389
- const right = [...used].sort((a, b) => a - b).flatMap((column, i) => rightColumns.includes(column) ? [i] : []);
4390
- const cellWidth = (cell) => cell === RULE ? 0 : textWidth(cell);
4391
- const widths = [];
4392
- for (const row of rows) {
4393
- for (const [i, cell] of row.entries()) {
4394
- if (i === row.length - 1 && !right.includes(i))
4395
- continue;
4396
- widths[i] = Math.max(widths[i] ?? 0, cellWidth(cell));
4397
- }
4398
- }
4399
- const pad = (cell, i) => " ".repeat(Math.max(0, (widths[i] ?? 0) - cellWidth(cell)));
4400
- const columnsWidth = (from, to) => widths.slice(from, to).reduce((sum, w) => sum + w + 2, 0);
4401
- return rows.map((row) => {
4402
- const first = row.indexOf(RULE);
4403
- if (first !== -1) {
4404
- const last = row.lastIndexOf(RULE);
4405
- const line = "─".repeat(columnsWidth(first, last + 1) - 2);
4406
- return `${indent}${" ".repeat(columnsWidth(0, first))}${paintRule(line)}`;
4407
- }
4408
- return `${indent}${row.map((cell, i) => right.includes(i) ? pad(cell, i) + cell : i === row.length - 1 ? cell : cell + pad(cell, i)).join(" ")}`.trimEnd();
4409
- });
4410
- }
4411
- var headerRow = (paint, cells) => cells.map((cell) => paint.faint(cell));
4412
- var plural = (count, one, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
4413
- var SILENT = { step: () => {}, clear: () => {} };
4414
- var BAR_WIDTH = 20;
4415
- var CLEAR_LINE = "\r\x1B[2K";
4416
- function createProgress(write, paint, nowMs) {
4417
- const startMs = nowMs();
4418
- let text = "";
4419
- let doneRatio = 0;
4420
- const render = () => {
4421
- const done = Math.round(Math.min(1, Math.max(0, doneRatio)) * BAR_WIDTH);
4422
- const bar = paint.good("━".repeat(done)) + paint.dim("─".repeat(BAR_WIDTH - done));
4423
- const seconds = Math.floor((nowMs() - startMs) / 1000);
4424
- write(`${CLEAR_LINE}${bar} ${text}${paint.dim(` · ${seconds} s`)}`);
4425
- };
4426
- const timer = setInterval(render, 1000);
4427
- timer.unref();
4428
- return {
4429
- step(next, ratio) {
4430
- text = next;
4431
- doneRatio = ratio;
4432
- render();
4433
- },
4434
- clear() {
4435
- clearInterval(timer);
4436
- write(CLEAR_LINE);
4437
- }
4438
- };
4439
- }
4440
-
4441
3888
  // src/tsconfig.ts
4442
3889
  import { posix as posix4 } from "node:path";
4443
3890
  var COMMENT2 = /("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g;
@@ -4447,7 +3894,7 @@ var RELATIVE2 = /^\.\.?(?:\/|$)/;
4447
3894
  function parseJsonc(text) {
4448
3895
  return JSON.parse(text.replace(BOM, "").replace(COMMENT2, (_, string) => string ?? " ").replace(TRAILING_COMMA, (_, string) => string ?? ""));
4449
3896
  }
4450
- function isStrings2(value) {
3897
+ function isStrings(value) {
4451
3898
  return Array.isArray(value) && value.every((item) => typeof item === "string");
4452
3899
  }
4453
3900
  function parse2(file, text) {
@@ -4457,24 +3904,24 @@ function parse2(file, text) {
4457
3904
  } catch (error) {
4458
3905
  return { error: error instanceof Error ? error.message : String(error) };
4459
3906
  }
4460
- if (!isRecord2(value))
3907
+ if (!isRecord(value))
4461
3908
  return { error: "not an object" };
4462
3909
  const dir = posix4.dirname(file);
4463
3910
  const { extends: extended } = value;
4464
3911
  const read = {
4465
3912
  extends: typeof extended === "string" ? [extended] : []
4466
3913
  };
4467
- if (isStrings2(extended))
3914
+ if (isStrings(extended))
4468
3915
  read.extends = extended;
4469
3916
  const options = value.compilerOptions;
4470
- if (isRecord2(options)) {
3917
+ if (isRecord(options)) {
4471
3918
  if (typeof options.baseUrl === "string") {
4472
3919
  read.baseUrl = posix4.join(dir, options.baseUrl);
4473
3920
  }
4474
- if (isRecord2(options.paths)) {
3921
+ if (isRecord(options.paths)) {
4475
3922
  const map = {};
4476
3923
  for (const [key, targets] of Object.entries(options.paths)) {
4477
- if (isStrings2(targets))
3924
+ if (isStrings(targets))
4478
3925
  map[key] = targets;
4479
3926
  }
4480
3927
  read.paths = { map, dir };
@@ -4624,7 +4071,7 @@ function parsed(text, jsonc) {
4624
4071
  }
4625
4072
  }
4626
4073
  function changedKeys(before, after) {
4627
- if (!(isRecord2(before) && isRecord2(after)))
4074
+ if (!(isRecord(before) && isRecord(after)))
4628
4075
  return;
4629
4076
  const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
4630
4077
  return [...keys].filter((key) => JSON.stringify(before[key]) !== JSON.stringify(after[key]));
@@ -4689,7 +4136,17 @@ async function readIfFile(path) {
4689
4136
  throw error;
4690
4137
  }
4691
4138
  }
4692
- function collectPackages(rootJson, sources) {
4139
+ async function readSources2(root, files) {
4140
+ const texts = await Promise.all(files.map((file) => readIfFile(join3(root, file))));
4141
+ const sources = new Map;
4142
+ for (const [i, file] of files.entries()) {
4143
+ const text = texts[i];
4144
+ if (text !== undefined)
4145
+ sources.set(file, text);
4146
+ }
4147
+ return sources;
4148
+ }
4149
+ function collectPackages2(rootJson, sources) {
4693
4150
  const packages = new Map;
4694
4151
  const parse = (text) => {
4695
4152
  try {
@@ -4725,14 +4182,14 @@ async function isFile(path) {
4725
4182
  throw error;
4726
4183
  }
4727
4184
  }
4728
- async function extractRevision(root, revision, cache) {
4185
+ async function extractRevision2(root, revision, cache) {
4729
4186
  const extractions = new Map;
4730
4187
  const texts = new Map;
4731
4188
  const missing = new Set;
4732
4189
  const tasks = [];
4733
4190
  let cached = 0;
4734
4191
  const read = async (file) => {
4735
- const text = await readIfFile(join4(root, file));
4192
+ const text = await readIfFile(join3(root, file));
4736
4193
  if (text === undefined)
4737
4194
  missing.add(file);
4738
4195
  return text;
@@ -4761,7 +4218,7 @@ async function extractRevision(root, revision, cache) {
4761
4218
  texts.set(file, source);
4762
4219
  }));
4763
4220
  } else if (!revision.present.has(file)) {
4764
- tasks.push(() => isFile(join4(root, file)).then((found) => {
4221
+ tasks.push(() => isFile(join3(root, file)).then((found) => {
4765
4222
  if (!found)
4766
4223
  missing.add(file);
4767
4224
  }));
@@ -4782,7 +4239,7 @@ async function extractRevision(root, revision, cache) {
4782
4239
  extracted: { cached, read: extractions.size - cached }
4783
4240
  };
4784
4241
  }
4785
- function graphView(graph, config) {
4242
+ function graphView2(graph, config) {
4786
4243
  const nodes = [...graph.keys()];
4787
4244
  return {
4788
4245
  nodes: () => nodes,
@@ -4805,14 +4262,14 @@ async function runNarrowers(root, revision, graph, config, suites, packages, set
4805
4262
  const wanted = config.narrowers.filter((narrower) => relevant.some(narrower.match) && (suites === undefined || narrower.suites.some((name) => suites.includes(name))));
4806
4263
  if (wanted.length === 0)
4807
4264
  return [];
4808
- const view = graphView(graph, config);
4265
+ const view = graphView2(graph, config);
4809
4266
  const base = {
4810
4267
  commit: await revision.mergeBase(),
4811
4268
  read: revision.readBase
4812
4269
  };
4813
4270
  const head = {
4814
4271
  commit: undefined,
4815
- read: (path) => readIfFile(join4(root, path))
4272
+ read: (path) => readIfFile(join3(root, path))
4816
4273
  };
4817
4274
  return Promise.all(wanted.map(async (narrower) => {
4818
4275
  const changed = relevant.filter(narrower.match);
@@ -4830,7 +4287,7 @@ async function runNarrowers(root, revision, graph, config, suites, packages, set
4830
4287
  }
4831
4288
  }));
4832
4289
  }
4833
- async function computePlan(root, base, config, {
4290
+ async function computePlan2(root, base, config, {
4834
4291
  cache: cacheOption = config.cache,
4835
4292
  suites,
4836
4293
  mergeBase = false
@@ -4841,7 +4298,7 @@ async function computePlan(root, base, config, {
4841
4298
  blobs: dir !== undefined,
4842
4299
  mergeBase
4843
4300
  }),
4844
- readFile3(join4(root, "package.json"), "utf-8").catch(() => {
4301
+ readFile3(join3(root, "package.json"), "utf-8").catch(() => {
4845
4302
  return;
4846
4303
  }),
4847
4304
  ExtractionCache.open(dir)
@@ -4856,19 +4313,19 @@ async function computePlan(root, base, config, {
4856
4313
  if (!listed.has(file))
4857
4314
  return;
4858
4315
  }
4859
- return readIfFile(join4(root, file));
4316
+ return readIfFile(join3(root, file));
4860
4317
  };
4861
4318
  const [{ files, extractions, manifests, extracted }, ts, packageDiff] = await Promise.all([
4862
- extractRevision(root, revision, cache),
4319
+ extractRevision2(root, revision, cache),
4863
4320
  readTsconfigs([
4864
4321
  "tsconfig.json",
4865
4322
  ...revision.files.filter((file) => file.endsWith("/tsconfig.json"))
4866
4323
  ], readTsconfig),
4867
- readPackageDiff(revision.changed, revision.listed, revision.readBase, (path) => readIfFile(join4(root, path)))
4324
+ readPackageDiff(revision.changed, revision.listed, revision.readBase, (path) => readIfFile(join3(root, path)))
4868
4325
  ]);
4869
4326
  const { tsconfigs } = ts;
4870
4327
  const basePending = new Map(revision.changed.filter((file) => config.isBarrel(file) && extractions.get(file)?.barrel).map((file) => [file, revision.readBase(file)]));
4871
- const packages = collectPackages(rootJson, manifests);
4328
+ const packages = collectPackages2(rootJson, manifests);
4872
4329
  const graph = graphFrom(files, extractions, {
4873
4330
  config,
4874
4331
  packages,
@@ -4882,7 +4339,7 @@ async function computePlan(root, base, config, {
4882
4339
  packages: packages.keys(),
4883
4340
  accounted: new Set(packageDiff?.files.keys()),
4884
4341
  base: revision.readBase,
4885
- head: (path) => readIfFile(join4(root, path))
4342
+ head: (path) => readIfFile(join3(root, path))
4886
4343
  });
4887
4344
  const moved = await Promise.all([...basePending].map(async ([file, pending]) => {
4888
4345
  const head = graph.get(file)?.barrel;
@@ -4918,18 +4375,18 @@ async function computePlan(root, base, config, {
4918
4375
  extracted
4919
4376
  };
4920
4377
  }
4921
- async function prepare({
4378
+ async function prepare2({
4922
4379
  cwd = process.cwd(),
4923
4380
  base,
4924
4381
  config,
4925
4382
  configFile
4926
4383
  }) {
4927
- const root = resolve2(cwd);
4384
+ const root = resolve(cwd);
4928
4385
  let resolved;
4929
4386
  if (config) {
4930
- resolved = resolveConfig(checkConfig(config));
4387
+ resolved = resolveConfig2(checkConfig2(config));
4931
4388
  } else {
4932
- const loaded = await loadConfig(root, configFile);
4389
+ const loaded = await loadConfig2(root, configFile);
4933
4390
  const isSelf = loaded.config.isSelf;
4934
4391
  resolved = {
4935
4392
  ...loaded.config,
@@ -4944,8 +4401,8 @@ async function prepare({
4944
4401
  };
4945
4402
  }
4946
4403
  async function plan2(options = {}) {
4947
- const { root, base, config } = await prepare(options);
4948
- const computed = await computePlan(root, base, config, {
4404
+ const { root, base, config } = await prepare2(options);
4405
+ const computed = await computePlan2(root, base, config, {
4949
4406
  ...options.cache !== undefined && { cache: options.cache },
4950
4407
  mergeBase: true
4951
4408
  });
@@ -4965,4 +4422,4 @@ async function plan2(options = {}) {
4965
4422
  };
4966
4423
  }
4967
4424
 
4968
- export { version, githubOutputPath, nowMs, environment, agentVariable, BiviumError2, didYouMean, globToRegExp, defineConfig2, inRoot, sorted, QUERY, UNDECLARED_READS, RELATIVE, aliasPath, createResolver, SCANNED, formatOf, extract, stringsOf, finish, gotoPage, walksByTypes, importersOf, affectedBy, formatSelection, orphanOf, PLAIN, createPaint, wantsColor, SEPARATOR, branch, NOTE_INDENT, closingLine, failLine, truncateWords, truncatePath, textWidth, MEASURE, RULE, aligned, headerRow, plural, SILENT, createProgress, computePlan, prepare, plan2 };
4425
+ export { githubOutputPath, nowMs, environment, agentVariable, version, QUERY, UNDECLARED_READS, RELATIVE, aliasPath, createResolver, SCANNED, formatOf, extract, stringsOf, finish, gotoPage, walksByTypes, importersOf, affectedBy, sorted, PLAIN, createPaint, wantsColor, isDumb, SEPARATOR, branch, NOTE_INDENT, closingLine, failLine, truncateWords, truncatePath, textWidth, MEASURE, RULE, aligned, headerRow, plural, SILENT, createProgress, formatSelection, orphanOf, readSources2, collectPackages2, extractRevision2, graphView2, computePlan2, prepare2, plan2 };