bivium 0.7.0 → 0.9.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.9.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) {
@@ -3431,24 +2459,231 @@ function affectedBy(graph, changed, {
3431
2459
  for (const dependent of dependents.get(path) ?? []) {
3432
2460
  visit(dependent, parents && { from: path, kind: fileKind(graph, dependent, path) });
3433
2461
  }
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);
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 LEADING_ESCAPE = /^\x1b\[[0-9;]*m/;
2572
+ var textWidth = (text) => typeof Bun === "undefined" ? [...text.replace(ESCAPE, "")].length : Bun.stringWidth(text);
2573
+ var MEASURE = 80;
2574
+ function hangOf(line) {
2575
+ const plain = line.replace(ESCAPE, "");
2576
+ const lead = /^ */.exec(plain)?.[0].length ?? 0;
2577
+ const gap = /^ *\S.*? {2,}(?=\S)/.exec(plain);
2578
+ return gap ? textWidth(gap[0]) : lead;
2579
+ }
2580
+ function splitAt(line, columns) {
2581
+ let seen = 0;
2582
+ let i = 0;
2583
+ while (i < line.length && seen < columns) {
2584
+ const escape = LEADING_ESCAPE.exec(line.slice(i));
2585
+ if (escape) {
2586
+ i += escape[0].length;
2587
+ continue;
2588
+ }
2589
+ const ch = String.fromCodePoint(line.codePointAt(i) ?? 32);
2590
+ seen += textWidth(ch);
2591
+ i += ch.length;
2592
+ }
2593
+ return [line.slice(0, i), line.slice(i)];
2594
+ }
2595
+ var fitTerminal = (text, terminal, columns) => terminal ? fitWidth(text, Math.min(MEASURE, columns || MEASURE)) : text;
2596
+ function fitWidth(text, width) {
2597
+ return text.split(`
2598
+ `).flatMap((line) => {
2599
+ if (textWidth(line) <= width)
2600
+ return [line];
2601
+ let hang = hangOf(line);
2602
+ if (hang > width / 2)
2603
+ hang = /^ */.exec(line.replace(ESCAPE, ""))?.[0].length ?? 0;
2604
+ const [head, rest] = splitAt(line, hang);
2605
+ const room = Math.max(1, width - hang);
2606
+ const lines = [];
2607
+ let current = "";
2608
+ const words = [];
2609
+ for (const word of rest.split(/ +/)) {
2610
+ const last = words.at(-1);
2611
+ if (last !== undefined && last.replace(ESCAPE, "") === "·") {
2612
+ words[words.length - 1] = `${last} ${word}`;
2613
+ } else if (word !== "")
2614
+ words.push(word);
2615
+ }
2616
+ for (const word of words) {
2617
+ const next = current === "" ? word : `${current} ${word}`;
2618
+ if (current !== "" && textWidth(next) > room) {
2619
+ lines.push(current);
2620
+ current = word;
2621
+ } else {
2622
+ current = next;
3439
2623
  }
3440
2624
  }
3441
- let matched = false;
3442
- for (const group of active) {
3443
- if (!group.re.test(path))
2625
+ if (current !== "")
2626
+ lines.push(current);
2627
+ return lines.map((part, k) => (k === 0 ? head : " ".repeat(hang)) + part);
2628
+ }).join(`
2629
+ `);
2630
+ }
2631
+ var RULE = "\x00rule";
2632
+ function aligned(table, rightColumns = [], paintRule = asIs, indent = " ") {
2633
+ const blank = (cell) => cell === "" || cell === RULE;
2634
+ const used = new Set(table.flatMap((row) => row.flatMap((cell, i) => blank(cell) ? [] : [i])));
2635
+ const keep = (row) => row.filter((_, i) => used.has(i));
2636
+ const rows = table.map(keep);
2637
+ const right = [...used].sort((a, b) => a - b).flatMap((column, i) => rightColumns.includes(column) ? [i] : []);
2638
+ const cellWidth = (cell) => cell === RULE ? 0 : textWidth(cell);
2639
+ const widths = [];
2640
+ for (const row of rows) {
2641
+ for (const [i, cell] of row.entries()) {
2642
+ if (i === row.length - 1 && !right.includes(i))
3444
2643
  continue;
3445
- spend(group, path);
3446
- matched = true;
2644
+ widths[i] = Math.max(widths[i] ?? 0, cellWidth(cell));
3447
2645
  }
3448
- if (matched)
3449
- active = active.filter((group) => !spent?.has(group));
3450
2646
  }
3451
- return affected;
2647
+ const pad = (cell, i) => " ".repeat(Math.max(0, (widths[i] ?? 0) - cellWidth(cell)));
2648
+ const columnsWidth = (from, to) => widths.slice(from, to).reduce((sum, w) => sum + w + 2, 0);
2649
+ return rows.map((row) => {
2650
+ const first = row.indexOf(RULE);
2651
+ if (first !== -1) {
2652
+ const last = row.lastIndexOf(RULE);
2653
+ const line = "─".repeat(columnsWidth(first, last + 1) - 2);
2654
+ return `${indent}${" ".repeat(columnsWidth(0, first))}${paintRule(line)}`;
2655
+ }
2656
+ return `${indent}${row.map((cell, i) => right.includes(i) ? pad(cell, i) + cell : i === row.length - 1 ? cell : cell + pad(cell, i)).join(" ")}`.trimEnd();
2657
+ });
2658
+ }
2659
+ var headerRow = (paint, cells) => cells.map((cell) => paint.faint(cell));
2660
+ var plural = (count, one, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
2661
+ var SILENT = { step: () => {}, clear: () => {} };
2662
+ var BAR_WIDTH = 20;
2663
+ var CLEAR_LINE = "\r\x1B[2K";
2664
+ function createProgress(write, paint, nowMs) {
2665
+ const startMs = nowMs();
2666
+ let text = "";
2667
+ let doneRatio = 0;
2668
+ const render = () => {
2669
+ const done = Math.round(Math.min(1, Math.max(0, doneRatio)) * BAR_WIDTH);
2670
+ const bar = paint.good("━".repeat(done)) + paint.dim("─".repeat(BAR_WIDTH - done));
2671
+ const seconds = Math.floor((nowMs() - startMs) / 1000);
2672
+ write(`${CLEAR_LINE}${bar} ${text}${paint.dim(` · ${seconds} s`)}`);
2673
+ };
2674
+ const timer = setInterval(render, 1000);
2675
+ timer.unref();
2676
+ return {
2677
+ step(next, ratio) {
2678
+ text = next;
2679
+ doneRatio = ratio;
2680
+ render();
2681
+ },
2682
+ clear() {
2683
+ clearInterval(timer);
2684
+ write(CLEAR_LINE);
2685
+ }
2686
+ };
3452
2687
  }
3453
2688
 
3454
2689
  // src/lockfile.ts
@@ -3613,831 +2848,1101 @@ function parseYaml(text) {
3613
2848
  items.push(value(text, indent, line));
3614
2849
  }
3615
2850
  }
3616
- return items;
2851
+ return items;
2852
+ }
2853
+ const document = block(0);
2854
+ const left = lines[at];
2855
+ if (left)
2856
+ fail2(left, "unexpected indentation");
2857
+ return document;
2858
+ }
2859
+
2860
+ // src/lockfile.ts
2861
+ var DEP_FIELDS2 = [
2862
+ "dependencies",
2863
+ "devDependencies",
2864
+ "peerDependencies",
2865
+ "optionalDependencies"
2866
+ ];
2867
+ function isRecord2(value) {
2868
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2869
+ }
2870
+ function isStringRecord2(value) {
2871
+ return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
2872
+ }
2873
+ var STRING_OR_TRAILING_COMMA = /"(?:[^"\\]|\\.)*"|,(\s*[}\]])/g;
2874
+ function parseLenient(text) {
2875
+ return JSON.parse(text.replace(STRING_OR_TRAILING_COMMA, (match, close) => close ?? match));
2876
+ }
2877
+ function specsOf(value) {
2878
+ const specs = new Map;
2879
+ for (const field of DEP_FIELDS2) {
2880
+ const deps = value[field];
2881
+ if (deps === undefined)
2882
+ continue;
2883
+ if (!isStringRecord2(deps))
2884
+ return;
2885
+ specs.set(field, new Map(Object.entries(deps)));
2886
+ }
2887
+ return specs;
2888
+ }
2889
+ function restOf(value, skip) {
2890
+ return JSON.stringify(Object.entries(value).filter(([key]) => !skip.includes(key)));
2891
+ }
2892
+ function install(packages, name, entry, version, info) {
2893
+ const installed = packages.get(name) ?? {
2894
+ entries: [],
2895
+ versions: [],
2896
+ dependencies: new Set,
2897
+ bin: false
2898
+ };
2899
+ if (info?.bin !== undefined || info?.hasBin === true || info?.hasBin === "true") {
2900
+ installed.bin = true;
2901
+ }
2902
+ installed.entries.push(JSON.stringify(entry));
2903
+ if (!installed.versions.includes(version))
2904
+ installed.versions.push(version);
2905
+ for (const field of [
2906
+ "dependencies",
2907
+ "optionalDependencies",
2908
+ "peerDependencies"
2909
+ ]) {
2910
+ const deps = info?.[field];
2911
+ if (isRecord2(deps)) {
2912
+ for (const dep of Object.keys(deps))
2913
+ installed.dependencies.add(dep);
2914
+ }
2915
+ }
2916
+ packages.set(name, installed);
2917
+ }
2918
+ function installedName(key) {
2919
+ const [name = key, scope] = key.split("/").reverse();
2920
+ return scope?.startsWith("@") ? `${scope}/${name}` : name;
2921
+ }
2922
+ function parseBunLock(text) {
2923
+ const value = parseLenient(text);
2924
+ if (!isRecord2(value))
2925
+ return;
2926
+ const { packages, workspaces } = value;
2927
+ if (!isRecord2(packages) || !isRecord2(workspaces))
2928
+ return;
2929
+ const lockfile = {
2930
+ packages: new Map,
2931
+ workspaces: new Map,
2932
+ rest: restOf(value, ["packages", "workspaces"])
2933
+ };
2934
+ for (const [key, entry] of Object.entries(packages)) {
2935
+ if (!Array.isArray(entry) || typeof entry[0] !== "string")
2936
+ return;
2937
+ const ident = entry[0];
2938
+ const at = ident.indexOf("@", 1);
2939
+ const version = at === -1 ? "" : ident.slice(at + 1);
2940
+ install(lockfile.packages, installedName(key), entry, version, entry.find(isRecord2));
2941
+ }
2942
+ for (const [dir, workspace] of Object.entries(workspaces)) {
2943
+ const specs = isRecord2(workspace) ? specsOf(workspace) : undefined;
2944
+ if (!specs)
2945
+ return;
2946
+ lockfile.workspaces.set(dir === "" ? "." : dir, specs);
2947
+ }
2948
+ return lockfile;
2949
+ }
2950
+ var NODE_MODULES = "node_modules/";
2951
+ function parsePackageLock(text) {
2952
+ const value = JSON.parse(text);
2953
+ if (!isRecord2(value) || !isRecord2(value.packages))
2954
+ return;
2955
+ const { lockfileVersion } = value;
2956
+ if (lockfileVersion !== 2 && lockfileVersion !== 3)
2957
+ return;
2958
+ const lockfile = {
2959
+ packages: new Map,
2960
+ workspaces: new Map,
2961
+ rest: restOf(value, ["packages", "dependencies", "name", "version"])
2962
+ };
2963
+ for (const [key, entry] of Object.entries(value.packages)) {
2964
+ if (!isRecord2(entry))
2965
+ return;
2966
+ const at = key.lastIndexOf(NODE_MODULES);
2967
+ if (at !== -1 && (at === 0 || key[at - 1] === "/")) {
2968
+ const version = typeof entry.version === "string" ? entry.version : "";
2969
+ const name = key.slice(at + NODE_MODULES.length);
2970
+ install(lockfile.packages, name, entry, version, entry);
2971
+ continue;
2972
+ }
2973
+ const specs = specsOf(entry);
2974
+ if (!specs)
2975
+ return;
2976
+ lockfile.workspaces.set(key === "" ? "." : key, specs);
2977
+ }
2978
+ return lockfile;
2979
+ }
2980
+ function pnpmKey(key) {
2981
+ const bare = key.startsWith("/") ? key.slice(1) : key;
2982
+ const at = bare.indexOf("@", 1);
2983
+ if (at === -1)
2984
+ return;
2985
+ return { name: bare.slice(0, at), version: withoutPeers(bare.slice(at + 1)) };
2986
+ }
2987
+ function withoutPeers(version) {
2988
+ const paren = version.indexOf("(");
2989
+ return paren === -1 ? version : version.slice(0, paren);
2990
+ }
2991
+ var YAML_DOCUMENT = /^---[ \t]*$/m;
2992
+ var PNPM_VERSION = /^[69]\./;
2993
+ var PNPM_DEP_FIELDS = [
2994
+ "dependencies",
2995
+ "devDependencies",
2996
+ "optionalDependencies"
2997
+ ];
2998
+ function parsePnpmLock(text) {
2999
+ const docs = text.split(YAML_DOCUMENT).filter((doc) => doc.trim() !== "").map(parseYaml);
3000
+ const main = docs.findLast((doc) => isRecord2(doc) && typeof doc.lockfileVersion === "string");
3001
+ if (!isRecord2(main))
3002
+ return;
3003
+ const { lockfileVersion, packages = {}, snapshots = {} } = main;
3004
+ if (typeof lockfileVersion !== "string")
3005
+ return;
3006
+ if (!PNPM_VERSION.test(lockfileVersion))
3007
+ return;
3008
+ if (!isRecord2(packages) || !isRecord2(snapshots))
3009
+ return;
3010
+ const workspaces = isRecord2(main.importers);
3011
+ const importers = isRecord2(main.importers) ? main.importers : { ".": main };
3012
+ const lockfile = {
3013
+ packages: new Map,
3014
+ workspaces: new Map,
3015
+ rest: JSON.stringify([
3016
+ restOf(main, ["importers", "packages", "snapshots", ...PNPM_DEP_FIELDS]),
3017
+ ...docs.filter((doc) => doc !== main)
3018
+ ])
3019
+ };
3020
+ const restOfImporters = [];
3021
+ for (const [dir, importer] of Object.entries(importers)) {
3022
+ if (!isRecord2(importer))
3023
+ return;
3024
+ const specs = new Map;
3025
+ for (const field of PNPM_DEP_FIELDS) {
3026
+ const deps = importer[field];
3027
+ if (deps === undefined)
3028
+ continue;
3029
+ if (!isRecord2(deps))
3030
+ return;
3031
+ const declared = new Map;
3032
+ for (const [name, dep] of Object.entries(deps)) {
3033
+ if (!isRecord2(dep) || typeof dep.specifier !== "string") {
3034
+ return;
3035
+ }
3036
+ declared.set(name, dep.specifier);
3037
+ const version = typeof dep.version === "string" ? dep.version : "";
3038
+ install(lockfile.packages, name, [dir, field, version], withoutPeers(version), {});
3039
+ }
3040
+ specs.set(field, declared);
3041
+ }
3042
+ lockfile.workspaces.set(dir, specs);
3043
+ if (workspaces) {
3044
+ const settings = restOf(importer, PNPM_DEP_FIELDS);
3045
+ if (settings !== "[]")
3046
+ restOfImporters.push([dir, settings]);
3047
+ }
3617
3048
  }
3618
- const document = block(0);
3619
- const left = lines[at];
3620
- if (left)
3621
- fail2(left, "unexpected indentation");
3622
- return document;
3049
+ lockfile.rest += JSON.stringify(restOfImporters);
3050
+ for (const section of [packages, snapshots]) {
3051
+ for (const [key, entry] of Object.entries(section)) {
3052
+ const parsed = pnpmKey(key);
3053
+ if (!parsed)
3054
+ return;
3055
+ const info = isRecord2(entry) ? entry : undefined;
3056
+ install(lockfile.packages, parsed.name, [key, entry], parsed.version, info);
3057
+ }
3058
+ }
3059
+ return lockfile;
3623
3060
  }
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);
3061
+ var FORMATS = new Map([
3062
+ ["bun.lock", parseBunLock],
3063
+ ["package-lock.json", parsePackageLock],
3064
+ ["pnpm-lock.yaml", parsePnpmLock]
3065
+ ]);
3066
+ var UNREAD = ["bun.lockb", "npm-shrinkwrap.json", "yarn.lock"];
3067
+ function parse(file, text) {
3068
+ const format = FORMATS.get(file);
3069
+ if (text === undefined || !format)
3070
+ return;
3071
+ try {
3072
+ return format(text);
3073
+ } catch {
3074
+ return;
3075
+ }
3634
3076
  }
