@kaynooo/cli-workspace 0.3.0 → 0.5.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 process18 from "process";
5
+ import process20 from "process";
6
6
 
7
7
  // ../kit/src/advisory.ts
8
8
  var SEVERITIES = ["low", "moderate", "high", "critical"];
@@ -13,14 +13,35 @@ function isIgnored(advisory, ignore) {
13
13
  return ignore.includes(advisory.ghsa ?? "") || ignore.includes(String(advisory.id));
14
14
  }
15
15
  // ../kit/src/args.ts
16
- import process8 from "process";
16
+ import process9 from "process";
17
17
  import { parseArgs } from "util";
18
18
 
19
19
  // ../kit/src/format.ts
20
- import process6 from "process";
20
+ import process7 from "process";
21
+
22
+ // ../kit/src/mode.ts
23
+ import process2 from "process";
24
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
25
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
26
+ function isSet(value) {
27
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
28
+ }
29
+ function outputMode(stream = process2.stdout, env = process2.env) {
30
+ const chosen = env.KIT_MODE;
31
+ if (chosen !== undefined && MODES.has(chosen))
32
+ return chosen;
33
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
34
+ return "agent";
35
+ if (stream.isTTY === true)
36
+ return "terminal";
37
+ return isSet(env.CI) ? "ci" : "pipe";
38
+ }
39
+ function isInteractive(streams = process2) {
40
+ return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
41
+ }
21
42
 
22
43
  // ../kit/src/style.ts
23
- import process5 from "process";
44
+ import process6 from "process";
24
45
 
