@kaynooo/cli-workspace 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process22 from "process";
5
+ import process24 from "process";
6
6
 
7
7
  // ../kit/src/advisory.ts
8
8
  var SEVERITIES = ["low", "moderate", "high", "critical"];
@@ -517,7 +517,7 @@ function printJson(value) {
517
517
 
518
518
  // ../kit/src/help.ts
519
519
  import process8 from "process";
520
- var OPTIONAL = /\[[^\]]+\]/g;
520
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
521
521
  var USAGE_PREFIX = /^usage:\s*/i;
522
522
  var FULL_STOP = /\.$/;
523
523
  function usageLine(usage, colors = paint(process8.stdout)) {
@@ -556,29 +556,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
556
556
  return [];
557
557
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
558
558
  }
559
+ var MAX_INLINE_CHOICES = 24;
559
560
  function optionRows(options, colors = paint(process8.stdout)) {
560
561
  const rows = Object.entries(options).map(([name, option]) => {
561
562
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
562
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
563
+ const choices = option.choices?.join("|");
564
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
565
+ const named = inline ? `<${choices}>` : "<value>";
563
566
  const placeholder = option.optional === undefined ? named : `[${named}]`;
564
567
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
565
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
568
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
569
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
566
570
  });
567
571
  const width = Math.max(0, ...rows.map((row) => row.width));
568
572
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
569
573
  }
570
574
 
571
575
  // ../kit/src/text.ts