3635
- function isStringRecord3(value) {
3636
- return isRecord3(value) && Object.values(value).every((item) => typeof item === "string");
3077
+ function describe(name, before, after) {
3078
+ if (before === undefined)
3079
+ return `${name} ${after} added`;
3080
+ if (after === undefined)
3081
+ return `${name} ${before} removed`;
3082
+ return before === after ? `${name} ${after}, entry changed` : `${name} ${before} → ${after}`;
3637
3083
  }
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));
3084
+ function versions(installed) {
3085
+ return installed && sorted(installed.versions).join(", ");
3641
3086
  }
3642
- function specsOf(value) {
3643
- const specs = new Map;
3087
+ function specChanges(before, after) {
3088
+ const changed = new Map;
3644
3089
  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)));
3090
+ const a = before?.get(field);
3091
+ const b = after?.get(field);
3092
+ for (const name of new Set([...a?.keys() ?? [], ...b?.keys() ?? []])) {
3093
+ if (a?.get(name) !== b?.get(name) && !changed.has(name)) {
3094
+ changed.set(name, [a?.get(name), b?.get(name)]);
3095
+ }
3096
+ }
3651
3097
  }
3652
- return specs;
3653
- }
3654
- function restOf(value, skip) {
3655
- return JSON.stringify(Object.entries(value).filter(([key]) => !skip.includes(key)));
3098
+ return changed;
3656
3099
  }
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;
3100
+ function lockfileChanges(file, base, head) {
3101
+ const changes = [];
3102
+ const names = new Set([...base.packages.keys(), ...head.packages.keys()]);
3103
+ for (const name of names) {
3104
+ const before = base.packages.get(name);
3105
+ const after = head.packages.get(name);
3106
+ const same = before !== undefined && after !== undefined && sorted(before.entries).join(`
3107
+ `) === sorted(after.entries).join(`
3108
+ `);
3109
+ if (same)
3110
+ continue;
3111
+ changes.push({
3112
+ name,
3113
+ detail: `${file}: ${describe(name, versions(before), versions(after))}`,
3114
+ file
3115
+ });
3666
3116
  }
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);
3117
+ const resolved = new Set(changes.map((change) => change.name));
3118
+ const dirs = new Set([...base.workspaces.keys(), ...head.workspaces.keys()]);
3119
+ for (const dir of dirs) {
3120
+ const declared = specChanges(base.workspaces.get(dir), head.workspaces.get(dir));
3121
+ for (const [name, [before, after]] of declared) {
3122
+ if (resolved.has(name))
3123
+ continue;
3124
+ resolved.add(name);
3125
+ changes.push({
3126
+ name,
3127
+ detail: `${file}: ${describe(`${name} range`, before, after)}`,
3128
+ file
3129
+ });
3679
3130
  }
3680
3131
  }
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;
3132
+ return changes;
3686
3133
  }
