@kaynooo/cli-code 0.15.0 → 0.17.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,21 +1,19 @@
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 process19 from "process";
6
- // ../kit/src/args.ts
7
- import process9 from "process";
8
- import { parseArgs } from "util";
9
-
10
- // ../kit/src/format.ts
11
- import process7 from "process";
12
-
13
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
14
- var ct = /[aeiou]y$/;
15
- var N = new Map;
16
- var Ot = /(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/;
17
- var Gt = /(?:knife|life|wife)$/;
18
- function K(t, e, { plural: r, zero: n = "singular" } = {}) {
15
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
16
+ function G(t, e, { plural: r, zero: n = "singular" } = {}) {
19
17
  if (e === 1 || e === 0 && n === "singular")
20
18
  return t;
21
19
  if (r !== undefined)
@@ -28,12 +26,10 @@ function K(t, e, { plural: r, zero: n = "singular" } = {}) {
28
26
  return `${t.slice(0, -1)}ves`;
29
27
  return Gt.test(t) ? `${t.slice(0, -2)}ves` : `${t}s`;
30
28
  }
31
- function go(t, e, { zero: r = "plural", ...n } = {}) {
32
- return `${t} ${K(e, t, { ...n, zero: r })}`;
29
+ function bo(t, e, { zero: r = "plural", ...n } = {}) {
30
+ return `${t} ${G(e, t, { ...n, zero: r })}`;
33
31
  }
34
- var Nt = /\s+\S*$/;
35
- var Y = /\s/;
36
- function ko(t, e, r = "...") {
32
+ function Ao(t, e, r = "...") {
37
33
  let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
38
34
  if (t.length <= e)
39
35
  return t;
@@ -44,13 +40,25 @@ function ko(t, e, r = "...") {
44
40
  c = c.trimEnd();
45
41
  return s ? (c + n).slice(0, l) : c + n;
46
42
  }
47
- 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));
48
- var z = new Map;
43
+ var ct, N, Ot, Gt, Nt, Y, be, W;
44
+ var init_chunk_rkhsft4a = __esm(() => {
45
+ ct = /[aeiou]y$/;
46
+ N = new Map;
47
+ Ot = /(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/;
48
+ Gt = /(?:knife|life|wife)$/;
49
+ Nt = /\s+\S*$/;
50
+ Y = /\s/;
51
+ 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
+ W = new Map;
53
+ });
54
+
55
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
56
+ var init_text = __esm(() => {
57
+ init_chunk_rkhsft4a();
58
+ });
49
59
 
50
60
  // ../kit/src/mode.ts
51
61
  import process2 from "process";
52
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
53
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
54
62
  function isSet(value) {
55
63
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
56
64
  }
@@ -64,14 +72,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
64
72
  return "terminal";
65
73
  return isSet(env.CI) ? "ci" : "pipe";
66
74
  }
75
+ var MODES, AGENT_VARIABLES;
76
+ var init_mode = __esm(() => {
77
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
78
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
79
+ });
67
80
 
68
- // ../kit/src/style.ts
69
- import { resolve as resolve3 } from "path";
70
- import process6 from "process";
71
- import { pathToFileURL } from "url";
72
-
73
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
74
- var G2 = /^[a-f0-9]+$/i;
81
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
75
82
  function b(r) {
76
83
  let e = r.startsWith("#") ? r.slice(1) : r;
77
84
  if (!G2.test(e))
@@ -82,11 +89,6 @@ function b(r) {
82
89
  throw Error(`Invalid hex color length: ${e.length}`);
83
90
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
84
91
  }
85
- 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") => {
86
- let [l, n, c] = b(r);
87
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
88
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
89
- var h = new Set(["", "1", "2", "3", "true"]);
90
92
  function C(r, e = globalThis.process?.env ?? {}) {
91
93
  if (e.FORCE_COLOR !== undefined)
92
94
  return h.has(e.FORCE_COLOR);
@@ -100,7 +102,7 @@ function f(r, e = []) {
100
102
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
101
103
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
102
104
  return new Proxy(c, { get(t, i) {
103
- let a = B2[i];
105
+ let a = B[i];
104
106
  if (Array.isArray(a)) {
105
107
  let s = g.get(i);
106
108
  if (s === undefined)
@@ -123,13 +125,21 @@ function f(r, e = []) {
123
125
  function Fe(r = {}) {
124
126
  return f(r);
125
127
  }
126
- var o = Fe();
128
+ var G2, B, h, o;
129
+ var init_chunk_x450vn3m = __esm(() => {
130
+ G2 = /^[a-f0-9]+$/i;
131
+ 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") => {
132
+ let [l, n, c] = b(r);
133
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
134
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
135
+ h = new Set(["", "1", "2", "3", "true"]);
136
+ o = Fe();
137
+ });
127
138
 
128
- // ../kit/src/theme.ts
129
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
130
- import { homedir as homedir2 } from "os";
131
- import { join as join3, resolve as resolve2 } from "path";
132
- import process5 from "process";
139
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
140
+ var init_colors = __esm(() => {
141
+ init_chunk_x450vn3m();
142
+ });
133
143
 
134
144
  // ../kit/src/config.ts
135
145
  import { existsSync } from "fs";
@@ -145,15 +155,21 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
145
155
  return;
146
156
  }
147
157
  }
158
+ var init_config = __esm(() => {
159
+ init_args();
160
+ });
148
161
 
149
162
  // ../kit/src/user-config.ts
150
163
  import { existsSync as existsSync2, readFileSync } from "fs";
151
164
  import { homedir } from "os";
152
- import { join as join2 } from "path";
165
+ import { isAbsolute, join as join2 } from "path";
153
166
  import process4 from "process";
167
+ function xdgFolder(value, fallback) {
168
+ return value !== undefined && isAbsolute(value) ? value : fallback;
169
+ }
154
170
  function configBase(where = {}) {
155
171
  const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
156
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
172
+ return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
157
173
  }
158
174
  function userConfigPath(bin, where = {}) {
159
175
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
@@ -180,36 +196,49 @@ function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
180
196
  const value = readUserConfig(bin, where, legacy)[key];
181
197
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
182
198
  }
199
+ var init_user_config = () => {};
183
200
 
184
201
  // ../kit/src/theme.ts
185
- var ENDS = new Map;
186
- var DEFAULT = {
187
- 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" },
188
- 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" },
189
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
190
- bins: {},
191
- gradient: ["#c084fc", "#67e8f9"]
192
- };
193
- 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" };
194
- 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" };
195
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
196
- var PRESETS = {
197
- default: {},
198
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
199
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
200
- ascii: { glyphs: ASCII }
201
- };
202
- 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"]);
203
- var HEX = /^#[0-9a-f]{6}$/i;
204
- var CONTROL = /\p{Cc}/u;
205
- var MAX_FILE_BYTES = 64 * 1024;
206
- var SPACES = /\s+/;
202
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
203
+ import { homedir as homedir2 } from "os";
204
+ import { join as join3, resolve as resolve2 } from "path";
205
+ import process5 from "process";
206
+ function toLinear(channel) {
207
+ const value = channel / 255;
208
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
209
+ }
210
+ function toOklab(hex) {
211
+ const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
212
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
213
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
214
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
215
+ 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];
216
+ }
217
+ function fromOklab([lightness, a, b]) {
218
+ const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
219
+ const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
220
+ const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
221
+ 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];
222
+ return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
223
+ }
224
+ function gradientAt(theme, ratio) {
225
+ if (theme.gradient === undefined)
226
+ return;
227
+ const key = theme.gradient.join();
228
+ let ends = ENDS.get(key);
229
+ if (ends === undefined) {
230
+ ends = [toOklab(theme.gradient[0]), toOklab(theme.gradient[1])];
231
+ ENDS.set(key, ends);
232
+ }
233
+ const at = Math.min(1, Math.max(0, ratio));
234
+ const [from, to] = ends;
235
+ return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
236
+ }
207
237
  function isColorSpec(spec) {
208
238
  if (typeof spec === "number")
209
239
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
210
240
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
211
241
  }
212
- var CUBE = [0, 95, 135, 175, 215, 255];
213
242
  function cubeLevel(channel) {
214
243
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
215
244
  }
@@ -234,6 +263,9 @@ function tinted(colors, spec, env = process5.env) {
234
263
  return chain[token] ?? chain;
235
264
  }, colors);
236
265
  }
266
+ function shaded(theme, colors, glyph, cells, width, env = process5.env) {
267
+ return Array.from({ length: cells }, (_, index) => tinted(colors, gradientAt(theme, width <= 1 ? 0 : index / (width - 1)) ?? theme.colors.accent, env)(glyph)).join("");
268
+ }
237
269
  function isRecord(value) {
238
270
  return typeof value === "object" && value !== null && !Array.isArray(value);
239
271
  }
@@ -314,7 +346,6 @@ function applyFile(theme, file, where, warn) {
314
346
  function endsWalk(home) {
315
347
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
316
348
  }
317
- var warned = new Set;
318
349
  function warnOnce(message) {
319
350
  if (warned.has(message))
320
351
  return;
@@ -351,8 +382,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
351
382
  }
352
383
  return { theme, sources, preset };
353
384
  }
354
- var current;
355
- var currentKey = "";
356
385
  function activeTheme() {
357
386
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
358
387
  if (current === undefined || key !== currentKey) {
@@ -361,9 +390,40 @@ function activeTheme() {
361
390
  }
362
391
  return current;
363
392
  }
393
+ 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 = "";
394
+ var init_theme = __esm(() => {
395
+ init_config();
396
+ init_user_config();
397
+ ENDS = new Map;
398
+ DEFAULT = {
399
+ 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" },
400
+ 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" },
401
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
402
+ bins: {},
403
+ gradient: ["#c084fc", "#67e8f9"]
404
+ };
405
+ 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" };
406
+ 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" };
407
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
408
+ PRESETS = {
409
+ default: {},
410
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
411
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
412
+ ascii: { glyphs: ASCII }
413
+ };
414
+ 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"]);
415
+ HEX = /^#[0-9a-f]{6}$/i;
416
+ CONTROL = /\p{Cc}/u;
417
+ MAX_FILE_BYTES = 64 * 1024;
418
+ SPACES = /\s+/;
419
+ CUBE = [0, 95, 135, 175, 215, 255];
420
+ warned = new Set;
421
+ });
364
422
 
365
423
  // ../kit/src/style.ts
366
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
424
+ import { resolve as resolve3 } from "path";
425
+ import process6 from "process";
426
+ import { pathToFileURL } from "url";
367
427
  function takesControlCodes(stream, env = process6.env) {
368
428
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
369
429
  }
@@ -386,14 +446,6 @@ function role(name, stream, env = process6.env) {
386
446
  const colors = paint(stream, env);
387
447
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
388
448
  }
389
- var STATUS_WORDS = {
390
- passed: ["passed", "success", "succeeded", "ok"],
391
- failed: ["failed", "failure", "error", "errored"],
392
- running: ["running", "in_progress", "started", "holding"],
393
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
394
- skipped: ["skipped", "cancelled", "canceled", "manual"]
395
- };
396
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
397
449
  function header(bin, context, stream, env = process6.env) {
398
450
  if (!takesControlCodes(stream, env))
399
451
  return "";
@@ -420,9 +472,24 @@ function hyperlink(text, url, stream, env = process6.env) {
420
472
  function fileLink(text, path, stream, from = process6.cwd(), env = process6.env) {
421
473
  return hyperlink(text, pathToFileURL(resolve3(from, path)).href, stream, env);
422
474
  }
475
+ var MARK_WORDS, STATUS_WORDS, STATUS_OF;
476
+ var init_style = __esm(() => {
477
+ init_colors();
478
+ init_mode();
479
+ init_theme();
480
+ MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
481
+ STATUS_WORDS = {
482
+ passed: ["passed", "success", "succeeded", "ok"],
483
+ failed: ["failed", "failure", "error", "errored"],
484
+ running: ["running", "in_progress", "started", "holding"],
485
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
486
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
487
+ };
488
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
489
+ });
423
490
 
424
491
  // ../kit/src/format.ts
425
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
492
+ import process7 from "process";
426
493
  function formatSeconds(total) {
427
494
  let rest = Math.max(0, Math.round(total));
428
495
  const amounts = UNITS.map(([unit, size]) => {
@@ -439,15 +506,16 @@ function formatSeconds(total) {
439
506
  function formatDuration(ms) {
440
507
  return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
441
508
  }
509
+ function formatElapsed(ms) {
510
+ return formatSeconds(Math.floor(Math.max(0, ms) / 1000));
511
+ }
442
512
  function upTo(text, separator) {
443
513
  const end = text.indexOf(separator);
444
514
  return end === -1 ? text : text.slice(0, end);
445
515
  }
446
516
  function truncate(text, width) {
447
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
517
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
448
518
  }
449
- var LINE_BREAKS = /\s*\n\s*/g;
450
- var ESCAPE = String.fromCharCode(27);
451
519
  function textWidth(text) {
452
520
  return Bun.stringWidth(text);
453
521
  }
@@ -496,14 +564,40 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
496
564
  function printJson(value) {
497
565
  console.log(jsonText(value));
498
566
  }
567
+ var UNITS, LINE_BREAKS, ESCAPE;
568
+ var init_format = __esm(() => {
569
+ init_text();
570
+ init_mode();
571
+ init_style();
572
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
573
+ LINE_BREAKS = /\s*\n\s*/g;
574
+ ESCAPE = String.fromCharCode(27);
575
+ });
499
576
 
500
577
  // ../kit/src/help.ts
501
578
  import process8 from "process";
502
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
503
- var USAGE_PREFIX = /^usage:\s*/i;
504
- var FULL_STOP = /\.$/;
505
579
  function usageLine(usage, colors = paint(process8.stdout)) {
506
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
580
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
581
+ `);
582
+ const blank = lines.indexOf("");
583
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
584
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
585
+ const colon = synopses[0].indexOf(": ");
586
+ const inline = synopses[0].slice(colon + 2);
587
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
588
+ if (colon !== -1)
589
+ synopses[0] = synopses[0].slice(0, colon);
590
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
591
+ `)}`;
592
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
593
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
594
+ return [head, ...lead, ...rest].join(`
595
+ `);
596
+ }
597
+ function prose(line, colors) {
598
+ if (colors.cyan("x") === "x")
599
+ return line;
600
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
507
601
  }
508
602
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
509
603
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -538,7 +632,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
538
632
  return [];
539
633
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
540
634
  }
541
- var MAX_INLINE_CHOICES = 24;
542
635
  function optionRows(options, colors = paint(process8.stdout)) {
543
636
  const rows = Object.entries(options).map(([name, option]) => {
544
637
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -553,6 +646,15 @@ function optionRows(options, colors = paint(process8.stdout)) {
553
646
  const width = Math.max(0, ...rows.map((row) => row.width));
554
647
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
555
648
  }
649
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
650
+ var init_help = __esm(() => {
651
+ init_mode();
652
+ init_style();
653
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
654
+ USAGE_PREFIX = /^usage:\s*/i;
655
+ FULL_STOP = /\.$/;
656
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
657
+ });
556
658
 
557
659
  // ../kit/src/text.ts
558
660
  function distance(a, b) {
@@ -580,9 +682,10 @@ function closest(name, names) {
580
682
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
581
683
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
582
684
  }
685
+ var init_text2 = () => {};
686
+
583
687
  // ../kit/src/input.ts
584
688
  import { fstatSync } from "fs";
585
- var WHOLE = /^\d+$/;
586
689
  function wholeNumber(value, name, fallback, min = 1) {
587
690
  if (value === undefined)
588
691
  return fallback;
@@ -591,8 +694,6 @@ function wholeNumber(value, name, fallback, min = 1) {
591
694
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
592
695
  return number;
593
696
  }
594
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
595
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
596
697
  function duration(value, name, fallback, unit = "s") {
597
698
  if (value === undefined)
598
699
  return fallback;
@@ -606,40 +707,27 @@ function isStdinPiped() {
606
707
  const stat = fstatSync(0);
607
708
  return stat.isFIFO() || stat.isFile();
608
709
  }
710
+ var WHOLE, DURATION, UNIT_MS;
711
+ var init_input = __esm(() => {
712
+ init_args();
713
+ WHOLE = /^\d+$/;
714
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
715
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
716
+ });
609
717
 
610
718
  // ../kit/src/args.ts
611
- var DASHES = /^-+/;
719
+ import process9 from "process";
720
+ import { parseArgs } from "util";
612
721
  function jsonOption(holds) {
613
722
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
614
723
  }
615
- class Exit extends Error {
616
- code;
617
- hint;
618
- constructor(message, code, hint) {
619
- super(message);
620
- this.code = code;
621
- this.hint = hint;
622
- }
623
- }
624
724
  function fail(message, code = 2, hint) {
625
725
  throw new Exit(message, code, hint);
626
726
  }
627
-
628
- class UsageError extends Exit {
629
- constructor(message, hint) {
630
- super(message, 2, hint);
631
- }
632
- }
633
727
  function badUsage(message) {
634
728
  throw new UsageError(message);
635
729
  }
636
730
 
637
- class HelpShown extends Exit {
638
- constructor() {
639
- super("help shown", 0);
640
- }
641
- }
642
-
643
731
  class Completing {
644
732
  options;
645
733
  positionals;
@@ -650,11 +738,6 @@ class Completing {
650
738
  this.candidates = candidates;
651
739
  }
652
740
  }
653
- var completion = { active: false };
654
- var OUTPUT_OPTIONS = {
655
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
656
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
657
- };
658
741
  function applyOutput(color, plain, env = process9.env) {
659
742
  const when = plain === true ? "never" : color ?? "auto";
660
743
  if (when === "auto")
@@ -808,7 +891,6 @@ function parseError(error) {
808
891
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
809
892
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
810
893
  }
811
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
812
894
  function nearestOption(message, options, allowNegative) {
813
895
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
814
896
  if (typed === undefined)
@@ -824,6 +906,66 @@ function nearestOption(message, options, allowNegative) {
824
906
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
825
907
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
826
908
  }
909
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
910
+ var init_args = __esm(() => {
911
+ init_format();
912
+ init_help();
913
+ init_text2();
914
+ init_help();
915
+ init_input();
916
+ DASHES = /^-+/;
917
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
918
+ Exit = class Exit extends Error {
919
+ code;
920
+ hint;
921
+ [EXIT] = true;
922
+ constructor(message, code, hint) {
923
+ super(message);
924
+ this.code = code;
925
+ this.hint = hint;
926
+ }
927
+ static [Symbol.hasInstance](value) {
928
+ if (this !== Exit)
929
+ return Function.prototype[Symbol.hasInstance].call(this, value);
930
+ return typeof value === "object" && value !== null && value[EXIT] === true;
931
+ }
932
+ };
933
+ UsageError = class UsageError extends Exit {
934
+ constructor(message, hint) {
935
+ super(message, 2, hint);
936
+ }
937
+ };
938
+ HelpShown = class HelpShown extends Exit {
939
+ constructor() {
940
+ super("help shown", 0);
941
+ }
942
+ };
943
+ completion = { active: false };
944
+ OUTPUT_OPTIONS = {
945
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
946
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
947
+ };
948
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
949
+ });
950
+
951
+ // ../kit/src/folders.ts
952
+ function ignoredFolders(extra = [], where = {}) {
953
+ const configured = readUserConfig("config", where).ignore;
954
+ const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
955
+ return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
956
+ }
957
+ var SKIPPED_FOLDERS;
958
+ var init_folders = __esm(() => {
959
+ init_user_config();
960
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
961
+ });
962
+
963
+ // src/cli.ts
964
+ import process21 from "process";
965
+
966
+ // ../kit/src/index.ts
967
+ init_args();
968
+
827
969
  // ../kit/src/argv.ts
828
970
  import { readFileSync as readFileSync3, realpathSync } from "fs";
829
971
  import { resolve as resolve4 } from "path";
@@ -848,10 +990,26 @@ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), scr
848
990
  const after = at === -1 ? [] : cmdline.slice(at + 1);
849
991
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
850
992
  }
993
+ // ../kit/src/chart.ts
994
+ init_format();
995
+ init_mode();
996
+ init_style();
997
+ init_theme();
998
+ // ../kit/src/ci.ts
999
+ init_args();
1000
+ init_format();
1001
+
1002
+ // ../kit/src/progress.ts
1003
+ init_format();
1004
+ import process12 from "process";
1005
+
851
1006
  // ../kit/src/process.ts
1007
+ import { readFileSync as readFileSync4 } from "fs";
852
1008
  import { constants } from "os";
853
1009
  import process11 from "process";
854
1010
  var KILL_GRACE_MS = 2000;
1011
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1012
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
855
1013
  function exitCodeOf(code, signal) {
856
1014
  if (code !== null)
857
1015
  return code;
@@ -859,10 +1017,57 @@ function exitCodeOf(code, signal) {
859
1017
  return 128 + signal;
860
1018
  return signal === null ? 129 : 128 + constants.signals[signal];
861
1019
  }
862
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
1020
+ function groupsOf(pid) {
1021
+ try {
1022
+ const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
1023
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
1024
+ return { group: Number(fields[2]), foreground: Number(fields[5]) };
1025
+ } catch {
1026
+ return;
1027
+ }
1028
+ }
1029
+ function heardTheTerminal(child) {
1030
+ if (child.pid === undefined)
1031
+ return false;
1032
+ const own = groupsOf("self");
1033
+ return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
1034
+ }
1035
+ function holdSignals(cleanup) {
1036
+ let received;
1037
+ let child;
1038
+ const held = {
1039
+ get signal() {
1040
+ return received;
1041
+ },
1042
+ forward: (to) => {
1043
+ child = to;
1044
+ },
1045
+ release: () => {
1046
+ for (const signal of SIGNALS)
1047
+ process11.off(signal, onSignal);
1048
+ }
1049
+ };
1050
+ function onSignal(signal) {
1051
+ received = signal;
1052
+ if (child !== undefined) {
1053
+ if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
1054
+ child.kill(signal);
1055
+ return;
1056
+ }
1057
+ if (cleanup === undefined)
1058
+ return;
1059
+ held.release();
1060
+ cleanup(signal);
1061
+ process11.kill(process11.pid, signal);
1062
+ }
1063
+ for (const signal of SIGNALS)
1064
+ process11.on(signal, onSignal);
1065
+ return held;
1066
+ }
1067
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
863
1068
  const chunks = [];
864
1069
  const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
865
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
1070
+ 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 } : {} });
866
1071
  const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
867
1072
  const timers = [];
868
1073
  const killGroup = (killing) => {
@@ -902,12 +1107,19 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
902
1107
  stop();
903
1108
  continue;
904
1109
  }
1110
+ if (state.truncated)
1111
+ continue;
1112
+ let kept = data;
905
1113
  if (state.kept + data.length > maxBytes) {
1114
+ let cut = maxBytes - state.kept;
1115
+ while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
1116
+ cut--;
1117
+ kept = data.subarray(0, cut);
906
1118
  state.truncated = true;
907
- continue;
908
1119
  }
909
- state.kept += data.length;
910
- chunks.push({ stream: name, data });
1120
+ state.kept += kept.length;
1121
+ if (kept.length > 0)
1122
+ chunks.push({ stream: name, data: kept });
911
1123
  }
912
1124
  };
913
1125
  try {
@@ -924,6 +1136,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
924
1136
  const joined = () => Buffer.concat(chunks.map(({ data }) => data));
925
1137
  let output;
926
1138
  let text;
1139
+ let stdout;
927
1140
  return {
928
1141
  code: exitCodeOf(proc.exitCode, proc.signalCode),
929
1142
  chunks,
@@ -934,49 +1147,379 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
934
1147
  },
935
1148
  get text() {
936
1149
  return text ??= (output ??= joined()).toString();
1150
+ },
1151
+ get stdout() {
1152
+ return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
937
1153
  }
938
1154
  };
939
1155
  }
940
1156
 
941
1157
  // ../kit/src/progress.ts
1158
+ init_style();
1159
+ init_theme();
1160
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1161
+ var FRAME_MS = 200;
1162
+ var BAR_WIDTH = 20;
1163
+ var CLEAR_BELOW = "\r\x1B[J";
942
1164
  var ESC = String.fromCharCode(27);
943
1165
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
944
1166
  var RESET_STYLE = `${ESC}[0m`;
1167
+ var CTRL_C = 3;
945
1168
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1169
+ var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
1170
+ function liveRegion(render, stream = process12.stderr, env = process12.env) {
1171
+ if (!takesControlCodes(stream, env))
1172
+ return { redraw: () => {
1173
+ return;
1174
+ }, print: (text) => void stream.write(`${text}
1175
+ `), stop: () => {
1176
+ return;
1177
+ }, pause: () => () => {
1178
+ return;
1179
+ } };
1180
+ const write = stream.write.bind(stream);
1181
+ let frame = 0;
1182
+ let drawn = false;
1183
+ let paused = false;
1184
+ let stopped = false;
1185
+ const columns = () => {
1186
+ const now = stream.getWindowSize?.()[0] ?? stream.columns;
1187
+ return now === undefined || now === 0 ? 80 : now;
1188
+ };
1189
+ const clear = () => {
1190
+ if (drawn)
1191
+ write(CLEAR_BELOW);
1192
+ drawn = false;
1193
+ };
1194
+ const draw = () => {
1195
+ if (paused)
1196
+ return;
1197
+ const width = columns() - 1;
1198
+ const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
1199
+ const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
1200
+ if (lines.length === 0) {
1201
+ clear();
1202
+ return;
1203
+ }
1204
+ write(`${CLEAR_BELOW}${lines.join(`
1205
+ `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
1206
+ drawn = true;
1207
+ };
1208
+ let timer = setInterval(draw, FRAME_MS);
1209
+ stream.on?.("resize", draw);
1210
+ let restore = interceptOutput(clear);
1211
+ let release = swallowInput();
1212
+ const onExit = () => {
1213
+ clear();
1214
+ release();
1215
+ };
1216
+ const signals = holdSignals(stop);
1217
+ function stop() {
1218
+ stopped = true;
1219
+ clearInterval(timer);
1220
+ stream.off?.("resize", draw);
1221
+ clear();
1222
+ restore();
1223
+ release();
1224
+ process12.off("exit", onExit);
1225
+ signals.release();
1226
+ }
1227
+ function pause() {
1228
+ if (paused || stopped)
1229
+ return () => {
1230
+ return;
1231
+ };
1232
+ paused = true;
1233
+ clearInterval(timer);
1234
+ stream.off?.("resize", draw);
1235
+ clear();
1236
+ restore();
1237
+ release();
1238
+ return () => {
1239
+ if (!paused || stopped)
1240
+ return;
1241
+ paused = false;
1242
+ timer = setInterval(draw, FRAME_MS);
1243
+ timer.unref();
1244
+ stream.on?.("resize", draw);
1245
+ restore = interceptOutput(clear);
1246
+ release = swallowInput();
1247
+ draw();
1248
+ };
1249
+ }
1250
+ timer.unref();
1251
+ process12.on("exit", onExit);
1252
+ return {
1253
+ redraw: draw,
1254
+ print: (text) => {
1255
+ clear();
1256
+ write(`${text}
1257
+ `);
1258
+ draw();
1259
+ },
1260
+ stop,
1261
+ pause
1262
+ };
1263
+ }
1264
+ function progressLine(stream = process12.stderr, env = process12.env) {
1265
+ const colors = paint(stream, env);
1266
+ const write = stream.write.bind(stream);
1267
+ const begun = performance.now();
1268
+ let started = begun;
1269
+ let current;
1270
+ const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
1271
+ const end = (line) => {
1272
+ region.stop();
1273
+ write(`${line}
1274
+ `);
1275
+ };
1276
+ return {
1277
+ update: (progress) => {
1278
+ const step = current?.step;
1279
+ current = progress;
1280
+ if (progress.step !== step) {
1281
+ started = performance.now();
1282
+ region.redraw();
1283
+ }
1284
+ },
1285
+ stop: region.stop,
1286
+ pause: region.pause,
1287
+ done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
1288
+ failed: (text) => end(marked("problem", text, stream, undefined, env))
1289
+ };
1290
+ }
1291
+ function progressParts({ step, done, total, unit }, spinner, ms) {
1292
+ const { theme } = activeTheme();
1293
+ const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
1294
+ if (total !== undefined && total > 0) {
1295
+ const counted = Math.min(done ?? 0, total);
1296
+ const filled = Math.round(counted / total * BAR_WIDTH);
1297
+ 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 });
1298
+ }
1299
+ parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
1300
+ return parts;
1301
+ }
1302
+ function plain(text) {
1303
+ return text;
1304
+ }
1305
+ function tintedParts(parts, colors) {
1306
+ return parts.map(({ text, tint }) => tint(colors)(text)).join("");
1307
+ }
1308
+ function cutToWidth(line, width) {
1309
+ if (Bun.stringWidth(line) <= width)
1310
+ return line;
1311
+ let room = width;
1312
+ let kept = "";
1313
+ let index = 0;
1314
+ let linked = false;
1315
+ while (index < line.length) {
1316
+ ESCAPE_CODE.lastIndex = index;
1317
+ const escape = ESCAPE_CODE.exec(line);
1318
+ if (escape !== null) {
1319
+ kept += escape[0];
1320
+ linked ||= escape[0].startsWith(`${ESC}]`);
1321
+ index = ESCAPE_CODE.lastIndex;
1322
+ continue;
1323
+ }
1324
+ const char = String.fromCodePoint(line.codePointAt(index));
1325
+ const columns = Bun.stringWidth(char);
1326
+ if (columns > room)
1327
+ break;
1328
+ kept += char;
1329
+ room -= columns;
1330
+ index += char.length;
1331
+ }
1332
+ return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1333
+ }
1334
+ function swallowInput() {
1335
+ const input = process12.stdin;
1336
+ if (!input.isTTY)
1337
+ return () => {
1338
+ return;
1339
+ };
1340
+ const onData = (data) => {
1341
+ if (data.includes(CTRL_C))
1342
+ process12.kill(process12.pid, "SIGINT");
1343
+ };
1344
+ input.setRawMode(true);
1345
+ input.on("data", onData);
1346
+ input.resume();
1347
+ let released = false;
1348
+ return () => {
1349
+ if (released)
1350
+ return;
1351
+ released = true;
1352
+ input.off("data", onData);
1353
+ input.pause();
1354
+ input.setRawMode(false);
1355
+ };
1356
+ }
1357
+ function interceptOutput(clear) {
1358
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1359
+ const wrapped = targets.map(([target, name]) => {
1360
+ const original = Reflect.get(target, name);
1361
+ const wrapper = (...args) => {
1362
+ clear();
1363
+ return original.apply(target, args);
1364
+ };
1365
+ Reflect.set(target, name, wrapper);
1366
+ return { target, name, original, wrapper };
1367
+ });
1368
+ return () => {
1369
+ for (const { target, name, original, wrapper } of wrapped) {
1370
+ if (Reflect.get(target, name) === wrapper)
1371
+ Reflect.set(target, name, original);
1372
+ }
1373
+ };
1374
+ }
1375
+
1376
+ // ../kit/src/ci.ts
1377
+ init_style();
1378
+
1379
+ // ../kit/src/tool.ts
1380
+ init_format();
946
1381
  // ../kit/src/cli.ts
947
- import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1382
+ init_args();
1383
+ import { readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
948
1384
  import { dirname as dirname3, join as join5 } from "path";
949
- import process14 from "process";
1385
+ import process16 from "process";
1386
+
1387
+ // ../kit/src/askpass.ts
1388
+ import process13 from "process";
1389
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1390
+ async function askpassClient(argv) {
1391
+ const socketPath = process13.env[SOCKET_VARIABLE];
1392
+ if (socketPath === undefined)
1393
+ return;
1394
+ const request = { prompt: argv[0] ?? "", ...process13.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1395
+ const { promise, resolve } = Promise.withResolvers();
1396
+ let received = "";
1397
+ try {
1398
+ await Bun.connect({
1399
+ unix: socketPath,
1400
+ socket: {
1401
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1402
+ `),
1403
+ data: (_, chunk) => {
1404
+ received += chunk.toString();
1405
+ },
1406
+ close: () => resolve(received),
1407
+ error: () => resolve("")
1408
+ }
1409
+ });
1410
+ } catch {
1411
+ return 1;
1412
+ }
1413
+ const reply = await promise;
1414
+ if (reply === "")
1415
+ return 1;
1416
+ const { answer } = JSON.parse(reply);
1417
+ if (request.notice === true)
1418
+ return 0;
1419
+ if (answer === undefined)
1420
+ return 1;
1421
+ process13.stdout.write(`${answer}
1422
+ `);
1423
+ return 0;
1424
+ }
1425
+
1426
+ // ../kit/src/completions.ts
1427
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1428
+ 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'
1429
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1430
+ set -l current (commandline -ct)
1431
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1432
+ if test "$line" = __files__
1433
+ __fish_complete_path $current
1434
+ else
1435
+ echo $line
1436
+ end
1437
+ end
1438
+ end`;
1439
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1440
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1441
+ local -a lines
1442
+ COMPREPLY=()
1443
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1444
+ for line in "\${lines[@]}"; do
1445
+ if [[ $line == __files__ ]]; then
1446
+ COMPREPLY+=($(compgen -f -- "$cur"))
1447
+ else
1448
+ words+="\${line%%$'\\t'*}"$'\\n'
1449
+ fi
1450
+ done
1451
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1452
+ }`;
1453
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1454
+ local line
1455
+ local -a described plain
1456
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1457
+ if [[ $line == __files__ ]]; then
1458
+ _files
1459
+ elif [[ $line == *$'\\t'* ]]; then
1460
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1461
+ else
1462
+ plain+=("$line")
1463
+ fi
1464
+ done
1465
+ (( \${#described} )) && _describe -V value described
1466
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1467
+ return 0
1468
+ }`;
1469
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1470
+ if (shell === "fish")
1471
+ return `${header}
1472
+ ${FISH_FUNCTION}
1473
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1474
+ `).join("")}`;
1475
+ if (shell === "bash")
1476
+ return `${header}
1477
+ ${BASH_FUNCTION}
1478
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1479
+ `;
1480
+ return `${header}
1481
+ ${ZSH_FUNCTION}
1482
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1483
+ `;
1484
+ }
950
1485
 
951
1486
  // ../kit/src/notify.ts
952
- import process12 from "process";
1487
+ init_format();
1488
+ init_mode();
1489
+ import process14 from "process";
953
1490
  var NOTIFY_AFTER_MS = 1e4;
954
1491
  var CANCELLED = 130;
955
1492
  function base64(text) {
956
1493
  return Buffer.from(text).toString("base64");
957
1494
  }
958
- function notification(title, body, env = process12.env) {
959
- const id = `kit${process12.pid}`;
1495
+ function notification(title, body, env = process14.env) {
1496
+ const id = `kit${process14.pid}`;
960
1497
  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\\`];
961
1498
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
962
1499
  }
963
- function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
1500
+ function notifyEnd(command, code, ms, { stream = process14.stderr, env = process14.env } = {}) {
964
1501
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
965
1502
  return;
966
1503
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
967
1504
  }
968
1505
 
1506
+ // ../kit/src/cli.ts
1507
+ init_style();
1508
+ init_text2();
1509
+
969
1510
  // ../kit/src/usage.ts
970
1511
  import { appendFileSync, mkdirSync } from "fs";
971
1512
  import { homedir as homedir3 } from "os";
972
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
973
- import process13 from "process";
1513
+ import { dirname as dirname2, join as join4 } from "path";
1514
+ import process15 from "process";
974
1515
 
975
1516
  // ../kit/src/logs.ts
1517
+ init_user_config();
976
1518
  var DAY_MS = 24 * 60 * 60 * 1000;
977
1519
  var CLI_FOLDER = "kaynooo-cli";
978
1520
 
979
1521
  // ../kit/src/usage.ts
1522
+ init_user_config();
980
1523
  var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
981
1524
  var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
982
1525
  var LONGEST_NAME = 40;
@@ -984,14 +1527,13 @@ var usageError;
984
1527
  function noteUsageError(message) {
985
1528
  usageError = message;
986
1529
  }
987
- function stateHome(env = process13.env) {
988
- const dir = env.XDG_STATE_HOME;
989
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1530
+ function stateHome(env = process15.env) {
1531
+ return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
990
1532
  }
991
- function usagePath(env = process13.env) {
1533
+ function usagePath(env = process15.env) {
992
1534
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
993
1535
  }
994
- function usageRecorded(env = process13.env) {
1536
+ function usageRecorded(env = process15.env) {
995
1537
  const off = env.KAYNOOO_CLI_NO_USAGE;
996
1538
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
997
1539
  }
@@ -1000,12 +1542,12 @@ function flagNames(argv) {
1000
1542
  const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1001
1543
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1002
1544
  }
1003
- function usageEntry(bin, command, argv, code, now = new Date) {
1545
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1004
1546
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1005
1547
  usageError = undefined;
1006
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1548
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1007
1549
  }
1008
- function recordUsage(entry, env = process13.env) {
1550
+ function recordUsage(entry, env = process15.env) {
1009
1551
  if (!usageRecorded(env))
1010
1552
  return;
1011
1553
  try {
@@ -1021,7 +1563,11 @@ var LEVEL_OPTIONS = {
1021
1563
  ...OUTPUT_OPTIONS,
1022
1564
  help: { type: "boolean", short: "h", description: "show this help" }
1023
1565
  };
1024
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1566
+ var TOP_OPTIONS = {
1567
+ ...LEVEL_OPTIONS,
1568
+ version: { type: "boolean", short: "v", description: "print the version" },
1569
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1570
+ };
1025
1571
  async function commandRows(all, colors) {
1026
1572
  const commands = shown(all);
1027
1573
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -1056,6 +1602,10 @@ function takeOutputFlags(argv) {
1056
1602
  async function resolveSummary(summary) {
1057
1603
  return typeof summary === "string" ? summary : summary();
1058
1604
  }
1605
+ function lookup({ commands, aliases }, word) {
1606
+ const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
1607
+ return Object.hasOwn(commands, name) ? commands[name] : undefined;
1608
+ }
1059
1609
  function scopeOf(commands, extra, aliases) {
1060
1610
  return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1061
1611
  }
@@ -1095,8 +1645,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1095
1645
  `);
1096
1646
  }
1097
1647
  function printError(prefix, message, hint, cause) {
1098
- const colors = paint(process14.stderr);
1099
- const styled = takesControlCodes(process14.stderr);
1648
+ const colors = paint(process16.stderr);
1649
+ const styled = takesControlCodes(process16.stderr);
1100
1650
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1101
1651
  const under = (label, text, tint) => text === undefined ? "" : `
1102
1652
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1139,23 +1689,23 @@ async function dispatch(level, typed, { version, redact }) {
1139
1689
  }
1140
1690
  }
1141
1691
  if (name === undefined && level.path.length > 1) {
1142
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
1692
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process16.stderr));
1143
1693
  return 2;
1144
1694
  }
1145
1695
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1146
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
1696
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process16.stdout));
1147
1697
  return 0;
1148
1698
  }
1149
1699
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1150
1700
  console.log(version);
1151
1701
  return 0;
1152
1702
  }
1153
- let command = level.commands[level.aliases?.[name] ?? name];
1703
+ let command = lookup(level, name);
1154
1704
  let rest = args;
1155
1705
  let ran = name;
1156
1706
  if (command === undefined && level.lazy.length > 0) {
1157
1707
  level = await expand(level, [...level.path.slice(1), ...argv]);
1158
- command = level.commands[level.aliases?.[name] ?? name];
1708
+ command = lookup(level, name);
1159
1709
  }
1160
1710
  if (command === undefined && level.defaultCommand !== undefined) {
1161
1711
  command = level.commands[level.defaultCommand];
@@ -1235,18 +1785,19 @@ async function leafCandidates(run, words) {
1235
1785
  async function candidates(scope, defaultCommand, words, before = []) {
1236
1786
  const [word = "", ...rest] = words;
1237
1787
  const listing = rest.length === 0 && !word.startsWith("-");
1238
- let { commands, aliases } = scope;
1239
- let command = commands[aliases?.[word] ?? word];
1788
+ let { commands } = scope;
1789
+ let command = lookup(scope, word);
1240
1790
  if (listing || command === undefined) {
1241
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
1242
- command = commands[aliases?.[word] ?? word];
1791
+ const expanded = await expand(scope, [...before, ...words]);
1792
+ commands = expanded.commands;
1793
+ command = lookup(expanded, word);
1243
1794
  }
1244
1795
  if (listing) {
1245
1796
  const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1246
1797
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1247
1798
  const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1248
1799
  const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1249
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1800
+ return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
1250
1801
  }
1251
1802
  if (command === undefined) {
1252
1803
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
@@ -1254,6 +1805,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1254
1805
  }
1255
1806
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1256
1807
  }
1808
+ var COMPLETIONS = "--completions";
1809
+ function flagValue([flag = "", ...rest]) {
1810
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1811
+ }
1812
+ function printCompletionScript(name, args) {
1813
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1814
+ if (shell === undefined || args.length !== 1) {
1815
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1816
+ return 2;
1817
+ }
1818
+ console.log(completionScript(shell, [name]).trimEnd());
1819
+ return 0;
1820
+ }
1257
1821
  async function printCandidates(found) {
1258
1822
  for (const line of await found)
1259
1823
  console.log(line);
@@ -1266,7 +1830,7 @@ function packageVersion(entry = Bun.main) {
1266
1830
  } catch {}
1267
1831
  for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1268
1832
  try {
1269
- const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1833
+ const { version } = JSON.parse(readFileSync5(join5(dir, "package.json"), "utf8"));
1270
1834
  if (typeof version === "string")
1271
1835
  return version;
1272
1836
  } catch {}
@@ -1276,15 +1840,20 @@ function packageVersion(entry = Bun.main) {
1276
1840
  }
1277
1841
  async function runCli(cli, argv = scriptArgs()) {
1278
1842
  const version = cli.version ?? packageVersion();
1843
+ const answered = await askpassClient(argv);
1844
+ if (answered !== undefined)
1845
+ return answered;
1279
1846
  if (argv[0] === COMPLETE)
1280
1847
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1848
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1849
+ return printCompletionScript(cli.name, flagValue(argv));
1281
1850
  const started = performance.now();
1282
1851
  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 });
1283
1852
  const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1284
1853
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1285
1854
  if (cli.usage !== false) {
1286
1855
  try {
1287
- recordUsage(usageEntry(cli.name, command, argv, code));
1856
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1288
1857
  } catch {}
1289
1858
  }
1290
1859
  return code;
@@ -1293,8 +1862,7 @@ function commandPath(scope, argv) {
1293
1862
  const path = [];
1294
1863
  let level = scope;
1295
1864
  for (const word of argv.filter((each) => !each.startsWith("-"))) {
1296
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1297
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1865
+ const command = lookup(level, word);
1298
1866
  if (command === undefined)
1299
1867
  break;
1300
1868
  path.push(word);
@@ -1304,36 +1872,21 @@ function commandPath(scope, argv) {
1304
1872
  }
1305
1873
  return path.length === 0 ? undefined : path.join(" ");
1306
1874
  }
1307
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1308
- if (argv[0] === COMPLETE)
1309
- return printCandidates(leafCandidates(run, argv.slice(1)));
1310
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1311
- console.log(version ?? packageVersion());
1312
- return 0;
1313
- }
1314
- let code;
1315
- const started = performance.now();
1316
- try {
1317
- code = await run(argv);
1318
- } catch (error) {
1319
- code = reportThrown(name, error, redact, wantsJson(argv));
1320
- }
1321
- notifyEnd(name, code, performance.now() - started);
1322
- if (usage !== false) {
1323
- try {
1324
- recordUsage(usageEntry(name, undefined, argv, code));
1325
- } catch {}
1326
- }
1327
- return code;
1328
- }
1329
- // ../kit/src/folders.ts
1330
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1331
- function ignoredFolders(extra = [], where = {}) {
1332
- const configured = readUserConfig("config", where).ignore;
1333
- const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1334
- return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1335
- }
1875
+
1876
+ // ../kit/src/index.ts
1877
+ init_config();
1878
+
1879
+ // ../kit/src/excerpt.ts
1880
+ init_text2();
1881
+
1882
+ // ../kit/src/index.ts
1883
+ init_folders();
1884
+ init_format();
1885
+
1886
+ // ../kit/src/git.ts
1887
+ init_args();
1336
1888
  // ../kit/src/limit.ts
1889
+ init_args();
1337
1890
  function limitOptions(fallback) {
1338
1891
  return {
1339
1892
  limit: { type: "string", short: "n", description: `show at most this many rows, the rest counted (${fallback})` },
@@ -1354,24 +1907,50 @@ function capped(rows, limit) {
1354
1907
  const more = rows.length - limit;
1355
1908
  return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
1356
1909
  }
1910
+
1911
+ // ../kit/src/index.ts
1912
+ init_mode();
1913
+
1914
+ // ../kit/src/report.ts
1915
+ init_style();
1916
+ init_text2();
1357
1917
  // ../kit/src/secrets.ts
1358
1918
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1919
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1359
1920
  // ../kit/src/sessions.ts
1360
1921
  var {Glob } = globalThis.Bun;
1361
1922
  var SESSION_FILES = new Glob("*.json");
1362
1923
  var ACCOUNT_DIRS = new Glob("*/sessions");
1924
+
1925
+ // ../kit/src/index.ts
1926
+ init_style();
1927
+ init_text2();
1928
+ init_theme();
1929
+ init_user_config();
1930
+
1931
+ // ../kit/src/watch.ts
1932
+ init_args();
1933
+ init_input();
1934
+ init_style();
1935
+ // ../kit/src/workspace-root.ts
1936
+ init_user_config();
1363
1937
  // src/hotspots.ts
1364
1938
  import { basename, join as join7 } from "path";
1365
- import process16 from "process";
1939
+ import process18 from "process";
1366
1940
 
1367
1941
  // src/churn.ts
1942
+ import { availableParallelism } from "os";
1368
1943
  var SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|kay|py|go|rs|rb|php|java|kt|swift|cs|c|cc|cpp|h|hpp|scala|dart|lua|sh|zsh|fish)$/;
1369
1944
  var TESTS = /(?:^|\/)(?:tests?|__tests__|spec|e2e|__mocks__|fixtures)\/|\.(?:test|spec|bench)\.[^/]+$|(?:^|\/)test_[^/]+$|_test\.(?:go|py)$/;
1370
1945
  var GENERATED = /(?:^|\/)(?:dist|build|out|generated|\.nuxt|\.output|\.next)\/|\.min\.[cm]?js$|\.d\.ts$|\.(?:generated|gen)\.[^/]+$|\.pb\.go$|\.snap$/;
1371
1946
  var LEADING_NEWLINE = /^\n/;
1947
+ var COMMITS_PER_RUN = 500;
1948
+ var MOST_RUNS = Math.max(1, Math.min(4, Math.floor(availableParallelism() / 2)));
1949
+ var COMMIT_START = 1;
1950
+ var LOG_FORMAT = ["--no-renames", "--numstat", "--format=%x01%ct%x02%ae", "-z"];
1372
1951
  var GENERATED_HEADER = /@generated|generated by|do not edit/i;
1373
1952
  var DECISION = /\b(?:if|elif|elsif|for|foreach|while|until|case|when|catch|except|rescue|match|guard|and|or)\b|&&|\|\||\?\?|\s\?(?![,):.?])/g;
1374
- var COMMENT_OR_STRING = /(\/\*[\s\S]*?\*\/|\/\/[^\n]*|^[ \t]*#[^\n]*)|'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`/gm;
1953
+ var COMMENT_OR_STRING = /(\/\*[\s\S]*?\*\/|\/\/[^\n]*|^[ \t]*#[^\n]*)|"""[\s\S]*?"""|'''[\s\S]*?'''|'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`/gm;
1375
1954
  function isCandidate(path) {
1376
1955
  return SOURCE.test(path) && !TESTS.test(path) && !GENERATED.test(path);
1377
1956
  }
@@ -1381,14 +1960,40 @@ function isGenerated(text) {
1381
1960
  function complexityOf(text) {
1382
1961
  return 1 + (text.replace(COMMENT_OR_STRING, (_, comment) => comment === undefined ? '""' : "").match(DECISION)?.length ?? 0);
1383
1962
  }
1384
- async function churnSince(cwd, since, { bulk, halfLifeMs, now = Date.now() }) {
1385
- const [log, top] = await Promise.all([runCommand(["git", "log", `--since=${since}`, "--no-renames", "--numstat", "--format=%x01%ct%x02%ae", "-z"], { cwd }), runCommand(["git", "rev-parse", "--show-prefix"], { cwd })]);
1386
- if (log.code !== 0 || top.code !== 0)
1963
+ async function readLog(cwd, commits, onProgress) {
1964
+ const runs = Math.min(MOST_RUNS, Math.ceil(commits.length / COMMITS_PER_RUN));
1965
+ const size = Math.ceil(commits.length / runs);
1966
+ let read = 0;
1967
+ const logs = await Promise.all(Array.from({ length: runs }, async (_, run) => runCommand(["git", "log", "--no-walk=unsorted", "--stdin", ...LOG_FORMAT], {
1968
+ cwd,
1969
+ input: `${commits.slice(run * size, (run + 1) * size).join(`
1970
+ `)}
1971
+ `,
1972
+ onChunk: ({ stream, data }) => {
1973
+ if (stream !== "stdout" || onProgress === undefined)
1974
+ return;
1975
+ for (const byte of data) {
1976
+ if (byte === COMMIT_START)
1977
+ read++;
1978
+ }
1979
+ onProgress(read, commits.length);
1980
+ }
1981
+ })));
1982
+ return logs.some((log) => log.code !== 0) ? undefined : logs.map((log) => log.text).join("");
1983
+ }
1984
+ async function churnSince(cwd, since, { bulk, halfLifeMs, now = Date.now(), onProgress }) {
1985
+ const [listed, top] = await Promise.all([runCommand(["git", "rev-list", `--since=${since}`, "HEAD"], { cwd }), runCommand(["git", "rev-parse", "--show-prefix"], { cwd })]);
1986
+ if (listed.code !== 0 || top.code !== 0)
1987
+ return;
1988
+ const commits = listed.text.split(`
1989
+ `).filter(Boolean);
1990
+ const log = commits.length === 0 ? "" : await readLog(cwd, commits, onProgress);
1991
+ if (log === undefined)
1387
1992
  return;
1388
1993
  const prefix = top.text.trim();
1389
1994
  const churn = new Map;
1390
1995
  const authors = new Map;
1391
- for (const commit of log.text.split("\x01").slice(1)) {
1996
+ for (const commit of log.split("\x01").slice(1)) {
1392
1997
  const [head = "", ...entries] = commit.split("\x00");
1393
1998
  const [stamp = "", author = ""] = head.split("\x02");
1394
1999
  const all = entries.map((entry) => entry.replace(LEADING_NEWLINE, "")).filter((entry) => entry !== "").map((entry) => {
@@ -1508,11 +2113,9 @@ var DEFAULT_BULK = configuredNumber("hotspots", "bulk", 25);
1508
2113
  var DAY_MS2 = 86400000;
1509
2114
  var DEFAULT_HALF_LIFE = "90d";
1510
2115
  var DEFAULT_COUNT = configuredNumber("hotspots", "limit", 20);
1511
- var USAGE = `hotspots [options] [dir]: ranks the source files under dir (here by default) by complexity times churn, the ones both hard to read and often edited first, honouring .gitignore
1512
-
1513
- Complexity is the count of decision points in the file (branches, loops, cases, catches, boolean operators, ternaries) plus one, churn the commits touching it since --since (${DEFAULT_SINCE}), score their product. A commit counts for less the older it is (half as much every --half-life, 0 for all alike) and a commit touching more than --bulk files, a format or rename sweep, is left out. --by-lines scores the lines changed instead of the commits. Each file also shows how many lines changed, its author count ("solo" when one author wrote every change) and its most complex declaration, found by indentation. Test files and generated or built files are left out unless --all.
2116
+ var USAGE = `src hotspots [options] [dir]: ranks the source files under dir (here by default) by complexity times churn, the ones both hard to read and often edited first, honouring .gitignore
1514
2117
 
1515
- Lists at most ${DEFAULT_COUNT} files, the count of the rest after them (--limit <n>, --full for all); --json is never cut unless --limit is given.`;
2118
+ Complexity is the count of decision points in the file plus one, churn the commits touching it since --since, score their product. A commit counts for less the older it is, and one touching more files than --bulk, a format or rename sweep, is left out. Each file also shows its lines changed, its author count ("solo" when one author wrote every change) and its most complex declaration. Test files and generated or built files are left out unless --all.`;
1516
2119
  var EXITS = [[0, "it ranked the files"], [1, "no file has commits in the window"], [2, "a usage error or outside a git repository"]];
1517
2120
  var OPTIONS = {
1518
2121
  since: { type: "string", short: "s", description: `only count the commits since this date, as git reads it (${DEFAULT_SINCE})` },
@@ -1526,31 +2129,37 @@ var OPTIONS = {
1526
2129
  var HOT = 0.66;
1527
2130
  var WARM = 0.33;
1528
2131
  async function hotspots(args) {
1529
- const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, positionals: ["[dir]"], replaces: "guessing which files are worth splitting first", examples: ["hotspots", 'hotspots src --since "3 months ago" --limit 10'] });
2132
+ const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, positionals: ["[dir]"], replaces: "guessing which files are worth splitting first", examples: ["hotspots", 'src hotspots src --since "3 months ago" --limit 10'] });
1530
2133
  if (positionals.length > 1)
1531
2134
  badUsage("give one folder");
1532
2135
  const count = limitOf(values, DEFAULT_COUNT);
1533
- const cwd = process16.cwd();
2136
+ const cwd = process18.cwd();
1534
2137
  const bulk = Number(values.bulk ?? DEFAULT_BULK);
1535
2138
  if (!Number.isInteger(bulk) || bulk < 1)
1536
2139
  badUsage(`--bulk takes a number of files, not ${values.bulk}`);
1537
2140
  const halfLifeMs = values["half-life"] === "0" ? 0 : duration(values["half-life"], "half-life", 90 * DAY_MS2);
1538
- const churn = await churnSince(cwd, values.since ?? DEFAULT_SINCE, { bulk, halfLifeMs });
1539
- if (churn === undefined)
1540
- fail("not a git repository, churn comes from its log");
2141
+ const progress = progressLine();
1541
2142
  const ranked = [];
1542
- for (const path of await listFiles(positionals[0] === undefined ? [] : [positionals[0]], cwd)) {
1543
- const touched = churn.get(path);
1544
- if (touched === undefined || values.all !== true && !isCandidate(path))
1545
- continue;
1546
- const text = await readText(join7(cwd, path));
1547
- if (text === undefined || values.all !== true && isGenerated(text))
1548
- continue;
1549
- const complexity = complexityOf(text);
1550
- const worst = worstUnit(text, path);
1551
- ranked.push({ path, score: Math.round(complexity * (values["by-lines"] === true ? touched.linesWeight : touched.weight)), churn: touched.commits, recent: Math.round(touched.weight * 10) / 10, changed: touched.lines, authors: touched.authors, solo: touched.authors === 1, complexity, worst: worst === undefined ? undefined : { name: worst.name, line: worst.line, complexity: worst.complexity }, lines: text.split(`
2143
+ try {
2144
+ progress.update({ step: "reading the git log" });
2145
+ const churn = await churnSince(cwd, values.since ?? DEFAULT_SINCE, { bulk, halfLifeMs, onProgress: (done, total) => progress.update({ step: "reading the git log", done, total, unit: "commits" }) });
2146
+ if (churn === undefined)
2147
+ fail("not a git repository, churn comes from its log");
2148
+ const listed = (await listFiles(positionals[0] === undefined ? [] : [positionals[0]], cwd)).filter((path) => churn.has(path) && (values.all === true || isCandidate(path)));
2149
+ for (const [done, path] of listed.entries()) {
2150
+ progress.update({ step: "measuring the files", done, total: listed.length, unit: "files" });
2151
+ const touched = churn.get(path);
2152
+ const text = await readText(join7(cwd, path));
2153
+ if (text === undefined || values.all !== true && isGenerated(text))
2154
+ continue;
2155
+ const complexity = complexityOf(text);
2156
+ const worst = worstUnit(text, path);
2157
+ ranked.push({ path, score: Math.round(complexity * (values["by-lines"] === true ? touched.linesWeight : touched.weight)), churn: touched.commits, recent: Math.round(touched.weight * 10) / 10, changed: touched.lines, authors: touched.authors, solo: touched.authors === 1, complexity, worst: worst === undefined ? undefined : { name: worst.name, line: worst.line, complexity: worst.complexity }, lines: text.split(`
1552
2158
  `).length - (text.endsWith(`
1553
2159
  `) ? 1 : 0) });
2160
+ }
2161
+ } finally {
2162
+ progress.stop();
1554
2163
  }
1555
2164
  if (ranked.length === 0)
1556
2165
  fail("no file with commits in that window", 1);
@@ -1561,8 +2170,8 @@ async function hotspots(args) {
1561
2170
  printJson(shown);
1562
2171
  return 0;
1563
2172
  }
1564
- const colors = paint(process16.stdout);
1565
- const path = role("path", process16.stdout);
2173
+ const colors = paint(process18.stdout);
2174
+ const path = role("path", process18.stdout);
1566
2175
  const top = shown.reduce((highest, row) => Math.max(highest, row.score), 0);
1567
2176
  const heat = (score, text) => {
1568
2177
  if (top > 0 && score >= top * HOT)
@@ -1570,7 +2179,7 @@ async function hotspots(args) {
1570
2179
  return top > 0 && score >= top * WARM ? colors.yellow(text) : text;
1571
2180
  };
1572
2181
  printHeader("hotspots", `${basename(cwd)} \xB7 since ${values.since ?? DEFAULT_SINCE}`);
1573
- console.log(table([["rank", "score", "churn", "recent", "changed", "authors", "complexity", "lines", "file", "most complex declaration"], ...shown.map((row) => [colors.dim(String(row.rank)), heat(row.score, String(row.score)), ...[row.churn, row.recent, row.changed].map(String), row.solo ? colors.dim("1 solo") : String(row.authors), ...[row.complexity, row.lines].map(String), fileLink(path(row.path), row.path, process16.stdout, cwd), row.worst === undefined ? "" : `${row.worst.name} (${row.worst.complexity}, line ${row.worst.line})`])], { header: true, align: ["right", "right", "right", "right", "right", "right", "right", "right", "left", "left"] }));
2182
+ console.log(table([["rank", "score", "churn", "recent", "changed", "authors", "complexity", "lines", "file", "most complex declaration"], ...shown.map((row) => [colors.dim(String(row.rank)), heat(row.score, String(row.score)), ...[row.churn, row.recent, row.changed].map(String), row.solo ? colors.dim("1 solo") : String(row.authors), ...[row.complexity, row.lines].map(String), fileLink(path(row.path), row.path, process18.stdout, cwd), row.worst === undefined ? "" : `${row.worst.name} (${row.worst.complexity}, line ${row.worst.line})`])], { header: true, align: ["right", "right", "right", "right", "right", "right", "right", "right", "left", "left"] }));
1574
2183
  if (footer !== undefined)
1575
2184
  console.log(footer);
1576
2185
  return 0;
@@ -1579,7 +2188,8 @@ async function hotspots(args) {
1579
2188
  // src/peek.ts
1580
2189
  import { realpathSync as realpathSync3 } from "fs";
1581
2190
  import { isAbsolute as isAbsolute2, join as join8, relative as relative2, resolve as resolve5, sep } from "path";
1582
- import process17 from "process";
2191
+ import process19 from "process";
2192
+ init_text();
1583
2193
 
1584
2194
  // src/source.ts
1585
2195
  var LOCATION = /^(?:\.\/)?([^\s:()]+)(?::(\d+)(?::\d+)?|\((\d+),\d+\))(?=[:\s)]|$)/;
@@ -1590,7 +2200,7 @@ var MODIFIERS = new RegExp(String.raw`^(?:(?:${MODIFIER_WORDS})+${RETURN_TYPE})?
1590
2200
  var MEMBER = new RegExp(String.raw`^(?:(?:${MODIFIER_WORDS})+${RETURN_TYPE})?[#\w$]+\s*(?:<[^>]*>\s*)?\(`);
1591
2201
  var RECEIVER = /^(?:\([^)]*\)\s*)?/;
1592
2202
  var STAR = /^\*?\s*/;
1593
- var HOLDS_MEMBERS = /\b(?:class|interface|trait|impl|struct)\s/;
2203
+ var HOLDS_MEMBERS = /\b(?:(?:class|interface|trait|struct|enum)\s|impl[\s<]|(?:record|extension|protocol|object)\s+[A-Z]|companion\s+object\b)/;
1594
2204
  var CALL_KEYWORDS = /^(?:if|for|while|switch|catch|return|await|throw|new|else|do|try|super|typeof)\b/;
1595
2205
  var LEADING = /^(?:\/\/|\/\*|\*|#(?!!)|@)/;
1596
2206
  var LOCAL_BINDING = /^(?:const|let|var)\s/;
@@ -1601,6 +2211,12 @@ var INDENTED = /\.(?:py|yml|yaml)$/i;
1601
2211
  var INDENT = /^\s*/;
1602
2212
  var CONTINUES = /(?:[=(,[{:?|&+\-*/<>]|=>)$/;
1603
2213
  var BODY_OPENER = /\s*\{\s*$/;
2214
+ var PROPERTY_FUNCTION = /^[#\w$]+\s*(?:[?!]?:[^=]*)?[:=]\s*(?:async\s+)?(?:function\b|(?:<[^>]*>\s*)?(?:\([^)]*\)|[\w$]+)\s*(?::[^=]+)?=>|(?:<[^>]*>\s*)?\($)/;
2215
+ var OBJECT_POSITION = /(?:[=(,[:?]|\|\||&&|\breturn|\bdefault)\s*$|\bnew\s+[\w$.]+(?:<[^>]*>)?\s*\([^()]*\)\s*$/;
2216
+ var CASE_LABEL = /(?:^|[\s;{])(?:case\b.*|default\s*):\s*$/;
2217
+ var REGEX_BEFORE = /(?:^|[(,=:[!&|?{};]|\b(?:return|typeof|case|throw|yield|await|in|of))\s*$/;
2218
+ var RUST_CHAR = /^'(?:\\(?:u\{[\da-f]{1,6}\}|x[\da-f]{2}|.)|[^'\\])'/i;
2219
+ var RUST = /\.rs$/i;
1604
2220
  var LONGEST_DEFINITION = 400;
1605
2221
  var LONGEST_SIGNATURE = 160;
1606
2222
  function indentOf2(line) {
@@ -1609,20 +2225,47 @@ function indentOf2(line) {
1609
2225
  function escaped(name) {
1610
2226
  return name.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
1611
2227
  }
1612
- function declares(line, name) {
2228
+ function declares(line, name, inMembers = true) {
1613
2229
  const text = line.trim();
1614
2230
  const word = new RegExp(String.raw`^${escaped(name)}\b`);
1615
2231
  if (DECLARATION.test(text)) {
1616
2232
  const rest = text.replace(DECLARATION, "").replace(RECEIVER, "");
1617
2233
  return word.test(rest.replace(STAR, ""));
1618
2234
  }
1619
- return line !== text && MEMBER.test(text) && !CALL_KEYWORDS.test(text) && word.test(text.replace(MODIFIERS, "")) && (text.endsWith("{") || text.endsWith(":"));
2235
+ if (!inMembers || line === text || CALL_KEYWORDS.test(text))
2236
+ return false;
2237
+ const named = text.replace(MODIFIERS, "");
2238
+ return word.test(named) && (MEMBER.test(text) && (text.endsWith("{") || text.endsWith(":")) || PROPERTY_FUNCTION.test(named));
2239
+ }
2240
+ function regexEnd(line, start) {
2241
+ let inClass = false;
2242
+ for (let i = start + 1;i < line.length; i++) {
2243
+ const char = line[i];
2244
+ if (char === "\\")
2245
+ i++;
2246
+ else if (char === "[")
2247
+ inClass = true;
2248
+ else if (char === "]")
2249
+ inClass = false;
2250
+ else if (char === "/" && !inClass)
2251
+ return i;
2252
+ }
2253
+ return -1;
1620
2254
  }
1621
- function depthChange(line, quote) {
1622
- let braces = 0;
1623
- let parens = 0;
2255
+ function codeChars(line, quote, rust, each) {
1624
2256
  for (let i = 0;i < line.length; i++) {
1625
2257
  const char = line[i] ?? "";
2258
+ if (quote.open === "/*") {
2259
+ if (rust && char === "/" && line[i + 1] === "*") {
2260
+ quote.depth++;
2261
+ i++;
2262
+ } else if (char === "*" && line[i + 1] === "/") {
2263
+ quote.depth--;
2264
+ quote.open = quote.depth === 0 ? "" : "/*";
2265
+ i++;
2266
+ }
2267
+ continue;
2268
+ }
1626
2269
  if (quote.open !== "") {
1627
2270
  if (char === "\\")
1628
2271
  i++;
@@ -1632,9 +2275,30 @@ function depthChange(line, quote) {
1632
2275
  }
1633
2276
  if (char === "/" && line[i + 1] === "/")
1634
2277
  break;
1635
- if (char === '"' || char === "'" || char === "`")
2278
+ if (char === "/" && line[i + 1] === "*") {
2279
+ quote.open = "/*";
2280
+ quote.depth = 1;
2281
+ i++;
2282
+ continue;
2283
+ }
2284
+ const regex = char === "/" && !rust && REGEX_BEFORE.test(line.slice(0, i)) ? regexEnd(line, i) : -1;
2285
+ if (regex !== -1)
2286
+ i = regex;
2287
+ else if (rust && char === "'")
2288
+ i += (RUST_CHAR.exec(line.slice(i))?.[0].length ?? 1) - 1;
2289
+ else if (char === '"' || char === "'" || char === "`")
1636
2290
  quote.open = char;
1637
- else if (char === "{")
2291
+ else
2292
+ each(char, i);
2293
+ }
2294
+ if (quote.open !== "`" && quote.open !== "/*")
2295
+ quote.open = "";
2296
+ }
2297
+ function depthChange(line, quote, rust) {
2298
+ let braces = 0;
2299
+ let parens = 0;
2300
+ codeChars(line, quote, rust, (char) => {
2301
+ if (char === "{")
1638
2302
  braces++;
1639
2303
  else if (char === "}")
1640
2304
  braces--;
@@ -1642,11 +2306,36 @@ function depthChange(line, quote) {
1642
2306
  parens++;
1643
2307
  else if (char === ")" || char === "]")
1644
2308
  parens--;
1645
- }
1646
- if (quote.open !== "`")
1647
- quote.open = "";
2309
+ });
1648
2310
  return { braces, parens };
1649
2311
  }
2312
+ function memberLines(lines, path) {
2313
+ const everywhere = lines.map(() => true);
2314
+ if (INDENTED.test(path))
2315
+ return everywhere;
2316
+ const quote = { open: "", depth: 0 };
2317
+ const rust = RUST.test(path);
2318
+ const open = [];
2319
+ let previous = "";
2320
+ let lost = false;
2321
+ const members = lines.map((line) => {
2322
+ const inMembers = open.at(-1) === true;
2323
+ codeChars(line, quote, rust, (char, index) => {
2324
+ if (char === "}") {
2325
+ lost ||= open.pop() === undefined;
2326
+ return;
2327
+ }
2328
+ if (char !== "{")
2329
+ return;
2330
+ const before = (line.slice(0, index).trim() === "" ? previous : line.slice(0, index)).trimEnd();
2331
+ open.push(HOLDS_MEMBERS.test(before) || OBJECT_POSITION.test(before) && !CASE_LABEL.test(before));
2332
+ });
2333
+ if (line.trim() !== "")
2334
+ previous = line;
2335
+ return inMembers;
2336
+ });
2337
+ return lost || open.length > 0 || quote.open !== "" ? everywhere : members;
2338
+ }
1650
2339
  function endOf(lines, start, path) {
1651
2340
  const last = Math.min(lines.length - 1, start + LONGEST_DEFINITION - 1);
1652
2341
  if (INDENTED.test(path)) {
@@ -1661,13 +2350,14 @@ function endOf(lines, start, path) {
1661
2350
  }
1662
2351
  return end;
1663
2352
  }
1664
- const quote = { open: "" };
2353
+ const quote = { open: "", depth: 0 };
2354
+ const rust = RUST.test(path);
1665
2355
  let braces = 0;
1666
2356
  let parens = 0;
1667
2357
  let opened = false;
1668
2358
  for (let i = start;i <= last; i++) {
1669
2359
  const line = lines[i] ?? "";
1670
- const change = depthChange(line, quote);
2360
+ const change = depthChange(line, quote, rust);
1671
2361
  opened ||= change.braces > 0 || line.includes("{");
1672
2362
  braces += change.braces;
1673
2363
  parens += change.parens;
@@ -1685,9 +2375,10 @@ function leadingStart(lines, start) {
1685
2375
  function definitions(text, path, name) {
1686
2376
  const lines = text.split(`
1687
2377
  `);
2378
+ const members = memberLines(lines, path);
1688
2379
  const spans = [];
1689
2380
  for (let i = 0;i < lines.length; i++) {
1690
- if (!declares(lines[i] ?? "", name))
2381
+ if (!declares(lines[i] ?? "", name, members[i]))
1691
2382
  continue;
1692
2383
  const end = endOf(lines, i, path);
1693
2384
  spans.push({ path, from: leadingStart(lines, i) + 1, to: end + 1 });
@@ -1756,17 +2447,15 @@ function locations(text) {
1756
2447
  }
1757
2448
 
1758
2449
  // src/peek.ts
1759
- var USAGE2 = `peek [options] <file[:from-to]>...: prints files or line spans with their line numbers, several in one call
2450
+ var USAGE2 = `src peek [options] <file[:from-to]>...: prints files or line spans with their line numbers, several in one call
1760
2451
 
1761
- peek src/a.ts:120-140 src/b.ts:1-40 the spans, src/a.ts:120 the one line, src/a.ts the whole file
1762
- peek --def <symbol> [path...] the whole declaration of the symbol, its comments included, --def again for more symbols
1763
- peek --refs <symbol> [path...] the lines naming the symbol, grouped by file, --defs-first printing its declarations before
1764
- peek --outline <file>... the declarations and class members, a Markdown file's headings
1765
- peek --around <regex> [-C 3] [path...] the lines around each match, overlapping ones merged
1766
- <output> | peek [-C 3] the lines around each path:line the output opens a line with (errs, rg -n, grep -n, tsc, linters)
1767
- The paths default to the files git keeps here (.gitignore holds).
1768
- --refs lists at most 100 lines and --around prints at most 20 spans, the count of the rest after them (--limit <n>, --full for all).
1769
- --json prints spans as [{path, from, to, lines}], --refs as [{path, line, text}] ({definitions, references} with --defs-first), --outline as [{path, line, depth, text}], the lines never cut and the rows never counted off unless --limit is given.`;
2452
+ src peek src/a.ts:120-140 src/b.ts:1-40 the spans, src/a.ts:120 the one line, src/a.ts the whole file
2453
+ src peek --def <symbol> [path...] the whole declaration of the symbol, its comments included, --def again for more symbols
2454
+ src peek --refs <symbol> [path...] the lines naming the symbol, grouped by file, --defs-first printing its declarations before
2455
+ src peek --outline <file>... the declarations and class members, a Markdown file's headings
2456
+ src peek --around <regex> [-C 3] [path...] the lines around each match, overlapping ones merged
2457
+ <output> | src peek [-C 3] the lines around each path:line the output opens a line with (errs, rg -n, grep -n, tsc, linters)
2458
+ The paths default to the files git keeps here (\`.gitignore\` holds).`;
1770
2459
  var EXITS2 = [[0, "it printed something"], [1, "nothing is found, a file cannot be read or a span starts past the end"], [2, "a usage error or a path outside the repository"]];
1771
2460
  var REFS_LIMIT = 100;
1772
2461
  var AROUND_LIMIT = 20;
@@ -1779,7 +2468,7 @@ var OPTIONS2 = {
1779
2468
  "defs-first": { type: "boolean", description: "with --refs, print the symbol's declarations before its lines" },
1780
2469
  context: { type: "string", short: "C", description: "lines on each side of an --around match or a piped location (3)" },
1781
2470
  ...limitOptions(REFS_LIMIT),
1782
- json: jsonOption()
2471
+ json: jsonOption("spans [{path, from, to, lines}], --refs [{path, line, text}] ({definitions, references} with --defs-first), --outline [{path, line, depth, text}]")
1783
2472
  };
1784
2473
  var TARGET = /^(.+?):(\d+)(?:-(\d+))?$/;
1785
2474
  var LONGEST_LINE = 300;
@@ -1788,13 +2477,13 @@ function cut(text) {
1788
2477
  return text.length > LONGEST_LINE ? `${text.slice(0, LONGEST_LINE - 1)}\u2026` : text;
1789
2478
  }
1790
2479
  async function readableRoot() {
1791
- const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process17.cwd() });
1792
- return realpathSync3(ran.code === 0 ? ran.text.trim() : process17.cwd());
2480
+ const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process19.cwd() });
2481
+ return realpathSync3(ran.code === 0 ? ran.text.trim() : process19.cwd());
1793
2482
  }
1794
2483
  async function isOutside(path) {
1795
2484
  let real;
1796
2485
  try {
1797
- real = realpathSync3(resolve5(process17.cwd(), path));
2486
+ real = realpathSync3(resolve5(process19.cwd(), path));
1798
2487
  } catch {
1799
2488
  return false;
1800
2489
  }
@@ -1808,7 +2497,7 @@ async function checkInside(path) {
1808
2497
  async function pipedSpans(text, context) {
1809
2498
  const spans = [];
1810
2499
  for (const [path, numbers] of locations(text)) {
1811
- const source = await isOutside(path) ? undefined : await readText(resolve5(process17.cwd(), path));
2500
+ const source = await isOutside(path) ? undefined : await readText(resolve5(process19.cwd(), path));
1812
2501
  if (source !== undefined)
1813
2502
  spans.push(...spansAround(path, source.replace(TRAILING_NEWLINE2, "").split(`
1814
2503
  `).length, numbers, context));
@@ -1817,7 +2506,7 @@ async function pipedSpans(text, context) {
1817
2506
  }
1818
2507
  async function textOf(path) {
1819
2508
  await checkInside(path);
1820
- const text = await readText(resolve5(process17.cwd(), path));
2509
+ const text = await readText(resolve5(process19.cwd(), path));
1821
2510
  if (text === undefined)
1822
2511
  fail(`cannot read ${path} (missing, binary or too large)`, 1);
1823
2512
  return text;
@@ -1869,14 +2558,14 @@ async function spanOf(target) {
1869
2558
  if (from < 1 || to < from)
1870
2559
  badUsage(`${target}: a span reads <file>:<from>-<to>, from 1 and from <= to`);
1871
2560
  if (from > count)
1872
- fail(`${path} has ${go(count, "line")}, ${target} starts past the end`, 1);
2561
+ fail(`${path} has ${bo(count, "line")}, ${target} starts past the end`, 1);
1873
2562
  return { path, from, to: Math.min(to, count) };
1874
2563
  }
1875
2564
  async function* sources(paths) {
1876
2565
  for (const path of paths)
1877
2566
  await checkInside(path);
1878
- for (const path of await listFiles(paths, process17.cwd())) {
1879
- const text = await readText(join8(process17.cwd(), path));
2567
+ for (const path of await listFiles(paths, process19.cwd())) {
2568
+ const text = await readText(join8(process19.cwd(), path));
1880
2569
  if (text !== undefined)
1881
2570
  yield { path, text };
1882
2571
  }
@@ -1900,7 +2589,7 @@ async function definitionsOf(symbols, paths) {
1900
2589
  return [...found.values()].flat();
1901
2590
  }
1902
2591
  async function peek(args) {
1903
- const { values, positionals } = parse(args, USAGE2, OPTIONS2, { exits: EXITS2, positionals: ["[target...]"], replaces: "sed -n N,Mp, grep -n chains and whole-file reads", examples: [["peek src/a.ts:120-140 src/b.ts:1-40", "two spans in one call"], ["peek --def parseArgs src", "a whole declaration"]] });
2592
+ const { values, positionals } = parse(args, USAGE2, OPTIONS2, { exits: EXITS2, positionals: ["[target...]"], replaces: "sed -n N,Mp, grep -n chains and whole-file reads", examples: [["src peek src/a.ts:120-140 src/b.ts:1-40", "two spans in one call"], ["src peek --def parseArgs src", "a whole declaration"]] });
1904
2593
  const modes = [values.def?.length === 0 ? undefined : values.def, values.refs, values.outline, values.around].filter((mode) => mode !== undefined && mode !== false);
1905
2594
  const json = values.json === true;
1906
2595
  if (values["defs-first"] === true && values.refs === undefined)
@@ -1977,7 +2666,7 @@ async function peek(args) {
1977
2666
 
1978
2667
  // src/todo-scan.ts
1979
2668
  import { join as join9 } from "path";
1980
- import process18 from "process";
2669
+ import process20 from "process";
1981
2670
 
1982
2671
  // src/todo.ts
1983
2672
  var COMMENT = /(?<![:\w/])\/\/|\/\*|<!--|(?:^|\s)(?:#|--)(?=\s)|^\s*\*(?=\s|$)/;
@@ -1985,13 +2674,20 @@ var MARKUP = /\.(?:md|mdx|markdown|html?|xml)$/i;
1985
2674
  var MARKUP_COMMENT = /<!--/;
1986
2675
  var CLOSERS = /\s*(?:\*\/|-->)\s*$/;
1987
2676
  var MARKER = /^(?:@|\[)?(TODO|FIXME|HACK|XXX)\b/;
1988
- var QUOTES = ["'", '"', "`"];
2677
+ var QUOTES = new Set(["'", '"', "`"]);
1989
2678
  var ESCAPE2 = /\\./g;
1990
2679
  var AFTER_FIRST_LINE = /\n[\s\S]*/;
1991
2680
  var REF = /(?<![\w./-])(\w[\w.-]*\/(?!\.+#)[\w.][\w.-]*)#(\d+)\b/g;
2681
+ var FILE_ANCHOR = /\.(?:md|mdx|markdown|txt|rst|adoc|html?)$/i;
1992
2682
  function isQuoted(line, index) {
1993
- const before = line.slice(0, index).replaceAll(ESCAPE2, "");
1994
- return QUOTES.some((quote) => before.split(quote).length % 2 === 0);
2683
+ let open;
2684
+ for (const char of line.slice(0, index).replaceAll(ESCAPE2, "")) {
2685
+ if (open === undefined && QUOTES.has(char))
2686
+ open = char;
2687
+ else if (char === open)
2688
+ open = undefined;
2689
+ }
2690
+ return open !== undefined;
1995
2691
  }
1996
2692
  var BLAME_HEADER = /^[0-9a-f]{40} \d+ (\d+)/;
1997
2693
  var DAY_S = 86400;
@@ -2003,7 +2699,7 @@ async function commitTimes(path, cwd) {
2003
2699
  const bySha = new Map;
2004
2700
  let sha = "";
2005
2701
  let line = 0;
2006
- for (const row of stdoutOf(blamed.chunks).split(`
2702
+ for (const row of blamed.stdout.split(`
2007
2703
  `)) {
2008
2704
  const header = BLAME_HEADER.exec(row);
2009
2705
  if (header !== null) {
@@ -2037,15 +2733,12 @@ function marksIn(text, path) {
2037
2733
  continue;
2038
2734
  const body = line.slice(opener.index + opener[0].length).replace(CLOSERS, "").trim();
2039
2735
  const marker = MARKER.exec(body)?.[1];
2040
- const refs = [...body.matchAll(REF)].map((found) => ({ repo: found[1] ?? "", number: Number(found[2]) }));
2736
+ const refs = [...body.matchAll(REF)].filter((found) => !FILE_ANCHOR.test(found[1] ?? "")).map((found) => ({ repo: found[1] ?? "", number: Number(found[2]) }));
2041
2737
  if (marker !== undefined || refs.length > 0)
2042
2738
  marks.push({ path, line: i + 1, kind: marker ?? "ref", text: body, refs });
2043
2739
  }
2044
2740
  return marks;
2045
2741
  }
2046
- function stdoutOf(chunks) {
2047
- return Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
2048
- }
2049
2742
  function refKey(ref) {
2050
2743
  return `${ref.repo}#${ref.number}`;
2051
2744
  }
@@ -2054,7 +2747,7 @@ async function lookUpOnGitHub(repo, numbers, cwd) {
2054
2747
  for (const ran of await Promise.all(numbers.map(async (number) => ({ number, ran: await runCommand(["gh", "api", `repos/${repo}/issues/${number}`, "--jq", ".state"], { cwd }) })))) {
2055
2748
  if (ran.ran.code !== 0)
2056
2749
  return ran.ran.text.trim().replace(AFTER_FIRST_LINE, "");
2057
- states.set(refKey({ repo, number: Number(ran.number) }), stdoutOf(ran.ran.chunks).trim());
2750
+ states.set(refKey({ repo, number: Number(ran.number) }), ran.ran.stdout.trim());
2058
2751
  }
2059
2752
  return states;
2060
2753
  }
@@ -2074,7 +2767,7 @@ async function lookUp(refs, cwd) {
2074
2767
  }
2075
2768
  continue;
2076
2769
  }
2077
- const parsed = JSON.parse(stdoutOf(ran.chunks));
2770
+ const parsed = JSON.parse(ran.stdout);
2078
2771
  for (const issue of Array.isArray(parsed) ? parsed : [parsed])
2079
2772
  lookup.states.set(refKey({ repo, number: issue.number }), issue.state);
2080
2773
  }
@@ -2082,13 +2775,10 @@ async function lookUp(refs, cwd) {
2082
2775
  }
2083
2776
 
2084
2777
  // src/todo-scan.ts
2085
- var USAGE3 = `todo-scan [options] [path...]: lists the TODO, FIXME, HACK, XXX and owner/repo#N comments under the paths (here by default), each as <file>:<line>: <comment>, honouring .gitignore
2086
-
2087
- --older <duration> keeps only the comments whose line last changed longer ago than that (30d, 12w, 6m: git blame dates each one, a file git cannot blame is left out) and shows each one's age.
2778
+ var USAGE3 = `src todo-scan [options] [path...]: lists the TODO, FIXME, HACK, XXX and owner/repo#N comments under the paths (here by default), each as <file>:<line>: <comment>, honouring .gitignore
2088
2779
 
2089
- --stale keeps only the comments naming a closed issue, each issue's state looked up with ft, or gh for a GitHub repository, and exits 1 when it finds one.
2090
-
2091
- Lists at most 100 comments, the count of the rest after them (--limit <n>, --full for all); --json is never cut unless --limit is given.`;
2780
+ --older <duration> keeps the comments whose line last changed longer ago than that (\`30d\`, \`12w\`, \`6m\`, dated by git blame) and shows each one's age.
2781
+ --stale keeps the comments naming a closed issue, looked up with \`ft\`, or \`gh\` for a GitHub repository, and exits 1 when it finds one.`;
2092
2782
  var EXITS3 = [[0, "it listed the comments or found no stale one"], [1, "--stale finds one"], [2, "a usage error or when --stale could not look a repository up (ft and gh both failed)"]];
2093
2783
  var LIST_LIMIT = 100;
2094
2784
  var DAY_MS3 = 86400000;
@@ -2105,8 +2795,8 @@ function printLines(lines, footer) {
2105
2795
  `));
2106
2796
  }
2107
2797
  async function todoScan(args) {
2108
- const { values, positionals } = parse(args, USAGE3, OPTIONS3, { exits: EXITS3, positionals: ["[path...]"], replaces: "grep -rn TODO, then opening each issue it names", examples: ["todo-scan src", ["todo-scan --stale", "only the comments naming a closed issue"]] });
2109
- const cwd = process18.cwd();
2798
+ const { values, positionals } = parse(args, USAGE3, OPTIONS3, { exits: EXITS3, positionals: ["[path...]"], replaces: "grep -rn TODO, then opening each issue it names", examples: ["src todo-scan src", ["src todo-scan --stale", "only the comments naming a closed issue"]] });
2799
+ const cwd = process20.cwd();
2110
2800
  const limit = limitOf(values, LIST_LIMIT);
2111
2801
  const found = [];
2112
2802
  for (const path of await listFiles(positionals, cwd)) {
@@ -2144,7 +2834,7 @@ async function todoScan(args) {
2144
2834
  }
2145
2835
 
2146
2836
  // src/cli.ts
2147
- process19.exitCode = await runCli({
2837
+ process21.exitCode = await runCli({
2148
2838
  name: "src",
2149
2839
  about: "reads and ranks the source of a folder: line spans, TODO comments and the files worth splitting",
2150
2840
  replaces: "sed -n N,Mp, grep -n chains and grep -rn TODO",