572
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
573
576
  function distance(a, b) {
574
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
575
- for (const [i, left] of [...a].entries()) {
577
+ const left = [...a];
578
+ const right = [...b];
579
+ let before = [];
580
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
581
+ for (const [i, x] of left.entries()) {
576
582
  const current = [i + 1];
577
- for (const [j, right] of [...b].entries())
578
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
583
+ for (const [j, y] of right.entries()) {
584
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
585
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
586
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
587
+ current.push(cost);
588
+ }
589
+ before = previous;
579
590
  previous = current;
580
591
  }
581
- return previous[b.length] ?? 0;
592
+ return previous[right.length] ?? 0;
582
593
  }
583
594
  function closest(name, names) {
584
595
  const started = names.find((known) => known.startsWith(name));
@@ -980,13 +991,31 @@ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
980
991
  // ../kit/src/cli.ts
981
992
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
982
993
  import { dirname as dirname3, join as join5 } from "path";
983
- import process14 from "process";
994
+ import process15 from "process";
995
+
996
+ // ../kit/src/notify.ts
997
+ import process13 from "process";
998
+ var NOTIFY_AFTER_MS = 1e4;
999
+ var CANCELLED = 130;
1000
+ function base64(text) {
1001
+ return Buffer.from(text).toString("base64");
1002
+ }
1003
+ function notification(title, body, env = process13.env) {
1004
+ const id = `kit${process13.pid}`;
1005
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
1006
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1007
+ }
1008
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1009
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1010
+ return;
1011
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1012
+ }
984
1013
 
985
1014
  // ../kit/src/usage.ts
986
1015
  import { appendFileSync, mkdirSync } from "fs";
987
1016
  import { homedir as homedir3 } from "os";
988
1017
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
989
- import process13 from "process";
1018
+ import process14 from "process";
990
1019
 
991
1020
  // ../kit/src/logs.ts
992
1021
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -1000,14 +1029,14 @@ var usageError;
1000
1029
  function noteUsageError(message) {
1001
1030
  usageError = message;
1002
1031
  }
1003
- function stateHome(env = process13.env) {
1032
+ function stateHome(env = process14.env) {
1004
1033
  const dir = env.XDG_STATE_HOME;
1005
1034
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1006
1035
  }
1007
- function usagePath(env = process13.env) {
1036
+ function usagePath(env = process14.env) {
1008
1037
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1009
1038
  }
1010
- function usageRecorded(env = process13.env) {
1039
+ function usageRecorded(env = process14.env) {
1011
1040
  const off = env.KAYNOOO_CLI_NO_USAGE;
1012
1041
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1013
1042
  }
@@ -1021,7 +1050,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1021
1050
  usageError = undefined;
1022
1051
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1023
1052
  }
1024
- function recordUsage(entry, env = process13.env) {
1053
+ function recordUsage(entry, env = process14.env) {
1025
1054
  if (!usageRecorded(env))
1026
1055
  return;
1027
1056
  try {
@@ -1111,8 +1140,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1111
1140
  `);
1112
1141
  }
1113
1142
  function printError(prefix, message, hint, cause) {
1114
- const colors = paint(process14.stderr);
1115
- const styled = takesControlCodes(process14.stderr);
1143
+ const colors = paint(process15.stderr);
1144
+ const styled = takesControlCodes(process15.stderr);
1116
1145
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1117
1146
  const under = (label, text, tint) => text === undefined ? "" : `
1118
1147
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1155,11 +1184,11 @@ async function dispatch(level, typed, { version, redact }) {
1155
1184
  }
1156
1185
  }
1157
1186
  if (name === undefined && level.path.length > 1) {
1158
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
1187
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1159
1188
  return 2;
1160
1189
  }
1161
1190
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1162
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
1191
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1163
1192
  return 0;
1164
1193
  }
1165
1194
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1294,10 +1323,13 @@ async function runCli(cli, argv = scriptArgs()) {
1294
1323
  const version = cli.version ?? packageVersion();
1295
1324
  if (argv[0] === COMPLETE)
1296
1325
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1326
+ const started = performance.now();
1297
1327
  const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1328
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1329
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1298
1330
  if (cli.usage !== false) {
1299
1331
  try {
1300
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1332
+ recordUsage(usageEntry(cli.name, command, argv, code));
1301
1333
  } catch {}
1302
1334
  }
1303
1335
  return code;
@@ -1325,11 +1357,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
1325
1357
  return 0;
1326
1358
  }
1327
1359
  let code;
1360
+ const started = performance.now();
1328
1361
  try {
1329
1362
  code = await run(argv);
1330
1363
  } catch (error) {
1331
1364
  code = reportThrown(name, error, redact, wantsJson(argv));
1332
1365
  }
1366
+ notifyEnd(name, code, performance.now() - started);
1333
1367
  if (usage !== false) {
1334
1368
  try {
1335
1369
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1369,7 +1403,7 @@ function parseSize(text, bareUnit = 1) {
1369
1403
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1370
1404
  }
1371
1405
  // ../kit/src/watch.ts
1372
- import process15 from "process";
1406
+ import process16 from "process";
1373
1407
  import { format } from "util";
1374
1408
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1375
1409
  var DEFAULT_SECONDS = 2;
@@ -1391,7 +1425,7 @@ function withoutWatch(args) {
1391
1425
  }
1392
1426
  return rest;
1393
1427
  }
1394
- async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1428
+ async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1395
1429
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1396
1430
  if (!takesControlCodes(stream))
1397
1431
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1399,12 +1433,12 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1399
1433
  for (let round = 0;round < rounds; round++) {
1400
1434
  const held = [];
1401
1435
  const { log, info } = console;
1402
- const write = process15.stdout.write.bind(process15.stdout);
1436
+ const write = process16.stdout.write.bind(process16.stdout);
1403
1437
  const hold = (...parts) => void held.push(`${format(...parts)}
1404
1438
  `);
1405
1439
  console.log = hold;
1406
1440
  console.info = hold;
1407
- process15.stdout.write = (text) => {
1441
+ process16.stdout.write = (text) => {
1408
1442
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1409
1443
  return true;
1410
1444
  };
@@ -1413,7 +1447,7 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1413
1447
  } finally {
1414
1448
  console.log = log;
1415
1449
  console.info = info;
1416
- process15.stdout.write = write;
1450
+ process16.stdout.write = write;
1417
1451
  }
1418
1452
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1419
1453
  await sleep(interval);
@@ -1423,7 +1457,7 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1423
1457
  // ../kit/src/workspace-root.ts
1424
1458
  import { homedir as homedir4 } from "os";
1425
1459
  import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1426
- import process16 from "process";
1460
+ import process17 from "process";
1427
1461
  function expandHome(path, home) {
1428
1462
  if (path === "~")
1429
1463
  return home;
@@ -1433,15 +1467,19 @@ function configured(env, home) {
1433
1467
  const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1434
1468
  return typeof folder === "string" && folder !== "" ? folder : undefined;
1435
1469
  }
1436
- function workspaceRoot({ given, env = process16.env, home = homedir4() } = {}) {
1470
+ function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1437
1471
  const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1438
1472
  return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1439
1473
  }
1440
1474
  // src/audit.ts
1441
- import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync6, statSync as statSync2 } from "fs";
1475
+ import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync7, statSync as statSync2 } from "fs";
1442
1476
  import { readdir } from "fs/promises";
1443
- import { join as join8, relative, resolve as resolve5 } from "path";
1444
- import process18 from "process";
1477
+ import { join as join9, relative, resolve as resolve5 } from "path";
1478
+ import process19 from "process";
1479
+
1480
+ // src/osv.ts
1481
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
1482
+ import { join as join8 } from "path";
1445
1483
 
1446
1484
  // src/report.ts
1447
1485
  import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
@@ -1558,14 +1596,121 @@ function workspaceFolders(root, children) {
1558
1596
  return patterns.filter((pattern) => typeof pattern === "string").flatMap((pattern) => pattern.endsWith("/*") ? children(pattern.slice(0, -2)).map((name) => join7(pattern.slice(0, -2), name)) : [pattern]);
1559
1597
  }
1560
1598
 
1599
+ // src/osv.ts
1600
+ var OSV = "https://api.osv.dev/v1";
1601
+ var BATCH = 1000;
1602
+ var DETAIL_CONCURRENCY = 8;
1603
+ var TIMEOUT_MS = 20000;
1604
+ var PACKAGE_BLOCK = /^\[\[package\]\]\s*$/m;
1605
+ var FIELD = /^(name|version|source) = (.+)$/gm;
1606
+ var QUOTED = /^"([^"]*)"$/;
1607
+ var LEADING_V = /^v/;
1608
+ function parseComposerLock(text) {
1609
+ const lock = JSON.parse(text);
1610
+ const entry = (prod) => (each) => ({ name: each.name, version: each.version.replace(LEADING_V, ""), prod });
1611
+ return [...(lock.packages ?? []).map(entry(true)), ...(lock["packages-dev"] ?? []).map(entry(false))];
1612
+ }
1613
+ function tomlPackages(text, fromRegistry) {
1614
+ const found = [];
1615
+ for (const block of text.split(PACKAGE_BLOCK).slice(1)) {
1616
+ const fields = new Map;
1617
+ for (const [, key, value] of block.matchAll(FIELD))
1618
+ fields.set(key, QUOTED.exec(value.trim())?.[1] ?? value.trim());
1619
+ const source = fields.get("source");
1620
+ const name = fields.get("name");
1621
+ const version = fields.get("version");
1622
+ if (name !== undefined && version !== undefined && source !== undefined && fromRegistry(source))
1623
+ found.push({ name, version, prod: true });
1624
+ }
1625
+ return found;
1626
+ }
1627
+ function parseCargoLock(text) {
1628
+ return tomlPackages(text, (source) => source.startsWith("registry+"));
1629
+ }
1630
+ function parseUvLock(text) {
1631
+ return tomlPackages(text, (source) => source.includes("registry"));
1632
+ }
1633
+ var ECOSYSTEMS = [
1634
+ { lockfile: "composer.lock", osv: "Packagist", parse: parseComposerLock },
1635
+ { lockfile: "Cargo.lock", osv: "crates.io", parse: parseCargoLock },
1636
+ { lockfile: "uv.lock", osv: "PyPI", parse: parseUvLock }
1637
+ ];
1638
+ function holdsOsvLock(dir) {
1639
+ return ECOSYSTEMS.some((each) => existsSync5(join8(dir, each.lockfile)));
1640
+ }
1641
+ var SEVERITY_NAMES = { LOW: "low", MODERATE: "moderate", MEDIUM: "moderate", HIGH: "high", CRITICAL: "critical" };
1642
+ async function ok2(response) {
1643
+ if (!response.ok)
1644
+ throw new Error(`osv.dev answered ${response.status}`);
1645
+ return response.json();
1646
+ }
1647
+ function rowOf(vuln, name) {
1648
+ const fixes = (vuln.affected ?? []).filter((each) => each.package?.name === name).flatMap((each) => each.ranges ?? []).flatMap((range) => range.events ?? []).map((event) => event.fixed).filter((fixed) => fixed !== undefined);
1649
+ return { id: 0, ghsa: vuln.id, url: `https://osv.dev/vulnerability/${vuln.id}`, title: vuln.summary ?? vuln.id, severity: SEVERITY_NAMES[vuln.database_specific?.severity?.toUpperCase() ?? ""] ?? "moderate", fixed: fixes.length === 0 ? undefined : fixedAt(fixes.map((fix) => `<${fix}`).join(" || ")) };
1650
+ }
1651
+ async function osvFindings(locked, ecosystem, direct, level, ignore, fetcher = fetch) {
1652
+ const hits = new Map;
1653
+ for (let start = 0;start < locked.length; start += BATCH) {
1654
+ const chunk = locked.slice(start, start + BATCH);
1655
+ const queries = chunk.map((each) => ({ package: { name: each.name, ecosystem }, version: each.version }));
1656
+ const answer = await ok2(await fetcher(`${OSV}/querybatch`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ queries }), signal: AbortSignal.timeout(TIMEOUT_MS) }));
1657
+ for (const [index, each] of chunk.entries()) {
1658
+ const ids = (answer.results[index]?.vulns ?? []).map((vuln) => vuln.id).filter((id) => !ignore.includes(id));
1659
+ if (ids.length > 0)
1660
+ hits.set(each, ids);
1661
+ }
1662
+ }
1663
+ const details = new Map;
1664
+ await pool([...new Set([...hits.values()].flat())], DETAIL_CONCURRENCY, async (id) => {
1665
+ details.set(id, await ok2(await fetcher(`${OSV}/vulns/${encodeURIComponent(id)}`, { signal: AbortSignal.timeout(TIMEOUT_MS) })));
1666
+ });
1667
+ const findings = [];
1668
+ let below = 0;
1669
+ for (const [each, ids] of hits) {
1670
+ const rows = ids.map((id) => rowOf(details.get(id), each.name));
1671
+ const advisories = rows.filter((row) => severityRank(row.severity) >= severityRank(level));
1672
+ below += rows.length - advisories.length;
1673
+ if (advisories.length === 0)
1674
+ continue;
1675
+ const fixes = advisories.map((row) => row.fixed);
1676
+ findings.push({
1677
+ package: each.name,
1678
+ severity: advisories.reduce((worst, row) => severityRank(row.severity) > severityRank(worst) ? row.severity : worst, advisories[0].severity),
1679
+ advisories,
1680
+ scope: each.prod ? "prod" : "dev",
1681
+ direct: direct.has(each.name),
1682
+ via: [],
1683
+ fix: fixes.includes(undefined) ? undefined : fixes.reduce((highest, fix) => Bun.semver.order(fix, highest) > 0 ? fix : highest)
1684
+ });
1685
+ }
1686
+ return { findings: findings.toSorted((a, b) => severityRank(b.severity) - severityRank(a.severity) || Number(b.scope === "prod") - Number(a.scope === "prod") || a.package.localeCompare(b.package)), below };
1687
+ }
1688
+ function manifestNames(dir) {
1689
+ try {
1690
+ const manifest = JSON.parse(readFileSync6(join8(dir, "composer.json"), "utf8"));
1691
+ return new Set([...Object.keys(manifest.require ?? {}), ...Object.keys(manifest["require-dev"] ?? {})]);
1692
+ } catch {
1693
+ return new Set;
1694
+ }
1695
+ }
1696
+ async function osvAudit(dir, level, ignore, fetcher = fetch) {
1697
+ const all = { findings: [], below: 0 };
1698
+ for (const each of ECOSYSTEMS.filter((each) => existsSync5(join8(dir, each.lockfile)))) {
1699
+ const done = await osvFindings(each.parse(readFileSync6(join8(dir, each.lockfile), "utf8")), each.osv, each.lockfile === "composer.lock" ? manifestNames(dir) : new Set, level, ignore, fetcher);
1700
+ all.findings.push(...done.findings);
1701
+ all.below += done.below;
1702
+ }
1703
+ return all;
1704
+ }
1705
+
1561
1706
  // src/audit.ts