3687
- function parseBunLock(text) {
3688
- const value = parseLenient(text);
3689
- if (!isRecord3(value))
3134
+ var MANIFEST = /(?:^|\/)package\.json$/;
3135
+ function parseManifest(text) {
3136
+ if (text === undefined)
3690
3137
  return;
3691
- const { packages, workspaces } = value;
3692
- if (!isRecord3(packages) || !isRecord3(workspaces))
3138
+ try {
3139
+ const value = JSON.parse(text);
3140
+ return isRecord2(value) ? value : undefined;
3141
+ } catch {
3693
3142
  return;
3694
- const lockfile = {
3695
- packages: new Map,
3696
- workspaces: new Map,
3697
- rest: restOf(value, ["packages", "workspaces"])
3143
+ }
3144
+ }
3145
+ async function readPackageDiff(changed, listed, base, head) {
3146
+ const lockfiles = changed.filter((file) => FORMATS.has(file));
3147
+ const manifests = changed.filter((file) => MANIFEST.test(file));
3148
+ if (lockfiles.length === 0 && manifests.length === 0)
3149
+ return;
3150
+ const read = (path) => Promise.all([base(path), head(path)]);
3151
+ const known = [...FORMATS.keys()];
3152
+ const [lockTexts, manifestTexts] = await Promise.all([
3153
+ Promise.all(known.map(async (file) => {
3154
+ if (lockfiles.includes(file))
3155
+ return [file, ...await read(file)];
3156
+ const text = await head(file);
3157
+ return [file, text, text];
3158
+ })),
3159
+ Promise.all(manifests.map(async (file) => [file, ...await read(file)]))
3160
+ ]);
3161
+ const diff = {
3162
+ files: new Map,
3163
+ changes: [],
3164
+ dependents: new Map,
3165
+ declared: new Set,
3166
+ bins: new Set
3698
3167
  };
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));
3168
+ const present = new Map;
3169
+ for (const [file, baseText, headText] of lockTexts) {
3170
+ const after = parse(file, headText);
3171
+ if (headText !== undefined)
3172
+ present.set(file, after);
3173
+ const before = parse(file, baseText);
3174
+ for (const lockfile of [before, after]) {
3175
+ if (!lockfile)
3176
+ continue;
3177
+ for (const [name, installed] of lockfile.packages) {
3178
+ if (installed.bin)
3179
+ diff.bins.add(name);
3180
+ for (const dependency of installed.dependencies) {
3181
+ const set = diff.dependents.get(dependency) ?? new Set;
3182
+ set.add(name);
3183
+ diff.dependents.set(dependency, set);
3184
+ }
3185
+ }
3186
+ for (const specs of lockfile.workspaces.values()) {
3187
+ for (const deps of specs.values()) {
3188
+ for (const name of deps.keys())
3189
+ diff.declared.add(name);
3190
+ }
3191
+ }
3192
+ }
3193
+ if (!lockfiles.includes(file))
3194
+ continue;
3195
+ if (baseText === undefined || headText === undefined) {
3196
+ diff.files.set(file, baseText === undefined ? "added" : "deleted");
3197
+ } else if (!(before && after)) {
3198
+ diff.files.set(file, "can't parse it");
3199
+ } else if (before.rest === after.rest) {
3200
+ diff.files.set(file, undefined);
3201
+ diff.changes.push(...lockfileChanges(file, before, after));
3202
+ } else {
3203
+ diff.files.set(file, "a setting other than the packages changed");
3204
+ }
3706
3205
  }
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);
3206
+ const unread = UNREAD.some((file) => listed.includes(file));
3207
+ for (const [file, beforeText, afterText] of manifestTexts) {
3208
+ const before = parseManifest(beforeText);
3209
+ const after = parseManifest(afterText);
3210
+ if (!(before && after) || unread || present.size === 0)
3211
+ continue;
3212
+ const others = (record) => restOf(record, DEP_FIELDS2);
3213
+ const specsBefore = specsOf(before);
3214
+ const specsAfter = specsOf(after);
3215
+ if (others(before) !== others(after) || !specsBefore || !specsAfter) {
3216
+ continue;
3217
+ }
3218
+ const dir = posix3.dirname(file);
3219
+ const declared = specChanges(specsBefore, specsAfter);
3220
+ const recorded = [...present.values()].every((lockfile) => {
3221
+ const specs = lockfile?.workspaces.get(dir);
3222
+ if (!specs)
3223
+ return false;
3224
+ return [...declared.keys()].every((name) => DEP_FIELDS2.every((field) => specs.get(field)?.get(name) === specsAfter.get(field)?.get(name)));
3225
+ });
3226
+ if (!recorded)
3227
+ continue;
3228
+ diff.files.set(file, undefined);
3229
+ for (const [name, [from, to]] of declared) {
3230
+ diff.declared.add(name);
3231
+ diff.changes.push({
3232
+ name,
3233
+ detail: `${file}: ${describe(`${name} range`, from, to)}`,
3234
+ file
3235
+ });
3236
+ }
3712
3237
  }
