@kaynooo/cli-workspace 0.11.0 → 0.14.2

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
@@ -1,28 +1,18 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
+ var __esm = (fn, res, err) => () => {
4
+ if (fn)
5
+ try {
6
+ res = fn(fn = 0);
7
+ } catch (e) {
8
+ err = [e];
9
+ }
10
+ if (err)
11
+ throw err[0];
12
+ return res;
13
+ };
3
14
 
4
- // src/cli.ts
5
- import process24 from "process";
6
-
7
- // ../kit/src/advisory.ts
8
- var SEVERITIES = ["low", "moderate", "high", "critical"];
9
- function severityRank(severity) {
10
- return SEVERITIES.indexOf(severity);
11
- }
12
- function isIgnored(advisory, ignore) {
13
- return ignore.includes(advisory.ghsa ?? "") || ignore.includes(String(advisory.id));
14
- }
15
- // ../kit/src/args.ts
16
- import process9 from "process";
17
- import { parseArgs } from "util";
18
-
19
- // ../kit/src/format.ts
20
- import process7 from "process";
21
-
22
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-n6z2kk96.js
23
- var r = new Map;
24
- var i = new Map;
25
- var l = new Map;
15
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-n6z2kk96.js
26
16
  function a(e, t, o) {
27
17
  return JSON.stringify([e ?? null, t ?? null, o]);
28
18
  }
@@ -32,12 +22,15 @@ function y(e, t) {
32
22
  n = new Intl.NumberFormat(e, t), i.set(o, n);
33
23
  return n;
34
24
  }
25
+ var r, i, l;
26
+ var init_chunk_n6z2kk96 = __esm(() => {
27
+ r = new Map;
28
+ i = new Map;
29
+ l = new Map;
30
+ });
35
31
 