25
46
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
26
47
  function x(s) {
@@ -287,13 +308,13 @@ var t = le();
287
308
  import { existsSync as existsSync3, readFileSync, statSync } from "fs";
288
309
  import { homedir as homedir2 } from "os";
289
310
  import { join as join3, resolve as resolve2 } from "path";
290
- import process4 from "process";
311
+ import process5 from "process";
291
312
 
292
313
  // ../kit/src/config.ts
293
314
  import { existsSync } from "fs";
294
315
  import { dirname, join, resolve } from "path";
295
- import process2 from "process";
296
- function findUp(names, from = process2.cwd(), stop = () => false) {
316
+ import process3 from "process";
317
+ function findUp(names, from = process3.cwd(), stop = () => false) {
297
318
  const wanted = typeof names === "string" ? [names] : names;
298
319
  for (let dir = resolve(from);; dir = dirname(dir)) {
299
320
  const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
@@ -308,9 +329,9 @@ function findUp(names, from = process2.cwd(), stop = () => false) {
308
329
  import { existsSync as existsSync2 } from "fs";
309
330
  import { homedir } from "os";
310
331
  import { join as join2 } from "path";
311
- import process3 from "process";
332
+ import process4 from "process";
312
333
  function configBase(where = {}) {
313
- const xdg = where.xdg ?? (where.home === undefined ? process3.env.XDG_CONFIG_HOME : undefined);
334
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
314
335
  return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
315
336
  }
316
337
  function userConfigPath(bin, where = {}) {
@@ -350,10 +371,30 @@ function isColorSpec(spec) {
350
371
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
351
372
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
352
373
  }
353
- function tinted(colors, spec) {
374
+ var CUBE = [0, 95, 135, 175, 215, 255];
375
+ function cubeLevel(channel) {
376
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
377
+ }
378
+ function nearest256(hex) {
379
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
380
+ const levels = rgb.map(cubeLevel);
381
+ const cube = levels.map((level) => CUBE[level]);
382
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
383
+ const greyValue = 8 + grey * 10;
384
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
385
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
386
+ }
387
+ function hasTrueColor(env) {
388
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
389
+ }
390
+ function tinted(colors, spec, env = process5.env) {
354
391
  if (typeof spec === "number")
355
392
  return colors.ansi256(spec);
356
- return spec.trim().split(SPACES).reduce((chain, token) => HEX.test(token) ? chain.hex(token) : chain[token] ?? chain, colors);
393
+ return spec.trim().split(SPACES).reduce((chain, token) => {
394
+ if (HEX.test(token))
395
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
396
+ return chain[token] ?? chain;
397
+ }, colors);
357
398
  }
358
399
  function isRecord(value) {
359
400
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -437,7 +478,7 @@ function warnOnce(message) {
437
478
  function isPath(chosen) {
438
479
  return chosen.includes("/") || chosen.endsWith(".json");
439
480
  }
440
- function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(), warn = warnOnce } = {}) {
481
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
441
482
  const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
442
483
  const sources = [];
443
484
  const chosen = env.KIT_THEME ?? "";
@@ -467,7 +508,7 @@ function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(
467
508
  var current;
468
509
  var currentKey = "";
469
510
  function activeTheme() {
470
- const key = `${process4.cwd()}\x00${process4.env.KIT_THEME ?? ""}\x00${process4.env.XDG_CONFIG_HOME ?? ""}`;
511
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
471
512
  if (current === undefined || key !== currentKey) {
472
513
  current = loadTheme();
473
514
  currentKey = key;
@@ -477,38 +518,38 @@ function activeTheme() {
477
518
 
478
519
  // ../kit/src/style.ts
479
520
  var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:" };
480
- function takesControlCodes(stream, env = process5.env) {
481
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
521
+ function takesControlCodes(stream, env = process6.env) {
522
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
482
523
  }
483
- function paint(stream, env = process5.env) {
524
+ function paint(stream, env = process6.env) {
484
525
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
485
526
  }
486
- function marked(mark, text, stream, detail, env = process5.env) {
527
+ function marked(mark, text, stream, detail, env = process6.env) {
487
528
  const colors = paint(stream, env);
488
529
  let head = MARK_WORDS[mark];
489
530
  if (takesControlCodes(stream, env)) {
490
531
  const { theme } = activeTheme();
491
- head = tinted(colors.bold, theme.colors[mark])(theme.glyphs[mark]);
532
+ head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
492
533
  }
493
534
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
494
535
  }
495
536
  function ok(text, detail) {
496
- console.log(marked("ok", text, process5.stdout, detail));
537
+ console.log(marked("ok", text, process6.stdout, detail));
497
538
  }
498
539
  function note(text, detail) {
499
- console.log(marked("note", text, process5.stdout, detail));
540
+ console.log(marked("note", text, process6.stdout, detail));
500
541
  }
501
542
  function problem(text, detail) {
502
- console.error(marked("problem", text, process5.stderr, detail));
543
+ console.error(marked("problem", text, process6.stderr, detail));
503
544
  }
504
- function role(name, stream, env = process5.env) {
545
+ function role(name, stream, env = process6.env) {
505
546
  const colors = paint(stream, env);
506
- return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name]) : colors;
547
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
507
548
  }
508
549
  var STATUS_WORDS = {
509
550
  passed: ["passed", "success", "succeeded", "ok"],
510
551
  failed: ["failed", "failure", "error", "errored"],
511
- running: ["running", "in_progress", "started"],
552
+ running: ["running", "in_progress", "started", "holding"],
512
553
  queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
513
554
  skipped: ["skipped", "cancelled", "canceled", "manual"]
514
555
  };
@@ -562,8 +603,11 @@ var ESCAPE = String.fromCharCode(27);
562
603
  function textWidth(text) {
563
604
  return Bun.stringWidth(text);
564
605
  }
565
- function table(rows, { cellWidth, header = false, align = [], fit, stream = process6.stdout } = {}) {
606
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
566
607
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
608
+ if (outputMode(stream, env) === "agent")
609
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
610
+ `);
567
611
  const widths = [];
568
612
  for (const row of cells) {
569
613
  for (const [index, cell] of row.entries())
@@ -598,32 +642,35 @@ function narrow(rows, widths, limit) {
598
642
  }
599
643
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
600
644
  }
645
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
646
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
647
+ }
601
648
  function printJson(value) {
602
- console.log(JSON.stringify(value, undefined, 2));
649
+ console.log(jsonText(value));
603
650
  }
604
651
 
605
652
  // ../kit/src/help.ts
606
- import process7 from "process";
653
+ import process8 from "process";
607
654
  var OPTIONAL = /\[[^\]]+\]/g;
608
655
  var USAGE_PREFIX = /^usage:\s*/i;
609
656
  var FULL_STOP = /\.$/;
610
- function usageLine(usage, colors = paint(process7.stdout)) {
657
+ function usageLine(usage, colors = paint(process8.stdout)) {
611
658
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
612
659
  }
613
- function helpText(usage, options, colors = paint(process7.stdout), { examples = [], replaces, exits = [] } = {}) {
660
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
614
661
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
615
662
  `);
616
663
  }
617
- function exitRows(exits, colors = paint(process7.stdout)) {
664
+ function exitRows(exits, colors = paint(process8.stdout)) {
618
665
  if (exits.length === 0)
619
666
  return [];
620
667
  const width = Math.max(...exits.map(([code]) => String(code).length));
621
668
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
622
669
  }
623
- function replacesRows(replaces, colors = paint(process7.stdout)) {
624
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
670
+ function replacesRows(replaces, colors = paint(process8.stdout)) {
671
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
625
672
  }
626
- function wantsHelpJson(env = process7.env) {
673
+ function wantsHelpJson(env = process8.env) {
627
674
  return env.KIT_HELP === "json";
628
675
  }
629
676
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -642,12 +689,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
642
689
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
643
690
  };
644
691
  }
645
- function exampleRows(examples, colors = paint(process7.stdout)) {
646
- if (examples.length === 0)
692
+ function exampleRows(examples, colors = paint(process8.stdout)) {
693
+ if (examples.length === 0 || outputMode() === "agent")
647
694
  return [];
648
695
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
649
696
  }
650
- function optionRows(options, colors = paint(process7.stdout)) {
697
+ function optionRows(options, colors = paint(process8.stdout)) {
651
698
  const rows = Object.entries(options).map(([name, option]) => {
652
699
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
653
700
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -740,7 +787,7 @@ var OUTPUT_OPTIONS = {
740
787
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
741
788
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
742
789
  };
743
- function applyOutput(color, plain, env = process8.env) {
790
+ function applyOutput(color, plain, env = process9.env) {
744
791
  const when = plain === true ? "never" : color ?? "auto";
745
792
  if (when === "auto")
746
793
  return;
@@ -911,7 +958,7 @@ function nearestOption(message, options, allowNegative) {
911
958
  }
912
959
  // ../kit/src/process.ts
913
960
  import { constants } from "os";
914
- import process9 from "process";
961
+ import process10 from "process";
915
962
  var KILL_GRACE_MS = 2000;
916
963
  function exitCodeOf(code, signal) {
917
964
  if (code !== null)
@@ -931,7 +978,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
931
978
  return;
932
979
  try {
933
980
  if (grouped)
934
- process9.kill(-proc.pid, killing);
981
+ process10.kill(-proc.pid, killing);
935
982
  else
936
983
  proc.kill(killing);
937
984
  } catch {}
@@ -1006,10 +1053,10 @@ var RESET_STYLE = `${ESC}[0m`;
1006
1053
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1007
1054
 
1008
1055
  // ../kit/src/tool.ts
1009
- import process10 from "process";
1056
+ import process11 from "process";
1010
1057
  function cwdGone() {
1011
1058
  try {
1012
- process10.cwd();
1059
+ process11.cwd();
1013
1060
  return false;
1014
1061
  } catch {
1015
1062
  return true;
@@ -1031,7 +1078,7 @@ function spawnFailure(command, error) {
1031
1078
  async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
1032
1079
  let ran;
1033
1080
  try {
1034
- ran = await runCommand(argv, { env: process10.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1081
+ ran = await runCommand(argv, { env: process11.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1035
1082
  } catch (error) {
1036
1083
  throw spawnFailure(label, error);
1037
1084
  }
@@ -1048,13 +1095,13 @@ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
1048
1095
  // ../kit/src/cli.ts
1049
1096
  import { readFileSync as readFileSync2, realpathSync } from "fs";
1050
1097
  import { dirname as dirname3, join as join5 } from "path";
1051
- import process12 from "process";
1098
+ import process13 from "process";
1052
1099
 
1053
1100
  // ../kit/src/usage.ts
1054
1101
  import { appendFileSync, mkdirSync } from "fs";
1055
1102
  import { homedir as homedir3 } from "os";
1056
1103
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1057
- import process11 from "process";
1104
+ import process12 from "process";
1058
1105
 
1059
1106
  // ../kit/src/logs.ts
1060
1107
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -1068,14 +1115,14 @@ var usageError;
1068
1115
  function noteUsageError(message) {
1069
1116
  usageError = message;
1070
1117
  }
1071
- function stateHome(env = process11.env) {
1118
+ function stateHome(env = process12.env) {
1072
1119
  const dir = env.XDG_STATE_HOME;
1073
1120
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1074
1121
  }
1075
- function usagePath(env = process11.env) {
1122
+ function usagePath(env = process12.env) {
1076
1123
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1077
1124
  }
1078
- function usageRecorded(env = process11.env) {
1125
+ function usageRecorded(env = process12.env) {
1079
1126
  const off = env.KAYNOOO_CLI_NO_USAGE;
1080
1127
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1081
1128
  }
@@ -1089,7 +1136,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1089
1136
  usageError = undefined;
1090
1137
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1091
1138
  }
1092
- function recordUsage(entry, env = process11.env) {
1139
+ function recordUsage(entry, env = process12.env) {
1093
1140
  if (!usageRecorded(env))
1094
1141
  return;
1095
1142
  try {
@@ -1180,8 +1227,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1180
1227
  `);
1181
1228
  }
1182
1229
  function printError(prefix, message, hint, cause) {
1183
- const colors = paint(process12.stderr);
1184
- const styled = takesControlCodes(process12.stderr);
1230
+ const colors = paint(process13.stderr);
1231
+ const styled = takesControlCodes(process13.stderr);
1185
1232
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1186
1233
  const under = (label, text, tint) => text === undefined ? "" : `
1187
1234
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1224,11 +1271,11 @@ async function dispatch(level, typed, { version, redact }) {
1224
1271
  }
1225
1272
  }
1226
1273
  if (name === undefined && level.path.length > 1) {
1227
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
1274
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1228
1275
  return 2;
1229
1276
  }
1230
1277
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1231
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
1278
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1232
1279
  return 0;
1233
1280
  }
1234
1281
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1355,7 +1402,7 @@ function packageVersion(entry = Bun.main) {
1355
1402
  return "0.0.0";
1356
1403
  }
1357
1404
  }
1358
- async function runCli(cli, argv = process12.argv.slice(2)) {
1405
+ async function runCli(cli, argv = process13.argv.slice(2)) {
1359
1406
  const version = cli.version ?? packageVersion();
1360
1407
  if (argv[0] === COMPLETE)
1361
1408
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -1382,7 +1429,7 @@ function commandPath(scope, argv) {
1382
1429
  }
1383
1430
  return path.length === 0 ? undefined : path.join(" ");
1384
1431
  }
1385
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1432
+ async function runMain({ name, version, run, redact, usage }, argv = process13.argv.slice(2)) {
1386
1433
  if (argv[0] === COMPLETE)
1387
1434
  return printCandidates(leafCandidates(run, argv.slice(1)));
1388
1435
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1402,6 +1449,19 @@ async function runMain({ name, version, run, redact, usage }, argv = process12.a
1402
1449
  }
1403
1450
  return code;
1404
1451
  }
1452
+ // ../kit/src/pool.ts
1453
+ async function pool(items, limit, task) {
1454
+ const results = Array.from({ length: items.length });
1455
+ let next = 0;
1456
+ async function worker() {
1457
+ while (next < items.length) {
1458
+ const index = next++;
1459
+ results[index] = await task(items[index]);
1460
+ }
1461
+ }
1462
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1463
+ return results;
1464
+ }
1405
1465
  // ../kit/src/secrets.ts
1406
1466
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1407
1467
  // ../kit/src/sessions.ts
@@ -1418,15 +1478,41 @@ function parseSize(text, bareUnit = 1) {
1418
1478
  const suffix = match[2].toLowerCase();
1419
1479
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1420
1480
  }
1481
+ // ../kit/src/workspace-root.ts
1482
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
1483
+ import { homedir as homedir4 } from "os";
1484
+ import { dirname as dirname4, join as join6, resolve as resolve3 } from "path";
1485
+ import process14 from "process";
1486
+ function expandHome(path, home) {
1487
+ if (path === "~")
1488
+ return home;
1489
+ return path.startsWith("~/") ? join6(home, path.slice(2)) : path;
1490
+ }
1491
+ function configured(env, home) {
1492
+ const path = userConfigPath("config", { home, xdg: env.XDG_CONFIG_HOME });
1493
+ if (!existsSync4(path))
1494
+ return;
1495
+ try {
1496
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
1497
+ const folder = typeof parsed === "object" && parsed !== null ? parsed.workspace : undefined;
1498
+ return typeof folder === "string" && folder !== "" ? folder : undefined;
1499
+ } catch {
1500
+ return;
1501
+ }
1502
+ }
1503
+ function workspaceRoot({ given, env = process14.env, home = homedir4() } = {}) {
1504
+ const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1505
+ return resolve3(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1506
+ }
1421
1507
  // src/audit.ts
1422
- import { existsSync as existsSync5, readdirSync, statSync as statSync2 } from "fs";
1508
+ import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
1423
1509
  import { readdir } from "fs/promises";
1424
- import { join as join7, relative, resolve as resolve3 } from "path";
1425
- import process14 from "process";
1510
+ import { join as join8, relative, resolve as resolve4 } from "path";
1511
+ import process16 from "process";
1426
1512
 
1427
1513
  // src/report.ts
1428
- import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
1429
- import { join as join6 } from "path";
1514
+ import { existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
1515
+ import { join as join7 } from "path";
1430
1516
  var UPPER_BOUND = /<\s*(\d[\w.+-]*)/;
1431
1517
  var DEPENDENCY_KINDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
1432
1518
  var GHSA = /GHSA-[\w-]+$/;
@@ -1450,7 +1536,7 @@ function fixFor(advisories) {
1450
1536
  return;
1451
1537
  return fixes.reduce((highest, fix) => Bun.semver.order(fix, highest) > 0 ? fix : highest);
1452
1538
  }
1453
- function findingsOf(audit, reaching, direct, level, ignore = []) {
1539
+ function findingsOf(audit, reaching, direct, level, ignore = [], via = new Map) {
1454
1540
  const found = [];
1455
1541
  for (const [name, all] of Object.entries(audit)) {
1456
1542
  const kept = all.filter((advisory) => severityRank(advisory.severity) >= severityRank(level) && !isIgnored({ id: advisory.id, ghsa: GHSA.exec(advisory.url)?.[0] }, ignore));
@@ -1463,14 +1549,53 @@ function findingsOf(audit, reaching, direct, level, ignore = []) {
1463
1549
  advisories,
1464
1550
  scope: reaching.has(name) ? "prod" : "dev",
1465
1551
  direct: direct.has(name),
1552
+ via: direct.has(name) ? [] : via.get(name) ?? [],
1466
1553
  fix: fixFor(kept)
1467
1554
  });
1468
1555
  }
1469
1556
  return found.toSorted((a, b) => severityRank(b.severity) - severityRank(a.severity) || Number(b.scope === "prod") - Number(a.scope === "prod") || a.package.localeCompare(b.package));
1470
1557
  }
1558
+ function lockGraph(lockText) {
1559
+ const graph = new Map;
1560
+ let lock;
1561
+ try {
1562
+ lock = Bun.JSONC.parse(lockText);
1563
+ } catch {
1564
+ return graph;
1565
+ }
1566
+ for (const entry of Object.values(lock?.packages ?? {})) {
1567
+ const resolution = entry[0];
1568
+ const info = entry[2];
1569
+ if (typeof resolution !== "string" || typeof info !== "object" || info === null)
1570
+ continue;
1571
+ const at = resolution.indexOf("@", 1);
1572
+ const name = at === -1 ? resolution : resolution.slice(0, at);
1573
+ const wanted = DEPENDENCY_KINDS.flatMap((kind) => Object.keys(info[kind] ?? {}));
1574
+ graph.set(name, [...new Set([...graph.get(name) ?? [], ...wanted])]);
1575
+ }
1576
+ return graph;
1577
+ }
1578
+ function reachedFrom(graph, direct, targets) {
1579
+ const from = new Map;
1580
+ for (const start of direct) {
1581
+ const seen = new Set([start]);
1582
+ const queue = [start];
1583
+ for (let name = queue.shift();name !== undefined; name = queue.shift()) {
1584
+ if (name !== start && targets.has(name))
1585
+ from.set(name, [...from.get(name) ?? [], start]);
1586
+ for (const next of graph.get(name) ?? []) {
1587
+ if (!seen.has(next)) {
1588
+ seen.add(next);
1589
+ queue.push(next);
1590
+ }
1591
+ }
1592
+ }
1593
+ }
1594
+ return new Map([...from].map(([name, starts]) => [name, starts.toSorted()]));
1595
+ }
1471
1596
  function readManifest(path) {
1472
1597
  try {
1473
- return existsSync4(path) ? JSON.parse(readFileSync3(path, "utf8")) : {};
1598
+ return existsSync5(path) ? JSON.parse(readFileSync4(path, "utf8")) : {};
1474
1599
  } catch {
1475
1600
  return {};
1476
1601
  }
@@ -1482,9 +1607,9 @@ function namesIn(manifest) {
1482
1607
  });
1483
1608
  }
1484
1609
  function directDependencies(root, workspaces) {
1485
- const names = new Set(namesIn(readManifest(join6(root, "package.json"))));
1610
+ const names = new Set(namesIn(readManifest(join7(root, "package.json"))));
1486
1611
  for (const workspace of workspaces) {
1487
- for (const name of namesIn(readManifest(join6(root, workspace, "package.json"))))
1612
+ for (const name of namesIn(readManifest(join7(root, workspace, "package.json"))))
1488
1613
  names.add(name);
1489
1614
  }
1490
1615
  return names;
@@ -1496,15 +1621,15 @@ function workspacePatterns(field) {
1496
1621
  return Array.isArray(packages) ? packages : [];
1497
1622
  }
1498
1623
  function workspaceFolders(root, children) {
1499
- const patterns = workspacePatterns(readManifest(join6(root, "package.json")).workspaces);
1500
- return patterns.filter((pattern) => typeof pattern === "string").flatMap((pattern) => pattern.endsWith("/*") ? children(pattern.slice(0, -2)).map((name) => join6(pattern.slice(0, -2), name)) : [pattern]);
1624
+ const patterns = workspacePatterns(readManifest(join7(root, "package.json")).workspaces);
1625
+ 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]);
1501
1626
  }
1502
1627
 
1503
1628
  // src/audit.ts
1504
1629
  var USAGE = `audit [options] [root]: the known vulnerabilities of the Bun repositories under root (the current folder by default), one table per repository
1505
1630
 
1506
- 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 version that fixes every advisory at once, "-" when an advisory names none. The worst and the production ones come first.
1507
- 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.
1631
+ 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.
1632
+ 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.
1508
1633
 
1509
1634
  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.`;
1510
1635
  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"]];
@@ -1512,13 +1637,18 @@ var OPTIONS = {
1512
1637
  level: { type: "string", choices: SEVERITIES, default: "moderate", description: "only the advisories at least this severe: low, moderate, high or critical" },
1513
1638
  prod: { type: "boolean", description: "only the packages a production dependency needs" },
1514
1639
  ignore: { type: "string", multiple: true, description: "an advisory skipped by GHSA or numeric id, repeatable" },
1515
- json: jsonOption("[{repo, path, findings: [{package, severity, scope, direct, fix, advisories: [{id, ghsa, url, title, severity, fixed}]}], error}]")
1640
+ json: jsonOption("[{repo, path, findings: [{package, severity, scope, direct, via, fix, advisories: [{id, ghsa, url, title, severity, fixed}]}], error}]")
1516
1641
  };
1517
1642
  var MAX_DEPTH = 3;
1518
1643
  var CONCURRENCY = 4;
1519
1644
  var AUDIT_MS = 60000;
1645
+ var WARNING = /^warn: .+$/gm;
1646
+ var VIA_SHOWN = 2;
1647
+ function countAdvisories(findings) {
1648
+ return findings.reduce((sum, found) => sum + found.advisories.length, 0);
1649
+ }
1520
1650
  function holdsLock(dir) {
1521
- return existsSync5(join7(dir, "bun.lock")) || existsSync5(join7(dir, "bun.lockb"));
1651
+ return existsSync6(join8(dir, "bun.lock")) || existsSync6(join8(dir, "bun.lockb"));
1522
1652
  }
1523
1653
  async function findRepos(root) {
1524
1654
  if (holdsLock(root))
@@ -1534,7 +1664,7 @@ async function findRepos(root) {
1534
1664
  for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1535
1665
  if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith("."))
1536
1666
  continue;
1537
- const path = join7(dir, entry.name);
1667
+ const path = join8(dir, entry.name);
1538
1668
  if (holdsLock(path))
1539
1669
  found.push(path);
1540
1670
  else if (depth < MAX_DEPTH)
@@ -1544,22 +1674,10 @@ async function findRepos(root) {
1544
1674
  await walk(root, 1);
1545
1675
  return found;
1546
1676
  }
1547
- async function pool(items, limit, task) {
1548
- const results = Array.from({ length: items.length });
1549
- let next = 0;
1550
- async function worker() {
1551
- while (next < items.length) {
1552
- const index = next++;
1553
- results[index] = await task(items[index]);
1554
- }
1555
- }
1556
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1557
- return results;
1558
- }
1559
1677
  function children(root) {
1560
1678
  return (folder) => {
1561
1679
  try {
1562
- return readdirSync(join7(root, folder), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
1680
+ return readdirSync(join8(root, folder), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
1563
1681
  } catch {
1564
1682
  return [];
1565
1683
  }
@@ -1573,10 +1691,26 @@ async function audited(path, shown, level, ignore) {
1573
1691
  const audit = parseAudit(stdoutOf(all));
1574
1692
  const reached = parseAudit(stdoutOf(production));
1575
1693
  if (audit === undefined || reached === undefined)
1576
- return { repo: shown, path, findings: [], error: failure(audit === undefined ? all : production) };
1694
+ return { repo: shown, path, findings: [], below: 0, warnings: [], error: failure(audit === undefined ? all : production) };
1577
1695
  const reaching = new Set(Object.keys(reached));
1578
1696
  const direct = directDependencies(path, workspaceFolders(path, children(path)));
1579
- return { repo: shown, path, findings: findingsOf(audit, reaching, direct, level, ignore), error: undefined };
1697
+ const via = reachedFrom(lockGraph(lockText(path)), direct, new Set(Object.keys(audit)));
1698
+ const findings = findingsOf(audit, reaching, direct, level, ignore, via);
1699
+ return { repo: shown, path, findings, below: countAdvisories(findingsOf(audit, reaching, direct, "low", ignore)) - countAdvisories(findings), warnings: [...new Set(all.text.match(WARNING) ?? [])], error: undefined };
1700
+ }
1701
+ function lockText(path) {
1702
+ try {
1703
+ return readFileSync5(join8(path, "bun.lock"), "utf8");
1704
+ } catch {
1705
+ return "";
1706
+ }
1707
+ }
1708
+ function originOf(found) {
1709
+ if (found.direct)
1710
+ return "direct";
1711
+ if (found.via.length === 0)
1712
+ return "via";
1713
+ return `via ${found.via.slice(0, VIA_SHOWN).join(", ")}${found.via.length > VIA_SHOWN ? ` +${found.via.length - VIA_SHOWN}` : ""}`;
1580
1714
  }
1581
1715
  function stdoutOf(ran) {
1582
1716
  return Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
@@ -1586,7 +1720,7 @@ function failure(ran) {
1586
1720
  `).at(-1) ?? `exit ${ran.code}`;
1587
1721
  }
1588
1722
  function tint(severity) {
1589
- const colors = paint(process14.stdout);
1723
+ const colors = paint(process16.stdout);
1590
1724
  if (severity === "critical" || severity === "high")
1591
1725
  return colors.red;
1592
1726
  return severity === "moderate" ? colors.yellow : colors.dim;
@@ -1597,14 +1731,14 @@ function rows(findings) {
1597
1731
  tint(found.severity)(found.severity),
1598
1732
  String(found.advisories.length),
1599
1733
  found.scope,
1600
- found.direct ? "direct" : "via",
1734
+ originOf(found),
1601
1735
  found.fix ?? "-"
1602
1736
  ]);
1603
1737
  }
1604
1738
  async function audit(args) {
1605
1739
  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"] });
1606
- const root = resolve3(positionals[0] ?? ".");
1607
- if (!existsSync5(root) || !statSync2(root).isDirectory())
1740
+ const root = resolve4(positionals[0] ?? ".");
1741
+ if (!existsSync6(root) || !statSync2(root).isDirectory())
1608
1742
  fail(`no folder ${root}`);
1609
1743
  const level = oneOf(values.level, "level", SEVERITIES);
1610
1744
  const paths = await findRepos(root);
@@ -1621,8 +1755,8 @@ async function audit(args) {
1621
1755
  return kept.some((each) => each.findings.length > 0) ? 1 : 0;
1622
1756
  }
1623
1757
  function show(audits, total) {
1624
- const label = role("label", process14.stdout);
1625
- const path = role("path", process14.stdout);
1758
+ const label = role("label", process16.stdout);
1759
+ const path = role("path", process16.stdout);
1626
1760
  const flagged = audits.filter((each) => each.error !== undefined || each.findings.length > 0);
1627
1761
  if (flagged.length === 0) {
1628
1762
  console.log(label(`no advisory in ${total} ${total === 1 ? "repository" : "repositories"}`));
@@ -1632,22 +1766,28 @@ function show(audits, total) {
1632
1766
  console.log(`${path(each.repo)} ${label(each.error === undefined ? `${each.findings.length} ${each.findings.length === 1 ? "package" : "packages"}` : `audit failed: ${each.error}`)}`);
1633
1767
  if (each.findings.length > 0)
1634
1768
  console.log(table([["package", "severity", "advisories", "scope", "origin", "fix"], ...rows(each.findings)], { header: true, align: ["left", "left", "right", "left", "left", "left"] }));
1769
+ if (each.findings.some((found) => !found.direct))
1770
+ console.log(label("via: a dependency of the ones named, fixed by upgrading one of them to a release that depends on the fixed version"));
1771
+ if (each.below > 0)
1772
+ console.log(label(`${each.below} ${each.below === 1 ? "advisory" : "advisories"} below the level left out, --level low lists them`));
1773
+ for (const warning of each.warnings)
1774
+ console.log(label(warning));
1635
1775
  }
1636
1776
  }
1637
1777
 
1638
1778
  // src/repos.ts
1639
- import { existsSync as existsSync7, statSync as statSync3 } from "fs";
1640
- import { homedir as homedir4 } from "os";
1641
- import { join as join9, relative as relative2, resolve as resolve4 } from "path";
1642
- import process16 from "process";
1779
+ import { existsSync as existsSync8, statSync as statSync3 } from "fs";
1780
+ import { relative as relative2 } from "path";
1781
+ import process18 from "process";
1643
1782
 
1644
1783
  // src/repos-scan.ts
1645
- import { existsSync as existsSync6 } from "fs";
1784
+ import { existsSync as existsSync7 } from "fs";
1646
1785
  import { readdir as readdir2 } from "fs/promises";
1647
- import { basename, join as join8 } from "path";
1648
- import process15 from "process";
1786
+ import { basename, join as join9 } from "path";
1787
+ import process17 from "process";
1649
1788
  var MAX_DEPTH2 = 3;
1650
1789
  var CONCURRENCY2 = 8;
1790
+ var PACKAGE_CONCURRENCY = 4;
1651
1791
  var GIT_MS = 1e4;
1652
1792
  var FETCH_MS = 30000;
1653
1793
  var AHEAD_BEHIND = /\+(\d+) -(\d+)/;
@@ -1666,7 +1806,7 @@ function reasonsOf(repo) {
1666
1806
  return reasons;
1667
1807
  }
1668
1808
  async function findRepos2(root, skip) {
1669
- if (existsSync6(join8(root, ".git")))
1809
+ if (existsSync7(join9(root, ".git")))
1670
1810
  return [root];
1671
1811
  const found = [];
1672
1812
  async function walk(dir, depth) {
@@ -1679,8 +1819,8 @@ async function findRepos2(root, skip) {
1679
1819
  for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1680
1820
  if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith(".") || skip.has(entry.name))
1681
1821
  continue;
1682
- const path = join8(dir, entry.name);
1683
- if (existsSync6(join8(path, ".git")))
1822
+ const path = join9(dir, entry.name);
1823
+ if (existsSync7(join9(path, ".git")))
1684
1824
  found.push(path);
1685
1825
  else if (depth < MAX_DEPTH2)
1686
1826
  await walk(path, depth + 1);
@@ -1691,7 +1831,7 @@ async function findRepos2(root, skip) {
1691
1831
  }
1692
1832
  async function read(path, args, timeoutMs = GIT_MS) {
1693
1833
  try {
1694
- const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process15.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
1834
+ const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process17.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
1695
1835
  return ran.code === 0 && !ran.timedOut ? ran.text.trim() : undefined;
1696
1836
  } catch {
1697
1837
  return;
@@ -1709,14 +1849,12 @@ async function packageReleases(path) {
1709
1849
  if (name !== undefined)
1710
1850
  names.add(name);
1711
1851
  }
1712
- const releases = [];
1713
- for (const name of [...names].toSorted()) {
1714
- const folder = [join8("packages", name), name].find((candidate) => existsSync6(join8(path, candidate)));
1852
+ const releases = await pool([...names].toSorted(), PACKAGE_CONCURRENCY, async (name) => {
1853
+ const folder = [join9("packages", name), name].find((candidate) => existsSync7(join9(path, candidate)));
1715
1854
  const tag = folder === undefined ? undefined : await read(path, ["describe", "--tags", "--abbrev=0", "--match", `${name}-v*`]);
1716
- if (folder !== undefined && tag !== undefined && tag !== "")
1717
- releases.push({ name, tag, unreleased: await commitsSince(path, tag, folder) });
1718
- }
1719
- return releases;
1855
+ return folder !== undefined && tag !== undefined && tag !== "" ? { name, tag, unreleased: await commitsSince(path, tag, folder) } : undefined;
1856
+ });
1857
+ return releases.filter((release) => release !== undefined);
1720
1858
  }
1721
1859
  async function inspect(path, fetch) {
1722
1860
  const fetched = fetch ? await read(path, ["fetch", "--quiet"], FETCH_MS) : "";
@@ -1770,7 +1908,7 @@ function firstLine(text) {
1770
1908
  }
1771
1909
  async function fastForward(path) {
1772
1910
  try {
1773
- const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...process15.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs: GIT_MS });
1911
+ const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...process17.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs: GIT_MS });
1774
1912
  if (ran.timedOut)
1775
1913
  return "timed out";
1776
1914
  return ran.code === 0 ? undefined : firstLine(ran.text.trim()) || `exit ${ran.code}`;
@@ -1778,21 +1916,9 @@ async function fastForward(path) {
1778
1916
  return error instanceof Error ? error.message : String(error);
1779
1917
  }
1780
1918
  }
1781
- async function pool2(items, limit, task) {
1782
- const results = new Array(items.length);
1783
- let next = 0;
1784
- async function worker() {
1785
- while (next < items.length) {
1786
- const index = next++;
1787
- results[index] = await task(items[index]);
1788
- }
1789
- }
1790
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1791
- return results;
1792
- }
1793
1919
 
1794
1920
  // src/repos.ts
1795
- var USAGE2 = `repos [options] [root]: the git repositories under root (~/Workspace by default) that need attention, with their branch, dirty files, ahead/behind their upstream, linked worktrees and commits since their latest tag
1921
+ var USAGE2 = `repos [options] [root]: the git repositories under root (the configured workspace, ~/Workspace by default) that need attention, with their branch, dirty files, ahead/behind their upstream, linked worktrees and commits since their latest tag
1796
1922
 
1797
1923
  A repository with nothing to report is left out unless --all. A monorepo tagging its packages <folder>-v<version> counts the unreleased commits per package folder. The walk goes ${MAX_DEPTH2} levels deep, stops at a .git and skips node_modules, hidden folders and the names in "skip" of ~/.config/kaynooo-cli/repos.json.
1798
1924
 
@@ -1810,7 +1936,7 @@ var OPTIONS2 = {
1810
1936
  };
1811
1937
  async function skipped() {
1812
1938
  const file = userConfigReadPath("repos");
1813
- if (!existsSync7(file))
1939
+ if (!existsSync8(file))
1814
1940
  return new Set;
1815
1941
  try {
1816
1942
  const config = await Bun.file(file).json();
@@ -1824,7 +1950,7 @@ function releasedCell(repo) {
1824
1950
  return repo.packages.filter((release) => release.unreleased > 0).map((release) => `${release.name} ${release.unreleased}`).join(", ") || "-";
1825
1951
  return repo.tag === null || repo.unreleased === 0 ? "-" : `${repo.unreleased} since ${repo.tag}`;
1826
1952
  }
1827
- function syncCell(repo, stream = process16.stdout) {
1953
+ function syncCell(repo, stream = process18.stdout) {
1828
1954
  const colors = paint(stream);
1829
1955
  const ahead = repo.ahead ?? 0;
1830
1956
  const behind = repo.behind ?? 0;
@@ -1834,15 +1960,18 @@ function syncCell(repo, stream = process16.stdout) {
1834
1960
  const diverged = takesControlCodes(stream) && ahead > 0 && behind > 0;
1835
1961
  return parts.length === 0 ? colors.dim("-") : `${parts.join(" ")}${diverged ? colors.yellow(" diverged") : ""}`;
1836
1962
  }
1837
- function branchCell(repo) {
1838
- const colors = paint(process16.stdout);
1963
+ var DEFAULT_BRANCHES = new Set(["main", "master"]);
1964
+ function branchCell(repo, stream = process18.stdout) {
1965
+ const colors = paint(stream);
1839
1966
  if (repo.unreadable)
1840
1967
  return colors.red("? (unreadable)");
1841
- return repo.branch === "(detached)" ? colors.yellow(repo.branch) : repo.branch;
1968
+ if (repo.branch === "(detached)")
1969
+ return colors.yellow(repo.branch);
1970
+ return DEFAULT_BRANCHES.has(repo.branch) ? repo.branch : role("accent", stream)(repo.branch);
1842
1971
  }
1843
1972
  function row(repo, shown) {
1844
- const colors = paint(process16.stdout);
1845
- const tint = role("path", process16.stdout);
1973
+ const colors = paint(process18.stdout);
1974
+ const tint = role("path", process18.stdout);
1846
1975
  const unreleased = releasedCell(repo);
1847
1976
  return [
1848
1977
  tint(shown),
@@ -1855,12 +1984,12 @@ function row(repo, shown) {
1855
1984
  }
1856
1985
  async function repos(args) {
1857
1986
  const { values, positionals } = parse(args, USAGE2, OPTIONS2, { positionals: ["[root]"], exits: EXITS2, replaces: "a cd, git status, git log and git tag loop over each repository of the workspace", examples: ["repos", "repos ~/Workspace --only unreleased --fetch", ["repos --only behind --pull", "fast-forward what is behind and clean"], ["repos --only dirty --path", "the paths, for xargs"]] });
1858
- const root = resolve4(positionals[0] ?? join9(homedir4(), "Workspace"));
1859
- if (!existsSync7(root) || !statSync3(root).isDirectory())
1987
+ const root = workspaceRoot({ given: positionals[0] });
1988
+ if (!existsSync8(root) || !statSync3(root).isDirectory())
1860
1989
  fail(`no folder ${root}`);
1861
1990
  const only = values.only === undefined ? undefined : oneOf(values.only, "only", REASONS);
1862
1991
  const paths = await findRepos2(root, await skipped());
1863
- const states = await pool2(paths, CONCURRENCY2, async (path) => inspect(path, values.fetch === true || values.pull === true));
1992
+ const states = await pool(paths, CONCURRENCY2, async (path) => inspect(path, values.fetch === true || values.pull === true));
1864
1993
  const keeps = (repo) => {
1865
1994
  const reasons = reasonsOf(repo);
1866
1995
  return only === undefined ? values.all === true || reasons.length > 0 || repo.unreadable : reasons.includes(only);
@@ -1874,12 +2003,12 @@ async function repos(args) {
1874
2003
  const blocker = pullBlocker(repo);
1875
2004
  const refused = blocker === undefined ? await fastForward(repo.path) : undefined;
1876
2005
  if (blocker !== undefined) {
1877
- log(marked("note", `${repo.name} skipped`, process16.stdout, blocker));
2006
+ log(marked("note", `${repo.name} skipped`, process18.stdout, blocker));
1878
2007
  } else if (refused !== undefined) {
1879
2008
  failedPulls++;
1880
- log(marked("problem", `${repo.name} not pulled`, process16.stdout, refused));
2009
+ log(marked("problem", `${repo.name} not pulled`, process18.stdout, refused));
1881
2010
  } else {
1882
- log(marked("ok", `${repo.name} pulled`, process16.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
2011
+ log(marked("ok", `${repo.name} pulled`, process18.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
1883
2012
  states[index] = await inspect(repo.path, false);
1884
2013
  }
1885
2014
  }
@@ -1894,7 +2023,7 @@ async function repos(args) {
1894
2023
  printJson(kept.map((repo) => ({ ...repo, reasons: reasonsOf(repo) })));
1895
2024
  return failedPulls > 0 ? 1 : 0;
1896
2025
  }
1897
- const label = role("label", process16.stdout);
2026
+ const label = role("label", process18.stdout);
1898
2027
  if (kept.length === 0) {
1899
2028
  console.log(label(`nothing needs attention in ${states.length} repositories`));
1900
2029
  return failedPulls > 0 ? 1 : 0;
@@ -1909,17 +2038,28 @@ async function repos(args) {
1909
2038
  }
1910
2039
 
1911
2040
  // src/sweep.ts
1912
- import { existsSync as existsSync10, statSync as statSync4 } from "fs";
2041
+ import { existsSync as existsSync11, statSync as statSync4 } from "fs";
1913
2042
  import { homedir as homedir6 } from "os";
1914
- import { join as join13, relative as relative3, resolve as resolve5 } from "path";
2043
+ import { relative as relative3 } from "path";
1915
2044
 
1916
2045
  // ../kit/src/prompt.ts
1917
- import process17 from "process";
2046
+ import process19 from "process";
1918
2047
  var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|[\s\S]/giu;
1919
2048
  var CONTROL2 = /^[\x00-\x1F\x7F]/;
1920
- var KEYS = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
1921
- function readKeys(input) {
1922
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => KEYS[sequence] ?? (CONTROL2.test(sequence) ? [] : [{ text: sequence }]));
2049
+ var PASTE_START = "\x1B[200~";
2050
+ var PASTE_END = "\x1B[201~";
2051
+ var KEYS = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\x1B[5~": "pageup", "\x1B[6~": "pagedown", "\x1B[H": "home", "\x1B[1~": "home", "\x1BOH": "home", "\x1B[F": "end", "\x1B[4~": "end", "\x1BOF": "end", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
2052
+ function readKeys(input, paste = { active: false }) {
2053
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
2054
+ if (sequence === PASTE_START || sequence === PASTE_END) {
2055
+ paste.active = sequence === PASTE_START;
2056
+ return [];
2057
+ }
2058
+ if (paste.active && (sequence === "\r" || sequence === `
2059
+ `))
2060
+ return [];
2061
+ return KEYS[sequence] ?? (CONTROL2.test(sequence) ? [] : [{ text: sequence }]);
2062
+ });
1923
2063
  }
1924
2064
  async function confirm(question, { default: fallback, ...settings } = {}) {
1925
2065
  let answered = fallback;
@@ -1943,27 +2083,34 @@ function asking(colors, question, typed, keys) {
1943
2083
  function answer(colors, question, state, picked) {
1944
2084
  return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1945
2085
  }
1946
- async function ask(question, { hint, terminal = process17 }, render, press) {
2086
+ async function ask(question, { hint, terminal = process19 }, render, press) {
1947
2087
  const { stdin, stderr } = terminal;
1948
- if (stdin.isTTY !== true || stderr.isTTY !== true)
2088
+ if (!isInteractive(terminal))
1949
2089
  fail(`cannot ask "${question}" off a terminal`, 2, hint);
1950
2090
  const colors = paint(stderr);
1951
- let drawn = 0;
2091
+ let drawn = [];
2092
+ let current = "asking";
1952
2093
  let outcome;
2094
+ const columns = () => stderr.columns || 80;
1953
2095
  const draw = (state) => {
1954
- const frame = render(colors, state, { columns: stderr.columns || 80, rows: stderr.rows || 24 });
1955
- stderr.write(`${drawn > 1 ? `\x1B[${drawn - 1}A` : ""}\r\x1B[0J${frame.join(`
2096
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
2097
+ const rows = drawn.reduce((sum, line) => sum + Math.max(1, Math.ceil(Bun.stringWidth(line) / columns())), 0);
2098
+ stderr.write(`${rows > 1 ? `\x1B[${rows - 1}A` : ""}\r\x1B[0J${frame.join(`
1956
2099
  `)}`);
1957
- drawn = frame.length;
2100
+ drawn = frame;
2101
+ current = state;
1958
2102
  };
2103
+ const redraw = () => draw(current);
2104
+ const paste = { active: false };
1959
2105
  try {
2106
+ stderr.on?.("resize", redraw);
1960
2107
  stdin.setRawMode(true);
1961
2108
  stdin.resume();
1962
- stderr.write("\x1B[?25l");
2109
+ stderr.write("\x1B[?25l\x1B[?2004h");
1963
2110
  draw("asking");
1964
2111
  return await new Promise((resolve) => {
1965
2112
  function onData(data) {
1966
- for (const key of readKeys(data.toString())) {
2113
+ for (const key of readKeys(data.toString(), paste)) {
1967
2114
  const pressed = press(key);
1968
2115
  if (pressed !== undefined) {
1969
2116
  settle(pressed);
@@ -1985,40 +2132,32 @@ async function ask(question, { hint, terminal = process17 }, render, press) {
1985
2132
  stdin.on("end", onEnd);
1986
2133
  });
1987
2134
  } finally {
2135
+ stderr.off?.("resize", redraw);
1988
2136
  draw(outcome ?? "cancel");
1989
2137
  stderr.write(`
1990
- \x1B[?25h`);
2138
+ \x1B[?25h\x1B[?2004l`);
1991
2139
  stdin.setRawMode(false);
1992
2140
  stdin.pause();
1993
2141
  }
1994
2142
  }
1995
2143
 
1996
2144
  // src/apply.ts
1997
- import { existsSync as existsSync9 } from "fs";
2145
+ import { existsSync as existsSync10 } from "fs";
1998
2146
  import { lstat as lstat3, rm } from "fs/promises";
1999
2147
  import { basename as basename3, join as join12 } from "path";
2000
2148
 
2001
2149
  // src/sweep-scan.ts
2002
- import { existsSync as existsSync8 } from "fs";
2150
+ import { existsSync as existsSync9 } from "fs";
2003
2151
  import { lstat as lstat2, readdir as readdir4, realpath } from "fs/promises";
2004
2152
  import { homedir as homedir5 } from "os";
2005
- import { basename as basename2, dirname as dirname4, join as join11 } from "path";
2153
+ import { basename as basename2, dirname as dirname5, join as join11 } from "path";
2006
2154
 
2007
2155
  // src/size.ts
2008
2156
  import { lstat, readdir as readdir3 } from "fs/promises";
2009
2157
  import { join as join10 } from "path";
2010
- async function pooled(items, limit, work) {
2011
- const results = Array.from({ length: items.length });
2012
- let next = 0;
2013
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
2014
- while (next < items.length) {
2015
- const index = next++;
2016
- results[index] = await work(items[index]);
2017
- }
2018
- }));
2019
- return results;
2020
- }
2021
2158
  var FS_LIMIT = 32;
2159
+ var FIND_MS = 60000;
2160
+ var FIND_LINE = /^(\d+) (\S+) (\d+)$/gm;
2022
2161
  var waiting = [];
2023
2162
  var running = 0;
2024
2163
  async function gated(call) {
@@ -2032,7 +2171,7 @@ async function gated(call) {
2032
2171
  waiting.shift()?.();
2033
2172
  }
2034
2173
  }
2035
- async function sizeOf(folder) {
2174
+ async function walkSize(folder) {
2036
2175
  const seen = new Set;
2037
2176
  let total = 0;
2038
2177
  const visit = async (dir) => {
@@ -2061,6 +2200,30 @@ async function sizeOf(folder) {
2061
2200
  await visit(folder);
2062
2201
  return total;
2063
2202
  }
2203
+ async function findSize(folder) {
2204
+ try {
2205
+ const ran = await runCommand(["find", "-P", folder, "(", "-type", "f", "-o", "-type", "l", ")", "-printf", "%n %D:%i %s\\n"], { timeoutMs: FIND_MS });
2206
+ const lines = [...ran.text.matchAll(FIND_LINE)];
2207
+ if (ran.timedOut || ran.code !== 0 && lines.length === 0)
2208
+ return;
2209
+ const seen = new Set;
2210
+ let total = 0;
2211
+ for (const [, links, id, bytes] of lines) {
2212
+ if (Number(links) > 1) {
2213
+ if (seen.has(id))
2214
+ continue;
2215
+ seen.add(id);
2216
+ }
2217
+ total += Number(bytes);
2218
+ }
2219
+ return total;
2220
+ } catch {
2221
+ return;
2222
+ }
2223
+ }
2224
+ async function sizeOf(folder) {
2225
+ return await findSize(folder) ?? await walkSize(folder);
2226
+ }
2064
2227
 
2065
2228
  // src/sweep-scan.ts
2066
2229
  var FOLDER_NAMES = new Set(["node_modules", ".nuxt", ".next", ".output", "dist", "build", ".turbo", ".svelte-kit", "target"]);
@@ -2068,7 +2231,7 @@ var MAX_DEPTH3 = 3;
2068
2231
  var PROJECT_CACHE_NAMES = new Set([".turbo", ".nuxt", ".next", ".svelte-kit"]);
2069
2232
  var GLOBAL_CACHES = [".bun/install/cache", ".npm/_cacache", ".cache/pip", ".cache/uv", ".cache/ms-playwright", ".cache/puppeteer", ".cache/go-build", ".cache/typescript", ".cargo/registry"];
2070
2233
  function isCachePath(path, home = homedir5()) {
2071
- return GLOBAL_CACHES.some((cache) => join11(home, cache) === path) || basename2(path) === ".cache" && basename2(dirname4(path)) === "node_modules";
2234
+ return GLOBAL_CACHES.some((cache) => join11(home, cache) === path) || basename2(path) === ".cache" && basename2(dirname5(path)) === "node_modules";
2072
2235
  }
2073
2236
  async function listing(dir) {
2074
2237
  try {
@@ -2110,7 +2273,7 @@ async function findCandidates(root, home = homedir5(), withGlobal = true) {
2110
2273
  }
2111
2274
  continue;
2112
2275
  }
2113
- if (FOLDER_NAMES.has(entry.name) && (entry.name !== "target" || existsSync8(join11(dir, "Cargo.toml")))) {
2276
+ if (FOLDER_NAMES.has(entry.name) && (entry.name !== "target" || existsSync9(join11(dir, "Cargo.toml")))) {
2114
2277
  if (entry.isSymbolicLink()) {
2115
2278
  found.skipped.push({ path, reason: "symlink" });
2116
2279
  } else if (entry.isDirectory()) {
@@ -2191,12 +2354,12 @@ var worktreesOf = memo(async (repo) => {
2191
2354
  return branches;
2192
2355
  });
2193
2356
  async function judgeFolder(path, kind, inside) {
2194
- const parent = dirname4(path);
2357
+ const parent = dirname5(path);
2195
2358
  const name = basename2(path);
2196
2359
  const located = await toplevelOf(parent);
2197
2360
  if (located === "failed")
2198
2361
  return { skip: "git failed" };
2199
- if (existsSync8(join11(path, ".git")))
2362
+ if (existsSync9(join11(path, ".git")))
2200
2363
  return { skip: "holds a git repository" };
2201
2364
  if (located === "none")
2202
2365
  return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside } } : { skip: "not in a git repository" };
@@ -2208,7 +2371,7 @@ async function judgeFolder(path, kind, inside) {
2208
2371
  return { entry: { path, kind, committedAt: await lastCommitOf(located.top), action: "remove", inside } };
2209
2372
  }
2210
2373
  async function judgeWorktree(path) {
2211
- const located = await toplevelOf(dirname4(path));
2374
+ const located = await toplevelOf(dirname5(path));
2212
2375
  if (located === "failed")
2213
2376
  return { skip: "git failed" };
2214
2377
  if (located === "none")
@@ -2247,7 +2410,7 @@ async function judge(candidate) {
2247
2410
  async function inspect2({ candidates, skipped }) {
2248
2411
  const entries = [];
2249
2412
  const rejected = [...skipped];
2250
- await pooled(candidates, 8, async (candidate) => {
2413
+ await pool(candidates, 8, async (candidate) => {
2251
2414
  const verdict = await judge(candidate);
2252
2415
  if ("skip" in verdict)
2253
2416
  rejected.push({ path: candidate.path, reason: verdict.skip });
@@ -2264,7 +2427,7 @@ async function removeFolder(entry) {
2264
2427
  const stat = await lstat3(entry.path);
2265
2428
  if (stat.isSymbolicLink() || !stat.isDirectory() || !(FOLDER_NAMES.has(basename3(entry.path)) || entry.kind === "cache" && isCachePath(entry.path)))
2266
2429
  return { path: entry.path, removed: false, error: "no longer a plain folder" };
2267
- if (existsSync9(join12(entry.path, ".git")))
2430
+ if (existsSync10(join12(entry.path, ".git")))
2268
2431
  return { path: entry.path, removed: false, error: "holds a git repository" };
2269
2432
  await rm(entry.path, { recursive: true, force: true });
2270
2433
  return { path: entry.path, removed: true };
@@ -2297,7 +2460,7 @@ async function applyAll(entries, done) {
2297
2460
  // src/sweep.ts
2298
2461
  var LARGE = 100 * 1024 ** 2;
2299
2462
  var BIG = 1024 ** 3;
2300
- 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 (~/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
2463
+ 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
2301
2464
 
2302
2465
  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.
2303
2466
 
@@ -2326,8 +2489,8 @@ async function sweep(args) {
2326
2489
  const { values, positionals } = parse(args, USAGE3, OPTIONS3, { positionals: ["[root]"], replaces: "find ~/Workspace -name node_modules, du -sh and rm -rf by hand", examples: ["sweep", "sweep ~/Workspace --older 30d --min 100M --apply", "sweep --only worktrees --apply"] });
2327
2490
  if (positionals.length > 1)
2328
2491
  badUsage("give one root");
2329
- const root = resolve5(positionals[0] ?? join13(homedir6(), "Workspace"));
2330
- if (!existsSync10(root) || !statSync4(root).isDirectory())
2492
+ const root = workspaceRoot({ given: positionals[0] });
2493
+ if (!existsSync11(root) || !statSync4(root).isDirectory())
2331
2494
  fail(`${root} is not a folder`);
2332
2495
  if (values.only !== undefined && !Object.hasOwn(ONLY_KINDS, values.only))
2333
2496
  badUsage(`--only takes worktrees, folders or caches, not ${values.only}`);
@@ -2401,7 +2564,7 @@ ${$e(reclaimable)} reclaimable${skipped === 0 ? "" : `, ${skipped} skipped (syml
2401
2564
  }
2402
2565
 
2403
2566
  // src/cli.ts
2404
- process18.exitCode = await runCli({
2567
+ process20.exitCode = await runCli({
2405
2568
  name: "ws",
2406
2569
  about: "the repositories under a root: the ones needing attention, the folders worth reclaiming and their known vulnerabilities",
2407
2570
  replaces: "a cd, git status and du loop over each repository of the workspace, and a bun audit run in each",