3713
- return lockfile;
3238
+ return diff;
3714
3239
  }
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"])
3240
+ function packageSeeds(graph, config, diff, files) {
3241
+ const result = { seeds: new Map, notes: [], reasons: [] };
3242
+ const { isLoadedByName } = config;
3243
+ const loadedOtherwise = (name) => isLoadedByName === undefined || diff.bins.has(name) || isLoadedByName(name);
3244
+ const tested = new Map;
3245
+ const reachesTest = (name) => {
3246
+ let found = tested.get(name);
3247
+ if (found === undefined) {
3248
+ const node = `pkg:${name}`;
3249
+ found = graph.has(node) && config.suites.some((suite) => reaches(graph, [node], suite.isTest, {
3250
+ includeUnknown: false,
3251
+ types: suite.types
3252
+ }));
3253
+ tested.set(name, found);
3254
+ }
3255
+ return found;
3727
3256
  };
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);
3257
+ const changes = diff.changes.filter((change) => files.includes(change.file)).sort((a, b) => byCodeUnit(a.name, b.name));
3258
+ const unused = new Map;
3259
+ const seen = new Set;
3260
+ for (const change of changes) {
3261
+ const { name, detail } = change;
3262
+ if (seen.has(name))
3736
3263
  continue;
3264
+ seen.add(name);
3265
+ const closure = new Set([name]);
3266
+ const queue = [name];
3267
+ for (const queued of queue) {
3268
+ for (const dependent of diff.dependents.get(queued) ?? []) {
3269
+ if (closure.has(dependent))
3270
+ continue;
3271
+ closure.add(dependent);
3272
+ queue.push(dependent);
3273
+ }
3737
3274
  }
3738
- const specs = specsOf(entry);
3739
- if (!specs)
3740
- return;
3741
- lockfile.workspaces.set(key === "" ? "." : key, specs);
3275
+ const through = [];
3276
+ let covered = true;
3277
+ let importOnly = false;
3278
+ for (const user of closure) {
3279
+ const node = `pkg:${user}`;
3280
+ const imported = graph.has(node);
3281
+ if (imported) {
3282
+ through.push(user);
3283
+ if (!result.seeds.has(node)) {
3284
+ result.seeds.set(node, user === name ? detail : `${detail}, which ${user} depends on`);
3285
+ }
3286
+ }
3287
+ const entry = imported || diff.declared.has(user) || !diff.dependents.has(user);
3288
+ if (!entry || reachesTest(user) || config.isInert(user))
3289
+ continue;
3290
+ if (loadedOtherwise(user)) {
3291
+ covered = false;
3292
+ const list = unused.get(user) ?? [];
3293
+ if (user === name)
3294
+ list.unshift(change);
3295
+ else
3296
+ list.push(change);
3297
+ unused.set(user, list);
3298
+ } else {
3299
+ importOnly = true;
3300
+ }
3301
+ }
3302
+ if (!covered)
3303
+ continue;
3304
+ if (through.length === 0) {
3305
+ result.notes.push(`${detail}, ${importOnly ? "imported by no test" : "inert"}`);
3306
+ continue;
3307
+ }
3308
+ const others = through.filter((user) => user !== name);
3309
+ const shown = others.slice(0, 3).join(", ");
3310
+ const rest = others.length > 3 ? ` and ${others.length - 3} more` : "";
3311
+ result.notes.push(others.length === 0 ? detail : `${detail}, through ${shown}${rest}`);
3742
3312
  }
3743
- return lockfile;
3313
+ for (const user of sorted(unused.keys())) {
3314
+ const [first, ...more] = unused.get(user) ?? [];
3315
+ if (!first)
3316
+ continue;
3317
+ const own = first.name === user;
3318
+ const also = more.length === 0 ? "" : ` (and ${more.length} more ${more.length === 1 ? "package" : "packages"} ${user} depends on)`;
3319
+ result.reasons.push({
3320
+ package: user,
3321
+ file: first.file,
3322
+ message: own ? `${first.detail}${also}, and no test imports it` : `${first.detail}, which ${user} depends on${also}, and no test imports ${user}`
3323
+ });
3324
+ }
3325
+ return result;
3744
3326
  }
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)) };
3327
+
3328
+ // src/plan.ts
3329
+ function formatSelection(selection) {
3330
+ return selection.mode === "some" ? selection.files.join(" ") : selection.mode;
3751
3331
  }
3752
- function withoutPeers(version) {
3753
- const paren = version.indexOf("(");
3754
- return paren === -1 ? version : version.slice(0, paren);
3332
+ function select(affected, tests) {
3333
+ const files = tests.filter((file) => affected.has(file));
3334
+ if (files.length === 0)
3335
+ return { mode: "none" };
3336
+ if (files.length === tests.length)
3337
+ return { mode: "all" };
3338
+ return { mode: "some", files };
3755
3339
  }
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);
3340
+ function classify(graph, changed, config, packages, settings) {
3341
+ const causes = [];
3342
+ const all = config.suites.map((suite) => suite.name);
3343
+ const runAll = (cause) => causes.push({ ...cause, suites: all });
3344
+ const relevant = [];
3345
+ const quiet = [];
3346
+ const packageFiles = [];
3347
+ const settingFiles = [];
3348
+ for (const file of changed) {
3349
+ const read = graph.has(file);
3350
+ const ignored = config.isIgnored(file);
3351
+ if (!read && ignored)
3352
+ continue;
3353
+ const wired = config.suites.filter((suite) => suite.isWiring(file));
3354
+ const diffed = packages?.files.has(file) ?? false;
3355
+ if (config.isSelf(file)) {
3356
+ runAll({
3357
+ kind: "self",
3358
+ file,
3359
+ message: `${file}: test selector changed`
3360
+ });
3361
+ continue;
3806
3362
  }
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]);
3363
+ for (const suite of wired) {
3364
+ causes.push({
3365
+ kind: "wiring",
3366
+ suites: [suite.name],
3367
+ file,
3368
+ message: `${file}: wires the ${suite.name} suite`
3369
+ });
3812
3370
  }
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);
3371
+ if (wired.length > 0 && !diffed)
3372
+ continue;
3373
+ if (diffed) {
3374
+ const reason = packages?.files.get(file);
3375
+ if (reason === undefined) {
3376
+ packageFiles.push(file);
3377
+ } else {
3378
+ runAll({ kind: "lockfile", file, message: `${file}: ${reason}` });
3379
+ }
3380
+ } else if (read || config.roots.some((root) => inRoot2(file, root))) {
3381
+ if (ignored)
3382
+ quiet.push(file);
3383
+ else
3384
+ ((settings?.has(file)) ? settingFiles : relevant).push(file);
3385
+ } else {
3386
+ runAll({
3387
+ kind: "outside",
3388
+ file,
3389
+ message: `${file}: outside the dependency graph`
3390
+ });
3822
3391
  }
3823
3392
  }