1562
- var USAGE = `audit [options] [root]: the known vulnerabilities of the Bun repositories under root (the current folder by default), one table per repository
1707
+ var USAGE = `audit [options] [root]: the known vulnerabilities of the Bun, Composer, Cargo and uv repositories under root (the current folder by default), one table per repository
1563
1708
 
1564
1709
  Each package with an advisory is one row: its worst severity, how many advisories, whether a production dependency needs it (prod) or only a development one (dev), whether the repository asks for it itself (direct) or a dependency does (the row then says via and the direct dependencies leading to it, upgrading one of which is what fixes it), and the version that fixes every advisory at once, "-" when an advisory names none. The worst and the production ones come first.
1565
- Advisories under --level (moderate by default) are counted under the table, and what \`bun audit\` warned about, such as a private registry that would not audit its packages, is repeated there. It runs \`bun audit --json\` in each repository holding a bun.lock, which reaches the registry; the walk goes three levels deep, stops at a bun.lock and skips node_modules and hidden folders.
1710
+ Advisories under --level (moderate by default) are counted under the table, and what \`bun audit\` warned about, such as a private registry that would not audit its packages, is repeated there. It runs \`bun audit --json\` in each repository holding a bun.lock, which reaches the registry, and asks osv.dev about the packages of a composer.lock, Cargo.lock or uv.lock (a severity the source leaves out reads as moderate, and only composer's manifest tells direct from pulled in); the walk goes three levels deep, stops at a lockfile and skips node_modules and hidden folders.
1566
1711
 
1567
1712
  Reach for it to sweep many repositories at once; \`pkg audit\` vets the one repository in a folder (package age, install scripts, licences) as well as its advisories, and shares --level, --prod and --ignore.`;