36
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
37
- var N = new Map;
38
- var Nt = /\s+\S*$/;
39
- var Y = /\s/;
40
- function ko(t, e, r = "...") {
32
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
33
+ function Ao(t, e, r = "...") {
41
34
  let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
42
35
  if (t.length <= e)
43
36
  return t;
@@ -48,13 +41,22 @@ function ko(t, e, r = "...") {
48
41
  c = c.trimEnd();
49
42
  return s ? (c + n).slice(0, l) : c + n;
50
43
  }
51
- var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
52
- var z = new Map;
44
+ var N, Nt, Y, be, W;
45
+ var init_chunk_rkhsft4a = __esm(() => {
46
+ N = new Map;
47
+ Nt = /\s+\S*$/;
48
+ Y = /\s/;
49
+ be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
50
+ W = new Map;
51
+ });
52
+
53
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
54
+ var init_text = __esm(() => {
55
+ init_chunk_rkhsft4a();
56
+ });
53
57
 
54
58
  // ../kit/src/mode.ts
55
59
  import process2 from "process";
56
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
57
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
58
60
  function isSet(value) {
59
61
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
60
62
  }
@@ -71,12 +73,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
71
73
  function isInteractive(streams = process2) {
72
74
  return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
73
75
  }
76
+ var MODES, AGENT_VARIABLES;
77
+ var init_mode = __esm(() => {
78
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
79
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
80
+ });
74
81
 
75
- // ../kit/src/style.ts
76
- import process6 from "process";
77
-
78
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
79
- var G2 = /^[a-f0-9]+$/i;
82
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
80
83
  function b(r) {
81
84
  let e = r.startsWith("#") ? r.slice(1) : r;
82
85
  if (!G2.test(e))
@@ -87,11 +90,6 @@ function b(r) {
87
90
  throw Error(`Invalid hex color length: ${e.length}`);
88
91
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
89
92
  }
90
- var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
91
- let [l, n, c] = b(r);
92
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
93
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
94
- var h = new Set(["", "1", "2", "3", "true"]);
95
93
  function C(r, e = globalThis.process?.env ?? {}) {
96
94
  if (e.FORCE_COLOR !== undefined)
97
95
  return h.has(e.FORCE_COLOR);
@@ -105,7 +103,7 @@ function f(r, e = []) {
105
103
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
106
104
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
107
105
  return new Proxy(c, { get(t, i) {
108
- let a = B2[i];
106
+ let a = B[i];
109
107
  if (Array.isArray(a)) {
110
108
  let s = g.get(i);
111
109
  if (s === undefined)
@@ -128,13 +126,21 @@ function f(r, e = []) {
128
126
  function Fe(r = {}) {
129
127
  return f(r);
130
128
  }
131
- var o = Fe();
129
+ var G2, B, h, o;
130
+ var init_chunk_x450vn3m = __esm(() => {
131
+ G2 = /^[a-f0-9]+$/i;
132
+ B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
133
+ let [l, n, c] = b(r);
134
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
135
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
136
+ h = new Set(["", "1", "2", "3", "true"]);
137
+ o = Fe();
138
+ });
132
139
 
133
- // ../kit/src/theme.ts
134
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
135
- import { homedir as homedir2 } from "os";
136
- import { join as join3, resolve as resolve2 } from "path";
137
- import process5 from "process";
140
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
141
+ var init_colors = __esm(() => {
142
+ init_chunk_x450vn3m();
143
+ });
138
144
 
139
145
  // ../kit/src/config.ts
140
146
  import { existsSync } from "fs";
@@ -150,15 +156,21 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
150
156
  return;
151
157
  }
152
158
  }
159
+ var init_config = __esm(() => {
160
+ init_args();
161
+ });
153
162
 
154
163
  // ../kit/src/user-config.ts
155
164
  import { existsSync as existsSync2, readFileSync } from "fs";
156
165
  import { homedir } from "os";
157
- import { join as join2 } from "path";
166
+ import { isAbsolute, join as join2 } from "path";
158
167
  import process4 from "process";
168
+ function xdgFolder(value, fallback) {
169
+ return value !== undefined && isAbsolute(value) ? value : fallback;
170
+ }
159
171
  function configBase(where = {}) {
160
172
  const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
161
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
173
+ return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
162
174
  }
163
175
  function userConfigPath(bin, where = {}) {
164
176
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
@@ -185,36 +197,49 @@ function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
185
197
  const value = readUserConfig(bin, where, legacy)[key];
186
198
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
187
199
  }
200
+ var init_user_config = () => {};
188
201
 
189
202
  // ../kit/src/theme.ts
190
- var ENDS = new Map;
191
- var DEFAULT = {
192
- colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
193
- glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
194
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
195
- bins: {},
196
- gradient: ["#c084fc", "#67e8f9"]
197
- };
198
- var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
199
- var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
200
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
201
- var PRESETS = {
202
- default: {},
203
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
204
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
205
- ascii: { glyphs: ASCII }
206
- };
207
- var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
208
- var HEX = /^#[0-9a-f]{6}$/i;
209
- var CONTROL = /\p{Cc}/u;
210
- var MAX_FILE_BYTES = 64 * 1024;
211
- var SPACES = /\s+/;
203
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
204
+ import { homedir as homedir2 } from "os";
205
+ import { join as join3, resolve as resolve2 } from "path";
206
+ import process5 from "process";
207
+ function toLinear(channel) {
208
+ const value = channel / 255;
209
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
210
+ }
211
+ function toOklab(hex) {
212
+ const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
213
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
214
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
215
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
216
+ return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
217
+ }
218
+ function fromOklab([lightness, a, b]) {
219
+ const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
220
+ const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
221
+ const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
222
+ const channels = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
223
+ return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
224
+ }
225
+ function gradientAt(theme, ratio) {
226
+ if (theme.gradient === undefined)
227
+ return;
228
+ const key = theme.gradient.join();
229
+ let ends = ENDS.get(key);
230
+ if (ends === undefined) {
231
+ ends = [toOklab(theme.gradient[0]), toOklab(theme.gradient[1])];
232
+ ENDS.set(key, ends);
233
+ }
234
+ const at = Math.min(1, Math.max(0, ratio));
235
+ const [from, to] = ends;
236
+ return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
237
+ }
212
238
  function isColorSpec(spec) {
213
239
  if (typeof spec === "number")
214
240
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
215
241
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
216
242
  }
217
- var CUBE = [0, 95, 135, 175, 215, 255];
218
243
  function cubeLevel(channel) {
219
244
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
220
245
  }
@@ -239,6 +264,9 @@ function tinted(colors, spec, env = process5.env) {
239
264
  return chain[token] ?? chain;
240
265
  }, colors);
241
266
  }
267
+ function shaded(theme, colors, glyph, cells, width, env = process5.env) {
268
+ return Array.from({ length: cells }, (_, index) => tinted(colors, gradientAt(theme, width <= 1 ? 0 : index / (width - 1)) ?? theme.colors.accent, env)(glyph)).join("");
269
+ }
242
270
  function isRecord(value) {
243
271
  return typeof value === "object" && value !== null && !Array.isArray(value);
244
272
  }
@@ -319,7 +347,6 @@ function applyFile(theme, file, where, warn) {
319
347
  function endsWalk(home) {
320
348
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
321
349
  }
322
- var warned = new Set;
323
350
  function warnOnce(message) {
324
351
  if (warned.has(message))
325
352
  return;
@@ -356,8 +383,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
356
383
  }
357
384
  return { theme, sources, preset };
358
385
  }
359
- var current;
360
- var currentKey = "";
361
386
  function activeTheme() {
362
387
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
363
388
  if (current === undefined || key !== currentKey) {
@@ -366,9 +391,38 @@ function activeTheme() {
366
391
  }
367
392
  return current;
368
393
  }
394
+ var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055))), ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
395
+ var init_theme = __esm(() => {
396
+ init_config();
397
+ init_user_config();
398
+ ENDS = new Map;
399
+ DEFAULT = {
400
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
401
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
402
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
403
+ bins: {},
404
+ gradient: ["#c084fc", "#67e8f9"]
405
+ };
406
+ BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
407
+ MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
408
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
409
+ PRESETS = {
410
+ default: {},
411
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
412
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
413
+ ascii: { glyphs: ASCII }
414
+ };
415
+ STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
416
+ HEX = /^#[0-9a-f]{6}$/i;
417
+ CONTROL = /\p{Cc}/u;
418
+ MAX_FILE_BYTES = 64 * 1024;
419
+ SPACES = /\s+/;
420
+ CUBE = [0, 95, 135, 175, 215, 255];
421
+ warned = new Set;
422
+ });
369
423
 
370
424
  // ../kit/src/style.ts
371
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
425
+ import process6 from "process";
372
426
  function takesControlCodes(stream, env = process6.env) {
373
427
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
374
428
  }
@@ -397,14 +451,6 @@ function role(name, stream, env = process6.env) {
397
451
  const colors = paint(stream, env);
398
452
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
399
453
  }
400
- var STATUS_WORDS = {
401
- passed: ["passed", "success", "succeeded", "ok"],
402
- failed: ["failed", "failure", "error", "errored"],
403
- running: ["running", "in_progress", "started", "holding"],
404
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
405
- skipped: ["skipped", "cancelled", "canceled", "manual"]
406
- };
407
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
408
454
  function header(bin, context, stream, env = process6.env) {
409
455
  if (!takesControlCodes(stream, env))
410
456
  return "";
@@ -420,7 +466,23 @@ function printHeader(bin, context, stream = process6.stdout, env = process6.env)
420
466
  if (line !== "")
421
467
  console.log(line);
422
468
  }
423
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-knqbxp56.js
469
+ var MARK_WORDS, STATUS_WORDS, STATUS_OF;
470
+ var init_style = __esm(() => {
471
+ init_colors();
472
+ init_mode();
473
+ init_theme();
474
+ MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
475
+ STATUS_WORDS = {
476
+ passed: ["passed", "success", "succeeded", "ok"],
477
+ failed: ["failed", "failure", "error", "errored"],
478
+ running: ["running", "in_progress", "started", "holding"],
479
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
480
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
481
+ };
482
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
483
+ });
484
+
485
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-knqbxp56.js
424
486
  function tt(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
425
487
  let e = r === "si" ? 1000 : 1024;
426
488
  if (Math.abs(i) < e)
@@ -431,9 +493,17 @@ function tt(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
431
493
  while (Math.round(Math.abs(i) * a) / a >= e && o < s.length - 1);
432
494
  return `${n ? y(n, { minimumFractionDigits: t, maximumFractionDigits: t }).format(i) : i.toFixed(t)} ${s[o]}`;
433
495
  }
496
+ var init_chunk_knqbxp56 = __esm(() => {
497
+ init_chunk_n6z2kk96();
498
+ });
499
+
500
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/format/index.js
501
+ var init_format = __esm(() => {
502
+ init_chunk_knqbxp56();
503
+ });
434
504
 
435
505
  // ../kit/src/format.ts
436
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
506
+ import process7 from "process";
437
507
  function formatSeconds(total) {
438
508
  let rest = Math.max(0, Math.round(total));
439
509
  const amounts = UNITS.map(([unit, size]) => {
@@ -450,6 +520,9 @@ function formatSeconds(total) {
450
520
  function formatDuration(ms) {
451
521
  return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
452
522
  }
523
+ function formatElapsed(ms) {
524
+ return formatSeconds(Math.floor(Math.max(0, ms) / 1000));
525
+ }
453
526
  function upTo(text, separator) {
454
527
  const end = text.indexOf(separator);
455
528
  return end === -1 ? text : text.slice(0, end);
@@ -462,10 +535,8 @@ function formatAge(date, now = Date.now()) {
462
535
  return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
463
536
  }
464
537
  function truncate(text, width) {
465
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
538
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
466
539
  }
467
- var LINE_BREAKS = /\s*\n\s*/g;
468
- var ESCAPE = String.fromCharCode(27);
469
540
  function textWidth(text) {
470
541
  return Bun.stringWidth(text);
471
542
  }
@@ -514,14 +585,41 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
514
585
  function printJson(value) {
515
586
  console.log(jsonText(value));
516
587
  }
588
+ var UNITS, LINE_BREAKS, ESCAPE;
589
+ var init_format2 = __esm(() => {
590
+ init_text();
591
+ init_mode();
592
+ init_style();
593
+ init_format();
594
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
595
+ LINE_BREAKS = /\s*\n\s*/g;
596
+ ESCAPE = String.fromCharCode(27);
597
+ });
517
598
 
518
599
  // ../kit/src/help.ts
519
600
  import process8 from "process";
520
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
521
- var USAGE_PREFIX = /^usage:\s*/i;
522
- var FULL_STOP = /\.$/;
523
601
  function usageLine(usage, colors = paint(process8.stdout)) {
524
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
602
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
603
+ `);
604
+ const blank = lines.indexOf("");
605
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
606
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
607
+ const colon = synopses[0].indexOf(": ");
608
+ const inline = synopses[0].slice(colon + 2);
609
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
610
+ if (colon !== -1)
611
+ synopses[0] = synopses[0].slice(0, colon);
612
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
613
+ `)}`;
614
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
615
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
616
+ return [head, ...lead, ...rest].join(`
617
+ `);
618
+ }
619
+ function prose(line, colors) {
620
+ if (colors.cyan("x") === "x")
621
+ return line;
622
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
525
623
  }
526
624
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
527
625
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -556,7 +654,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
556
654
  return [];
557
655
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
558
656
  }
559
- var MAX_INLINE_CHOICES = 24;
560
657
  function optionRows(options, colors = paint(process8.stdout)) {
561
658
  const rows = Object.entries(options).map(([name, option]) => {
562
659
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -571,6 +668,15 @@ function optionRows(options, colors = paint(process8.stdout)) {
571
668
  const width = Math.max(0, ...rows.map((row) => row.width));
572
669
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
573
670
  }
671
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
672
+ var init_help = __esm(() => {
673
+ init_mode();
674
+ init_style();
675
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
676
+ USAGE_PREFIX = /^usage:\s*/i;
677
+ FULL_STOP = /\.$/;
678
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
679
+ });
574
680
 
575
681
  // ../kit/src/text.ts
576
682
  function distance(a, b) {
@@ -598,9 +704,9 @@ function closest(name, names) {
598
704
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
599
705
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
600
706
  }
707
+ var init_text2 = () => {};
708
+
601
709
  // ../kit/src/input.ts
602
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
603
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
604
710
  function duration(value, name, fallback, unit = "s") {
605
711
  if (value === undefined)
606
712
  return fallback;
@@ -610,40 +716,26 @@ function duration(value, name, fallback, unit = "s") {
610
716
  badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
611
717
  return ms;
612
718
  }
719
+ var DURATION, UNIT_MS;
720
+ var init_input = __esm(() => {
721
+ init_args();
722
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
723
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
724
+ });
613
725
 
614
726
  // ../kit/src/args.ts
615
- var DASHES = /^-+/;
727
+ import process9 from "process";
728
+ import { parseArgs } from "util";
616
729
  function jsonOption(holds) {
617
730
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
618
731
  }
619
- class Exit extends Error {
620
- code;
621
- hint;
622
- constructor(message, code, hint) {
623
- super(message);
624
- this.code = code;
625
- this.hint = hint;
626
- }
627
- }
628
732
  function fail(message, code = 2, hint) {
629
733
  throw new Exit(message, code, hint);
630
734
  }
631
-
632
- class UsageError extends Exit {
633
- constructor(message, hint) {
634
- super(message, 2, hint);
635
- }
636
- }
637
735
  function badUsage(message) {
638
736
  throw new UsageError(message);
639
737
  }
640
738
 
641
- class HelpShown extends Exit {
642
- constructor() {
643
- super("help shown", 0);
644
- }
645
- }
646
-
647
739
  class Completing {
648
740
  options;
649
741
  positionals;
@@ -654,11 +746,6 @@ class Completing {
654
746
  this.candidates = candidates;
655
747
  }
656
748
  }
657
- var completion = { active: false };
658
- var OUTPUT_OPTIONS = {
659
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
660
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
661
- };
662
749
  function applyOutput(color, plain, env = process9.env) {
663
750
  const when = plain === true ? "never" : color ?? "auto";
664
751
  if (when === "auto")
@@ -812,7 +899,6 @@ function parseError(error) {
812
899
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
813
900
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
814
901
  }
815
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
816
902
  function nearestOption(message, options, allowNegative) {
817
903
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
818
904
  if (typed === undefined)
@@ -828,6 +914,303 @@ function nearestOption(message, options, allowNegative) {
828
914
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
829
915
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
830
916
  }
917
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
918
+ var init_args = __esm(() => {
919
+ init_format2();
920
+ init_help();
921
+ init_text2();
922
+ init_help();
923
+ init_input();
924
+ DASHES = /^-+/;
925
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
926
+ Exit = class Exit extends Error {
927
+ code;
928
+ hint;
929
+ [EXIT] = true;
930
+ constructor(message, code, hint) {
931
+ super(message);
932
+ this.code = code;
933
+ this.hint = hint;
934
+ }
935
+ static [Symbol.hasInstance](value) {
936
+ if (this !== Exit)
937
+ return Function.prototype[Symbol.hasInstance].call(this, value);
938
+ return typeof value === "object" && value !== null && value[EXIT] === true;
939
+ }
940
+ };
941
+ UsageError = class UsageError extends Exit {
942
+ constructor(message, hint) {
943
+ super(message, 2, hint);
944
+ }
945
+ };
946
+ HelpShown = class HelpShown extends Exit {
947
+ constructor() {
948
+ super("help shown", 0);
949
+ }
950
+ };
951
+ completion = { active: false };
952
+ OUTPUT_OPTIONS = {
953
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
954
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
955
+ };
956
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
957
+ });
958
+
959
+ // ../kit/src/folders.ts
960
+ var SKIPPED_FOLDERS;
961
+ var init_folders = __esm(() => {
962
+ init_user_config();
963
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
964
+ });
965
+
966
+ // ../kit/src/answers.ts
967
+ var init_answers = __esm(() => {
968
+ init_folders();
969
+ });
970
+
971
+ // ../kit/src/job.ts
972
+ import process24 from "process";
973
+ function stopJob() {
974
+ process24.kill(0, "SIGTSTP");
975
+ }
976
+ var init_job = () => {};
977
+
978
+ // ../kit/src/picker/line.ts
979
+ function isEditKey(key) {
980
+ return EDIT_KEYS.has(key);
981
+ }
982
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS;
983
+ var init_line = __esm(() => {
984
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
985
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
986
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
987
+ });
988
+
989
+ // ../kit/src/picker/score.ts
990
+ var BOUNDARY_AFTER, NONE;
991
+ var init_score = __esm(() => {
992
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
993
+ NONE = Number.NEGATIVE_INFINITY;
994
+ });
995
+
996
+ // ../kit/src/picker/state.ts
997
+ function repeat(value, count) {
998
+ return Array.from({ length: count }).fill(value);
999
+ }
1000
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1001
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1002
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1003
+ const wheel = MOUSE.exec(sequence)?.[1];
1004
+ if (wheel !== undefined)
1005
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1006
+ const named = codes.get(sequence);
1007
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1008
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1009
+ paste.active = sequence === PASTE_START;
1010
+ return [];
1011
+ }
1012
+ if (paste.active && (sequence === "\r" || sequence === `
1013
+ `))
1014
+ return [];
1015
+ if (key !== undefined)
1016
+ return [key];
1017
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1018
+ });
1019
+ }
1020
+ var IS_CONTROL, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
1021
+ var init_state = __esm(() => {
1022
+ init_text2();
1023
+ init_line();
1024
+ init_score();
1025
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1026
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1027
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1028
+ KEYS = {
1029
+ "\x1B[A": "up",
1030
+ "\x1BOA": "up",
1031
+ "\x10": "up",
1032
+ "\x1B[B": "down",
1033
+ "\x1BOB": "down",
1034
+ "\x0E": "down",
1035
+ "\x1B[5~": "pageup",
1036
+ "\x1B[6~": "pagedown",
1037
+ "\x1B[H": "home",
1038
+ "\x1B[1~": "home",
1039
+ "\x1BOH": "home",
1040
+ "\x1B[F": "end",
1041
+ "\x1B[4~": "end",
1042
+ "\x1BOF": "end",
1043
+ "\r": "enter",
1044
+ "\n": "enter",
1045
+ "\x03": "cancel",
1046
+ "\x1B": "cancel",
1047
+ "\x1B[D": "left",
1048
+ "\x1BOD": "left",
1049
+ "\x1B[C": "right",
1050
+ "\x1BOC": "right",
1051
+ "\x1B[1;5D": "wordleft",
1052
+ "\x1B[1;3D": "wordleft",
1053
+ "\x1Bb": "wordleft",
1054
+ "\x1B[1;5C": "wordright",
1055
+ "\x1B[1;3C": "wordright",
1056
+ "\x1Bf": "wordright",
1057
+ "\x01": "linestart",
1058
+ "\x05": "lineend",
1059
+ "\x7F": "erase",
1060
+ "\x1B[3~": "delete",
1061
+ "\b": "killword",
1062
+ "\x1B\x7F": "killword",
1063
+ "\x1B[3;5~": "killnext",
1064
+ "\x1Bd": "killnext",
1065
+ "\x15": "clear",
1066
+ "\v": "killend",
1067
+ "\x17": "word",
1068
+ "\x19": "yank",
1069
+ "\x1A": "suspend",
1070
+ "\t": "tab",
1071
+ "\x1F": "help",
1072
+ "\x1BOP": "help",
1073
+ "\x1B[11~": "help"
1074
+ };
1075
+ });
1076
+
1077
+ // ../kit/src/redraw.ts
1078
+ function overwrite(lines, columns) {
1079
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1080
+ `);
1081
+ }
1082
+ function rowsTaken(lines, columns) {
1083
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1084
+ }
1085
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
1086
+ var init_redraw = __esm(() => {
1087
+ init_format2();
1088
+ });
1089
+
1090
+ // ../kit/src/prompt.ts
1091
+ import process25 from "process";
1092
+ function readKeys(input, paste = { active: false }) {
1093
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1094
+ }
1095
+ async function confirm(question, { default: fallback, ...settings } = {}) {
1096
+ let answered = fallback;
1097
+ const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
1098
+ const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
1099
+ if (key === "cancel")
1100
+ return "cancel";
1101
+ if (key === "enter")
1102
+ return answered === undefined ? undefined : "enter";
1103
+ const letter = typeof key === "object" ? key.text.toLowerCase() : "";
1104
+ if (letter !== "y" && letter !== "n")
1105
+ return;
1106
+ answered = letter === "y";
1107
+ return "enter";
1108
+ });
1109
+ return accepted ? answered : undefined;
1110
+ }
1111
+ function asking(colors, question, typed, keys) {
1112
+ return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
1113
+ }
1114
+ function answer(colors, question, state, picked) {
1115
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1116
+ }
1117
+ async function ask(question, { hint, terminal = process25 }, render, press) {
1118
+ const { stdin, stderr } = terminal;
1119
+ if (!isInteractive(terminal))
1120
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1121
+ const colors = paint(stderr);
1122
+ let current = "asking";
1123
+ let outcome;
1124
+ const columns = () => stderr.columns || 80;
1125
+ const draw = (state, last = false) => {
1126
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1127
+ const rows = rowsTaken(frame, columns());
1128
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1129
+ current = state;
1130
+ };
1131
+ const redraw = () => draw(current);
1132
+ const paste = { active: false };
1133
+ const stop = terminal.stop ?? (terminal === process25 ? stopJob : undefined);
1134
+ const suspend = () => {
1135
+ if (stop === undefined)
1136
+ return;
1137
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1138
+ stdin.setRawMode(false);
1139
+ stop();
1140
+ stdin.setRawMode(true);
1141
+ stderr.write("\x1B[?25l\x1B[?2004h");
1142
+ };
1143
+ try {
1144
+ stderr.on?.("resize", redraw);
1145
+ stdin.setRawMode(true);
1146
+ stdin.resume();
1147
+ stderr.write("\x1B[?25l\x1B[?2004h");
1148
+ draw("asking");
1149
+ return await new Promise((resolve) => {
1150
+ function onData(data) {
1151
+ for (const key of readKeys(data.toString(), paste)) {
1152
+ if (key === "suspend") {
1153
+ suspend();
1154
+ continue;
1155
+ }
1156
+ const pressed = press(key);
1157
+ if (pressed !== undefined) {
1158
+ settle(pressed);
1159
+ return;
1160
+ }
1161
+ }
1162
+ draw("asking");
1163
+ }
1164
+ function onEnd() {
1165
+ settle("cancel");
1166
+ }
1167
+ function settle(settled) {
1168
+ outcome = settled;
1169
+ stdin.off("data", onData);
1170
+ stdin.off("end", onEnd);
1171
+ resolve(settled === "enter");
1172
+ }
1173
+ stdin.on("data", onData);
1174
+ stdin.on("end", onEnd);
1175
+ });
1176
+ } finally {
1177
+ stderr.off?.("resize", redraw);
1178
+ draw(outcome ?? "cancel", true);
1179
+ stderr.write(`
1180
+ \x1B[?25h\x1B[?2004l`);
1181
+ stdin.setRawMode(false);
1182
+ stdin.pause();
1183
+ }
1184
+ }
1185
+ var PROMPT_KEYS;
1186
+ var init_prompt = __esm(() => {
1187
+ init_answers();
1188
+ init_args();
1189
+ init_format2();
1190
+ init_job();
1191
+ init_mode();
1192
+ init_line();
1193
+ init_state();
1194
+ init_redraw();
1195
+ init_style();
1196
+ PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1197
+ });
1198
+
1199
+ // src/cli.ts
1200
+ import process26 from "process";
1201
+
1202
+ // ../kit/src/advisory.ts
1203
+ var SEVERITIES = ["low", "moderate", "high", "critical"];
1204
+ function severityRank(severity) {
1205
+ return SEVERITIES.indexOf(severity);
1206
+ }
1207
+ function isIgnored(advisory, ignore) {
1208
+ return ignore.includes(advisory.ghsa ?? "") || ignore.includes(String(advisory.id));
1209
+ }
1210
+
1211
+ // ../kit/src/index.ts
1212
+ init_args();
1213
+
831
1214
  // ../kit/src/argv.ts
832
1215
  import { readFileSync as readFileSync3, realpathSync } from "fs";
833
1216
  import { resolve as resolve3 } from "path";
@@ -852,10 +1235,26 @@ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), scr
852
1235
  const after = at === -1 ? [] : cmdline.slice(at + 1);
853
1236
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
854
1237
  }
1238
+ // ../kit/src/chart.ts
1239
+ init_format2();
1240
+ init_mode();
1241
+ init_style();
1242
+ init_theme();
1243
+ // ../kit/src/ci.ts
1244
+ init_args();
1245
+ init_format2();
1246
+
1247
+ // ../kit/src/progress.ts
1248
+ init_format2();
1249
+ import process12 from "process";
1250
+
855
1251
  // ../kit/src/process.ts
1252
+ import { readFileSync as readFileSync4 } from "fs";
856
1253
  import { constants } from "os";
857
1254
  import process11 from "process";
858
1255
  var KILL_GRACE_MS = 2000;
1256
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1257
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
859
1258
  function exitCodeOf(code, signal) {
860
1259
  if (code !== null)
861
1260
  return code;
@@ -863,10 +1262,57 @@ function exitCodeOf(code, signal) {
863
1262
  return 128 + signal;
864
1263
  return signal === null ? 129 : 128 + constants.signals[signal];
865
1264
  }
866
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
1265
+ function groupsOf(pid) {
1266
+ try {
1267
+ const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
1268
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
1269
+ return { group: Number(fields[2]), foreground: Number(fields[5]) };
1270
+ } catch {
1271
+ return;
1272
+ }
1273
+ }
1274
+ function heardTheTerminal(child) {
1275
+ if (child.pid === undefined)
1276
+ return false;
1277
+ const own = groupsOf("self");
1278
+ return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
1279
+ }
1280
+ function holdSignals(cleanup) {
1281
+ let received;
1282
+ let child;
1283
+ const held = {
1284
+ get signal() {
1285
+ return received;
1286
+ },
1287
+ forward: (to) => {
1288
+ child = to;
1289
+ },
1290
+ release: () => {
1291
+ for (const signal of SIGNALS)
1292
+ process11.off(signal, onSignal);
1293
+ }
1294
+ };
1295
+ function onSignal(signal) {
1296
+ received = signal;
1297
+ if (child !== undefined) {
1298
+ if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
1299
+ child.kill(signal);
1300
+ return;
1301
+ }
1302
+ if (cleanup === undefined)
1303
+ return;
1304
+ held.release();
1305
+ cleanup(signal);
1306
+ process11.kill(process11.pid, signal);
1307
+ }
1308
+ for (const signal of SIGNALS)
1309
+ process11.on(signal, onSignal);
1310
+ return held;
1311
+ }
1312
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
867
1313
  const chunks = [];
868
1314
  const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
869
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
1315
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin: input === undefined ? stdin : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
870
1316
  const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
871
1317
  const timers = [];
872
1318
  const killGroup = (killing) => {
@@ -906,12 +1352,19 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
906
1352
  stop();
907
1353
  continue;
908
1354
  }
1355
+ if (state.truncated)
1356
+ continue;
1357
+ let kept = data;
909
1358
  if (state.kept + data.length > maxBytes) {
1359
+ let cut = maxBytes - state.kept;
1360
+ while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
1361
+ cut--;
1362
+ kept = data.subarray(0, cut);
910
1363
  state.truncated = true;
911
- continue;
912
1364
  }
913
- state.kept += data.length;
914
- chunks.push({ stream: name, data });
1365
+ state.kept += kept.length;
1366
+ if (kept.length > 0)
1367
+ chunks.push({ stream: name, data: kept });
915
1368
  }
916
1369
  };
917
1370
  try {
@@ -928,6 +1381,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
928
1381
  const joined = () => Buffer.concat(chunks.map(({ data }) => data));
929
1382
  let output;
930
1383
  let text;
1384
+ let stdout;
931
1385
  return {
932
1386
  code: exitCodeOf(proc.exitCode, proc.signalCode),
933
1387
  chunks,
@@ -938,21 +1392,241 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
938
1392
  },
939
1393
  get text() {
940
1394
  return text ??= (output ??= joined()).toString();
1395
+ },
1396
+ get stdout() {
1397
+ return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1398
+ }
1399
+ };
1400
+ }
1401
+
1402
+ // ../kit/src/progress.ts
1403
+ init_style();
1404
+ init_theme();
1405
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1406
+ var FRAME_MS = 200;
1407
+ var BAR_WIDTH = 20;
1408
+ var CLEAR_BELOW = "\r\x1B[J";
1409
+ var ESC = String.fromCharCode(27);
1410
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1411
+ var RESET_STYLE = `${ESC}[0m`;
1412
+ var CTRL_C = 3;
1413
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1414
+ var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
1415
+ function liveRegion(render, stream = process12.stderr, env = process12.env) {
1416
+ if (!takesControlCodes(stream, env))
1417
+ return { redraw: () => {
1418
+ return;
1419
+ }, print: (text) => void stream.write(`${text}
1420
+ `), stop: () => {
1421
+ return;
1422
+ }, pause: () => () => {
1423
+ return;
1424
+ } };
1425
+ const write = stream.write.bind(stream);
1426
+ let frame = 0;
1427
+ let drawn = false;
1428
+ let paused = false;
1429
+ let stopped = false;
1430
+ const columns = () => {
1431
+ const now = stream.getWindowSize?.()[0] ?? stream.columns;
1432
+ return now === undefined || now === 0 ? 80 : now;
1433
+ };
1434
+ const clear = () => {
1435
+ if (drawn)
1436
+ write(CLEAR_BELOW);
1437
+ drawn = false;
1438
+ };
1439
+ const draw = () => {
1440
+ if (paused)
1441
+ return;
1442
+ const width = columns() - 1;
1443
+ const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
1444
+ const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
1445
+ if (lines.length === 0) {
1446
+ clear();
1447
+ return;
1448
+ }
1449
+ write(`${CLEAR_BELOW}${lines.join(`
1450
+ `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
1451
+ drawn = true;
1452
+ };
1453
+ let timer = setInterval(draw, FRAME_MS);
1454
+ stream.on?.("resize", draw);
1455
+ let restore = interceptOutput(clear);
1456
+ let release = swallowInput();
1457
+ const onExit = () => {
1458
+ clear();
1459
+ release();
1460
+ };
1461
+ const signals = holdSignals(stop);
1462
+ function stop() {
1463
+ stopped = true;
1464
+ clearInterval(timer);
1465
+ stream.off?.("resize", draw);
1466
+ clear();
1467
+ restore();
1468
+ release();
1469
+ process12.off("exit", onExit);
1470
+ signals.release();
1471
+ }
1472
+ function pause() {
1473
+ if (paused || stopped)
1474
+ return () => {
1475
+ return;
1476
+ };
1477
+ paused = true;
1478
+ clearInterval(timer);
1479
+ stream.off?.("resize", draw);
1480
+ clear();
1481
+ restore();
1482
+ release();
1483
+ return () => {
1484
+ if (!paused || stopped)
1485
+ return;
1486
+ paused = false;
1487
+ timer = setInterval(draw, FRAME_MS);
1488
+ timer.unref();
1489
+ stream.on?.("resize", draw);
1490
+ restore = interceptOutput(clear);
1491
+ release = swallowInput();
1492
+ draw();
1493
+ };
1494
+ }
1495
+ timer.unref();
1496
+ process12.on("exit", onExit);
1497
+ return {
1498
+ redraw: draw,
1499
+ print: (text) => {
1500
+ clear();
1501
+ write(`${text}
1502
+ `);
1503
+ draw();
1504
+ },
1505
+ stop,
1506
+ pause
1507
+ };
1508
+ }
1509
+ function progressLine(stream = process12.stderr, env = process12.env) {
1510
+ const colors = paint(stream, env);
1511
+ const write = stream.write.bind(stream);
1512
+ const begun = performance.now();
1513
+ let started = begun;
1514
+ let current;
1515
+ const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
1516
+ const end = (line) => {
1517
+ region.stop();
1518
+ write(`${line}
1519
+ `);
1520
+ };
1521
+ return {
1522
+ update: (progress) => {
1523
+ const step = current?.step;
1524
+ current = progress;
1525
+ if (progress.step !== step) {
1526
+ started = performance.now();
1527
+ region.redraw();
1528
+ }
1529
+ },
1530
+ stop: region.stop,
1531
+ pause: region.pause,
1532
+ done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
1533
+ failed: (text) => end(marked("problem", text, stream, undefined, env))
1534
+ };
1535
+ }
1536
+ function progressParts({ step, done, total, unit }, spinner, ms) {
1537
+ const { theme } = activeTheme();
1538
+ const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
1539
+ if (total !== undefined && total > 0) {
1540
+ const counted = Math.min(done ?? 0, total);
1541
+ const filled = Math.round(counted / total * BAR_WIDTH);
1542
+ parts.push({ text: " ", tint: () => plain }, { text: theme.glyphs.bar.repeat(filled), tint: (colors) => () => shaded(theme, colors, theme.glyphs.bar, filled, BAR_WIDTH) }, { text: theme.glyphs.bar.repeat(BAR_WIDTH - filled), tint: (colors) => colors.dim }, { text: ` ${counted}/${total}${unit === undefined ? "" : ` ${unit}`}`, tint: (colors) => colors.dim });
1543
+ }
1544
+ parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
1545
+ return parts;
1546
+ }
1547
+ function plain(text) {
1548
+ return text;
1549
+ }
1550
+ function tintedParts(parts, colors) {
1551
+ return parts.map(({ text, tint }) => tint(colors)(text)).join("");
1552
+ }
1553
+ function cutToWidth(line, width) {
1554
+ if (Bun.stringWidth(line) <= width)
1555
+ return line;
1556
+ let room = width;
1557
+ let kept = "";
1558
+ let index = 0;
1559
+ let linked = false;
1560
+ while (index < line.length) {
1561
+ ESCAPE_CODE.lastIndex = index;
1562
+ const escape = ESCAPE_CODE.exec(line);
1563
+ if (escape !== null) {
1564
+ kept += escape[0];
1565
+ linked ||= escape[0].startsWith(`${ESC}]`);
1566
+ index = ESCAPE_CODE.lastIndex;
1567
+ continue;
1568
+ }
1569
+ const char = String.fromCodePoint(line.codePointAt(index));
1570
+ const columns = Bun.stringWidth(char);
1571
+ if (columns > room)
1572
+ break;
1573
+ kept += char;
1574
+ room -= columns;
1575
+ index += char.length;
1576
+ }
1577
+ return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1578
+ }
1579
+ function swallowInput() {
1580
+ const input = process12.stdin;
1581
+ if (!input.isTTY)
1582
+ return () => {
1583
+ return;
1584
+ };
1585
+ const onData = (data) => {
1586
+ if (data.includes(CTRL_C))
1587
+ process12.kill(process12.pid, "SIGINT");
1588
+ };
1589
+ input.setRawMode(true);
1590
+ input.on("data", onData);
1591
+ input.resume();
1592
+ let released = false;
1593
+ return () => {
1594
+ if (released)
1595
+ return;
1596
+ released = true;
1597
+ input.off("data", onData);
1598
+ input.pause();
1599
+ input.setRawMode(false);
1600
+ };
1601
+ }
1602
+ function interceptOutput(clear) {
1603
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1604
+ const wrapped = targets.map(([target, name]) => {
1605
+ const original = Reflect.get(target, name);
1606
+ const wrapper = (...args) => {
1607
+ clear();
1608
+ return original.apply(target, args);
1609
+ };
1610
+ Reflect.set(target, name, wrapper);
1611
+ return { target, name, original, wrapper };
1612
+ });
1613
+ return () => {
1614
+ for (const { target, name, original, wrapper } of wrapped) {
1615
+ if (Reflect.get(target, name) === wrapper)
1616
+ Reflect.set(target, name, original);
941
1617
  }
942
1618
  };
943
1619
  }
944
1620
 
945
- // ../kit/src/progress.ts
946
- var ESC = String.fromCharCode(27);
947
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
948
- var RESET_STYLE = `${ESC}[0m`;
949
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1621
+ // ../kit/src/ci.ts
1622
+ init_style();
950
1623
 
951
1624
  // ../kit/src/tool.ts
952
- import process12 from "process";
1625
+ init_format2();
1626
+ import process13 from "process";
953
1627
  function cwdGone() {
954
1628
  try {
955
- process12.cwd();
1629
+ process13.cwd();
956
1630
  return false;
957
1631
  } catch {
958
1632
  return true;
@@ -971,10 +1645,10 @@ function spawnFailure(command, error) {
971
1645
  const missing = !gone && error?.code === "ENOENT";
972
1646
  return new SpawnError(`${command}: ${error instanceof Error ? error.message : String(error)}${gone ? " (the working directory was removed)" : ""}`, missing);
973
1647
  }
974
- async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
1648
+ async function runTool(label, argv, { timeoutMs, cwd, onStart, env } = {}) {
975
1649
  let ran;
976
1650
  try {
977
- ran = await runCommand(argv, { env: process12.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1651
+ ran = await runCommand(argv, { env: { ...process13.env, ...env }, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
978
1652
  } catch (error) {
979
1653
  throw spawnFailure(label, error);
980
1654
  }
@@ -989,39 +1663,147 @@ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
989
1663
  return { code: ran.code, ...streams };
990
1664
  }
991
1665
  // ../kit/src/cli.ts
992
- import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1666
+ init_args();
1667
+ import { readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
993
1668
  import { dirname as dirname3, join as join5 } from "path";
994
- import process15 from "process";
1669
+ import process17 from "process";
1670
+
1671
+ // ../kit/src/askpass.ts
1672
+ import process14 from "process";
1673
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1674
+ async function askpassClient(argv) {
1675
+ const socketPath = process14.env[SOCKET_VARIABLE];
1676
+ if (socketPath === undefined)
1677
+ return;
1678
+ const request = { prompt: argv[0] ?? "", ...process14.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1679
+ const { promise, resolve } = Promise.withResolvers();
1680
+ let received = "";
1681
+ try {
1682
+ await Bun.connect({
1683
+ unix: socketPath,
1684
+ socket: {
1685
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1686
+ `),
1687
+ data: (_, chunk) => {
1688
+ received += chunk.toString();
1689
+ },
1690
+ close: () => resolve(received),
1691
+ error: () => resolve("")
1692
+ }
1693
+ });
1694
+ } catch {
1695
+ return 1;
1696
+ }
1697
+ const reply = await promise;
1698
+ if (reply === "")
1699
+ return 1;
1700
+ const { answer } = JSON.parse(reply);
1701
+ if (request.notice === true)
1702
+ return 0;
1703
+ if (answer === undefined)
1704
+ return 1;
1705
+ process14.stdout.write(`${answer}
1706
+ `);
1707
+ return 0;
1708
+ }
1709
+
1710
+ // ../kit/src/completions.ts
1711
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1712
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
1713
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1714
+ set -l current (commandline -ct)
1715
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1716
+ if test "$line" = __files__
1717
+ __fish_complete_path $current
1718
+ else
1719
+ echo $line
1720
+ end
1721
+ end
1722
+ end`;
1723
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1724
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1725
+ local -a lines
1726
+ COMPREPLY=()
1727
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1728
+ for line in "\${lines[@]}"; do
1729
+ if [[ $line == __files__ ]]; then
1730
+ COMPREPLY+=($(compgen -f -- "$cur"))
1731
+ else
1732
+ words+="\${line%%$'\\t'*}"$'\\n'
1733
+ fi
1734
+ done
1735
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1736
+ }`;
1737
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1738
+ local line
1739
+ local -a described plain
1740
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1741
+ if [[ $line == __files__ ]]; then
1742
+ _files
1743
+ elif [[ $line == *$'\\t'* ]]; then
1744
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1745
+ else
1746
+ plain+=("$line")
1747
+ fi
1748
+ done
1749
+ (( \${#described} )) && _describe -V value described
1750
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1751
+ return 0
1752
+ }`;
1753
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1754
+ if (shell === "fish")
1755
+ return `${header}
1756
+ ${FISH_FUNCTION}
1757
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1758
+ `).join("")}`;
1759
+ if (shell === "bash")
1760
+ return `${header}
1761
+ ${BASH_FUNCTION}
1762
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1763
+ `;
1764
+ return `${header}
1765
+ ${ZSH_FUNCTION}
1766
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1767
+ `;
1768
+ }
995
1769
 
996
1770
  // ../kit/src/notify.ts
997
- import process13 from "process";
1771
+ init_format2();
1772
+ init_mode();
1773
+ import process15 from "process";
998
1774
  var NOTIFY_AFTER_MS = 1e4;
999
1775
  var CANCELLED = 130;
1000
1776
  function base64(text) {
1001
1777
  return Buffer.from(text).toString("base64");
1002
1778
  }
1003
- function notification(title, body, env = process13.env) {
1004
- const id = `kit${process13.pid}`;
1779
+ function notification(title, body, env = process15.env) {
1780
+ const id = `kit${process15.pid}`;
1005
1781
  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
1782
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1007
1783
  }
1008
- function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1784
+ function notifyEnd(command, code, ms, { stream = process15.stderr, env = process15.env } = {}) {
1009
1785
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1010
1786
  return;
1011
1787
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1012
1788
  }
1013
1789
 
1790
+ // ../kit/src/cli.ts
1791
+ init_style();
1792
+ init_text2();
1793
+
1014
1794
  // ../kit/src/usage.ts
1015
1795
  import { appendFileSync, mkdirSync } from "fs";
1016
1796
  import { homedir as homedir3 } from "os";
1017
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1018
- import process14 from "process";
1797
+ import { dirname as dirname2, join as join4 } from "path";
1798
+ import process16 from "process";
1019
1799
 
1020
1800
  // ../kit/src/logs.ts
1801
+ init_user_config();
1021
1802
  var DAY_MS = 24 * 60 * 60 * 1000;
1022
1803
  var CLI_FOLDER = "kaynooo-cli";
1023
1804
 
1024
1805
  // ../kit/src/usage.ts
1806
+ init_user_config();
1025
1807
  var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1026
1808
  var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1027
1809
  var LONGEST_NAME = 40;
@@ -1029,14 +1811,13 @@ var usageError;
1029
1811
  function noteUsageError(message) {
1030
1812
  usageError = message;
1031
1813
  }
1032
- function stateHome(env = process14.env) {
1033
- const dir = env.XDG_STATE_HOME;
1034
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1814
+ function stateHome(env = process16.env) {
1815
+ return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
1035
1816
  }
1036
- function usagePath(env = process14.env) {
1817
+ function usagePath(env = process16.env) {
1037
1818
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1038
1819
  }
1039
- function usageRecorded(env = process14.env) {
1820
+ function usageRecorded(env = process16.env) {
1040
1821
  const off = env.KAYNOOO_CLI_NO_USAGE;
1041
1822
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1042
1823
  }
@@ -1045,12 +1826,12 @@ function flagNames(argv) {
1045
1826
  const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1046
1827
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1047
1828
  }
1048
- function usageEntry(bin, command, argv, code, now = new Date) {
1829
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1049
1830
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1050
1831
  usageError = undefined;
1051
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1832
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1052
1833
  }
1053
- function recordUsage(entry, env = process14.env) {
1834
+ function recordUsage(entry, env = process16.env) {
1054
1835
  if (!usageRecorded(env))
1055
1836
  return;
1056
1837
  try {
@@ -1066,7 +1847,11 @@ var LEVEL_OPTIONS = {
1066
1847
  ...OUTPUT_OPTIONS,
1067
1848
  help: { type: "boolean", short: "h", description: "show this help" }
1068
1849
  };
1069
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1850
+ var TOP_OPTIONS = {
1851
+ ...LEVEL_OPTIONS,
1852
+ version: { type: "boolean", short: "v", description: "print the version" },
1853
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1854
+ };
1070
1855
  async function commandRows(all, colors) {
1071
1856
  const commands = shown(all);
1072
1857
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -1101,6 +1886,10 @@ function takeOutputFlags(argv) {
1101
1886
  async function resolveSummary(summary) {
1102
1887
  return typeof summary === "string" ? summary : summary();
1103
1888
  }
1889
+ function lookup({ commands, aliases }, word) {
1890
+ const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
1891
+ return Object.hasOwn(commands, name) ? commands[name] : undefined;
1892
+ }
1104
1893
  function scopeOf(commands, extra, aliases) {
1105
1894
  return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1106
1895
  }
@@ -1140,8 +1929,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1140
1929
  `);
1141
1930
  }
1142
1931
  function printError(prefix, message, hint, cause) {
1143
- const colors = paint(process15.stderr);
1144
- const styled = takesControlCodes(process15.stderr);
1932
+ const colors = paint(process17.stderr);
1933
+ const styled = takesControlCodes(process17.stderr);
1145
1934
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1146
1935
  const under = (label, text, tint) => text === undefined ? "" : `
1147
1936
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1184,23 +1973,23 @@ async function dispatch(level, typed, { version, redact }) {
1184
1973
  }
1185
1974
  }
1186
1975
  if (name === undefined && level.path.length > 1) {
1187
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1976
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stderr));
1188
1977
  return 2;
1189
1978
  }
1190
1979
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1191
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1980
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stdout));
1192
1981
  return 0;
1193
1982
  }
1194
1983
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1195
1984
  console.log(version);
1196
1985
  return 0;
1197
1986
  }
1198
- let command = level.commands[level.aliases?.[name] ?? name];
1987
+ let command = lookup(level, name);
1199
1988
  let rest = args;
1200
1989
  let ran = name;
1201
1990
  if (command === undefined && level.lazy.length > 0) {
1202
1991
  level = await expand(level, [...level.path.slice(1), ...argv]);
1203
- command = level.commands[level.aliases?.[name] ?? name];
1992
+ command = lookup(level, name);
1204
1993
  }
1205
1994
  if (command === undefined && level.defaultCommand !== undefined) {
1206
1995
  command = level.commands[level.defaultCommand];
@@ -1280,18 +2069,19 @@ async function leafCandidates(run, words) {
1280
2069
  async function candidates(scope, defaultCommand, words, before = []) {
1281
2070
  const [word = "", ...rest] = words;
1282
2071
  const listing = rest.length === 0 && !word.startsWith("-");
1283
- let { commands, aliases } = scope;
1284
- let command = commands[aliases?.[word] ?? word];
2072
+ let { commands } = scope;
2073
+ let command = lookup(scope, word);
1285
2074
  if (listing || command === undefined) {
1286
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
1287
- command = commands[aliases?.[word] ?? word];
2075
+ const expanded = await expand(scope, [...before, ...words]);
2076
+ commands = expanded.commands;
2077
+ command = lookup(expanded, word);
1288
2078
  }
1289
2079
  if (listing) {
1290
2080
  const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1291
2081
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1292
2082
  const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1293
2083
  const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1294
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
2084
+ return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
1295
2085
  }
1296
2086
  if (command === undefined) {
1297
2087
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
@@ -1299,6 +2089,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1299
2089
  }
1300
2090
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1301
2091
  }
2092
+ var COMPLETIONS = "--completions";
2093
+ function flagValue([flag = "", ...rest]) {
2094
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
2095
+ }
2096
+ function printCompletionScript(name, args) {
2097
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
2098
+ if (shell === undefined || args.length !== 1) {
2099
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
2100
+ return 2;
2101
+ }
2102
+ console.log(completionScript(shell, [name]).trimEnd());
2103
+ return 0;
2104
+ }
1302
2105
  async function printCandidates(found) {
1303
2106
  for (const line of await found)
1304
2107
  console.log(line);
@@ -1311,7 +2114,7 @@ function packageVersion(entry = Bun.main) {
1311
2114
  } catch {}
1312
2115
  for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1313
2116
  try {
1314
- const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
2117
+ const { version } = JSON.parse(readFileSync5(join5(dir, "package.json"), "utf8"));
1315
2118
  if (typeof version === "string")
1316
2119
  return version;
1317
2120
  } catch {}
@@ -1321,15 +2124,20 @@ function packageVersion(entry = Bun.main) {
1321
2124
  }
1322
2125
  async function runCli(cli, argv = scriptArgs()) {
1323
2126
  const version = cli.version ?? packageVersion();
2127
+ const answered = await askpassClient(argv);
2128
+ if (answered !== undefined)
2129
+ return answered;
1324
2130
  if (argv[0] === COMPLETE)
1325
2131
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
2132
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
2133
+ return printCompletionScript(cli.name, flagValue(argv));
1326
2134
  const started = performance.now();
1327
2135
  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
2136
  const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1329
2137
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1330
2138
  if (cli.usage !== false) {
1331
2139
  try {
1332
- recordUsage(usageEntry(cli.name, command, argv, code));
2140
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1333
2141
  } catch {}
1334
2142
  }
1335
2143
  return code;
@@ -1338,8 +2146,7 @@ function commandPath(scope, argv) {
1338
2146
  const path = [];
1339
2147
  let level = scope;
1340
2148
  for (const word of argv.filter((each) => !each.startsWith("-"))) {
1341
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1342
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
2149
+ const command = lookup(level, word);
1343
2150
  if (command === undefined)
1344
2151
  break;
1345
2152
  path.push(word);
@@ -1349,61 +2156,77 @@ function commandPath(scope, argv) {
1349
2156
  }
1350
2157
  return path.length === 0 ? undefined : path.join(" ");
1351
2158
  }
1352
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1353
- if (argv[0] === COMPLETE)
1354
- return printCandidates(leafCandidates(run, argv.slice(1)));
1355
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1356
- console.log(version ?? packageVersion());
1357
- return 0;
1358
- }
1359
- let code;
1360
- const started = performance.now();
1361
- try {
1362
- code = await run(argv);
1363
- } catch (error) {
1364
- code = reportThrown(name, error, redact, wantsJson(argv));
1365
- }
1366
- notifyEnd(name, code, performance.now() - started);
1367
- if (usage !== false) {
1368
- try {
1369
- recordUsage(usageEntry(name, undefined, argv, code));
1370
- } catch {}
1371
- }
1372
- return code;
1373
- }
1374
- // ../kit/src/folders.ts
1375
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
2159
+
2160
+ // ../kit/src/index.ts
2161
+ init_config();
2162
+
2163
+ // ../kit/src/excerpt.ts
2164
+ init_text2();
2165
+
2166
+ // ../kit/src/index.ts
2167
+ init_folders();
2168
+ init_format2();
2169
+
2170
+ // ../kit/src/git.ts
2171
+ init_args();
2172
+ // ../kit/src/limit.ts
2173
+ init_args();
2174
+
2175
+ // ../kit/src/index.ts
2176
+ init_mode();
2177
+
1376
2178
  // ../kit/src/pool.ts
1377
- async function pool(items, limit, task) {
2179
+ async function pool(items, limit, task, onDone) {
1378
2180
  const results = Array.from({ length: items.length });
1379
2181
  let next = 0;
2182
+ let done = 0;
1380
2183
  async function worker() {
1381
2184
  while (next < items.length) {
1382
2185
  const index = next++;
1383
2186
  results[index] = await task(items[index]);
2187
+ onDone?.(++done, items.length);
1384
2188
  }
1385
2189
  }
1386
2190
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1387
2191
  return results;
1388
2192
  }
2193
+ // ../kit/src/report.ts
2194
+ init_style();
2195
+ init_text2();
1389
2196
  // ../kit/src/secrets.ts
1390
2197
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
2198
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1391
2199
  // ../kit/src/sessions.ts
1392
2200
  var {Glob } = globalThis.Bun;
1393
2201
  var SESSION_FILES = new Glob("*.json");
1394
2202
  var ACCOUNT_DIRS = new Glob("*/sessions");
1395
2203
  // ../kit/src/size.ts
1396
- var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
2204
+ var SIZE = /^(\d+(?:\.\d+)?)\s*(?:([kmgt])i?b?|(b))?$/i;
1397
2205
  var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
1398
2206
  function parseSize(text, bareUnit = 1) {
1399
2207
  const match = SIZE.exec(text.trim());
1400
2208
  if (match === null)
1401
2209
  return;
1402
- const suffix = match[2].toLowerCase();
1403
- return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
2210
+ const suffix = match[2]?.toLowerCase();
2211
+ let unit = bareUnit;
2212
+ if (match[3] !== undefined)
2213
+ unit = 1;
2214
+ else if (suffix !== undefined)
2215
+ unit = 1024 ** POWERS[suffix];
2216
+ return Math.round(Number(match[1]) * unit);
1404
2217
  }
2218
+
2219
+ // ../kit/src/index.ts
2220
+ init_style();
2221
+ init_text2();
2222
+ init_theme();
2223
+ init_user_config();
2224
+
1405
2225
  // ../kit/src/watch.ts
1406
- import process16 from "process";
2226
+ init_args();
2227
+ init_input();
2228
+ init_style();
2229
+ import process18 from "process";
1407
2230
  import { format } from "util";
1408
2231
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1409
2232
  var DEFAULT_SECONDS = 2;
@@ -1425,7 +2248,7 @@ function withoutWatch(args) {
1425
2248
  }
1426
2249
  return rest;
1427
2250
  }
1428
- async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
2251
+ async function watching(value, step, stream = process18.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1429
2252
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1430
2253
  if (!takesControlCodes(stream))
1431
2254
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1433,12 +2256,12 @@ async function watching(value, step, stream = process16.stdout, sleep = Bun.slee
1433
2256
  for (let round = 0;round < rounds; round++) {
1434
2257
  const held = [];
1435
2258
  const { log, info } = console;
1436
- const write = process16.stdout.write.bind(process16.stdout);
2259
+ const write = process18.stdout.write.bind(process18.stdout);
1437
2260
  const hold = (...parts) => void held.push(`${format(...parts)}
1438
2261
  `);
1439
2262
  console.log = hold;
1440
2263
  console.info = hold;
1441
- process16.stdout.write = (text) => {
2264
+ process18.stdout.write = (text) => {
1442
2265
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1443
2266
  return true;
1444
2267
  };
@@ -1447,7 +2270,7 @@ async function watching(value, step, stream = process16.stdout, sleep = Bun.slee
1447
2270
  } finally {
1448
2271
  console.log = log;
1449
2272
  console.info = info;
1450
- process16.stdout.write = write;
2273
+ process18.stdout.write = write;
1451
2274
  }
1452
2275
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1453
2276
  await sleep(interval);
@@ -1455,9 +2278,10 @@ async function watching(value, step, stream = process16.stdout, sleep = Bun.slee
1455
2278
  return code;
1456
2279
  }
1457
2280
  // ../kit/src/workspace-root.ts
2281
+ init_user_config();
1458
2282
  import { homedir as homedir4 } from "os";
1459
2283
  import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1460
- import process17 from "process";
2284
+ import process19 from "process";
1461
2285
  function expandHome(path, home) {
1462
2286
  if (path === "~")
1463
2287
  return home;
@@ -1467,22 +2291,22 @@ function configured(env, home) {
1467
2291
  const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1468
2292
  return typeof folder === "string" && folder !== "" ? folder : undefined;
1469
2293
  }
1470
- function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
2294
+ function workspaceRoot({ given, env = process19.env, home = homedir4() } = {}) {
1471
2295
  const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1472
2296
  return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1473
2297
  }
1474
2298
  // src/audit.ts
1475
- import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync7, statSync as statSync2 } from "fs";
2299
+ import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync8, statSync as statSync2 } from "fs";
1476
2300
  import { readdir } from "fs/promises";
1477
2301
  import { join as join9, relative, resolve as resolve5 } from "path";
1478
- import process19 from "process";
2302
+ import process21 from "process";
1479
2303
 
1480
2304
  // src/osv.ts
1481
- import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
2305
+ import { existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
1482
2306
  import { join as join8 } from "path";
1483
2307
 
1484
2308
  // src/report.ts
1485
- import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
2309
+ import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
1486
2310
  import { join as join7 } from "path";
1487
2311
  var UPPER_BOUND = /<\s*(\d[\w.+-]*)/;
1488
2312
  var DEPENDENCY_KINDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
@@ -1566,7 +2390,7 @@ function reachedFrom(graph, direct, targets) {
1566
2390
  }
1567
2391
  function readManifest(path) {
1568
2392
  try {
1569
- return existsSync4(path) ? JSON.parse(readFileSync5(path, "utf8")) : {};
2393
+ return existsSync4(path) ? JSON.parse(readFileSync6(path, "utf8")) : {};
1570
2394
  } catch {
1571
2395
  return {};
1572
2396
  }
@@ -1687,7 +2511,7 @@ async function osvFindings(locked, ecosystem, direct, level, ignore, fetcher = f
1687
2511
  }
1688
2512
  function manifestNames(dir) {
1689
2513
  try {
1690
- const manifest = JSON.parse(readFileSync6(join8(dir, "composer.json"), "utf8"));
2514
+ const manifest = JSON.parse(readFileSync7(join8(dir, "composer.json"), "utf8"));
1691
2515
  return new Set([...Object.keys(manifest.require ?? {}), ...Object.keys(manifest["require-dev"] ?? {})]);
1692
2516
  } catch {
1693
2517
  return new Set;
@@ -1696,7 +2520,7 @@ function manifestNames(dir) {
1696
2520
  async function osvAudit(dir, level, ignore, fetcher = fetch) {
1697
2521
  const all = { findings: [], below: 0 };
1698
2522
  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);
2523
+ const done = await osvFindings(each.parse(readFileSync7(join8(dir, each.lockfile), "utf8")), each.osv, each.lockfile === "composer.lock" ? manifestNames(dir) : new Set, level, ignore, fetcher);
1700
2524
  all.findings.push(...done.findings);
1701
2525
  all.below += done.below;
1702
2526
  }
@@ -1704,12 +2528,11 @@ async function osvAudit(dir, level, ignore, fetcher = fetch) {
1704
2528
  }
1705
2529
 
1706
2530
  // src/audit.ts
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
2531
+ var USAGE = `ws 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
1708
2532
 
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.
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.
1711
-
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.`;
2533
+ Each package with an advisory is one row: its worst severity, advisory count, prod or dev, direct or via the direct dependencies leading to it, and the version that fixes every advisory at once.
2534
+ It reaches the network: \`bun audit --json\` for a bun.lock, osv.dev for a composer.lock, Cargo.lock or uv.lock; the walk goes three levels deep and stops at a lockfile.
2535
+ To sweep many repositories at once; \`pkg audit\` vets the one repository in depth.`;
1713
2536
  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"]];
1714
2537
  var OPTIONS = {
1715
2538
  level: { type: "string", choices: SEVERITIES, default: "moderate", description: "only the advisories at least this severe: low, moderate, high or critical" },
@@ -1780,8 +2603,8 @@ async function bunAudited(path, shown, level, ignore) {
1780
2603
  runCommand(["bun", "audit", "--json"], { cwd: path, timeoutMs: AUDIT_MS }),
1781
2604
  runCommand(["bun", "audit", "--json", "--prod"], { cwd: path, timeoutMs: AUDIT_MS })
1782
2605
  ]);
1783
- const audit = parseAudit(stdoutOf(all));
1784
- const reached = parseAudit(stdoutOf(production));
2606
+ const audit = parseAudit(all.stdout);
2607
+ const reached = parseAudit(production.stdout);
1785
2608
  if (audit === undefined || reached === undefined)
1786
2609
  return { repo: shown, path, findings: [], below: 0, warnings: [], error: failure(audit === undefined ? all : production) };
1787
2610
  const reaching = new Set(Object.keys(reached));
@@ -1792,7 +2615,7 @@ async function bunAudited(path, shown, level, ignore) {
1792
2615
  }
1793
2616
  function lockText(path) {
1794
2617
  try {
1795
- return readFileSync7(join9(path, "bun.lock"), "utf8");
2618
+ return readFileSync8(join9(path, "bun.lock"), "utf8");
1796
2619
  } catch {
1797
2620
  return "";
1798
2621
  }
@@ -1804,15 +2627,12 @@ function originOf(found) {
1804
2627
  return "via";
1805
2628
  return `via ${found.via.slice(0, VIA_SHOWN).join(", ")}${found.via.length > VIA_SHOWN ? ` +${found.via.length - VIA_SHOWN}` : ""}`;
1806
2629
  }
1807
- function stdoutOf(ran) {
1808
- return Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1809
- }
1810
2630
  function failure(ran) {
1811
2631
  return ran.timedOut ? `timed out after ${AUDIT_MS / 1000}s` : ran.text.trim().split(`
1812
2632
  `).at(-1) ?? `exit ${ran.code}`;
1813
2633
  }
1814
2634
  function tint(severity) {
1815
- const colors = paint(process19.stdout);
2635
+ const colors = paint(process21.stdout);
1816
2636
  if (severity === "critical" || severity === "high")
1817
2637
  return colors.red;
1818
2638
  return severity === "moderate" ? colors.yellow : colors.dim;
@@ -1828,15 +2648,23 @@ function rows(findings) {
1828
2648
  ]);
1829
2649
  }
1830
2650
  async function audit(args) {
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"] });
2651
+ 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: ["ws audit", "ws audit ~/Workspace --level high --prod"] });
1832
2652
  const root = resolve5(positionals[0] ?? ".");
1833
2653
  if (!existsSync6(root) || !statSync2(root).isDirectory())
1834
2654
  fail(`no folder ${root}`);
1835
2655
  const level = oneOf(values.level, "level", SEVERITIES);
1836
- const paths = await findRepos(root);
1837
- if (paths.length === 0)
1838
- fail(`no bun.lock, composer.lock, Cargo.lock or uv.lock under ${root}`);
1839
- const audits = await pool(paths, configuredNumber("audit", "concurrency", CONCURRENCY), async (path) => audited(path, relative(root, path) || ".", level, values.ignore ?? []));
2656
+ const progress = progressLine();
2657
+ let audits;
2658
+ try {
2659
+ progress.update({ step: "finding the repositories" });
2660
+ const paths = await findRepos(root);
2661
+ if (paths.length === 0)
2662
+ fail(`no bun.lock, composer.lock, Cargo.lock or uv.lock under ${root}`);
2663
+ progress.update({ step: "auditing", done: 0, total: paths.length, unit: "repositories" });
2664
+ audits = await pool(paths, configuredNumber("audit", "concurrency", CONCURRENCY), async (path) => audited(path, relative(root, path) || ".", level, values.ignore ?? []), (done, total) => progress.update({ step: "auditing", done, total, unit: "repositories" }));
2665
+ } finally {
2666
+ progress.stop();
2667
+ }
1840
2668
  const kept = audits.map((each) => ({ ...each, findings: values.prod === true ? each.findings.filter((found) => found.scope === "prod") : each.findings }));
1841
2669
  if (values.json === true)
1842
2670
  printJson(kept);
@@ -1847,8 +2675,8 @@ async function audit(args) {
1847
2675
  return kept.some((each) => each.findings.length > 0) ? 1 : 0;
1848
2676
  }
1849
2677
  function show(audits, total) {
1850
- const label = role("label", process19.stdout);
1851
- const path = role("path", process19.stdout);
2678
+ const label = role("label", process21.stdout);
2679
+ const path = role("path", process21.stdout);
1852
2680
  const flagged = audits.filter((each) => each.error !== undefined || each.findings.length > 0);
1853
2681
  if (flagged.length === 0) {
1854
2682
  console.log(label(`no advisory in ${total} ${total === 1 ? "repository" : "repositories"}`));
@@ -1870,13 +2698,13 @@ function show(audits, total) {
1870
2698
  // src/repos.ts
1871
2699
  import { existsSync as existsSync8, statSync as statSync3 } from "fs";
1872
2700
  import { basename as basename2, relative as relative2 } from "path";
1873
- import process21 from "process";
2701
+ import process23 from "process";
1874
2702
 
1875
2703
  // src/repos-scan.ts
1876
2704
  import { existsSync as existsSync7 } from "fs";
1877
2705
  import { readdir as readdir2 } from "fs/promises";
1878
2706
  import { basename, join as join10 } from "path";
1879
- import process20 from "process";
2707
+ import process22 from "process";
1880
2708
  var MAX_DEPTH2 = 3;
1881
2709
  var CONCURRENCY2 = 8;
1882
2710
  var PACKAGE_CONCURRENCY = 4;
@@ -1923,8 +2751,8 @@ async function findRepos2(root, skip) {
1923
2751
  }
1924
2752
  async function read(path, args, timeoutMs = GIT_MS) {
1925
2753
  try {
1926
- const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process20.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
1927
- return ran.code === 0 && !ran.timedOut ? ran.text.trim() : undefined;
2754
+ const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process22.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
2755
+ return ran.code === 0 && !ran.timedOut ? ran.stdout.trim() : undefined;
1928
2756
  } catch {
1929
2757
  return;
1930
2758
  }
@@ -2000,7 +2828,7 @@ function firstLine(text) {
2000
2828
  }
2001
2829
  async function fastForward(path) {
2002
2830
  try {
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 });
2831
+ const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...process22.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs: GIT_MS });
2004
2832
  if (ran.timedOut)
2005
2833
  return "timed out";
2006
2834
  return ran.code === 0 ? undefined : firstLine(ran.text.trim()) || `exit ${ran.code}`;
@@ -2010,17 +2838,14 @@ async function fastForward(path) {
2010
2838
  }
2011
2839
 
2012
2840
  // src/repos.ts
2013
- 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
2841
+ var USAGE2 = `ws repos [options] [root]: the git repositories under root (the configured workspace by default) that need attention: dirty files, commits not pushed, an upstream ahead, commits since the latest tag
2014
2842
 
2015
- 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.
2016
-
2017
- Ahead and behind are those of the last fetch unless --fetch refreshes the upstreams first, which reaches the remote.
2018
- --pull fetches, then fast-forwards the repositories listed that are clean, on a branch and only behind their upstream, and touches nothing else: a dirty, ahead, diverged or detached one is reported as skipped. A repository pulled is listed again as it now stands.
2019
- --path prints only the paths of the repositories listed, one per line, for xargs -d '\\n'.`;
2843
+ A clean repository, or one with only unreleased commits, is left out unless --all or --only unreleased. The walk goes ${MAX_DEPTH2} levels deep and skips the names in "skip" of \`~/.config/kaynooo-cli/repos.json\`; ahead and behind are those of the last fetch unless --fetch reaches the remote.
2844
+ --pull fetches, then fast-forwards only the repositories listed that are clean, on a branch and only behind their upstream; the others are reported as skipped.`;
2020
2845
  var EXITS2 = [[0, "it listed the repositories, including when none needs attention"], [1, "a fast-forward --pull attempted failed"], [2, "a usage error, an unreadable config or a root that is no folder"]];
2021
2846
  var OPTIONS2 = {
2022
2847
  all: { type: "boolean", short: "a", description: "list the repositories with nothing to report too" },
2023
- only: { type: "string", choices: REASONS, description: "only the repositories with this reason: dirty, unpushed, unreleased or behind" },
2848
+ only: { type: "string", multiple: true, choices: REASONS, description: "only the repositories with this reason: dirty, unpushed, unreleased or behind, repeatable" },
2024
2849
  watch: watchOption("the repositories"),
2025
2850
  fetch: { type: "boolean", conflicts: ["watch"], description: "refresh the upstreams first (reaches the remote)" },
2026
2851
  pull: { type: "boolean", conflicts: ["watch"], description: "fetch, then fast-forward the clean repositories listed that are only behind their upstream (reaches the remote)" },
@@ -2043,7 +2868,7 @@ function releasedCell(repo) {
2043
2868
  return repo.packages.filter((release) => release.unreleased > 0).map((release) => `${release.name} ${release.unreleased}`).join(", ") || "-";
2044
2869
  return repo.tag === null || repo.unreleased === 0 ? "-" : `${repo.unreleased} since ${repo.tag}`;
2045
2870
  }
2046
- function syncCell(repo, stream = process21.stdout) {
2871
+ function syncCell(repo, stream = process23.stdout) {
2047
2872
  const colors = paint(stream);
2048
2873
  const ahead = repo.ahead ?? 0;
2049
2874
  const behind = repo.behind ?? 0;
@@ -2054,7 +2879,7 @@ function syncCell(repo, stream = process21.stdout) {
2054
2879
  return parts.length === 0 ? colors.dim("-") : `${parts.join(" ")}${diverged ? colors.yellow(" diverged") : ""}`;
2055
2880
  }
2056
2881
  var DEFAULT_BRANCHES = new Set(["main", "master"]);
2057
- function branchCell(repo, stream = process21.stdout) {
2882
+ function branchCell(repo, stream = process23.stdout) {
2058
2883
  const colors = paint(stream);
2059
2884
  if (repo.unreadable)
2060
2885
  return colors.red("? (unreadable)");
@@ -2063,8 +2888,8 @@ function branchCell(repo, stream = process21.stdout) {
2063
2888
  return DEFAULT_BRANCHES.has(repo.branch) ? repo.branch : role("accent", stream)(repo.branch);
2064
2889
  }
2065
2890
  function row(repo, shown) {
2066
- const colors = paint(process21.stdout);
2067
- const tint = role("path", process21.stdout);
2891
+ const colors = paint(process23.stdout);
2892
+ const tint = role("path", process23.stdout);
2068
2893
  const unreleased = releasedCell(repo);
2069
2894
  return [
2070
2895
  tint(shown),
@@ -2075,19 +2900,31 @@ function row(repo, shown) {
2075
2900
  unreleased === "-" ? colors.dim("-") : colors.cyan(unreleased)
2076
2901
  ];
2077
2902
  }
2078
- async function repos(args) {
2079
- 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"]] });
2903
+ async function repos(args, watched = false) {
2904
+ 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: ["ws repos", "ws repos ~/Workspace --only unreleased --fetch", ["ws repos --only behind --pull", "fast-forward what is behind and clean"], ["ws repos --only dirty --path", "the paths, for xargs"]] });
2080
2905
  if (values.watch !== undefined)
2081
- return watching(values.watch, async () => repos(withoutWatch(args)));
2906
+ return watching(values.watch, async () => repos(withoutWatch(args), true));
2082
2907
  const root = workspaceRoot({ given: positionals[0] });
2083
2908
  if (!existsSync8(root) || !statSync3(root).isDirectory())
2084
2909
  fail(`no folder ${root}`);
2085
- const only = values.only === undefined ? undefined : oneOf(values.only, "only", REASONS);
2086
- const paths = await findRepos2(root, await skipped());
2087
- const states = await pool(paths, configuredNumber("repos", "concurrency", CONCURRENCY2), async (path) => inspect(path, values.fetch === true || values.pull === true));
2910
+ const only = values.only ?? [];
2911
+ const progress = watched ? undefined : progressLine();
2912
+ const fetching = values.fetch === true || values.pull === true;
2913
+ const step = fetching ? "fetching" : "reading";
2914
+ let states;
2915
+ try {
2916
+ progress?.update({ step: "finding the repositories" });
2917
+ const paths = await findRepos2(root, await skipped());
2918
+ progress?.update({ step, done: 0, total: paths.length, unit: "repositories" });
2919
+ states = await pool(paths, configuredNumber("repos", "concurrency", CONCURRENCY2), async (path) => inspect(path, fetching), (done, total) => progress?.update({ step, done, total, unit: "repositories" }));
2920
+ } finally {
2921
+ progress?.stop();
2922
+ }
2088
2923
  const keeps = (repo) => {
2089
2924
  const reasons = reasonsOf(repo);
2090
- return only === undefined ? values.all === true || reasons.length > 0 || repo.unreadable : reasons.includes(only);
2925
+ if (only.length > 0)
2926
+ return reasons.some((reason) => only.includes(reason));
2927
+ return values.all === true || reasons.some((reason) => reason !== "unreleased") || repo.unreadable;
2091
2928
  };
2092
2929
  let failedPulls = 0;
2093
2930
  if (values.pull === true) {
@@ -2098,12 +2935,12 @@ async function repos(args) {
2098
2935
  const blocker = pullBlocker(repo);
2099
2936
  const refused = blocker === undefined ? await fastForward(repo.path) : undefined;
2100
2937
  if (blocker !== undefined) {
2101
- log(marked("note", `${repo.name} skipped`, process21.stdout, blocker));
2938
+ log(marked("note", `${repo.name} skipped`, process23.stdout, blocker));
2102
2939
  } else if (refused !== undefined) {
2103
2940
  failedPulls++;
2104
- log(marked("problem", `${repo.name} not pulled`, process21.stdout, refused));
2941
+ log(marked("problem", `${repo.name} not pulled`, process23.stdout, refused));
2105
2942
  } else {
2106
- log(marked("ok", `${repo.name} pulled`, process21.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
2943
+ log(marked("ok", `${repo.name} pulled`, process23.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
2107
2944
  states[index] = await inspect(repo.path, false);
2108
2945
  }
2109
2946
  }
@@ -2118,7 +2955,7 @@ async function repos(args) {
2118
2955
  printJson(kept.map((repo) => ({ ...repo, reasons: reasonsOf(repo) })));
2119
2956
  return failedPulls > 0 ? 1 : 0;
2120
2957
  }
2121
- const label = role("label", process21.stdout);
2958
+ const label = role("label", process23.stdout);
2122
2959
  printHeader("repos", `${basename2(root)} \xB7 ${states.length} ${states.length === 1 ? "repository" : "repositories"}`);
2123
2960
  if (kept.length === 0) {
2124
2961
  console.log(label(`nothing needs attention in ${states.length} repositories`));
@@ -2137,212 +2974,7 @@ async function repos(args) {
2137
2974
  import { existsSync as existsSync11, statSync as statSync4 } from "fs";
2138
2975
  import { homedir as homedir6 } from "os";
2139
2976
  import { relative as relative3 } from "path";
2140
-
2141
- // ../kit/src/prompt.ts
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
- }
2157
-
2158
- // ../kit/src/picker/score.ts
2159
- var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
2160
- var NONE = Number.NEGATIVE_INFINITY;
2161
-
2162
- // ../kit/src/picker/state.ts
2163
- var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
2164
- var PASTE_START = "\x1B[200~";
2165
- var PASTE_END = "\x1B[201~";
2166
- var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
2167
- var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
2168
- var WHEEL_LINES = 3;
2169
- var KEYS = {
2170
- "\x1B[A": "up",
2171
- "\x1BOA": "up",
2172
- "\x10": "up",
2173
- "\x1B[B": "down",
2174
- "\x1BOB": "down",
2175
- "\x0E": "down",
2176
- "\x1B[5~": "pageup",
2177
- "\x1B[6~": "pagedown",
2178
- "\x1B[H": "home",
2179
- "\x1B[1~": "home",
2180
- "\x1BOH": "home",
2181
- "\x1B[F": "end",
2182
- "\x1B[4~": "end",
2183
- "\x1BOF": "end",
2184
- "\r": "enter",
2185
- "\n": "enter",
2186
- "\x03": "cancel",
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",
2200
- "\x7F": "erase",
2201
- "\x1B[3~": "delete",
2202
- "\b": "killword",
2203
- "\x1B\x7F": "killword",
2204
- "\x1B[3;5~": "killnext",
2205
- "\x1Bd": "killnext",
2206
- "\x15": "clear",
2207
- "\v": "killend",
2208
- "\x17": "word",
2209
- "\x19": "yank",
2210
- "\x1A": "suspend",
2211
- "\t": "tab",
2212
- "\x1F": "help",
2213
- "\x1BOP": "help",
2214
- "\x1B[11~": "help"
2215
- };
2216
- function repeat(value, count) {
2217
- return Array.from({ length: count }).fill(value);
2218
- }
2219
- function parseKeys(input, paste = { active: false }, ctrls = []) {
2220
- const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
2221
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
2222
- const wheel = MOUSE.exec(sequence)?.[1];
2223
- if (wheel !== undefined)
2224
- return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
2225
- const named = codes.get(sequence);
2226
- const key = named === undefined ? KEYS[sequence] : { ctrl: named };
2227
- if (sequence === PASTE_START || sequence === PASTE_END) {
2228
- paste.active = sequence === PASTE_START;
2229
- return [];
2230
- }
2231
- if (paste.active && (sequence === "\r" || sequence === `
2232
- `))
2233
- return [];
2234
- if (key !== undefined)
2235
- return [key];
2236
- return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
2237
- });
2238
- }
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
-
2251
- // ../kit/src/prompt.ts
2252
- var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
2253
- function readKeys(input, paste = { active: false }) {
2254
- return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
2255
- }
2256
- async function confirm(question, { default: fallback, ...settings } = {}) {
2257
- let answered = fallback;
2258
- const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
2259
- const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
2260
- if (key === "cancel")
2261
- return "cancel";
2262
- if (key === "enter")
2263
- return answered === undefined ? undefined : "enter";
2264
- const letter = typeof key === "object" ? key.text.toLowerCase() : "";
2265
- if (letter !== "y" && letter !== "n")
2266
- return;
2267
- answered = letter === "y";
2268
- return "enter";
2269
- });
2270
- return accepted ? answered : undefined;
2271
- }
2272
- function asking(colors, question, typed, keys) {
2273
- return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
2274
- }
2275
- function answer(colors, question, state, picked) {
2276
- return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
2277
- }
2278
- async function ask(question, { hint, terminal = process23 }, render, press) {
2279
- const { stdin, stderr } = terminal;
2280
- if (!isInteractive(terminal))
2281
- fail(`cannot ask "${question}" off a terminal`, 2, hint);
2282
- const colors = paint(stderr);
2283
- let current = "asking";
2284
- let outcome;
2285
- const columns = () => stderr.columns || 80;
2286
- const draw = (state, last = false) => {
2287
- const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
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}`);
2290
- current = state;
2291
- };
2292
- const redraw = () => draw(current);
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
- };
2304
- try {
2305
- stderr.on?.("resize", redraw);
2306
- stdin.setRawMode(true);
2307
- stdin.resume();
2308
- stderr.write("\x1B[?25l\x1B[?2004h");
2309
- draw("asking");
2310
- return await new Promise((resolve) => {
2311
- function onData(data) {
2312
- for (const key of readKeys(data.toString(), paste)) {
2313
- if (key === "suspend") {
2314
- suspend();
2315
- continue;
2316
- }
2317
- const pressed = press(key);
2318
- if (pressed !== undefined) {
2319
- settle(pressed);
2320
- return;
2321
- }
2322
- }
2323
- draw("asking");
2324
- }
2325
- function onEnd() {
2326
- settle("cancel");
2327
- }
2328
- function settle(settled) {
2329
- outcome = settled;
2330
- stdin.off("data", onData);
2331
- stdin.off("end", onEnd);
2332
- resolve(settled === "enter");
2333
- }
2334
- stdin.on("data", onData);
2335
- stdin.on("end", onEnd);
2336
- });
2337
- } finally {
2338
- stderr.off?.("resize", redraw);
2339
- draw(outcome ?? "cancel", true);
2340
- stderr.write(`
2341
- \x1B[?25h\x1B[?2004l`);
2342
- stdin.setRawMode(false);
2343
- stdin.pause();
2344
- }
2345
- }
2977
+ init_prompt();
2346
2978
 
2347
2979
  // src/apply.ts
2348
2980
  import { existsSync as existsSync10 } from "fs";
@@ -2360,7 +2992,8 @@ import { lstat, readdir as readdir3 } from "fs/promises";
2360
2992
  import { join as join11 } from "path";
2361
2993
  var FS_LIMIT = 32;
2362
2994
  var FIND_MS = 60000;
2363
- var FIND_LINE = /^(\d+) (\S+) (\d+)$/gm;
2995
+ var FIND_LINE = /^(\w) (\d+) (\S+) (\d+) (\d+)$/gm;
2996
+ var OWN_UID = process.getuid?.() ?? -1;
2364
2997
  var waiting = [];
2365
2998
  var running = 0;
2366
2999
  async function gated(call) {
@@ -2374,9 +3007,10 @@ async function gated(call) {
2374
3007
  waiting.shift()?.();
2375
3008
  }
2376
3009
  }
2377
- async function walkSize(folder) {
3010
+ async function walk(folder, uid) {
2378
3011
  const seen = new Set;
2379
3012
  let total = 0;
3013
+ let foreign = 0;
2380
3014
  const visit = async (dir) => {
2381
3015
  let entries;
2382
3016
  try {
@@ -2386,10 +3020,12 @@ async function walkSize(folder) {
2386
3020
  }
2387
3021
  await Promise.all(entries.map(async (entry) => {
2388
3022
  const path = join11(dir, entry.name);
2389
- if (entry.isDirectory())
2390
- return visit(path);
2391
3023
  try {
2392
3024
  const stat = await gated(async () => lstat(path));
3025
+ if (stat.uid !== uid)
3026
+ foreign++;
3027
+ if (entry.isDirectory())
3028
+ return await visit(path);
2393
3029
  if (stat.nlink > 1) {
2394
3030
  const key = `${stat.dev}:${stat.ino}`;
2395
3031
  if (seen.has(key))
@@ -2400,18 +3036,27 @@ async function walkSize(folder) {
2400
3036
  } catch {}
2401
3037
  }));
2402
3038
  };
3039
+ try {
3040
+ if ((await lstat(folder)).uid !== uid)
3041
+ foreign++;
3042
+ } catch {}
2403
3043
  await visit(folder);
2404
- return total;
3044
+ return { bytes: total, foreign };
2405
3045
  }
2406
- async function findSize(folder) {
3046
+ async function findSize(folder, uid) {
2407
3047
  try {
2408
- const ran = await runCommand(["find", "-P", folder, "(", "-type", "f", "-o", "-type", "l", ")", "-printf", "%n %D:%i %s\\n"], { timeoutMs: FIND_MS });
3048
+ const ran = await runCommand(["find", "-P", folder, "-printf", "%y %n %D:%i %s %U\\n"], { timeoutMs: FIND_MS });
2409
3049
  const lines = [...ran.text.matchAll(FIND_LINE)];
2410
3050
  if (ran.timedOut || ran.code !== 0 && lines.length === 0)
2411
3051
  return;
2412
3052
  const seen = new Set;
2413
3053
  let total = 0;
2414
- for (const [, links, id, bytes] of lines) {
3054
+ let foreign = 0;
3055
+ for (const [, type, links, id, bytes, owner] of lines) {
3056
+ if (Number(owner) !== uid)
3057
+ foreign++;
3058
+ if (type !== "f" && type !== "l")
3059
+ continue;
2415
3060
  if (Number(links) > 1) {
2416
3061
  if (seen.has(id))
2417
3062
  continue;
@@ -2419,13 +3064,13 @@ async function findSize(folder) {
2419
3064
  }
2420
3065
  total += Number(bytes);
2421
3066
  }
2422
- return total;
3067
+ return { bytes: total, foreign };
2423
3068
  } catch {
2424
3069
  return;
2425
3070
  }
2426
3071
  }
2427
- async function sizeOf(folder) {
2428
- return await findSize(folder) ?? await walkSize(folder);
3072
+ async function measure(folder, uid = OWN_UID) {
3073
+ return await findSize(folder, uid) ?? await walk(folder, uid);
2429
3074
  }
2430
3075
 
2431
3076
  // src/sweep-scan.ts
@@ -2566,13 +3211,13 @@ async function judgeFolder(path, kind, inside) {
2566
3211
  if (existsSync9(join12(path, ".git")))
2567
3212
  return { skip: "holds a git repository" };
2568
3213
  if (located === "none")
2569
- return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside } } : { skip: "not in a git repository" };
3214
+ return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside, project: dirname5(inside ?? path) } } : { skip: "not in a git repository" };
2570
3215
  const tracked = await gitIn(parent, ["ls-files", "--", name]);
2571
3216
  if (tracked.code !== 0 || tracked.stdout !== "")
2572
3217
  return { skip: "tracked by git" };
2573
3218
  if (name !== "node_modules" && inside === undefined && (await gitIn(parent, ["check-ignore", "-q", "--", name])).code !== 0)
2574
3219
  return { skip: "not ignored by git" };
2575
- return { entry: { path, kind, committedAt: await lastCommitOf(located.top), action: "remove", inside } };
3220
+ return { entry: { path, kind, committedAt: await lastCommitOf(located.top), action: "remove", inside, project: located.top } };
2576
3221
  }
2577
3222
  async function judgeWorktree(path) {
2578
3223
  const located = await toplevelOf(dirname5(path));
@@ -2604,23 +3249,26 @@ async function judgeWorktree(path) {
2604
3249
  if (unique.stdout !== "")
2605
3250
  return keep(`${unique.stdout.split(`
2606
3251
  `).length} commits on no other branch or remote`);
2607
- return { entry: { path, kind: "worktree", committedAt, action: "remove", repo: top } };
3252
+ return { entry: { path, kind: "worktree", committedAt, action: "remove", repo: top, project: path } };
2608
3253
  }
2609
3254
  async function judge(candidate) {
2610
3255
  if (candidate.global === true)
2611
3256
  return { entry: { path: candidate.path, kind: candidate.kind, committedAt: undefined, action: "remove" } };
2612
3257
  return candidate.kind === "worktree" ? judgeWorktree(candidate.path) : judgeFolder(candidate.path, candidate.kind, candidate.inside);
2613
3258
  }
2614
- async function inspect2({ candidates, skipped }) {
3259
+ async function inspect2({ candidates, skipped }, onDone, uid) {
2615
3260
  const entries = [];
2616
3261
  const rejected = [...skipped];
2617
3262
  await pool(candidates, 8, async (candidate) => {
2618
3263
  const verdict = await judge(candidate);
2619
- if ("skip" in verdict)
3264
+ if ("skip" in verdict) {
2620
3265
  rejected.push({ path: candidate.path, reason: verdict.skip });
2621
- else
2622
- entries.push({ ...verdict.entry, bytes: await sizeOf(candidate.path) });
2623
- });
3266
+ return;
3267
+ }
3268
+ const { bytes, foreign } = await measure(candidate.path, uid);
3269
+ const owned = foreign > 0 && verdict.entry.action === "remove" ? { action: "keep", reason: `${foreign} ${foreign === 1 ? "entry" : "entries"} owned by another user (a container's?)` } : {};
3270
+ entries.push({ ...verdict.entry, ...owned, bytes });
3271
+ }, onDone);
2624
3272
  const listed = new Set(entries.filter((entry) => entry.action === "remove").map((entry) => entry.path));
2625
3273
  return { entries: entries.filter((entry) => entry.inside === undefined || !listed.has(entry.inside)), skipped: rejected };
2626
3274
  }
@@ -2661,12 +3309,81 @@ async function applyAll(entries, done) {
2661
3309
  return outcomes;
2662
3310
  }
2663
3311
 
3312
+ // src/busy.ts
3313
+ import { readdir as readdir5, readFile, readlink } from "fs/promises";
3314
+ import { basename as basename5, join as join14 } from "path";
3315
+ var DEV_PROGRAMS = new Set(["node", "bun", "deno", "npm", "npx", "pnpm", "yarn", "bunx", "vite", "esbuild", "ruby", "java", "cargo", "go", "php", "php-fpm"]);
3316
+ var DEV_PREFIXES = ["python", "php"];
3317
+ var DOCKER_MS = 5000;
3318
+ var PID = /^\d+$/;
3319
+ var PARENT = /^ \S+ (\d+)/;
3320
+ function isDevProgram(comm) {
3321
+ return DEV_PROGRAMS.has(comm) || DEV_PREFIXES.some((prefix) => comm.startsWith(prefix));
3322
+ }
3323
+ async function quietly(read) {
3324
+ try {
3325
+ return await read();
3326
+ } catch {
3327
+ return;
3328
+ }
3329
+ }
3330
+ async function lineage(pid, root) {
3331
+ const seen = new Set;
3332
+ for (let current = pid;current > 1 && !seen.has(current); ) {
3333
+ seen.add(current);
3334
+ const stat = await quietly(async () => readFile(join14(root, String(current), "stat"), "utf8"));
3335
+ const parent = Number(PARENT.exec(stat?.slice(stat.lastIndexOf(")") + 1) ?? "")?.[1]);
3336
+ if (!Number.isInteger(parent))
3337
+ break;
3338
+ current = parent;
3339
+ }
3340
+ return seen;
3341
+ }
3342
+ async function processPlaces(root = "/proc", self = process.pid) {
3343
+ const own = await lineage(self, root);
3344
+ const pids = (await quietly(async () => readdir5(root)) ?? []).filter((name) => PID.test(name)).map(Number).filter((pid) => !own.has(pid));
3345
+ const places = [];
3346
+ await Promise.all(pids.map(async (pid) => {
3347
+ const comm = (await quietly(async () => readFile(join14(root, String(pid), "comm"), "utf8")))?.trim();
3348
+ if (comm === undefined || !isDevProgram(comm))
3349
+ return;
3350
+ const cwd = await quietly(async () => readlink(join14(root, String(pid), "cwd")));
3351
+ const argv = (await quietly(async () => readFile(join14(root, String(pid), "cmdline"), "utf8")))?.split("\x00").filter((arg) => arg.startsWith("/")) ?? [];
3352
+ const who = `pid ${pid} ${comm}`;
3353
+ for (const path of [cwd, ...argv.slice(1)]) {
3354
+ if (path !== undefined)
3355
+ places.push({ path, who });
3356
+ }
3357
+ }));
3358
+ return places;
3359
+ }
3360
+ async function containerPlaces() {
3361
+ const ids = await quietly(async () => runCommand(["docker", "ps", "-q"], { timeoutMs: DOCKER_MS }));
3362
+ if (ids === undefined || ids.code !== 0 || ids.text.trim() === "")
3363
+ return [];
3364
+ const inspected = await quietly(async () => runCommand(["docker", "inspect", "--format", '{{.Name}}{{range .Mounts}}{{if eq .Type "bind"}}\t{{.Source}}{{end}}{{end}}', ...ids.text.trim().split(`
3365
+ `)], { timeoutMs: DOCKER_MS }));
3366
+ if (inspected === undefined || inspected.code !== 0)
3367
+ return [];
3368
+ return inspected.text.trim().split(`
3369
+ `).flatMap((line) => {
3370
+ const [name = "", ...sources] = line.split("\t");
3371
+ return sources.map((path) => ({ path, who: `container ${basename5(name)}` }));
3372
+ });
3373
+ }
3374
+ var within = (path, folder) => path === folder || path.startsWith(`${folder}/`);
3375
+ function userOf(folder, processes, containers) {
3376
+ return processes.find((place) => within(place.path, folder))?.who ?? containers.find((place) => within(place.path, folder) || within(folder, place.path))?.who;
3377
+ }
3378
+
2664
3379
  // src/sweep.ts
2665
3380
  var LARGE = 100 * 1024 ** 2;
2666
3381
  var BIG = 1024 ** 3;
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
3382
+ var USAGE3 = `ws sweep [options] [root]: lists the regenerable folders, caches and worktrees under root (the configured workspace by default, ${MAX_DEPTH3} levels down), largest first with the age of the repo's last commit
2668
3383
 
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.`;
3384
+ Dry unless --apply, which deletes for good, not trashed, after a confirm showing the total (off a terminal, pass --yes).
3385
+ 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.
3386
+ What a running dev process or container uses, a folder holding files another user owns and a worktree that is not removable stay listed as kept, with the reason, and count for nothing in the total.`;
2670
3387
  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"]];
2671
3388
  var ONLY_KINDS = { worktrees: "worktree", folders: "folder", caches: "cache" };
2672
3389
  var OPTIONS3 = {
@@ -2674,7 +3391,7 @@ var OPTIONS3 = {
2674
3391
  yes: { type: "boolean", short: "y", description: "with --apply, skip the confirm" },
2675
3392
  older: { type: "string", description: "only the entries whose repo last committed longer ago than this (30d, 12h)" },
2676
3393
  min: { type: "string", description: "only the entries of at least this size (500K, 10M, 1G)" },
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)" },
3394
+ only: { type: "string", choices: Object.keys(ONLY_KINDS), description: "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)" },
2678
3395
  docker: { type: "boolean", description: "add the docker system df output, which alone takes about ten seconds" },
2679
3396
  json: jsonOption("{root, entries: [{path, kind (folder, worktree or cache), bytes, committedAt, action (remove or keep), reason}], skipped: [{path, reason}], reclaimable, docker, removed?}")
2680
3397
  };
@@ -2689,22 +3406,31 @@ async function dockerUsage() {
2689
3406
  }
2690
3407
  }
2691
3408
  async function sweep(args) {
2692
- const { values, positionals } = parse(args, USAGE3, OPTIONS3, { exits: EXITS3, 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"] });
3409
+ const { values, positionals } = parse(args, USAGE3, OPTIONS3, { exits: EXITS3, positionals: ["[root]"], replaces: "find ~/Workspace -name node_modules, du -sh and rm -rf by hand", examples: ["ws sweep", "ws sweep ~/Workspace --older 30d --min 100M --apply", "ws sweep --only worktrees --apply"] });
2693
3410
  if (positionals.length > 1)
2694
3411
  badUsage("give one root");
2695
3412
  const root = workspaceRoot({ given: positionals[0] });
2696
3413
  if (!existsSync11(root) || !statSync4(root).isDirectory())
2697
3414
  fail(`${root} is not a folder`);
2698
- if (values.only !== undefined && !Object.hasOwn(ONLY_KINDS, values.only))
2699
- badUsage(`--only takes worktrees, folders or caches, not ${values.only}`);
2700
3415
  const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0);
2701
3416
  const minBytes = values.min === undefined ? 0 : parseSize(values.min);
2702
3417
  if (minBytes === undefined)
2703
3418
  badUsage(`--min takes a size such as 500K, 10M or 1G, not ${values.min}`);
2704
3419
  const now = Date.now();
2705
- const found = await findCandidates(root, homedir6(), positionals.length === 0 || values.only === "caches");
2706
- const wanted = values.only === undefined ? found.candidates : found.candidates.filter((candidate) => candidate.kind === ONLY_KINDS[values.only]);
2707
- const { entries: all, skipped } = await inspect2({ candidates: wanted, skipped: found.skipped });
3420
+ const progress = progressLine();
3421
+ let scanned;
3422
+ try {
3423
+ progress.update({ step: "finding the folders" });
3424
+ const found = await findCandidates(root, homedir6(), positionals.length === 0 || values.only === "caches");
3425
+ const wanted = values.only === undefined ? found.candidates : found.candidates.filter((candidate) => candidate.kind === ONLY_KINDS[values.only]);
3426
+ progress.update({ step: "sizing", done: 0, total: wanted.length, unit: "folders" });
3427
+ scanned = await inspect2({ candidates: wanted, skipped: found.skipped }, (done, total) => progress.update({ step: "sizing", done, total, unit: "folders" }));
3428
+ progress.update({ step: "looking for running servers and containers" });
3429
+ await keepWhatIsInUse(scanned.entries);
3430
+ } finally {
3431
+ progress.stop();
3432
+ }
3433
+ const { entries: all, skipped } = scanned;
2708
3434
  const entries = all.filter((entry) => entry.bytes >= minBytes && (olderMs === undefined || entry.committedAt !== undefined && now - entry.committedAt >= olderMs)).sort((a, b) => b.bytes - a.bytes || a.path.localeCompare(b.path));
2709
3435
  const removable = entries.filter((entry) => entry.action === "remove");
2710
3436
  const reclaimable = removable.reduce((sum, entry) => sum + entry.bytes, 0);
@@ -2749,6 +3475,19 @@ function report2(root, outcome, json) {
2749
3475
  else
2750
3476
  problem(`kept ${relative3(root, outcome.path)}`, outcome.error);
2751
3477
  }
3478
+ async function keepWhatIsInUse(entries) {
3479
+ const candidates = entries.filter((entry) => entry.action === "remove" && entry.project !== undefined);
3480
+ if (candidates.length === 0)
3481
+ return;
3482
+ const [processes, containers] = await Promise.all([processPlaces(), containerPlaces()]);
3483
+ for (const entry of candidates) {
3484
+ const who = userOf(entry.project, processes, containers);
3485
+ if (who !== undefined) {
3486
+ entry.action = "keep";
3487
+ entry.reason = `in use by ${who}`;
3488
+ }
3489
+ }
3490
+ }
2752
3491
  function print(root, entries, skipped, reclaimable, now) {
2753
3492
  if (entries.length === 0) {
2754
3493
  console.log("nothing to sweep");
@@ -2767,7 +3506,7 @@ ${tt(reclaimable)} reclaimable${skipped === 0 ? "" : `, ${skipped} skipped (syml
2767
3506
  }
2768
3507
 
2769
3508
  // src/cli.ts
2770
- process24.exitCode = await runCli({
3509
+ process26.exitCode = await runCli({
2771
3510
  name: "ws",
2772
3511
  about: "the repositories under a root: the ones needing attention, the folders worth reclaiming and their known vulnerabilities",
2773
3512
  replaces: "a cd, git status and du loop over each repository of the workspace, and a bun audit run in each",