3824
- return lockfile;
3393
+ return { relevant, quiet, packageFiles, settingFiles, causes };
3825
3394
  }
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)
3395
+ function narrowedWalk(graph, seeds, {
3396
+ quiet,
3397
+ layout,
3398
+ types
3399
+ }, coarse, narrowings) {
3400
+ const matched = new Set(narrowings.flatMap((narrowing) => narrowing.matched));
3401
+ const fine = affectedBy(graph, seeds.filter((seed) => !matched.has(seed)), { quiet, layout, types });
3402
+ for (const narrowing of narrowings) {
3403
+ const walk = affectedBy(graph, [...narrowing.matched, ...narrowing.seeds], {
3404
+ opaque: narrowing.narrower.opaque,
3405
+ layout,
3406
+ types
3407
+ });
3408
+ for (const node of walk)
3409
+ fine.add(node);
3410
+ }
3411
+ return new Set([...fine].filter((node) => coarse.has(node)));
3412
+ }
3413
+ function orphanOf(graph, config, suite, file) {
3414
+ if (!suite.roots.some((root) => inRoot2(file, root)))
3835
3415
  return;
3836
- try {
3837
- return format(text);
3838
- } catch {
3416
+ const wired = (path) => suite.isTest(path) || suite.isPage(path);
3417
+ if (reaches(graph, [file], wired, {
3418
+ includeUnknown: false,
3419
+ types: suite.types || DECLARATION.test(file)
3420
+ })) {
3839
3421
  return;
3840
3422
  }
3423
+ const deleted = !graph.has(file);
3424
+ if (deleted && suite.isTest(file))
3425
+ return;
3426
+ if (deleted && config.isImportOnly(file))
3427
+ return;
3428
+ if (suite.isNonInput(file))
3429
+ return;
3430
+ const typed = !suite.types && reaches(graph, [file], suite.isTest, { includeUnknown: false });
3431
+ return { typed };
3841
3432
  }
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)]);
3433
+ function planTests(graph, changed, config, {
3434
+ barrelNames = [],
3435
+ layout = new Set,
3436
+ narrowed = [],
3437
+ packages,
3438
+ settings
3439
+ } = {}) {
3440
+ const { relevant, quiet, packageFiles, settingFiles, causes } = classify(graph, changed, config, packages, settings);
3441
+ const settingCauses = new Map;
3442
+ const settingNotes = [];
3443
+ for (const file of settingFiles) {
3444
+ const change = settings?.get(file);
3445
+ if (!change)
3446
+ continue;
3447
+ settingNotes.push(change.note);
3448
+ for (const seed of change.seeds) {
3449
+ if (!settingCauses.has(seed)) {
3450
+ settingCauses.set(seed, `governed by ${file}, which changed`);
3860
3451
  }
3861
3452
  }
3862
3453
  }
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
- });
3454
+ const bumped = packages && packageFiles.length > 0 ? packageSeeds(graph, config, packages, packageFiles) : { seeds: new Map, notes: [], reasons: [] };
3455
+ const all = config.suites.map((suite) => suite.name);
3456
+ for (const unused of bumped.reasons) {
3457
+ causes.push({ kind: "package", suites: all, ...unused });
3881
3458
  }
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))
3459
+ const seeds = [
3460
+ ...relevant,
3461
+ ...settingFiles,
3462
+ ...settingCauses.keys(),
3463
+ ...barrelNames,
3464
+ ...packageFiles,
3465
+ ...bumped.seeds.keys()
3466
+ ];
3467
+ const affected = walksByTypes(graph, seeds, { quiet, layout });
3468
+ const nodes = [...graph.keys()];
3469
+ const tests = new Map(config.suites.map((suite) => [suite.name, nodes.filter(suite.isTest)]));
3470
+ for (const suite of config.suites) {
3471
+ for (const file of relevant) {
3472
+ const orphan = orphanOf(graph, config, suite, file);
3473
+ if (!orphan)
3888
3474
  continue;
3889
- resolved.add(name);
3890
- changes.push({
3891
- name,
3892
- detail: `${file}: ${describe(`${name} range`, before, after)}`,
3893
- file
3475
+ const { typed } = orphan;
3476
+ causes.push({
3477
+ kind: "orphan",
3478
+ suites: [suite.name],
3479
+ file,
3480
+ 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
3481
  });
3895
3482
  }
3896
3483
  }
3897
- return changes;
3484
+ const narrowings = new Map;
3485
+ for (const { narrower, result } of narrowed) {
3486
+ const matched = relevant.filter(narrower.match);
3487
+ if (matched.length === 0)
3488
+ continue;
3489
+ if ("all" in result) {
3490
+ causes.push({
3491
+ kind: "narrower",
3492
+ suites: narrower.suites,
3493
+ narrower: narrower.name,
3494
+ message: `${narrower.name}: ${result.all}`
3495
+ });
3496
+ continue;
3497
+ }
3498
+ for (const name of narrower.suites) {
3499
+ const list = narrowings.get(name) ?? [];
3500
+ list.push({ matched, narrower, seeds: result.seeds });
3501
+ narrowings.set(name, list);
3502
+ }
3503
+ }
3504
+ const full = new Set(causes.flatMap((cause) => cause.suites));
3505
+ const suites = {};
3506
+ for (const suite of config.suites) {
3507
+ if (full.has(suite.name)) {
3508
+ suites[suite.name] = { mode: "all" };
3509
+ continue;
3510
+ }
3511
+ const coarse = affected(suite.types);
3512
+ const narrowing = narrowings.get(suite.name);
3513
+ suites[suite.name] = select(narrowing ? narrowedWalk(graph, seeds, { quiet, layout, types: suite.types }, coarse, narrowing) : coarse, tests.get(suite.name) ?? []);
3514
+ }
3515
+ return {
3516
+ suites,
3517
+ reasons: causes.map((cause) => cause.message),
3518
+ causes,
3519
+ totals: Object.fromEntries(config.suites.map((suite) => [
3520
+ suite.name,
3521
+ tests.get(suite.name)?.length ?? 0
3522
+ ])),
3523
+ full: [...full],
3524
+ packages: bumped.notes,
3525
+ settings: settingNotes,
3526
+ settingCauses,
3527
+ seeds,
3528
+ quiet,
3529
+ layout,
3530
+ packageCauses: bumped.seeds,
3531
+ narrowings
3532
+ };
3898
3533
  }
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 {
3534
+
3535
+ // src/compute.ts
3536
+ import { readFile as readFile3, stat } from "node:fs/promises";
3537
+ import { join as join3, posix as posix6, resolve } from "node:path";
3538
+
3539
+ // src/cache.ts
3540
+ import { existsSync } from "node:fs";
3541
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3542
+ import { isAbsolute, join } from "node:path";
3543
+ var SCANNER_VERSION = 9;
3544
+ var MAGIC = "bivium-extractions";
3545
+ var FILE = "extractions.json";
3546
+ function isHeader(value) {
3547
+ 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";
3548
+ }
3549
+ function cacheDir(root, cache) {
3550
+ if (cache === false)
3907
3551
  return;
3552
+ if (typeof cache === "string") {
3553
+ return isAbsolute(cache) ? cache : join(root, cache);
3908
3554
  }
3555
+ const modules = join(root, "node_modules");
3556
+ return existsSync(modules) ? join(modules, ".cache", "bivium") : join(root, ".bivium", "cache");
3909
3557
  }
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
- }
3558
+
3559
+ class ExtractionCache {
3560
+ #rows = new Map;
3561
+ #strings = [];
3562
+ #used = new Map;
3563
+ #dirty = false;
3564
+ dir;
3565
+ constructor(dir) {
3566
+ this.dir = dir;
3567
+ }
3568
+ static async open(dir) {
3569
+ const cache = new ExtractionCache(dir);
3570
+ if (!dir)
3571
+ return cache;
3572
+ const text = await readFile(join(dir, FILE), "utf-8").catch(() => "");
3573
+ if (text)
3574
+ cache.#load(text);
3575
+ return cache;
3576
+ }
3577
+ #load(text) {
3578
+ try {
3579
+ const parsed = JSON.parse(text);
3580
+ if (!Array.isArray(parsed))
3581
+ return;
3582
+ const fields = parsed;
3583
+ const [header, strings, rows] = fields;
3584
+ if (!isHeader(header) || !Array.isArray(strings) || !Array.isArray(rows) || header.strings !== strings.length || header.rows !== rows.length) {
3585
+ return;
3950
3586
  }
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);
3587
+ this.#strings = strings;
3588
+ for (const row of rows) {
3589
+ if (Array.isArray(row) && typeof row[0] === "string") {
3590
+ this.#rows.set(row[0], row);
3955
3591
  }
3956
3592
  }
3593
+ } catch {}
3594
+ }
3595
+ get size() {
3596
+ return this.#rows.size;
3597
+ }
3598
+ get(oid, format) {
3599
+ const key = `${format}:${oid}`;
3600
+ const used = this.#used.get(key);
3601
+ if (used)
3602
+ return used;
3603
+ const row = this.#rows.get(key);
3604
+ if (!row)
3605
+ return;
3606
+ let extraction;
3607
+ try {
3608
+ extraction = decode(row, this.#strings);
3609
+ } catch {
3610
+ this.#rows.delete(key);
3611
+ return;
3957
3612
  }
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
- }
3613
+ this.#used.set(key, extraction);
3614
+ return extraction;
3970
3615
  }
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;
3616
+ set(oid, format, extraction) {
3617
+ const key = `${format}:${oid}`;
3618
+ this.#used.set(key, extraction);
3619
+ this.#dirty = true;
3620
+ }
3621
+ async save() {
3622
+ if (!this.dir || !this.#dirty)
3623
+ return;
3624
+ const table = createStrings();
3625
+ const rows = [];
3626
+ for (const [key, extraction] of this.#used) {
3627
+ rows.push(encode(key, extraction, table));
3982
3628
  }
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
3629
+ let stale = Math.floor(this.#used.size / 2);
3630
+ for (const [key, row] of this.#rows) {
3631
+ if (stale === 0)
3632
+ break;
3633
+ if (this.#used.has(key))
3634
+ continue;
3635
+ try {
3636
+ rows.push(encode(key, decode(row, this.#strings), table));
3637
+ stale--;
3638
+ } catch {}
3639
+ }
3640
+ const header = {
3641
+ magic: MAGIC,
3642
+ bivium: version,
3643
+ scanner: SCANNER_VERSION,
3644
+ rows: rows.length,
3645
+ strings: table.list.length
3646
+ };
3647
+ const file = join(this.dir, FILE);
3648
+ const temp = `${file}.${process.pid}.${nowMs()}.tmp`;
3649
+ try {
3650
+ await mkdir(this.dir, { recursive: true });
3651
+ const ignore = join(this.dir, ".gitignore");
3652
+ if (!existsSync(ignore))
3653
+ await writeFile(ignore, `*
3654
+ `);
3655
+ await writeFile(temp, JSON.stringify([header, table.list, rows]));
3656
+ await rename(temp, file);
3657
+ this.#dirty = false;
3658
+ } catch {
3659
+ await unlink(temp).catch(() => {
3660
+ return;
4000
3661
  });
4001
3662
  }
4002
3663
  }
4003
- return diff;
4004
3664
  }
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);
3665
+ function createStrings() {
3666
+ const list = [];
3667
+ const idsByValue = new Map;
3668
+ const id = (value) => {
3669
+ let found = idsByValue.get(value);
4012
3670
  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);
3671
+ found = list.length;
3672
+ list.push(value);
3673
+ idsByValue.set(value, found);
4019
3674
  }
4020
3675
  return found;
4021
3676
  };
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
- }
3677
+ const ids = (values) => values.length === 0 ? 0 : values.map(id);
3678
+ return { list, id, ids };
3679
+ }
3680
+ function typeIndexes(imports) {
3681
+ const indexes = [];
3682
+ for (const [i, ref] of imports.entries())
3683
+ if (ref.type)
3684
+ indexes.push(i);
3685
+ return indexes.length === 0 ? 0 : indexes;
3686
+ }
3687
+ function encode(key, e, table) {
3688
+ const imports = e.imports.map(({ specifier, names }) => names ? [table.id(specifier), ...names.map((n) => table.id(n))] : table.id(specifier));
3689
+ const barrel = e.barrel && [
3690
+ [...e.barrel.names].flatMap(([name, from]) => [
3691
+ table.id(name),
3692
+ table.id(from)
3693
+ ]),
3694
+ table.ids(e.barrel.stars)
3695
+ ];
3696
+ return [
3697
+ key,
3698
+ imports.length === 0 ? 0 : imports,
3699
+ table.ids(e.globs),
3700
+ table.ids(e.gotos),
3701
+ table.ids(e.dependsOn),
3702
+ table.ids(e.reads),
3703
+ table.ids(e.unknown),
3704
+ e.fallback === undefined ? 0 : table.id(e.fallback),
3705
+ barrel ?? 0,
3706
+ typeIndexes(e.imports),
3707
+ table.ids(e.lists)
3708
+ ];
3709
+ }
3710
+ function decode(row, strings) {
3711
+ const str = (id) => {
3712
+ const value = typeof id === "number" ? strings[id] : undefined;
3713
+ if (typeof value !== "string")
3714
+ throw new Error("bad string id");
3715
+ return value;
3716
+ };
3717
+ const list = (ids) => {
3718
+ if (ids === 0)
3719
+ return [];
3720
+ if (!Array.isArray(ids))
3721
+ throw new Error("bad list");
3722
+ return ids.map(str);
3723
+ };
3724
+ const refs = row[1] === 0 ? [] : row[1];
3725
+ if (!Array.isArray(refs))
3726
+ throw new Error("bad imports");
3727
+ const imports = refs.map((item) => Array.isArray(item) ? { specifier: str(item[0]), names: item.slice(1).map(str) } : { specifier: str(item) });
3728
+ if (row[9] !== 0) {
3729
+ if (!Array.isArray(row[9]))
3730
+ throw new Error("bad types");
3731
+ for (const i of row[9]) {
3732
+ const ref = typeof i === "number" ? imports[i] : undefined;
3733
+ if (!ref)
3734
+ throw new Error("bad type index");
3735
+ ref.type = true;
4066
3736
  }
4067
- if (!covered)
4068
- continue;
4069
- if (through.length === 0) {
4070
- result.notes.push(`${detail}, ${importOnly ? "imported by no test" : "inert"}`);
4071
- continue;
3737
+ }
3738
+ const extraction = {
3739
+ imports,
3740
+ globs: list(row[2]),
3741
+ gotos: list(row[3]),
3742
+ dependsOn: list(row[4]),
3743
+ reads: list(row[5]),
3744
+ lists: list(row[10]),
3745
+ unknown: list(row[6])
3746
+ };
3747
+ if (row[7] !== 0)
3748
+ extraction.fallback = str(row[7]);
3749
+ if (row[8] !== 0) {
3750
+ if (!Array.isArray(row[8]))
3751
+ throw new Error("bad barrel");
3752
+ const barrel = row[8];
3753
+ const [pairs, stars] = barrel;
3754
+ if (!Array.isArray(pairs))
3755
+ throw new Error("bad barrel names");
3756
+ const names = new Map;
3757
+ for (let i = 0;i < pairs.length; i += 2) {
3758
+ names.set(str(pairs[i]), str(pairs[i + 1]));
4072
3759
  }
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
- });
3760
+ extraction.barrel = { names, stars: list(stars) };
4089
3761
  }
4090
- return result;
3762
+ return extraction;
4091
3763
  }