1568
- var EXITS = [[0, "no repository has an advisory at the level asked"], [1, "one has"], [2, "a repository's audit failed, no bun.lock sits under root, a usage error or a root that is no folder"]];
1713
+ var EXITS = [[0, "no repository has an advisory at the level asked"], [1, "one has"], [2, "a repository's audit failed, no lockfile sits under root, a usage error or a root that is no folder"]];
1569
1714
  var OPTIONS = {
1570
1715
  level: { type: "string", choices: SEVERITIES, default: "moderate", description: "only the advisories at least this severe: low, moderate, high or critical" },
1571
1716
  prod: { type: "boolean", description: "only the packages a production dependency needs" },
@@ -1580,8 +1725,11 @@ var VIA_SHOWN = 2;
1580
1725
  function countAdvisories(findings) {
1581
1726
  return findings.reduce((sum, found) => sum + found.advisories.length, 0);
1582
1727
  }
1728
+ function holdsBunLock(dir) {
1729
+ return existsSync6(join9(dir, "bun.lock")) || existsSync6(join9(dir, "bun.lockb"));
1730
+ }
1583
1731
  function holdsLock(dir) {
1584
- return existsSync5(join8(dir, "bun.lock")) || existsSync5(join8(dir, "bun.lockb"));
1732
+ return holdsBunLock(dir) || holdsOsvLock(dir);
1585
1733
  }
1586
1734
  async function findRepos(root) {
1587
1735
  if (holdsLock(root))
@@ -1597,7 +1745,7 @@ async function findRepos(root) {
1597
1745
  for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1598
1746
  if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith("."))
1599
1747
  continue;
1600
- const path = join8(dir, entry.name);
1748
+ const path = join9(dir, entry.name);
1601
1749
  if (holdsLock(path))
1602
1750
  found.push(path);
1603
1751
  else if (depth < MAX_DEPTH)
@@ -1610,13 +1758,24 @@ async function findRepos(root) {
1610
1758
  function children(root) {
1611
1759
  return (folder) => {
1612
1760
  try {
1613
- return readdirSync(join8(root, folder), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
1761
+ return readdirSync(join9(root, folder), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
1614
1762
  } catch {
1615
1763
  return [];
1616
1764
  }
1617
1765
  };
1618
1766
  }
1619
1767
  async function audited(path, shown, level, ignore) {
1768
+ const bun = holdsBunLock(path) ? await bunAudited(path, shown, level, ignore) : { repo: shown, path, findings: [], below: 0, warnings: [], error: undefined };
1769
+ if (bun.error !== undefined || !holdsOsvLock(path))
1770
+ return bun;
1771
+ try {
1772
+ const osv = await osvAudit(path, level, ignore);
1773
+ return { ...bun, findings: [...bun.findings, ...osv.findings], below: bun.below + osv.below };
1774
+ } catch (error) {
1775
+ return { ...bun, error: `osv.dev: ${error instanceof Error ? error.message : String(error)}` };
1776
+ }
1777
+ }
1778
+ async function bunAudited(path, shown, level, ignore) {
1620
1779
  const [all, production] = await Promise.all([
1621
1780
  runCommand(["bun", "audit", "--json"], { cwd: path, timeoutMs: AUDIT_MS }),
1622
1781
  runCommand(["bun", "audit", "--json", "--prod"], { cwd: path, timeoutMs: AUDIT_MS })
@@ -1633,7 +1792,7 @@ async function audited(path, shown, level, ignore) {
1633
1792
  }
1634
1793
  function lockText(path) {
1635
1794
  try {
1636
- return readFileSync6(join8(path, "bun.lock"), "utf8");
1795
+ return readFileSync7(join9(path, "bun.lock"), "utf8");
1637
1796
  } catch {
1638
1797
  return "";
1639
1798
  }
@@ -1653,7 +1812,7 @@ function failure(ran) {
1653
1812
  `).at(-1) ?? `exit ${ran.code}`;
1654
1813
  }
1655
1814
  function tint(severity) {
1656
- const colors = paint(process18.stdout);
1815
+ const colors = paint(process19.stdout);
1657
1816
  if (severity === "critical" || severity === "high")
1658
1817
  return colors.red;
1659
1818
  return severity === "moderate" ? colors.yellow : colors.dim;
@@ -1671,12 +1830,12 @@ function rows(findings) {
1671
1830
  async function audit(args) {
1672
1831
  const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[root]"], exits: EXITS, replaces: "a bun audit run in each repository and a read of every advisory to find what is worth fixing", examples: ["audit", "audit ~/Workspace --level high --prod"] });
1673
1832
  const root = resolve5(positionals[0] ?? ".");
1674
- if (!existsSync5(root) || !statSync2(root).isDirectory())
1833
+ if (!existsSync6(root) || !statSync2(root).isDirectory())
1675
1834
  fail(`no folder ${root}`);
1676
1835
  const level = oneOf(values.level, "level", SEVERITIES);
1677
1836
  const paths = await findRepos(root);
1678
1837
  if (paths.length === 0)
1679
- fail(`no bun.lock under ${root}`);
1838
+ fail(`no bun.lock, composer.lock, Cargo.lock or uv.lock under ${root}`);
1680
1839
  const audits = await pool(paths, configuredNumber("audit", "concurrency", CONCURRENCY), async (path) => audited(path, relative(root, path) || ".", level, values.ignore ?? []));
1681
1840
  const kept = audits.map((each) => ({ ...each, findings: values.prod === true ? each.findings.filter((found) => found.scope === "prod") : each.findings }));
1682
1841
  if (values.json === true)
@@ -1688,8 +1847,8 @@ async function audit(args) {
1688
1847
  return kept.some((each) => each.findings.length > 0) ? 1 : 0;
1689
1848
  }
1690
1849
  function show(audits, total) {
1691
- const label = role("label", process18.stdout);
1692
- const path = role("path", process18.stdout);
1850
+ const label = role("label", process19.stdout);
1851
+ const path = role("path", process19.stdout);
1693
1852
  const flagged = audits.filter((each) => each.error !== undefined || each.findings.length > 0);
1694
1853
  if (flagged.length === 0) {
1695
1854
  console.log(label(`no advisory in ${total} ${total === 1 ? "repository" : "repositories"}`));
@@ -1709,15 +1868,15 @@ function show(audits, total) {
1709
1868
  }
1710
1869
 
1711
1870
  // src/repos.ts
1712
- import { existsSync as existsSync7, statSync as statSync3 } from "fs";
1871
+ import { existsSync as existsSync8, statSync as statSync3 } from "fs";
1713
1872
  import { basename as basename2, relative as relative2 } from "path";
1714
- import process20 from "process";
1873
+ import process21 from "process";
1715
1874
 
1716
1875
  // src/repos-scan.ts
1717
- import { existsSync as existsSync6 } from "fs";
1876
+ import { existsSync as existsSync7 } from "fs";
1718
1877
  import { readdir as readdir2 } from "fs/promises";
1719
- import { basename, join as join9 } from "path";
1720
- import process19 from "process";
1878
+ import { basename, join as join10 } from "path";
1879
+ import process20 from "process";
1721
1880
  var MAX_DEPTH2 = 3;
1722
1881
  var CONCURRENCY2 = 8;
1723
1882
  var PACKAGE_CONCURRENCY = 4;
@@ -1739,7 +1898,7 @@ function reasonsOf(repo) {
1739
1898
  return reasons;
1740
1899
  }
1741
1900
  async function findRepos2(root, skip) {
1742
- if (existsSync6(join9(root, ".git")))
1901
+ if (existsSync7(join10(root, ".git")))
1743
1902
  return [root];
1744
1903
  const found = [];
1745
1904
  async function walk(dir, depth) {
@@ -1752,8 +1911,8 @@ async function findRepos2(root, skip) {
1752
1911
  for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1753
1912
  if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith(".") || skip.has(entry.name))
1754
1913
  continue;
1755
- const path = join9(dir, entry.name);
1756
- if (existsSync6(join9(path, ".git")))
1914
+ const path = join10(dir, entry.name);
1915
+ if (existsSync7(join10(path, ".git")))
1757
1916
  found.push(path);
1758
1917
  else if (depth < MAX_DEPTH2)
1759
1918
  await walk(path, depth + 1);
@@ -1764,7 +1923,7 @@ async function findRepos2(root, skip) {
1764
1923
  }
1765
1924
  async function read(path, args, timeoutMs = GIT_MS) {
1766
1925
  try {
1767
- const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process19.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
1926
+ const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process20.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
1768
1927
  return ran.code === 0 && !ran.timedOut ? ran.text.trim() : undefined;
1769
1928
  } catch {
1770
1929
  return;
@@ -1783,14 +1942,14 @@ async function packageReleases(path) {
1783
1942
  names.add(name);
1784
1943
  }
1785
1944
  const releases = await pool([...names].toSorted(), PACKAGE_CONCURRENCY, async (name) => {
1786
- const folder = [join9("packages", name), name].find((candidate) => existsSync6(join9(path, candidate)));
1945
+ const folder = [join10("packages", name), name].find((candidate) => existsSync7(join10(path, candidate)));
1787
1946
  const tag = folder === undefined ? undefined : await read(path, ["describe", "--tags", "--abbrev=0", "--match", `${name}-v*`]);
1788
1947
  return folder !== undefined && tag !== undefined && tag !== "" ? { name, tag, unreleased: await commitsSince(path, tag, folder) } : undefined;
1789
1948
  });
1790
1949
  return releases.filter((release) => release !== undefined);
1791
1950
  }
1792
- async function inspect(path, fetch) {
1793
- const fetched = fetch ? await read(path, ["fetch", "--quiet"], FETCH_MS) : "";
1951
+ async function inspect(path, fetch2) {
1952
+ const fetched = fetch2 ? await read(path, ["fetch", "--quiet"], FETCH_MS) : "";
1794
1953
  const [status, worktrees, packages] = await Promise.all([
1795
1954
  read(path, ["status", "--porcelain=v2", "--branch"]),
1796
1955
  read(path, ["worktree", "list", "--porcelain"]),
@@ -1841,7 +2000,7 @@ function firstLine(text) {
1841
2000
  }
1842
2001
  async function fastForward(path) {
1843
2002
  try {
1844
- const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...process19.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs: GIT_MS });
2003
+ const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...process20.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs: GIT_MS });
1845
2004
  if (ran.timedOut)
1846
2005
  return "timed out";
1847
2006
  return ran.code === 0 ? undefined : firstLine(ran.text.trim()) || `exit ${ran.code}`;
@@ -1870,7 +2029,7 @@ var OPTIONS2 = {
1870
2029
  };
1871
2030
  async function skipped() {
1872
2031
  const file = userConfigReadPath("repos");
1873
- if (!existsSync7(file))
2032
+ if (!existsSync8(file))
1874
2033
  return new Set;
1875
2034
  try {
1876
2035
  const config = await Bun.file(file).json();
@@ -1884,7 +2043,7 @@ function releasedCell(repo) {
1884
2043
  return repo.packages.filter((release) => release.unreleased > 0).map((release) => `${release.name} ${release.unreleased}`).join(", ") || "-";
1885
2044
  return repo.tag === null || repo.unreleased === 0 ? "-" : `${repo.unreleased} since ${repo.tag}`;
1886
2045
  }
1887
- function syncCell(repo, stream = process20.stdout) {
2046
+ function syncCell(repo, stream = process21.stdout) {
1888
2047
  const colors = paint(stream);
1889
2048
  const ahead = repo.ahead ?? 0;
1890
2049
  const behind = repo.behind ?? 0;
@@ -1895,7 +2054,7 @@ function syncCell(repo, stream = process20.stdout) {
1895
2054
  return parts.length === 0 ? colors.dim("-") : `${parts.join(" ")}${diverged ? colors.yellow(" diverged") : ""}`;
1896
2055
  }
1897
2056
  var DEFAULT_BRANCHES = new Set(["main", "master"]);
1898
- function branchCell(repo, stream = process20.stdout) {
2057
+ function branchCell(repo, stream = process21.stdout) {
1899
2058
  const colors = paint(stream);
1900
2059
  if (repo.unreadable)
1901
2060
  return colors.red("? (unreadable)");
@@ -1904,8 +2063,8 @@ function branchCell(repo, stream = process20.stdout) {
1904
2063
  return DEFAULT_BRANCHES.has(repo.branch) ? repo.branch : role("accent", stream)(repo.branch);
1905
2064
  }
1906
2065
  function row(repo, shown) {
1907
- const colors = paint(process20.stdout);
1908
- const tint = role("path", process20.stdout);
2066
+ const colors = paint(process21.stdout);
2067
+ const tint = role("path", process21.stdout);
1909
2068
  const unreleased = releasedCell(repo);
1910
2069
  return [
1911
2070
  tint(shown),
@@ -1921,7 +2080,7 @@ async function repos(args) {
1921
2080
  if (values.watch !== undefined)
1922
2081
  return watching(values.watch, async () => repos(withoutWatch(args)));
1923
2082
  const root = workspaceRoot({ given: positionals[0] });
1924
- if (!existsSync7(root) || !statSync3(root).isDirectory())
2083
+ if (!existsSync8(root) || !statSync3(root).isDirectory())
1925
2084
  fail(`no folder ${root}`);
1926
2085
  const only = values.only === undefined ? undefined : oneOf(values.only, "only", REASONS);
1927
2086
  const paths = await findRepos2(root, await skipped());
@@ -1939,12 +2098,12 @@ async function repos(args) {
1939
2098
  const blocker = pullBlocker(repo);
1940
2099
  const refused = blocker === undefined ? await fastForward(repo.path) : undefined;
1941
2100
  if (blocker !== undefined) {
1942
- log(marked("note", `${repo.name} skipped`, process20.stdout, blocker));
2101
+ log(marked("note", `${repo.name} skipped`, process21.stdout, blocker));
1943
2102
  } else if (refused !== undefined) {
1944
2103
  failedPulls++;
1945
- log(marked("problem", `${repo.name} not pulled`, process20.stdout, refused));
2104
+ log(marked("problem", `${repo.name} not pulled`, process21.stdout, refused));
1946
2105
  } else {
1947
- log(marked("ok", `${repo.name} pulled`, process20.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
2106
+ log(marked("ok", `${repo.name} pulled`, process21.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
1948
2107
  states[index] = await inspect(repo.path, false);
1949
2108
  }
1950
2109
  }
@@ -1959,7 +2118,7 @@ async function repos(args) {
1959
2118
  printJson(kept.map((repo) => ({ ...repo, reasons: reasonsOf(repo) })));
1960
2119
  return failedPulls > 0 ? 1 : 0;
1961
2120
  }
1962
- const label = role("label", process20.stdout);
2121
+ const label = role("label", process21.stdout);
1963
2122
  printHeader("repos", `${basename2(root)} \xB7 ${states.length} ${states.length === 1 ? "repository" : "repositories"}`);
1964
2123
  if (kept.length === 0) {
1965
2124
  console.log(label(`nothing needs attention in ${states.length} repositories`));
@@ -1975,12 +2134,26 @@ async function repos(args) {
1975
2134
  }
1976
2135
 
1977
2136
  // src/sweep.ts
1978
- import { existsSync as existsSync10, statSync as statSync4 } from "fs";
2137
+ import { existsSync as existsSync11, statSync as statSync4 } from "fs";
1979
2138
  import { homedir as homedir6 } from "os";
1980
2139
  import { relative as relative3 } from "path";
1981
2140
 
1982
2141
  // ../kit/src/prompt.ts
1983
- import process21 from "process";
2142
+ import process23 from "process";
2143
+
2144
+ // ../kit/src/job.ts
2145
+ import process22 from "process";
2146
+ function stopJob() {
2147
+ process22.kill(0, "SIGTSTP");
2148
+ }
2149
+
2150
+ // ../kit/src/picker/line.ts
2151
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
2152
+ var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
2153
+ var FORWARD_KILLS = new Set(["killnext", "killend"]);
2154
+ function isEditKey(key) {
2155
+ return EDIT_KEYS.has(key);
2156
+ }
1984
2157
 
1985
2158
  // ../kit/src/picker/score.ts
1986
2159
  var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
@@ -2012,10 +2185,29 @@ var KEYS = {
2012
2185
  "\n": "enter",
2013
2186
  "\x03": "cancel",
2014
2187
  "\x1B": "cancel",
2188
+ "\x1B[D": "left",
2189
+ "\x1BOD": "left",
2190
+ "\x1B[C": "right",
2191
+ "\x1BOC": "right",
2192
+ "\x1B[1;5D": "wordleft",
2193
+ "\x1B[1;3D": "wordleft",
2194
+ "\x1Bb": "wordleft",
2195
+ "\x1B[1;5C": "wordright",
2196
+ "\x1B[1;3C": "wordright",
2197
+ "\x1Bf": "wordright",
2198
+ "\x01": "linestart",
2199
+ "\x05": "lineend",
2015
2200
  "\x7F": "erase",
2016
- "\b": "erase",
2201
+ "\x1B[3~": "delete",
2202
+ "\b": "killword",
2203
+ "\x1B\x7F": "killword",
2204
+ "\x1B[3;5~": "killnext",
2205
+ "\x1Bd": "killnext",
2017
2206
  "\x15": "clear",
2207
+ "\v": "killend",
2018
2208
  "\x17": "word",
2209
+ "\x19": "yank",
2210
+ "\x1A": "suspend",
2019
2211
  "\t": "tab",
2020
2212
  "\x1F": "help",
2021
2213
  "\x1BOP": "help",
@@ -2045,10 +2237,21 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
2045
2237
  });
2046
2238
  }
2047
2239
 
2240
+ // ../kit/src/redraw.ts
2241
+ var SYNC_START = "\x1B[?2026h";
2242
+ var SYNC_END = "\x1B[?2026l";
2243
+ function overwrite(lines, columns) {
2244
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
2245
+ `);
2246
+ }
2247
+ function rowsTaken(lines, columns) {
2248
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
2249
+ }
2250
+
2048
2251
  // ../kit/src/prompt.ts
2049
- var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "erase"]);
2252
+ var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
2050
2253
  function readKeys(input, paste = { active: false }) {
2051
- return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key));
2254
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
2052
2255
  }
2053
2256
  async function confirm(question, { default: fallback, ...settings } = {}) {
2054
2257
  let answered = fallback;
@@ -2072,7 +2275,7 @@ function asking(colors, question, typed, keys) {
2072
2275
  function answer(colors, question, state, picked) {
2073
2276
  return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
2074
2277
  }
2075
- async function ask(question, { hint, terminal = process21 }, render, press) {
2278
+ async function ask(question, { hint, terminal = process23 }, render, press) {
2076
2279
  const { stdin, stderr } = terminal;
2077
2280
  if (!isInteractive(terminal))
2078
2281
  fail(`cannot ask "${question}" off a terminal`, 2, hint);
@@ -2082,12 +2285,22 @@ async function ask(question, { hint, terminal = process21 }, render, press) {
2082
2285
  const columns = () => stderr.columns || 80;
2083
2286
  const draw = (state, last = false) => {
2084
2287
  const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
2085
- stderr.write(`\r\x1B[0J${frame.join(`
2086
- `)}${last || frame.length < 2 ? "" : `\x1B[${frame.length - 1}A`}${last ? "" : "\r"}`);
2288
+ const rows = rowsTaken(frame, columns());
2289
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
2087
2290
  current = state;
2088
2291
  };
2089
2292
  const redraw = () => draw(current);
2090
2293
  const paste = { active: false };
2294
+ const stop = terminal.stop ?? (terminal === process23 ? stopJob : undefined);
2295
+ const suspend = () => {
2296
+ if (stop === undefined)
2297
+ return;
2298
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
2299
+ stdin.setRawMode(false);
2300
+ stop();
2301
+ stdin.setRawMode(true);
2302
+ stderr.write("\x1B[?25l\x1B[?2004h");
2303
+ };
2091
2304
  try {
2092
2305
  stderr.on?.("resize", redraw);
2093
2306
  stdin.setRawMode(true);
@@ -2097,6 +2310,10 @@ async function ask(question, { hint, terminal = process21 }, render, press) {
2097
2310
  return await new Promise((resolve) => {
2098
2311
  function onData(data) {
2099
2312
  for (const key of readKeys(data.toString(), paste)) {
2313
+ if (key === "suspend") {
2314
+ suspend();
2315
+ continue;
2316
+ }
2100
2317
  const pressed = press(key);
2101
2318
  if (pressed !== undefined) {
2102
2319
  settle(pressed);
@@ -2128,19 +2345,19 @@ async function ask(question, { hint, terminal = process21 }, render, press) {
2128
2345
  }
2129
2346
 
2130
2347
  // src/apply.ts
2131
- import { existsSync as existsSync9 } from "fs";
2348
+ import { existsSync as existsSync10 } from "fs";
2132
2349
  import { lstat as lstat3, rm } from "fs/promises";
2133
- import { basename as basename4, join as join12 } from "path";
2350
+ import { basename as basename4, join as join13 } from "path";
2134
2351
 
2135
2352
  // src/sweep-scan.ts
2136
- import { existsSync as existsSync8 } from "fs";
2353
+ import { existsSync as existsSync9 } from "fs";
2137
2354
  import { lstat as lstat2, readdir as readdir4, realpath } from "fs/promises";
2138
2355
  import { homedir as homedir5 } from "os";
2139
- import { basename as basename3, dirname as dirname5, join as join11 } from "path";
2356
+ import { basename as basename3, dirname as dirname5, join as join12 } from "path";
2140
2357
 
2141
2358
  // src/size.ts
2142
2359
  import { lstat, readdir as readdir3 } from "fs/promises";
2143
- import { join as join10 } from "path";
2360
+ import { join as join11 } from "path";
2144
2361
  var FS_LIMIT = 32;
2145
2362
  var FIND_MS = 60000;
2146
2363
  var FIND_LINE = /^(\d+) (\S+) (\d+)$/gm;
@@ -2168,7 +2385,7 @@ async function walkSize(folder) {
2168
2385
  return;
2169
2386
  }
2170
2387
  await Promise.all(entries.map(async (entry) => {
2171
- const path = join10(dir, entry.name);
2388
+ const path = join11(dir, entry.name);
2172
2389
  if (entry.isDirectory())
2173
2390
  return visit(path);
2174
2391
  try {
@@ -2212,12 +2429,13 @@ async function sizeOf(folder) {
2212
2429
  }
2213
2430
 
2214
2431
  // src/sweep-scan.ts
2215
- var FOLDER_NAMES = new Set(["node_modules", ".nuxt", ".next", ".output", "dist", "build", ".turbo", ".svelte-kit", "target"]);
2432
+ var FOLDER_NAMES = new Set(["node_modules", ".nuxt", ".next", ".output", "dist", "build", ".turbo", ".svelte-kit", "target", "vendor", ".venv", "__pycache__", ".gradle"]);
2433
+ var NEEDS_BESIDE = { target: ["Cargo.toml"], vendor: ["composer.json", "composer.lock"] };
2216
2434
  var MAX_DEPTH3 = 3;
2217
- var PROJECT_CACHE_NAMES = new Set([".turbo", ".nuxt", ".next", ".svelte-kit"]);
2435
+ var PROJECT_CACHE_NAMES = new Set([".turbo", ".nuxt", ".next", ".svelte-kit", "__pycache__", ".gradle"]);
2218
2436
  var GLOBAL_CACHES = [".bun/install/cache", ".npm/_cacache", ".cache/pip", ".cache/uv", ".cache/ms-playwright", ".cache/puppeteer", ".cache/go-build", ".cache/typescript", ".cargo/registry"];
2219
2437
  function isCachePath(path, home = homedir5()) {
2220
- return GLOBAL_CACHES.some((cache) => join11(home, cache) === path) || basename3(path) === ".cache" && basename3(dirname5(path)) === "node_modules";
2438
+ return GLOBAL_CACHES.some((cache) => join12(home, cache) === path) || basename3(path) === ".cache" && basename3(dirname5(path)) === "node_modules";
2221
2439
  }
2222
2440
  async function listing(dir) {
2223
2441
  try {
@@ -2228,7 +2446,7 @@ async function listing(dir) {
2228
2446
  }
2229
2447
  async function addGlobalCaches(found, home) {
2230
2448
  for (const cache of GLOBAL_CACHES) {
2231
- const path = join11(home, cache);
2449
+ const path = join12(home, cache);
2232
2450
  try {
2233
2451
  const stat = await lstat2(path);
2234
2452
  if (stat.isSymbolicLink())
@@ -2243,7 +2461,7 @@ async function findCandidates(root, home = homedir5(), withGlobal = true) {
2243
2461
  const visit = async (dir, depth) => {
2244
2462
  const entries = await listing(dir);
2245
2463
  for (const entry of entries) {
2246
- const path = join11(dir, entry.name);
2464
+ const path = join12(dir, entry.name);
2247
2465
  if (entry.name === ".git")
2248
2466
  continue;
2249
2467
  if (entry.name === ".worktrees" || entry.name === "worktrees" && basename3(dir) === ".claude") {
@@ -2253,13 +2471,13 @@ async function findCandidates(root, home = homedir5(), withGlobal = true) {
2253
2471
  }
2254
2472
  for (const worktree of await listing(path)) {
2255
2473
  if (worktree.isDirectory())
2256
- found.candidates.push({ path: join11(path, worktree.name), kind: "worktree" });
2474
+ found.candidates.push({ path: join12(path, worktree.name), kind: "worktree" });
2257
2475
  else if (worktree.isSymbolicLink())
2258
- found.skipped.push({ path: join11(path, worktree.name), reason: "symlink" });
2476
+ found.skipped.push({ path: join12(path, worktree.name), reason: "symlink" });
2259
2477
  }
2260
2478
  continue;
2261
2479
  }
2262
- if (FOLDER_NAMES.has(entry.name) && (entry.name !== "target" || existsSync8(join11(dir, "Cargo.toml")))) {
2480
+ if (FOLDER_NAMES.has(entry.name) && (NEEDS_BESIDE[entry.name]?.some((file) => existsSync9(join12(dir, file))) ?? true)) {
2263
2481
  if (entry.isSymbolicLink()) {
2264
2482
  found.skipped.push({ path, reason: "symlink" });
2265
2483
  } else if (entry.isDirectory()) {
@@ -2267,9 +2485,9 @@ async function findCandidates(root, home = homedir5(), withGlobal = true) {
2267
2485
  if (entry.name === "node_modules") {
2268
2486
  const cache = (await listing(path)).find((inner) => inner.name === ".cache");
2269
2487
  if (cache?.isSymbolicLink())
2270
- found.skipped.push({ path: join11(path, ".cache"), reason: "symlink" });
2488
+ found.skipped.push({ path: join12(path, ".cache"), reason: "symlink" });
2271
2489
  else if (cache?.isDirectory())
2272
- found.candidates.push({ path: join11(path, ".cache"), kind: "cache", inside: path });
2490
+ found.candidates.push({ path: join12(path, ".cache"), kind: "cache", inside: path });
2273
2491
  }
2274
2492
  }
2275
2493
  continue;
@@ -2345,7 +2563,7 @@ async function judgeFolder(path, kind, inside) {
2345
2563
  const located = await toplevelOf(parent);
2346
2564
  if (located === "failed")
2347
2565
  return { skip: "git failed" };
2348
- if (existsSync8(join11(path, ".git")))
2566
+ if (existsSync9(join12(path, ".git")))
2349
2567
  return { skip: "holds a git repository" };
2350
2568
  if (located === "none")
2351
2569
  return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside } } : { skip: "not in a git repository" };
@@ -2413,7 +2631,7 @@ async function removeFolder(entry) {
2413
2631
  const stat = await lstat3(entry.path);
2414
2632
  if (stat.isSymbolicLink() || !stat.isDirectory() || !(FOLDER_NAMES.has(basename4(entry.path)) || entry.kind === "cache" && isCachePath(entry.path)))
2415
2633
  return { path: entry.path, removed: false, error: "no longer a plain folder" };
2416
- if (existsSync9(join12(entry.path, ".git")))
2634
+ if (existsSync10(join13(entry.path, ".git")))
2417
2635
  return { path: entry.path, removed: false, error: "holds a git repository" };
2418
2636
  await rm(entry.path, { recursive: true, force: true });
2419
2637
  return { path: entry.path, removed: true };
@@ -2446,7 +2664,7 @@ async function applyAll(entries, done) {
2446
2664
  // src/sweep.ts
2447
2665
  var LARGE = 100 * 1024 ** 2;
2448
2666
  var BIG = 1024 ** 3;
2449
- var USAGE3 = `sweep [options] [root]: lists the regenerable folders (node_modules, .output, dist, build, target beside a Cargo.toml), the caches (.nuxt, .next, .turbo, .svelte-kit and node_modules/.cache per project; ~/.bun/install/cache, ~/.npm/_cacache, ~/.cache/{pip,uv,ms-playwright,puppeteer,go-build,typescript} and ~/.cargo/registry, exact paths only, listed only when no root is given or with --only caches) and the .worktrees/* and .claude/worktrees/* entries under root (the configured workspace, ~/Workspace by default, ${MAX_DEPTH3} levels down), largest first with the age of the repo's last commit; --only worktrees, folders or caches keeps one kind
2667
+ var USAGE3 = `sweep [options] [root]: lists the regenerable folders (node_modules, .output, dist, build, .venv, target beside a Cargo.toml, vendor beside a composer.json or composer.lock), the caches (.nuxt, .next, .turbo, .svelte-kit, __pycache__, .gradle and node_modules/.cache per project; ~/.bun/install/cache, ~/.npm/_cacache, ~/.cache/{pip,uv,ms-playwright,puppeteer,go-build,typescript} and ~/.cargo/registry, exact paths only, listed only when no root is given or with --only caches) and the .worktrees/* and .claude/worktrees/* entries under root (the configured workspace, ~/Workspace by default, ${MAX_DEPTH3} levels down), largest first with the age of the repo's last commit; --only worktrees, folders or caches keeps one kind
2450
2668
 
2451
2669
  Dry unless --apply, which deletes after a confirm showing the total (read from the terminal; off one, pass --yes). A folder is deleted for good, not trashed. Never touched: a symlink, a folder git tracks files in, a build folder git does not ignore. A worktree is removed with git worktree remove, never forced, and only when it is clean and every commit of its branch is on another branch or a remote; the others stay listed as kept and count for nothing in the total. With --docker the Docker usage comes after the list, left to dclean.`;
2452
2670
  var EXITS3 = [[0, "it listed, or removed every entry it was allowed to"], [1, "a removal failed or the confirm was declined"], [2, "a usage error, a missing root, or --apply off a terminal without --yes"]];
@@ -2456,7 +2674,7 @@ var OPTIONS3 = {
2456
2674
  yes: { type: "boolean", short: "y", description: "with --apply, skip the confirm" },
2457
2675
  older: { type: "string", description: "only the entries whose repo last committed longer ago than this (30d, 12h)" },
2458
2676
  min: { type: "string", description: "only the entries of at least this size (500K, 10M, 1G)" },
2459
- only: { type: "string", description: "worktrees, folders or caches: leave the other kinds out (.nuxt, .next, .turbo and .svelte-kit are caches; the global caches are listed with no root or with caches)" },
2677
+ only: { type: "string", description: "worktrees, folders or caches: leave the other kinds out (.nuxt, .next, .turbo, .svelte-kit, __pycache__ and .gradle are caches; the global caches are listed with no root or with caches)" },
2460
2678
  docker: { type: "boolean", description: "add the docker system df output, which alone takes about ten seconds" },
2461
2679
  json: jsonOption("{root, entries: [{path, kind (folder, worktree or cache), bytes, committedAt, action (remove or keep), reason}], skipped: [{path, reason}], reclaimable, docker, removed?}")
2462
2680
  };
@@ -2475,7 +2693,7 @@ async function sweep(args) {
2475
2693
  if (positionals.length > 1)
2476
2694
  badUsage("give one root");
2477
2695
  const root = workspaceRoot({ given: positionals[0] });
2478
- if (!existsSync10(root) || !statSync4(root).isDirectory())
2696
+ if (!existsSync11(root) || !statSync4(root).isDirectory())
2479
2697
  fail(`${root} is not a folder`);
2480
2698
  if (values.only !== undefined && !Object.hasOwn(ONLY_KINDS, values.only))
2481
2699
  badUsage(`--only takes worktrees, folders or caches, not ${values.only}`);
@@ -2549,7 +2767,7 @@ ${tt(reclaimable)} reclaimable${skipped === 0 ? "" : `, ${skipped} skipped (syml
2549
2767
  }
2550
2768
 
2551
2769
  // src/cli.ts
2552
- process22.exitCode = await runCli({
2770
+ process24.exitCode = await runCli({
2553
2771
  name: "ws",
2554
2772
  about: "the repositories under a root: the ones needing attention, the folders worth reclaiming and their known vulnerabilities",
2555
2773
  replaces: "a cd, git status and du loop over each repository of the workspace, and a bun audit run in each",
@@ -2557,6 +2775,6 @@ process22.exitCode = await runCli({
2557
2775
  commands: {
2558
2776
  repos: { summary: "the git repositories that need attention: dirty, ahead or behind, worktrees, unreleased commits", run: repos },
2559
2777
  sweep: { summary: "the regenerable folders, caches and clean worktrees, largest first, deleted only on --apply", run: sweep },
2560
- audit: { summary: "the known vulnerabilities of the Bun repositories, one table per repository", run: audit }
2778
+ audit: { summary: "the known vulnerabilities of the Bun, Composer, Cargo and uv repositories, one table per repository", run: audit }
2561
2779
  }
2562
2780
  });