4092
3764
 
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`
3765
+ // src/git.ts
3766
+ import { spawn } from "node:child_process";
3767
+ import { readFile as readFile2 } from "node:fs/promises";
3768
+ import { join as join2 } from "node:path";
3769
+ function git(cwd, ...args) {
3770
+ return new Promise((resolve, reject) => {
3771
+ const child = spawn("git", args, { cwd });
3772
+ const chunks = [];
3773
+ const errors = [];
3774
+ child.stdout.on("data", (chunk) => chunks.push(chunk));
3775
+ child.stderr.on("data", (chunk) => errors.push(chunk));
3776
+ child.on("error", reject);
3777
+ child.on("close", (status) => {
3778
+ resolve({
3779
+ status: status ?? 1,
3780
+ stdout: Buffer.concat(chunks).toString("utf-8"),
3781
+ stderr: Buffer.concat(errors).toString("utf-8")
4155
3782
  });
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
3783
  });
4173
- for (const node of walk)
4174
- fine.add(node);
4175
- }
4176
- return new Set([...fine].filter((node) => coarse.has(node)));
3784
+ });
4177
3785
  }
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;
3786
+ async function gitOrThrow(cwd, ...args) {
3787
+ const result = await git(cwd, ...args);
3788
+ if (result.status !== 0) {
3789
+ const said = result.stderr.trim().split(`
3790
+ `)[0];
3791
+ throw new BiviumError2("BV_GIT_FAILED", `bivium: git ${args.join(" ")} failed${said ? `: ${said}` : ""}`);
4187
3792
  }
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 };
3793
+ return result.stdout;
4197
3794
  }
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
- }
3795
+ function lines(output) {
3796
+ return output.split(`
3797
+ `).filter(Boolean);
3798
+ }
3799
+ var INDEX_ENTRY = /^(\S) (\d{6}) ([0-9a-f]+) (\d)\t(.*)$/;
3800
+ var RAW_ENTRY = /^:(\d{6}) \d{6} ([0-9a-f]+) [0-9a-f]+ ([A-Z])\d*\t(.*)$/;
3801
+ async function missingHistory(cwd, base) {
3802
+ const [known, forked, shallow] = await Promise.all([
3803
+ git(cwd, "rev-parse", "--verify", "--quiet", `${base}^{commit}`),
3804
+ git(cwd, "merge-base", base, "HEAD"),
3805
+ git(cwd, "rev-parse", "--is-shallow-repository")
3806
+ ]);
3807
+ const fix = shallow.stdout.trim() === "true" ? " The clone is shallow: fetch the history (actions/checkout: `fetch-depth: 0`)." : "";
3808
+ if (known.status !== 0) {
3809
+ return new BiviumError2("BV_GIT_NO_BASE", `bivium: no commit ${base} here to diff against: fetch it.${fix}`);
4218
3810
  }
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 });
3811
+ if (forked.status !== 0) {
3812
+ 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
3813
  }
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)" : ""}`
3814
+ return;
3815
+ }
3816
+ function mergeBaseOf(cwd, base) {
3817
+ let pending;
3818
+ return () => {
3819
+ if (pending === undefined) {
3820
+ pending = gitOrThrow(cwd, "merge-base", base, "HEAD").then((out) => out.trim());
3821
+ pending.catch(() => {
3822
+ return;
4246
3823
  });
4247
3824
  }
3825
+ return pending;
3826
+ };
3827
+ }
3828
+ async function readRevision(cwd, base, roots, {
3829
+ blobs = false,
3830
+ mergeBase: eager = false
3831
+ } = {}) {
3832
+ const mergeBase = mergeBaseOf(cwd, base);
3833
+ if (eager)
3834
+ mergeBase();
3835
+ const diffArgs = ["--no-renames", "--merge-base", base];
3836
+ const [listing, diff, staged] = await Promise.all([
3837
+ gitOrThrow(cwd, "ls-files", "-s", "-v", "-o", "--exclude-standard"),
3838
+ gitOrThrow(cwd, "diff", "--raw", "--no-abbrev", ...diffArgs),
3839
+ gitOrThrow(cwd, "diff", "--cached", "--name-only", ...diffArgs)
3840
+ ]).catch(async (error) => {
3841
+ throw await missingHistory(cwd, base) ?? error;
3842
+ });
3843
+ const entries = lines(listing);
3844
+ const untracked = [];
3845
+ for (const line of entries) {
3846
+ if (line.startsWith("? "))
3847
+ untracked.push(line.slice(2));
3848
+ }
3849
+ const before = new Map;
3850
+ const diffed = [];
3851
+ const layout = new Set(untracked);
3852
+ for (const line of lines(diff)) {
3853
+ const [, mode, oid, status, path] = RAW_ENTRY.exec(line) ?? [];
3854
+ if (mode === undefined || oid === undefined || status === undefined || path === undefined) {
3855
+ throw new Error(`git diff: unexpected line ${line}`);
3856
+ }
3857
+ diffed.push(path);
3858
+ if (status === "A" || status === "D")
3859
+ layout.add(path);
3860
+ if (status === "A")
3861
+ before.set(path, undefined);
3862
+ else if ("MTD".includes(status) && mode !== "160000") {
3863
+ before.set(path, oid);
3864
+ }
4248
3865
  }
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;
3866
+ const reads = new Map;
3867
+ const readBase = (path) => {
3868
+ let read = reads.get(path);
3869
+ if (read === undefined) {
3870
+ read = readBaseOnce(path);
3871
+ reads.set(path, read);
4262
3872
  }
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);
3873
+ return read;
3874
+ };
3875
+ const readBaseOnce = (path) => {
3876
+ if (!before.has(path)) {
3877
+ if (present.has(path)) {
3878
+ return readFile2(join2(cwd, path), "utf-8").catch(() => mergeBase().then((commit) => show(cwd, `${commit}:${path}`)));
3879
+ }
3880
+ return mergeBase().then((commit) => show(cwd, `${commit}:${path}`));
4267
3881
  }
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" };
3882
+ const oid = before.get(path);
3883
+ return oid === undefined ? Promise.resolve(undefined) : show(cwd, oid);
3884
+ };
3885
+ const changed = [...new Set([...diffed, ...untracked])];
3886
+ const dirty = new Set([...changed, ...lines(staged)]);
3887
+ const underRoots = (path) => roots.some((root) => inRoot2(path, root));
3888
+ const files = new Set;
3889
+ const tracked = new Set;
3890
+ const present = new Set;
3891
+ const oids = new Map;
3892
+ for (const line of entries) {
3893
+ const entry = INDEX_ENTRY.exec(line);
3894
+ if (!entry) {
3895
+ if (line.startsWith("? ") && underRoots(line.slice(2))) {
3896
+ files.add(line.slice(2));
3897
+ }
4274
3898
  continue;
4275
3899
  }
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) ?? []);
3900
+ const [, tag, mode, oid, stage, path] = entry;
3901
+ if (tag === undefined || mode === undefined || oid === undefined || stage === undefined || path === undefined) {
3902
+ throw new Error(`bivium: git: unexpected ls-files line ${line}.`);
3903
+ }
3904
+ tracked.add(path);
3905
+ if (mode === "160000" || !underRoots(path))
3906
+ continue;
3907
+ files.add(path);
3908
+ if (dirty.has(path) || stage !== "0" || tag !== "H")
3909
+ continue;
3910
+ if (mode !== "100644" && mode !== "100755")
3911
+ continue;
3912
+ present.add(path);
3913
+ if (blobs)
3914
+ oids.set(path, oid);
4279
3915
  }
4280
3916
  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,
3917
+ files: sorted(files),
3918
+ listed: [...tracked, ...untracked],
3919
+ changed,
4294
3920
  layout,
4295
- packageCauses: bumped.seeds,
4296
- narrowings
3921
+ mergeBase,
3922
+ readBase,
3923
+ blobs: oids,
3924
+ present
4297
3925
  };
4298
3926
  }
3927
+ async function show(cwd, object) {
3928
+ const result = await git(cwd, "show", object);
3929
+ return result.status === 0 ? result.stdout : undefined;
3930
+ }
3931
+ async function defaultBase(cwd) {
3932
+ const head = await git(cwd, "symbolic-ref", "--short", "refs/remotes/origin/HEAD");
3933
+ if (head.status === 0 && head.stdout.trim())
3934
+ return head.stdout.trim();
3935
+ const refs = ["origin/main", "origin/master", "main", "master"];
3936
+ const found = await Promise.all(refs.map((ref) => git(cwd, "rev-parse", "--verify", "--quiet", ref)));
3937
+ const branch = refs[found.findIndex((result) => result.status === 0)];
3938
+ if (branch)
3939
+ return branch;
3940
+ 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`);
3941
+ }
4299
3942
 
4300
3943
  // src/settings.ts
4301
3944
  import { posix as posix5 } from "node:path";
4302
3945
 
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
3946
  // src/tsconfig.ts
4442
3947
  import { posix as posix4 } from "node:path";
4443
3948
  var COMMENT2 = /("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g;
@@ -4447,7 +3952,7 @@ var RELATIVE2 = /^\.\.?(?:\/|$)/;
4447
3952
  function parseJsonc(text) {
4448
3953
  return JSON.parse(text.replace(BOM, "").replace(COMMENT2, (_, string) => string ?? " ").replace(TRAILING_COMMA, (_, string) => string ?? ""));
4449
3954
  }
4450
- function isStrings2(value) {
3955
+ function isStrings(value) {
4451
3956
  return Array.isArray(value) && value.every((item) => typeof item === "string");
4452
3957
  }
4453
3958
  function parse2(file, text) {
@@ -4457,24 +3962,24 @@ function parse2(file, text) {
4457
3962
  } catch (error) {
4458
3963
  return { error: error instanceof Error ? error.message : String(error) };
4459
3964
  }
4460
- if (!isRecord2(value))
3965
+ if (!isRecord(value))
4461
3966
  return { error: "not an object" };
4462
3967
  const dir = posix4.dirname(file);
4463
3968
  const { extends: extended } = value;
4464
3969
  const read = {
4465
3970
  extends: typeof extended === "string" ? [extended] : []
4466
3971
  };
4467
- if (isStrings2(extended))
3972
+ if (isStrings(extended))
4468
3973
  read.extends = extended;
4469
3974
  const options = value.compilerOptions;
4470
- if (isRecord2(options)) {
3975
+ if (isRecord(options)) {
4471
3976
  if (typeof options.baseUrl === "string") {
4472
3977
  read.baseUrl = posix4.join(dir, options.baseUrl);
4473
3978
  }
4474
- if (isRecord2(options.paths)) {
3979
+ if (isRecord(options.paths)) {
4475
3980
  const map = {};
4476
3981
  for (const [key, targets] of Object.entries(options.paths)) {
4477
- if (isStrings2(targets))
3982
+ if (isStrings(targets))
4478
3983
  map[key] = targets;
4479
3984
  }
4480
3985
  read.paths = { map, dir };
@@ -4624,7 +4129,7 @@ function parsed(text, jsonc) {
4624
4129
  }
4625
4130
  }
4626
4131
  function changedKeys(before, after) {
4627
- if (!(isRecord2(before) && isRecord2(after)))
4132
+ if (!(isRecord(before) && isRecord(after)))
4628
4133
  return;
4629
4134
  const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
4630
4135
  return [...keys].filter((key) => JSON.stringify(before[key]) !== JSON.stringify(after[key]));
@@ -4689,7 +4194,17 @@ async function readIfFile(path) {
4689
4194
  throw error;
4690
4195
  }
4691
4196
  }
4692
- function collectPackages(rootJson, sources) {
4197
+ async function readSources2(root, files) {
4198
+ const texts = await Promise.all(files.map((file) => readIfFile(join3(root, file))));
4199
+ const sources = new Map;
4200
+ for (const [i, file] of files.entries()) {
4201
+ const text = texts[i];
4202
+ if (text !== undefined)
4203
+ sources.set(file, text);
4204
+ }
4205
+ return sources;
4206
+ }
4207
+ function collectPackages2(rootJson, sources) {
4693
4208
  const packages = new Map;
4694
4209
  const parse = (text) => {
4695
4210
  try {
@@ -4725,14 +4240,14 @@ async function isFile(path) {
4725
4240
  throw error;
4726
4241
  }
4727
4242
  }
4728
- async function extractRevision(root, revision, cache) {
4243
+ async function extractRevision2(root, revision, cache) {
4729
4244
  const extractions = new Map;
4730
4245
  const texts = new Map;
4731
4246
  const missing = new Set;
4732
4247
  const tasks = [];
4733
4248
  let cached = 0;
4734
4249
  const read = async (file) => {
4735
- const text = await readIfFile(join4(root, file));
4250
+ const text = await readIfFile(join3(root, file));
4736
4251
  if (text === undefined)
4737
4252
  missing.add(file);
4738
4253
  return text;
@@ -4761,7 +4276,7 @@ async function extractRevision(root, revision, cache) {
4761
4276
  texts.set(file, source);
4762
4277
  }));
4763
4278
  } else if (!revision.present.has(file)) {
4764
- tasks.push(() => isFile(join4(root, file)).then((found) => {
4279
+ tasks.push(() => isFile(join3(root, file)).then((found) => {
4765
4280
  if (!found)
4766
4281
  missing.add(file);
4767
4282
  }));
@@ -4782,7 +4297,7 @@ async function extractRevision(root, revision, cache) {
4782
4297
  extracted: { cached, read: extractions.size - cached }
4783
4298
  };
4784
4299
  }
4785
- function graphView(graph, config) {
4300
+ function graphView2(graph, config) {
4786
4301
  const nodes = [...graph.keys()];
4787
4302
  return {
4788
4303
  nodes: () => nodes,
@@ -4805,14 +4320,14 @@ async function runNarrowers(root, revision, graph, config, suites, packages, set
4805
4320
  const wanted = config.narrowers.filter((narrower) => relevant.some(narrower.match) && (suites === undefined || narrower.suites.some((name) => suites.includes(name))));
4806
4321
  if (wanted.length === 0)
4807
4322
  return [];
4808
- const view = graphView(graph, config);
4323
+ const view = graphView2(graph, config);
4809
4324
  const base = {
4810
4325
  commit: await revision.mergeBase(),
4811
4326
  read: revision.readBase
4812
4327
  };
4813
4328
  const head = {
4814
4329
  commit: undefined,
4815
- read: (path) => readIfFile(join4(root, path))
4330
+ read: (path) => readIfFile(join3(root, path))
4816
4331
  };
4817
4332
  return Promise.all(wanted.map(async (narrower) => {
4818
4333
  const changed = relevant.filter(narrower.match);
@@ -4830,7 +4345,7 @@ async function runNarrowers(root, revision, graph, config, suites, packages, set
4830
4345
  }
4831
4346
  }));
4832
4347
  }
4833
- async function computePlan(root, base, config, {
4348
+ async function computePlan2(root, base, config, {
4834
4349
  cache: cacheOption = config.cache,
4835
4350
  suites,
4836
4351
  mergeBase = false
@@ -4841,7 +4356,7 @@ async function computePlan(root, base, config, {
4841
4356
  blobs: dir !== undefined,
4842
4357
  mergeBase
4843
4358
  }),
4844
- readFile3(join4(root, "package.json"), "utf-8").catch(() => {
4359
+ readFile3(join3(root, "package.json"), "utf-8").catch(() => {
4845
4360
  return;
4846
4361
  }),
4847
4362
  ExtractionCache.open(dir)
@@ -4856,19 +4371,19 @@ async function computePlan(root, base, config, {
4856
4371
  if (!listed.has(file))
4857
4372
  return;
4858
4373
  }
4859
- return readIfFile(join4(root, file));
4374
+ return readIfFile(join3(root, file));
4860
4375
  };
4861
4376
  const [{ files, extractions, manifests, extracted }, ts, packageDiff] = await Promise.all([
4862
- extractRevision(root, revision, cache),
4377
+ extractRevision2(root, revision, cache),
4863
4378
  readTsconfigs([
4864
4379
  "tsconfig.json",
4865
4380
  ...revision.files.filter((file) => file.endsWith("/tsconfig.json"))
4866
4381
  ], readTsconfig),
4867
- readPackageDiff(revision.changed, revision.listed, revision.readBase, (path) => readIfFile(join4(root, path)))
4382
+ readPackageDiff(revision.changed, revision.listed, revision.readBase, (path) => readIfFile(join3(root, path)))
4868
4383
  ]);
4869
4384
  const { tsconfigs } = ts;
4870
4385
  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);
4386
+ const packages = collectPackages2(rootJson, manifests);
4872
4387
  const graph = graphFrom(files, extractions, {
4873
4388
  config,
4874
4389
  packages,
@@ -4882,7 +4397,7 @@ async function computePlan(root, base, config, {
4882
4397
  packages: packages.keys(),
4883
4398
  accounted: new Set(packageDiff?.files.keys()),
4884
4399
  base: revision.readBase,
4885
- head: (path) => readIfFile(join4(root, path))
4400
+ head: (path) => readIfFile(join3(root, path))
4886
4401
  });
4887
4402
  const moved = await Promise.all([...basePending].map(async ([file, pending]) => {
4888
4403
  const head = graph.get(file)?.barrel;
@@ -4918,18 +4433,18 @@ async function computePlan(root, base, config, {
4918
4433
  extracted
4919
4434
  };
4920
4435
  }
4921
- async function prepare({
4436
+ async function prepare2({
4922
4437
  cwd = process.cwd(),
4923
4438
  base,
4924
4439
  config,
4925
4440
  configFile
4926
4441
  }) {
4927
- const root = resolve2(cwd);
4442
+ const root = resolve(cwd);
4928
4443
  let resolved;
4929
4444
  if (config) {
4930
- resolved = resolveConfig(checkConfig(config));
4445
+ resolved = resolveConfig2(checkConfig2(config));
4931
4446
  } else {
4932
- const loaded = await loadConfig(root, configFile);
4447
+ const loaded = await loadConfig2(root, configFile);
4933
4448
  const isSelf = loaded.config.isSelf;
4934
4449
  resolved = {
4935
4450
  ...loaded.config,
@@ -4944,8 +4459,8 @@ async function prepare({
4944
4459
  };
4945
4460
  }
4946
4461
  async function plan2(options = {}) {
4947
- const { root, base, config } = await prepare(options);
4948
- const computed = await computePlan(root, base, config, {
4462
+ const { root, base, config } = await prepare2(options);
4463
+ const computed = await computePlan2(root, base, config, {
4949
4464
  ...options.cache !== undefined && { cache: options.cache },
4950
4465
  mergeBase: true
4951
4466
  });
@@ -4965,4 +4480,4 @@ async function plan2(options = {}) {
4965
4480
  };
4966
4481
  }
4967
4482
 
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 };
4483
+ 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, fitTerminal, RULE, aligned, headerRow, plural, SILENT, createProgress, formatSelection, orphanOf, readSources2, collectPackages2, extractRevision2, graphView2, computePlan2, prepare2, plan2 };