@kaynooo/cli-git 0.16.1 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (11) hide show
  1. package/README.md +5 -4
  2. package/dist/gb.js +1728 -1143
  3. package/dist/gc.js +1173 -178
  4. package/dist/gcl.js +1165 -181
  5. package/dist/gd.js +1152 -183
  6. package/dist/gf.js +1172 -182
  7. package/dist/gm.js +1799 -1172
  8. package/dist/gp.js +1183 -188
  9. package/dist/gst.js +1149 -185
  10. package/dist/gu.js +1152 -178
  11. package/package.json +5 -5
package/dist/gb.js CHANGED
@@ -1,20 +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/gb.ts
5
- import process23 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 N = new Map;
15
- var Nt = /\s+\S*$/;
16
- var Y = /\s/;
17
- function ko(t, e, r = "...") {
15
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
16
+ function Ao(t, e, r = "...") {
18
17
  let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
19
18
  if (t.length <= e)
20
19
  return t;
@@ -25,13 +24,22 @@ function ko(t, e, r = "...") {
25
24
  c = c.trimEnd();
26
25
  return s ? (c + n).slice(0, l) : c + n;
27
26
  }
28
- 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));
29
- var z = new Map;
27
+ var N, Nt, Y, be, W;
28
+ var init_chunk_rkhsft4a = __esm(() => {
29
+ N = new Map;
30
+ Nt = /\s+\S*$/;
31
+ Y = /\s/;
32
+ 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));
33
+ W = new Map;
34
+ });
35
+
36
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
37
+ var init_text = __esm(() => {
38
+ init_chunk_rkhsft4a();
39
+ });
30
40
 
31
41
  // ../kit/src/mode.ts
32
42
  import process2 from "process";
33
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
34
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
35
43
  function isSet(value) {
36
44
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
37
45
  }
@@ -48,12 +56,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
48
56
  function isInteractive(streams = process2) {
49
57
  return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
50
58
  }
59
+ var MODES, AGENT_VARIABLES;
60
+ var init_mode = __esm(() => {
61
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
62
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
63
+ });
51
64
 
52
- // ../kit/src/style.ts
53
- import process6 from "process";
54
-
55
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
56
- var G2 = /^[a-f0-9]+$/i;
65
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
57
66
  function b(r) {
58
67
  let e = r.startsWith("#") ? r.slice(1) : r;
59
68
  if (!G2.test(e))
@@ -64,11 +73,6 @@ function b(r) {
64
73
  throw Error(`Invalid hex color length: ${e.length}`);
65
74
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
66
75
  }
67
- 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") => {
68
- let [l, n, c] = b(r);
69
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
70
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
71
- var h = new Set(["", "1", "2", "3", "true"]);
72
76
  function C(r, e = globalThis.process?.env ?? {}) {
73
77
  if (e.FORCE_COLOR !== undefined)
74
78
  return h.has(e.FORCE_COLOR);
@@ -82,7 +86,7 @@ function f(r, e = []) {
82
86
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
83
87
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
84
88
  return new Proxy(c, { get(t, i) {
85
- let a = B2[i];
89
+ let a = B[i];
86
90
  if (Array.isArray(a)) {
87
91
  let s = g.get(i);
88
92
  if (s === undefined)
@@ -105,13 +109,21 @@ function f(r, e = []) {
105
109
  function Fe(r = {}) {
106
110
  return f(r);
107
111
  }
108
- var o = Fe();
112
+ var G2, B, h, o;
113
+ var init_chunk_x450vn3m = __esm(() => {
114
+ G2 = /^[a-f0-9]+$/i;
115
+ 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") => {
116
+ let [l, n, c] = b(r);
117
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
118
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
119
+ h = new Set(["", "1", "2", "3", "true"]);
120
+ o = Fe();
121
+ });
109
122
 
110
- // ../kit/src/theme.ts
111
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
112
- import { homedir as homedir2 } from "os";
113
- import { join as join3, resolve as resolve2 } from "path";
114
- import process5 from "process";
123
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
124
+ var init_colors = __esm(() => {
125
+ init_chunk_x450vn3m();
126
+ });
115
127
 
116
128
  // ../kit/src/config.ts
117
129
  import { existsSync } from "fs";
@@ -127,15 +139,21 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
127
139
  return;
128
140
  }
129
141
  }
142
+ var init_config = __esm(() => {
143
+ init_args();
144
+ });
130
145
 
131
146
  // ../kit/src/user-config.ts
132
147
  import { existsSync as existsSync2, readFileSync } from "fs";
133
148
  import { homedir } from "os";
134
- import { join as join2 } from "path";
149
+ import { isAbsolute, join as join2 } from "path";
135
150
  import process4 from "process";
151
+ function xdgFolder(value, fallback) {
152
+ return value !== undefined && isAbsolute(value) ? value : fallback;
153
+ }
136
154
  function configBase(where = {}) {
137
155
  const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
138
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
156
+ return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
139
157
  }
140
158
  function userConfigPath(bin, where = {}) {
141
159
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
@@ -158,13 +176,17 @@ function readUserConfig(bin, where = {}, legacy = []) {
158
176
  return {};
159
177
  }
160
178
  }
179
+ var init_user_config = () => {};
161
180
 
162
181
  // ../kit/src/theme.ts
182
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
183
+ import { homedir as homedir2 } from "os";
184
+ import { join as join3, resolve as resolve2 } from "path";
185
+ import process5 from "process";
163
186
  function toLinear(channel) {
164
187
  const value = channel / 255;
165
188
  return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
166
189
  }
167
- 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)));
168
190
  function toOklab(hex) {
169
191
  const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
170
192
  const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
@@ -179,7 +201,6 @@ function fromOklab([lightness, a, b]) {
179
201
  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];
180
202
  return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
181
203
  }
182
- var ENDS = new Map;
183
204
  function gradientAt(theme, ratio) {
184
205
  if (theme.gradient === undefined)
185
206
  return;
@@ -193,33 +214,11 @@ function gradientAt(theme, ratio) {
193
214
  const [from, to] = ends;
194
215
  return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
195
216
  }
196
- var DEFAULT = {
197
- 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" },
198
- 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" },
199
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
200
- bins: {},
201
- gradient: ["#c084fc", "#67e8f9"]
202
- };
203
- 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" };
204
- 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" };
205
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
206
- var PRESETS = {
207
- default: {},
208
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
209
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
210
- ascii: { glyphs: ASCII }
211
- };
212
- 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"]);
213
- var HEX = /^#[0-9a-f]{6}$/i;
214
- var CONTROL = /\p{Cc}/u;
215
- var MAX_FILE_BYTES = 64 * 1024;
216
- var SPACES = /\s+/;
217
217
  function isColorSpec(spec) {
218
218
  if (typeof spec === "number")
219
219
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
220
220
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
221
221
  }
222
- var CUBE = [0, 95, 135, 175, 215, 255];
223
222
  function cubeLevel(channel) {
224
223
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
225
224
  }
@@ -327,7 +326,6 @@ function applyFile(theme, file, where, warn) {
327
326
  function endsWalk(home) {
328
327
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
329
328
  }
330
- var warned = new Set;
331
329
  function warnOnce(message) {
332
330
  if (warned.has(message))
333
331
  return;
@@ -364,8 +362,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
364
362
  }
365
363
  return { theme, sources, preset };
366
364
  }
367
- var current;
368
- var currentKey = "";
369
365
  function activeTheme() {
370
366
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
371
367
  if (current === undefined || key !== currentKey) {
@@ -374,9 +370,38 @@ function activeTheme() {
374
370
  }
375
371
  return current;
376
372
  }
373
+ 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 = "";
374
+ var init_theme = __esm(() => {
375
+ init_config();
376
+ init_user_config();
377
+ ENDS = new Map;
378
+ DEFAULT = {
379
+ 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" },
380
+ 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" },
381
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
382
+ bins: {},
383
+ gradient: ["#c084fc", "#67e8f9"]
384
+ };
385
+ 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" };
386
+ 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" };
387
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
388
+ PRESETS = {
389
+ default: {},
390
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
391
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
392
+ ascii: { glyphs: ASCII }
393
+ };
394
+ 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"]);
395
+ HEX = /^#[0-9a-f]{6}$/i;
396
+ CONTROL = /\p{Cc}/u;
397
+ MAX_FILE_BYTES = 64 * 1024;
398
+ SPACES = /\s+/;
399
+ CUBE = [0, 95, 135, 175, 215, 255];
400
+ warned = new Set;
401
+ });
377
402
 
378
403
  // ../kit/src/style.ts
379
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
404
+ import process6 from "process";
380
405
  function takesControlCodes(stream, env = process6.env) {
381
406
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
382
407
  }
@@ -396,17 +421,24 @@ function role(name, stream, env = process6.env) {
396
421
  const colors = paint(stream, env);
397
422
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
398
423
  }
399
- var STATUS_WORDS = {
400
- passed: ["passed", "success", "succeeded", "ok"],
401
- failed: ["failed", "failure", "error", "errored"],
402
- running: ["running", "in_progress", "started", "holding"],
403
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
404
- skipped: ["skipped", "cancelled", "canceled", "manual"]
405
- };
406
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
424
+ var MARK_WORDS, STATUS_WORDS, STATUS_OF;
425
+ var init_style = __esm(() => {
426
+ init_colors();
427
+ init_mode();
428
+ init_theme();
429
+ MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
430
+ STATUS_WORDS = {
431
+ passed: ["passed", "success", "succeeded", "ok"],
432
+ failed: ["failed", "failure", "error", "errored"],
433
+ running: ["running", "in_progress", "started", "holding"],
434
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
435
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
436
+ };
437
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
438
+ });
407
439
 
408
440
  // ../kit/src/format.ts
409
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
441
+ import process7 from "process";
410
442
  function formatSeconds(total) {
411
443
  let rest = Math.max(0, Math.round(total));
412
444
  const amounts = UNITS.map(([unit, size]) => {
@@ -438,10 +470,8 @@ function formatAge(date, now = Date.now()) {
438
470
  return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
439
471
  }
440
472
  function truncate(text, width) {
441
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
473
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
442
474
  }
443
- var LINE_BREAKS = /\s*\n\s*/g;
444
- var ESCAPE = String.fromCharCode(27);
445
475
  function textWidth(text) {
446
476
  return Bun.stringWidth(text);
447
477
  }
@@ -490,14 +520,40 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
490
520
  function printJson(value) {
491
521
  console.log(jsonText(value));
492
522
  }
523
+ var UNITS, LINE_BREAKS, ESCAPE;
524
+ var init_format = __esm(() => {
525
+ init_text();
526
+ init_mode();
527
+ init_style();
528
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
529
+ LINE_BREAKS = /\s*\n\s*/g;
530
+ ESCAPE = String.fromCharCode(27);
531
+ });
493
532
 
494
533
  // ../kit/src/help.ts
495
534
  import process8 from "process";
496
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
497
- var USAGE_PREFIX = /^usage:\s*/i;
498
- var FULL_STOP = /\.$/;
499
535
  function usageLine(usage, colors = paint(process8.stdout)) {
500
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
536
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
537
+ `);
538
+ const blank = lines.indexOf("");
539
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
540
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
541
+ const colon = synopses[0].indexOf(": ");
542
+ const inline = synopses[0].slice(colon + 2);
543
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
544
+ if (colon !== -1)
545
+ synopses[0] = synopses[0].slice(0, colon);
546
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
547
+ `)}`;
548
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
549
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
550
+ return [head, ...lead, ...rest].join(`
551
+ `);
552
+ }
553
+ function prose(line, colors) {
554
+ if (colors.cyan("x") === "x")
555
+ return line;
556
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
501
557
  }
502
558
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
503
559
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -532,7 +588,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
532
588
  return [];
533
589
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
534
590
  }
535
- var MAX_INLINE_CHOICES = 24;
536
591
  function optionRows(options, colors = paint(process8.stdout)) {
537
592
  const rows = Object.entries(options).map(([name, option]) => {
538
593
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -547,9 +602,17 @@ function optionRows(options, colors = paint(process8.stdout)) {
547
602
  const width = Math.max(0, ...rows.map((row) => row.width));
548
603
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
549
604
  }
605
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
606
+ var init_help = __esm(() => {
607
+ init_mode();
608
+ init_style();
609
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
610
+ USAGE_PREFIX = /^usage:\s*/i;
611
+ FULL_STOP = /\.$/;
612
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
613
+ });
550
614
 
551
615
  // ../kit/src/text.ts
552
- var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
553
616
  function distance(a, b) {
554
617
  const left = [...a];
555
618
  const right = [...b];
@@ -575,8 +638,12 @@ function closest(name, names) {
575
638
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
576
639
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
577
640
  }
641
+ var ANSI;
642
+ var init_text2 = __esm(() => {
643
+ ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
644
+ });
645
+
578
646
  // ../kit/src/input.ts
579
- var WHOLE = /^\d+$/;
580
647
  function wholeNumber(value, name, fallback, min = 1) {
581
648
  if (value === undefined)
582
649
  return fallback;
@@ -585,8 +652,6 @@ function wholeNumber(value, name, fallback, min = 1) {
585
652
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
586
653
  return number;
587
654
  }
588
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
589
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
590
655
  function duration(value, name, fallback, unit = "s") {
591
656
  if (value === undefined)
592
657
  return fallback;
@@ -596,40 +661,27 @@ function duration(value, name, fallback, unit = "s") {
596
661
  badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
597
662
  return ms;
598
663
  }
664
+ var WHOLE, DURATION, UNIT_MS;
665
+ var init_input = __esm(() => {
666
+ init_args();
667
+ WHOLE = /^\d+$/;
668
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
669
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
670
+ });
599
671
 
600
672
  // ../kit/src/args.ts
601
- var DASHES = /^-+/;
673
+ import process9 from "process";
674
+ import { parseArgs } from "util";
602
675
  function jsonOption(holds) {
603
676
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
604
677
  }
605
- class Exit extends Error {
606
- code;
607
- hint;
608
- constructor(message, code, hint) {
609
- super(message);
610
- this.code = code;
611
- this.hint = hint;
612
- }
613
- }
614
678
  function fail(message, code = 2, hint) {
615
679
  throw new Exit(message, code, hint);
616
680
  }
617
-
618
- class UsageError extends Exit {
619
- constructor(message, hint) {
620
- super(message, 2, hint);
621
- }
622
- }
623
681
  function badUsage(message) {
624
682
  throw new UsageError(message);
625
683
  }
626
684
 
627
- class HelpShown extends Exit {
628
- constructor() {
629
- super("help shown", 0);
630
- }
631
- }
632
-
633
685
  class Completing {
634
686
  options;
635
687
  positionals;
@@ -640,11 +692,6 @@ class Completing {
640
692
  this.candidates = candidates;
641
693
  }
642
694
  }
643
- var completion = { active: false };
644
- var OUTPUT_OPTIONS = {
645
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
646
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
647
- };
648
695
  function applyOutput(color, plain, env = process9.env) {
649
696
  const when = plain === true ? "never" : color ?? "auto";
650
697
  if (when === "auto")
@@ -798,7 +845,6 @@ function parseError(error) {
798
845
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
799
846
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
800
847
  }
801
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
802
848
  function nearestOption(message, options, allowNegative) {
803
849
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
804
850
  if (typed === undefined)
@@ -814,1121 +860,1635 @@ function nearestOption(message, options, allowNegative) {
814
860
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
815
861
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
816
862
  }
817
- // ../kit/src/argv.ts
818
- import { readFileSync as readFileSync3, realpathSync } from "fs";
819
- import { resolve as resolve3 } from "path";
820
- import process10 from "process";
821
- function commandLine() {
863
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
864
+ var init_args = __esm(() => {
865
+ init_format();
866
+ init_help();
867
+ init_text2();
868
+ init_help();
869
+ init_input();
870
+ DASHES = /^-+/;
871
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
872
+ Exit = class Exit extends Error {
873
+ code;
874
+ hint;
875
+ [EXIT] = true;
876
+ constructor(message, code, hint) {
877
+ super(message);
878
+ this.code = code;
879
+ this.hint = hint;
880
+ }
881
+ static [Symbol.hasInstance](value) {
882
+ if (this !== Exit)
883
+ return Function.prototype[Symbol.hasInstance].call(this, value);
884
+ return typeof value === "object" && value !== null && value[EXIT] === true;
885
+ }
886
+ };
887
+ UsageError = class UsageError extends Exit {
888
+ constructor(message, hint) {
889
+ super(message, 2, hint);
890
+ }
891
+ };
892
+ HelpShown = class HelpShown extends Exit {
893
+ constructor() {
894
+ super("help shown", 0);
895
+ }
896
+ };
897
+ completion = { active: false };
898
+ OUTPUT_OPTIONS = {
899
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
900
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
901
+ };
902
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
903
+ });
904
+
905
+ // ../kit/src/folders.ts
906
+ import { homedir as homedir3 } from "os";
907
+ import { join as join4 } from "path";
908
+ import process13 from "process";
909
+ function cacheFolder({ home = homedir3(), env = process13.env } = {}) {
910
+ return xdgFolder(env.XDG_CACHE_HOME, join4(home, ".cache"));
911
+ }
912
+ var SKIPPED_FOLDERS;
913
+ var init_folders = __esm(() => {
914
+ init_user_config();
915
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
916
+ });
917
+
918
+ // ../kit/src/answers.ts
919
+ import { mkdirSync, readFileSync as readFileSync5, writeFileSync } from "fs";
920
+ import { dirname as dirname2, join as join5 } from "path";
921
+ function answersFile() {
922
+ return join5(cacheFolder(), "kaynooo-cli", "answers.json");
923
+ }
924
+ function stored() {
822
925
  try {
823
- return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
926
+ const parsed = JSON.parse(readFileSync5(answersFile(), "utf-8"));
927
+ if (typeof parsed !== "object" || parsed === null)
928
+ return {};
929
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
824
930
  } catch {
825
- return;
931
+ return {};
826
932
  }
827
933
  }
828
- function realPath(word) {
934
+ function earlierAnswers(key) {
935
+ return stored()[key] ?? [];
936
+ }
937
+ function rememberAnswer(key, answer) {
938
+ const all = stored();
939
+ const file = answersFile();
940
+ all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
829
941
  try {
830
- return realpathSync(resolve3(word));
831
- } catch {
832
- return;
833
- }
942
+ mkdirSync(dirname2(file), { recursive: true });
943
+ writeFileSync(file, JSON.stringify(all));
944
+ } catch {}
834
945
  }
835
- function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
836
- const target = script === undefined ? undefined : realPath(script) ?? script;
837
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
838
- const after = at === -1 ? [] : cmdline.slice(at + 1);
839
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
946
+ var KEPT = 50;
947
+ var init_answers = __esm(() => {
948
+ init_folders();
949
+ });
950
+
951
+ // ../kit/src/job.ts
952
+ import process14 from "process";
953
+ function stopJob() {
954
+ process14.kill(0, "SIGTSTP");
840
955
  }
841
- // ../kit/src/progress.ts
842
- import process12 from "process";
956
+ var init_job = () => {};
843
957
 
844
- // ../kit/src/process.ts
845
- import { constants } from "os";
846
- import process11 from "process";
847
- var KILL_GRACE_MS = 2000;
848
- var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
849
- function exitCodeOf(code, signal) {
850
- if (code !== null)
851
- return code;
852
- if (typeof signal === "number")
853
- return 128 + signal;
854
- return signal === null ? 129 : 128 + constants.signals[signal];
958
+ // ../kit/src/picker/line.ts
959
+ function isEditKey(key) {
960
+ return EDIT_KEYS.has(key);
855
961
  }
856
- function holdSignals(cleanup) {
857
- let received;
858
- let child;
859
- const held = {
860
- get signal() {
861
- return received;
862
- },
863
- forward: (to) => {
864
- child = to;
865
- },
866
- release: () => {
867
- for (const signal of SIGNALS)
868
- process11.off(signal, onSignal);
869
- }
870
- };
871
- function onSignal(signal) {
872
- received = signal;
873
- if (child !== undefined) {
874
- child.kill(signal);
875
- return;
876
- }
877
- if (cleanup === undefined)
878
- return;
879
- held.release();
880
- cleanup(signal);
881
- process11.kill(process11.pid, signal);
882
- }
883
- for (const signal of SIGNALS)
884
- process11.on(signal, onSignal);
885
- return held;
962
+ function endsKills(key) {
963
+ return typeof key !== "object" && !isEditKey(key);
886
964
  }
887
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
888
- const chunks = [];
889
- const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
890
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
891
- const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
892
- const timers = [];
893
- const killGroup = (killing) => {
894
- if (state.done)
895
- return;
896
- try {
897
- if (grouped)
898
- process11.kill(-proc.pid, killing);
899
- else
900
- proc.kill(killing);
901
- } catch {}
902
- };
903
- const stop = () => {
904
- killGroup("SIGTERM");
905
- timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
906
- };
907
- const onAbort = () => stop();
908
- if (timeoutMs !== undefined) {
909
- timers.push(setTimeout(() => {
910
- state.timedOut = true;
911
- stop();
912
- }, timeoutMs));
913
- }
914
- if (signal?.aborted === true)
915
- onAbort();
916
- else
917
- signal?.addEventListener("abort", onAbort, { once: true });
918
- onStart?.({ kill: (killing) => killGroup(killing) });
919
- const drain = async (stream, name) => {
920
- for await (const data of stream) {
921
- if (state.failure !== undefined)
922
- continue;
923
- try {
924
- onChunk?.({ stream: name, data });
925
- } catch (error) {
926
- state.failure = error;
927
- stop();
928
- continue;
929
- }
930
- if (state.kept + data.length > maxBytes) {
931
- state.truncated = true;
932
- continue;
933
- }
934
- state.kept += data.length;
935
- chunks.push({ stream: name, data });
936
- }
937
- };
938
- try {
939
- await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
940
- await proc.exited;
941
- } finally {
942
- state.done = true;
943
- for (const timer of timers)
944
- clearTimeout(timer);
945
- signal?.removeEventListener("abort", onAbort);
946
- }
947
- if (state.failure !== undefined)
948
- throw state.failure;
949
- const joined = () => Buffer.concat(chunks.map(({ data }) => data));
950
- let output;
951
- let text;
952
- return {
953
- code: exitCodeOf(proc.exitCode, proc.signalCode),
954
- chunks,
955
- timedOut: state.timedOut,
956
- truncated: state.truncated,
957
- get output() {
958
- return output ??= joined();
959
- },
960
- get text() {
961
- return text ??= (output ??= joined()).toString();
962
- }
963
- };
965
+ function isWord(char) {
966
+ return char !== undefined && WORD_CHARACTER.test(char);
964
967
  }
965
-
966
- // ../kit/src/progress.ts
967
- var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
968
- var FRAME_MS = 200;
969
- var BAR_WIDTH = 20;
970
- var CLEAR_BELOW = "\r\x1B[J";
971
- var ESC = String.fromCharCode(27);
972
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
973
- var RESET_STYLE = `${ESC}[0m`;
974
- var CTRL_C = 3;
975
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
976
- var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
977
- function liveRegion(render, stream = process12.stderr, env = process12.env) {
978
- if (!takesControlCodes(stream, env))
979
- return { redraw: () => {
980
- return;
981
- }, print: (text) => void stream.write(`${text}
982
- `), stop: () => {
983
- return;
984
- } };
985
- const write = stream.write.bind(stream);
986
- let frame = 0;
987
- let drawn = false;
988
- const columns = () => {
989
- const now = stream.getWindowSize?.()[0] ?? stream.columns;
990
- return now === undefined || now === 0 ? 80 : now;
991
- };
992
- const clear = () => {
993
- if (drawn)
994
- write(CLEAR_BELOW);
995
- drawn = false;
996
- };
997
- const draw = () => {
998
- const width = columns() - 1;
999
- const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
1000
- const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
1001
- if (lines.length === 0) {
1002
- clear();
1003
- return;
1004
- }
1005
- write(`${CLEAR_BELOW}${lines.join(`
1006
- `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
1007
- drawn = true;
1008
- };
1009
- const timer = setInterval(draw, FRAME_MS);
1010
- stream.on?.("resize", draw);
1011
- const restore = interceptOutput(clear);
1012
- const release = swallowInput();
1013
- const onExit = () => {
1014
- clear();
1015
- release();
1016
- };
1017
- const signals = holdSignals(stop);
1018
- function stop() {
1019
- clearInterval(timer);
1020
- stream.off?.("resize", draw);
1021
- clear();
1022
- restore();
1023
- release();
1024
- process12.off("exit", onExit);
1025
- signals.release();
1026
- }
1027
- timer.unref();
1028
- process12.on("exit", onExit);
1029
- return {
1030
- redraw: draw,
1031
- print: (text) => {
1032
- clear();
1033
- write(`${text}
1034
- `);
1035
- draw();
1036
- },
1037
- stop
1038
- };
968
+ function wordStart(chars, from) {
969
+ let at = from;
970
+ while (at > 0 && !isWord(chars[at - 1]))
971
+ at--;
972
+ while (at > 0 && isWord(chars[at - 1]))
973
+ at--;
974
+ return at;
1039
975
  }
1040
- function progressLine(stream = process12.stderr, env = process12.env) {
1041
- const colors = paint(stream, env);
1042
- const write = stream.write.bind(stream);
1043
- const begun = performance.now();
1044
- let started = begun;
1045
- let current;
1046
- const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
1047
- const end = (line) => {
1048
- region.stop();
1049
- write(`${line}
1050
- `);
1051
- };
1052
- return {
1053
- update: (progress) => {
1054
- const step = current?.step;
1055
- current = progress;
1056
- if (progress.step !== step) {
1057
- started = performance.now();
1058
- region.redraw();
1059
- }
1060
- },
1061
- stop: region.stop,
1062
- done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
1063
- failed: (text) => end(marked("problem", text, stream, undefined, env))
1064
- };
976
+ function wordEnd(chars, from) {
977
+ let at = from;
978
+ while (at < chars.length && !isWord(chars[at]))
979
+ at++;
980
+ while (at < chars.length && isWord(chars[at]))
981
+ at++;
982
+ return at;
1065
983
  }
1066
- function progressParts({ step, done, total, unit }, spinner, ms) {
1067
- const { theme } = activeTheme();
1068
- const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
1069
- if (total !== undefined && total > 0) {
1070
- const counted = Math.min(done ?? 0, total);
1071
- const filled = Math.round(counted / total * BAR_WIDTH);
1072
- 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 });
984
+ function spacedStart(chars, from) {
985
+ let at = from;
986
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
987
+ at--;
988
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
989
+ at--;
990
+ return at;
991
+ }
992
+ function cut(chars, from, to) {
993
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
994
+ }
995
+ function insert(chars, at, text) {
996
+ const typed = [...text];
997
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
998
+ }
999
+ function editLine(line, key) {
1000
+ const { killed = "", chained = false } = line;
1001
+ const chars = [...line.text];
1002
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
1003
+ const edited = edit(chars, at, key, killed);
1004
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1005
+ return line.killed === undefined ? edited : { ...edited, killed };
1006
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1007
+ if (taken === "")
1008
+ return { ...edited, killed, chained };
1009
+ if (!chained)
1010
+ return { ...edited, killed: taken, chained: true };
1011
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1012
+ }
1013
+ function edit(chars, at, key, killed) {
1014
+ const text = chars.join("");
1015
+ if (typeof key === "object")
1016
+ return insert(chars, at, key.text);
1017
+ switch (key) {
1018
+ case "left":
1019
+ return { text, caret: Math.max(at - 1, 0) };
1020
+ case "right":
1021
+ return { text, caret: Math.min(at + 1, chars.length) };
1022
+ case "wordleft":
1023
+ return { text, caret: wordStart(chars, at) };
1024
+ case "wordright":
1025
+ return { text, caret: wordEnd(chars, at) };
1026
+ case "linestart":
1027
+ return { text, caret: 0 };
1028
+ case "lineend":
1029
+ return { text, caret: chars.length };
1030
+ case "erase":
1031
+ return cut(chars, Math.max(at - 1, 0), at);
1032
+ case "delete":
1033
+ return cut(chars, at, Math.min(at + 1, chars.length));
1034
+ case "word":
1035
+ return cut(chars, spacedStart(chars, at), at);
1036
+ case "killword":
1037
+ return cut(chars, wordStart(chars, at), at);
1038
+ case "killnext":
1039
+ return cut(chars, at, wordEnd(chars, at));
1040
+ case "clear":
1041
+ return cut(chars, 0, at);
1042
+ case "killend":
1043
+ return cut(chars, at, chars.length);
1044
+ case "yank":
1045
+ return insert(chars, at, killed);
1073
1046
  }
1074
- parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
1075
- return parts;
1076
1047
  }
1077
- function plain(text) {
1078
- return text;
1048
+ function visible({ text, caret }, room) {
1049
+ const chars = [...text];
1050
+ const at = Math.min(Math.max(caret, 0), chars.length);
1051
+ const cells = at === chars.length ? [...chars, " "] : chars;
1052
+ const widths = cells.map((char) => Bun.stringWidth(char));
1053
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1054
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1055
+ let start = at;
1056
+ let end = at + 1;
1057
+ while (start > 0 && fits(start - 1, end))
1058
+ start--;
1059
+ while (end < cells.length && fits(start, end + 1))
1060
+ end++;
1061
+ const left = start > 0 ? "\u2026" : "";
1062
+ const right = end < cells.length ? "\u2026" : "";
1063
+ return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
1079
1064
  }
1080
- function tintedParts(parts, colors) {
1081
- return parts.map(({ text, tint }) => tint(colors)(text)).join("");
1065
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
1066
+ var init_line = __esm(() => {
1067
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1068
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1069
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
1070
+ WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1071
+ SPACE = /\s/;
1072
+ });
1073
+
1074
+ // ../kit/src/picker/score.ts
1075
+ function startsWord(text, index) {
1076
+ if (index === 0)
1077
+ return true;
1078
+ const before = text[index - 1];
1079
+ return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
1082
1080
  }
1083
- function cutToWidth(line, width) {
1084
- if (Bun.stringWidth(line) <= width)
1085
- return line;
1086
- let room = width;
1087
- let kept = "";
1088
- let index = 0;
1089
- let linked = false;
1090
- while (index < line.length) {
1091
- ESCAPE_CODE.lastIndex = index;
1092
- const escape = ESCAPE_CODE.exec(line);
1093
- if (escape !== null) {
1094
- kept += escape[0];
1095
- linked ||= escape[0].startsWith(`${ESC}]`);
1096
- index = ESCAPE_CODE.lastIndex;
1097
- continue;
1081
+ function fuzzy(query, text) {
1082
+ if (query === "")
1083
+ return { score: 0, positions: [] };
1084
+ const exact = query !== query.toLowerCase();
1085
+ const needle = exact ? query : query.toLowerCase();
1086
+ const haystack = exact ? text : text.toLowerCase();
1087
+ if (haystack.length !== text.length || needle.length > haystack.length)
1088
+ return;
1089
+ const width = haystack.length;
1090
+ const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
1091
+ const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
1092
+ for (let j = 0;j < needle.length; j++) {
1093
+ let run = NONE;
1094
+ let runAt = -1;
1095
+ for (let i = j;i < width; i++) {
1096
+ if (j > 0 && i - 2 >= j - 1) {
1097
+ const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
1098
+ if (candidate > run) {
1099
+ run = candidate;
1100
+ runAt = i - 2;
1101
+ }
1102
+ }
1103
+ if (haystack[i] !== needle[j])
1104
+ continue;
1105
+ const here = MATCH + (startsWord(text, i) ? BOUNDARY : 0) + (i === 0 ? PREFIX : 0);
1106
+ if (j === 0) {
1107
+ best[0][i] = here - i * GAP;
1108
+ continue;
1109
+ }
1110
+ const joined = best[j - 1][i - 1] + CONSECUTIVE;
1111
+ const skipped = run - (i - 1) * GAP;
1112
+ if (joined > NONE && joined >= skipped) {
1113
+ best[j][i] = joined + here;
1114
+ from[j][i] = i - 1;
1115
+ } else if (skipped > NONE) {
1116
+ best[j][i] = skipped + here;
1117
+ from[j][i] = runAt;
1118
+ }
1098
1119
  }
1099
- const char = String.fromCodePoint(line.codePointAt(index));
1100
- const columns = Bun.stringWidth(char);
1101
- if (columns > room)
1102
- break;
1103
- kept += char;
1104
- room -= columns;
1105
- index += char.length;
1106
1120
  }
1107
- return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1121
+ const last = best[needle.length - 1];
1122
+ let end = -1;
1123
+ for (let i = 0;i < width; i++) {
1124
+ if (last[i] > NONE && (end === -1 || last[i] > last[end]))
1125
+ end = i;
1126
+ }
1127
+ if (end === -1)
1128
+ return;
1129
+ const positions = [];
1130
+ for (let j = needle.length - 1, i = end;j >= 0; j--) {
1131
+ positions.unshift(i);
1132
+ i = from[j][i];
1133
+ }
1134
+ return { score: last[end], positions };
1108
1135
  }
1109
- function swallowInput() {
1110
- const input = process12.stdin;
1111
- if (!input.isTTY)
1112
- return () => {
1113
- return;
1114
- };
1115
- const onData = (data) => {
1116
- if (data.includes(CTRL_C))
1117
- process12.kill(process12.pid, "SIGINT");
1118
- };
1119
- input.setRawMode(true);
1120
- input.on("data", onData);
1121
- input.resume();
1122
- let released = false;
1123
- return () => {
1124
- if (released)
1125
- return;
1126
- released = true;
1127
- input.off("data", onData);
1128
- input.pause();
1129
- input.setRawMode(false);
1130
- };
1136
+ function rank(query, lines) {
1137
+ if (query === "")
1138
+ return lines.map((_, index) => ({ index, positions: [] }));
1139
+ const found = [];
1140
+ for (const [index, line] of lines.entries()) {
1141
+ const match = fuzzy(query, line);
1142
+ if (match !== undefined)
1143
+ found.push({ index, positions: match.positions, score: match.score });
1144
+ }
1145
+ return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
1131
1146
  }
1132
- function interceptOutput(clear) {
1133
- const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1134
- const wrapped = targets.map(([target, name]) => {
1135
- const original = Reflect.get(target, name);
1136
- const wrapper = (...args) => {
1137
- clear();
1138
- return original.apply(target, args);
1139
- };
1140
- Reflect.set(target, name, wrapper);
1141
- return { target, name, original, wrapper };
1142
- });
1143
- return () => {
1144
- for (const { target, name, original, wrapper } of wrapped) {
1145
- if (Reflect.get(target, name) === wrapper)
1146
- Reflect.set(target, name, original);
1147
+ var MATCH = 16, CONSECUTIVE = 12, BOUNDARY = 10, PREFIX = 8, GAP = 1, BOUNDARY_AFTER, UPPER, LOWER, NONE;
1148
+ var init_score = __esm(() => {
1149
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1150
+ UPPER = /\p{Lu}/u;
1151
+ LOWER = /\p{Ll}/u;
1152
+ NONE = Number.NEGATIVE_INFINITY;
1153
+ });
1154
+
1155
+ // ../kit/src/picker/state.ts
1156
+ function repeat(value, count) {
1157
+ return Array.from({ length: count }).fill(value);
1158
+ }
1159
+ function styled(line) {
1160
+ let text = "";
1161
+ const styles = [];
1162
+ let active = "";
1163
+ let colored = false;
1164
+ let last = 0;
1165
+ function add(chunk) {
1166
+ const flat = chunk.replace(CONTROL2, " ");
1167
+ text += flat;
1168
+ colored ||= active !== "" && flat !== "";
1169
+ styles.push(...repeat(active, flat.length));
1170
+ }
1171
+ for (const found of line.matchAll(ANSI)) {
1172
+ add(line.slice(last, found.index));
1173
+ last = found.index + found[0].length;
1174
+ if (SGR.test(found[0]))
1175
+ active = RESET.test(found[0]) ? "" : active + found[0];
1176
+ }
1177
+ add(line.slice(last));
1178
+ return { text, styles: colored ? styles : undefined };
1179
+ }
1180
+ function lay(rows, searched) {
1181
+ const parsed = rows.map((row) => row.cells.map(styled));
1182
+ const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1183
+ return parsed.map((cells, at) => {
1184
+ let text = "";
1185
+ const styles = [];
1186
+ let colored = false;
1187
+ let searchEnd = 0;
1188
+ for (const [column, cell] of cells.entries()) {
1189
+ const last = column === cells.length - 1;
1190
+ const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1191
+ text += shown;
1192
+ colored ||= cell.styles !== undefined;
1193
+ styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1194
+ if (column < searched)
1195
+ searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1196
+ if (!last) {
1197
+ const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1198
+ text += " ".repeat(pad);
1199
+ styles.push(...repeat("", pad));
1200
+ }
1147
1201
  }
1148
- };
1202
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1203
+ });
1149
1204
  }
1150
- // ../kit/src/cli.ts
1151
- import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1152
- import { dirname as dirname3, join as join5 } from "path";
1153
- import process15 from "process";
1154
-
1155
- // ../kit/src/completions.ts
1156
- var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1157
- 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'
1158
- set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1159
- set -l current (commandline -ct)
1160
- for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1161
- if test "$line" = __files__
1162
- __fish_complete_path $current
1163
- else
1164
- echo $line
1165
- end
1166
- end
1167
- end`;
1168
- var BASH_FUNCTION = `__kaynooo_cli_complete() {
1169
- local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1170
- local -a lines
1171
- COMPREPLY=()
1172
- lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1173
- for line in "\${lines[@]}"; do
1174
- if [[ $line == __files__ ]]; then
1175
- COMPREPLY+=($(compgen -f -- "$cur"))
1176
- else
1177
- words+="\${line%%$'\\t'*}"$'\\n'
1178
- fi
1179
- done
1180
- COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1181
- }`;
1182
- var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1183
- local line
1184
- local -a described plain
1185
- for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1186
- if [[ $line == __files__ ]]; then
1187
- _files
1188
- elif [[ $line == *$'\\t'* ]]; then
1189
- described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1190
- else
1191
- plain+=("$line")
1192
- fi
1193
- done
1194
- (( \${#described} )) && _describe -V value described
1195
- (( \${#plain} )) && compadd -- "\${plain[@]}"
1196
- return 0
1197
- }`;
1198
- function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1199
- if (shell === "fish")
1200
- return `${header}
1201
- ${FISH_FUNCTION}
1202
- ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1203
- `).join("")}`;
1204
- if (shell === "bash")
1205
- return `${header}
1206
- ${BASH_FUNCTION}
1207
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
1208
- `;
1209
- return `${header}
1210
- ${ZSH_FUNCTION}
1211
- compdef __kaynooo_cli_complete ${bins.join(" ")}
1212
- `;
1205
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1206
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1207
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1208
+ const wheel = MOUSE.exec(sequence)?.[1];
1209
+ if (wheel !== undefined)
1210
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1211
+ const named = codes.get(sequence);
1212
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1213
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1214
+ paste.active = sequence === PASTE_START;
1215
+ return [];
1216
+ }
1217
+ if (paste.active && (sequence === "\r" || sequence === `
1218
+ `))
1219
+ return [];
1220
+ if (key !== undefined)
1221
+ return [key];
1222
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1223
+ });
1213
1224
  }
1214
-
1215
- // ../kit/src/notify.ts
1216
- import process13 from "process";
1217
- var NOTIFY_AFTER_MS = 1e4;
1218
- var CANCELLED = 130;
1219
- function base64(text) {
1220
- return Buffer.from(text).toString("base64");
1225
+ function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1226
+ const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1227
+ return withRows(state, rows);
1221
1228
  }
1222
- function notification(title, body, env = process13.env) {
1223
- const id = `kit${process13.pid}`;
1224
- 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\\`];
1225
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1229
+ function withRows(state, rows, header = state.header) {
1230
+ const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1231
+ const laid = lay(cells, state.searched);
1232
+ const searchable = laid.map((row) => row.searchable);
1233
+ const matches = rank(state.query, searchable);
1234
+ return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
1226
1235
  }
1227
- function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1228
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1229
- return;
1230
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1236
+ function withQuery(state, key) {
1237
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1238
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1231
1239
  }
1232
-
1233
- // ../kit/src/usage.ts
1234
- import { appendFileSync, mkdirSync } from "fs";
1235
- import { homedir as homedir3 } from "os";
1236
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1237
- import process14 from "process";
1238
-
1239
- // ../kit/src/logs.ts
1240
- var DAY_MS = 24 * 60 * 60 * 1000;
1241
- var CLI_FOLDER = "kaynooo-cli";
1242
-
1243
- // ../kit/src/usage.ts
1244
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1245
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1246
- var LONGEST_NAME = 40;
1247
- var usageError;
1248
- function noteUsageError(message) {
1249
- usageError = message;
1240
+ function move(state, by) {
1241
+ return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1250
1242
  }
1251
- function stateHome(env = process14.env) {
1252
- const dir = env.XDG_STATE_HOME;
1253
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1243
+ function highlighted(state) {
1244
+ return state.matches[state.cursor]?.index;
1254
1245
  }
1255
- function usagePath(env = process14.env) {
1256
- return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1246
+ function press(state, key) {
1247
+ if (state.done !== undefined)
1248
+ return state;
1249
+ if (state.chained && endsKills(key))
1250
+ state = { ...state, chained: false };
1251
+ if (state.help)
1252
+ return { ...state, help: false };
1253
+ if (typeof key === "object") {
1254
+ if ("text" in key)
1255
+ return withQuery(state, key);
1256
+ return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1257
+ }
1258
+ if (isEditKey(key))
1259
+ return withQuery(state, key);
1260
+ switch (key) {
1261
+ case "up":
1262
+ return move(state, -1);
1263
+ case "down":
1264
+ return move(state, 1);
1265
+ case "pageup":
1266
+ return move(state, -state.page);
1267
+ case "pagedown":
1268
+ return move(state, state.page);
1269
+ case "home":
1270
+ return move(state, -state.matches.length);
1271
+ case "end":
1272
+ return move(state, state.matches.length);
1273
+ case "cancel":
1274
+ return { ...state, done: "cancel" };
1275
+ case "help":
1276
+ return { ...state, help: true };
1277
+ case "suspend":
1278
+ return state;
1279
+ case "enter":
1280
+ return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1281
+ case "tab": {
1282
+ const at = highlighted(state);
1283
+ if (!state.multi || at === undefined)
1284
+ return state;
1285
+ const marked = new Set(state.marked);
1286
+ if (!marked.delete(at))
1287
+ marked.add(at);
1288
+ return move({ ...state, marked }, 1);
1289
+ }
1290
+ }
1257
1291
  }
1258
- function usageRecorded(env = process14.env) {
1259
- const off = env.KAYNOOO_CLI_NO_USAGE;
1260
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1292
+ function chosen(state) {
1293
+ if (state.marked.size > 0)
1294
+ return state.rows.filter((_, index) => state.marked.has(index));
1295
+ const at = highlighted(state);
1296
+ return at === undefined ? [] : [state.rows[at]];
1261
1297
  }
1262
- function flagNames(argv) {
1263
- const end = argv.indexOf("--");
1264
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1265
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1298
+ var CONTROL2, IS_CONTROL, SGR, RESET, COLUMN_GAP = 2, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS, CTRL_KEY;
1299
+ var init_state = __esm(() => {
1300
+ init_text2();
1301
+ init_line();
1302
+ init_score();
1303
+ CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1304
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1305
+ SGR = /^\x1B\[[0-9;]*m$/;
1306
+ RESET = /^\x1B\[0?m$/;
1307
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1308
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1309
+ KEYS = {
1310
+ "\x1B[A": "up",
1311
+ "\x1BOA": "up",
1312
+ "\x10": "up",
1313
+ "\x1B[B": "down",
1314
+ "\x1BOB": "down",
1315
+ "\x0E": "down",
1316
+ "\x1B[5~": "pageup",
1317
+ "\x1B[6~": "pagedown",
1318
+ "\x1B[H": "home",
1319
+ "\x1B[1~": "home",
1320
+ "\x1BOH": "home",
1321
+ "\x1B[F": "end",
1322
+ "\x1B[4~": "end",
1323
+ "\x1BOF": "end",
1324
+ "\r": "enter",
1325
+ "\n": "enter",
1326
+ "\x03": "cancel",
1327
+ "\x1B": "cancel",
1328
+ "\x1B[D": "left",
1329
+ "\x1BOD": "left",
1330
+ "\x1B[C": "right",
1331
+ "\x1BOC": "right",
1332
+ "\x1B[1;5D": "wordleft",
1333
+ "\x1B[1;3D": "wordleft",
1334
+ "\x1Bb": "wordleft",
1335
+ "\x1B[1;5C": "wordright",
1336
+ "\x1B[1;3C": "wordright",
1337
+ "\x1Bf": "wordright",
1338
+ "\x01": "linestart",
1339
+ "\x05": "lineend",
1340
+ "\x7F": "erase",
1341
+ "\x1B[3~": "delete",
1342
+ "\b": "killword",
1343
+ "\x1B\x7F": "killword",
1344
+ "\x1B[3;5~": "killnext",
1345
+ "\x1Bd": "killnext",
1346
+ "\x15": "clear",
1347
+ "\v": "killend",
1348
+ "\x17": "word",
1349
+ "\x19": "yank",
1350
+ "\x1A": "suspend",
1351
+ "\t": "tab",
1352
+ "\x1F": "help",
1353
+ "\x1BOP": "help",
1354
+ "\x1B[11~": "help"
1355
+ };
1356
+ CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
1357
+ });
1358
+
1359
+ // ../kit/src/redraw.ts
1360
+ function overwrite(lines, columns) {
1361
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1362
+ `);
1266
1363
  }
1267
- function usageEntry(bin, command, argv, code, now = new Date) {
1268
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1269
- usageError = undefined;
1270
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1364
+ function rowsTaken(lines, columns) {
1365
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1271
1366
  }
1272
- function recordUsage(entry, env = process14.env) {
1273
- if (!usageRecorded(env))
1367
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
1368
+ var init_redraw = __esm(() => {
1369
+ init_format();
1370
+ });
1371
+
1372
+ // ../kit/src/prompt.ts
1373
+ import process15 from "process";
1374
+ function readKeys(input, paste = { active: false }) {
1375
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1376
+ }
1377
+ function roomAfter(question, columns) {
1378
+ return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
1379
+ }
1380
+ function withCaret(colors, line, room, dim = false) {
1381
+ const { before, at, after } = visible(line, room);
1382
+ const tone = dim ? colors.dim : (text) => text;
1383
+ return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
1384
+ }
1385
+ function sharedStart(texts) {
1386
+ const [first = [], ...rest] = texts.map((text) => [...text]);
1387
+ let length = first.length;
1388
+ for (const chars of rest) {
1389
+ const differs = chars.findIndex((char, index) => char !== first[index]);
1390
+ length = Math.min(length, differs === -1 ? chars.length : differs);
1391
+ }
1392
+ return first.slice(0, length).join("");
1393
+ }
1394
+ function listed2(colors, found, columns) {
1395
+ const shared = sharedStart(found);
1396
+ const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
1397
+ const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
1398
+ const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
1399
+ return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
1400
+ }
1401
+ async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
1402
+ let line = { text: "", caret: 0 };
1403
+ let invalid;
1404
+ let completions = [];
1405
+ const remembered = history === undefined || mask ? undefined : history;
1406
+ const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
1407
+ let recalled = -1;
1408
+ let draft = line;
1409
+ const taken = () => line.text === "" ? fallback ?? "" : line.text;
1410
+ const shown = () => mask ? "*".repeat([...taken()].length) : taken();
1411
+ const accepted = await ask(question, settings, (colors, state, { columns }) => {
1412
+ if (state !== "asking")
1413
+ return [answer(colors, question, state, shown())];
1414
+ const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
1415
+ return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
1416
+ }, (key) => {
1417
+ if (key === "cancel")
1418
+ return "cancel";
1419
+ invalid = undefined;
1420
+ completions = [];
1421
+ if (line.chained === true && endsKills(key))
1422
+ line = { ...line, chained: false };
1423
+ if (key === "tab") {
1424
+ const chars = [...line.text];
1425
+ const before = chars.slice(0, line.caret).join("");
1426
+ const found = complete?.(before) ?? [];
1427
+ const filled = sharedStart(found);
1428
+ if ([...filled].length > [...before].length)
1429
+ line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
1430
+ else
1431
+ completions = found;
1432
+ return;
1433
+ }
1434
+ if (key === "enter") {
1435
+ invalid = validate?.(taken());
1436
+ return invalid === undefined ? "enter" : undefined;
1437
+ }
1438
+ if (key === "up" || key === "down") {
1439
+ const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
1440
+ if (recalled === -1)
1441
+ draft = line;
1442
+ recalled = to;
1443
+ const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
1444
+ line = { ...shown, killed: line.killed ?? "" };
1445
+ return;
1446
+ }
1447
+ const edit = { home: "linestart", end: "lineend" }[key] ?? key;
1448
+ if (typeof edit === "object" || isEditKey(edit))
1449
+ line = editLine(line, edit);
1450
+ return;
1451
+ });
1452
+ if (!accepted)
1274
1453
  return;
1454
+ if (remembered !== undefined && taken() !== "")
1455
+ rememberAnswer(remembered, taken());
1456
+ return taken();
1457
+ }
1458
+ function answer(colors, question, state, picked) {
1459
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1460
+ }
1461
+ async function ask(question, { hint, terminal = process15 }, render, press) {
1462
+ const { stdin, stderr } = terminal;
1463
+ if (!isInteractive(terminal))
1464
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1465
+ const colors = paint(stderr);
1466
+ let current = "asking";
1467
+ let outcome;
1468
+ const columns = () => stderr.columns || 80;
1469
+ const draw = (state, last = false) => {
1470
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1471
+ const rows = rowsTaken(frame, columns());
1472
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1473
+ current = state;
1474
+ };
1475
+ const redraw = () => draw(current);
1476
+ const paste = { active: false };
1477
+ const stop = terminal.stop ?? (terminal === process15 ? stopJob : undefined);
1478
+ const suspend = () => {
1479
+ if (stop === undefined)
1480
+ return;
1481
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1482
+ stdin.setRawMode(false);
1483
+ stop();
1484
+ stdin.setRawMode(true);
1485
+ stderr.write("\x1B[?25l\x1B[?2004h");
1486
+ };
1275
1487
  try {
1276
- const path = usagePath(env);
1277
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1278
- appendFileSync(path, `${JSON.stringify(entry)}
1279
- `, { mode: 384 });
1280
- } catch {}
1281
- }
1488
+ stderr.on?.("resize", redraw);
1489
+ stdin.setRawMode(true);
1490
+ stdin.resume();
1491
+ stderr.write("\x1B[?25l\x1B[?2004h");
1492
+ draw("asking");
1493
+ return await new Promise((resolve) => {
1494
+ function onData(data) {
1495
+ for (const key of readKeys(data.toString(), paste)) {
1496
+ if (key === "suspend") {
1497
+ suspend();
1498
+ continue;
1499
+ }
1500
+ const pressed = press(key);
1501
+ if (pressed !== undefined) {
1502
+ settle(pressed);
1503
+ return;
1504
+ }
1505
+ }
1506
+ draw("asking");
1507
+ }
1508
+ function onEnd() {
1509
+ settle("cancel");
1510
+ }
1511
+ function settle(settled) {
1512
+ outcome = settled;
1513
+ stdin.off("data", onData);
1514
+ stdin.off("end", onEnd);
1515
+ resolve(settled === "enter");
1516
+ }
1517
+ stdin.on("data", onData);
1518
+ stdin.on("end", onEnd);
1519
+ });
1520
+ } finally {
1521
+ stderr.off?.("resize", redraw);
1522
+ draw(outcome ?? "cancel", true);
1523
+ stderr.write(`
1524
+ \x1B[?25h\x1B[?2004l`);
1525
+ stdin.setRawMode(false);
1526
+ stdin.pause();
1527
+ }
1528
+ }
1529
+ var PROMPT_KEYS, MAX_LISTED = 12;
1530
+ var init_prompt = __esm(() => {
1531
+ init_answers();
1532
+ init_args();
1533
+ init_format();
1534
+ init_job();
1535
+ init_mode();
1536
+ init_line();
1537
+ init_state();
1538
+ init_redraw();
1539
+ init_style();
1540
+ PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1541
+ });
1282
1542
 
1283
- // ../kit/src/cli.ts
1284
- var LEVEL_OPTIONS = {
1285
- ...OUTPUT_OPTIONS,
1286
- help: { type: "boolean", short: "h", description: "show this help" }
1287
- };
1288
- var TOP_OPTIONS = {
1289
- ...LEVEL_OPTIONS,
1290
- version: { type: "boolean", short: "v", description: "print the version" },
1291
- completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1292
- };
1293
- function printError(prefix, message, hint, cause) {
1294
- const colors = paint(process15.stderr);
1295
- const styled = takesControlCodes(process15.stderr);
1296
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1297
- const under = (label, text, tint) => text === undefined ? "" : `
1298
- ${styled ? tint(label) : `${label}:`} ${text}`;
1299
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1300
- }
1301
- function runHint(command, effect) {
1302
- return `run \`${command}\`${effect === undefined ? "" : ` to ${effect}`}`;
1303
- }
1304
- function printJsonError(message, hint, cause) {
1305
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1306
- }
1307
- function wantsJson(argv) {
1308
- const end = argv.indexOf("--");
1309
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1310
- }
1311
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
1312
- if (error instanceof HelpShown)
1313
- return 0;
1314
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1315
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1316
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1317
- if (error instanceof Exit && error.code === 2)
1318
- noteUsageError(error.message);
1319
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1320
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1321
- return error instanceof Exit ? error.code : 1;
1543
+ // src/gb.ts
1544
+ import process26 from "process";
1545
+
1546
+ // ../kit/src/index.ts
1547
+ init_args();
1548
+
1549
+ // ../kit/src/argv.ts
1550
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
1551
+ import { resolve as resolve3 } from "path";
1552
+ import process10 from "process";
1553
+ function commandLine() {
1554
+ try {
1555
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
1556
+ } catch {
1557
+ return;
1558
+ }
1322
1559
  }
1323
- var COMPLETE = "__complete";
1324
- var FILES = "__files__";
1325
- async function completingOf(run) {
1326
- completion.active = true;
1560
+ function realPath(word) {
1327
1561
  try {
1328
- await run([]);
1329
- } catch (error) {
1330
- if (error instanceof Completing)
1331
- return error;
1332
- } finally {
1333
- completion.active = false;
1562
+ return realpathSync(resolve3(word));
1563
+ } catch {
1564
+ return;
1334
1565
  }
1335
- return new Completing({});
1336
1566
  }
1337
- function candidateLine(candidate) {
1338
- return typeof candidate === "string" ? candidate : candidate.join("\t");
1567
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
1568
+ const target = script === undefined ? undefined : realPath(script) ?? script;
1569
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
1570
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
1571
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
1339
1572
  }
1340
- function positionalBeingTyped(before, { options, positionals }) {
1341
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1342
- const typed = [];
1343
- let at = 0;
1344
- while (at < before.length) {
1345
- const word = before[at];
1346
- if (word === "--") {
1347
- typed.push(...before.slice(at + 1));
1348
- break;
1349
- }
1350
- if (!word.startsWith("-"))
1351
- typed.push(word);
1352
- else if (takesValue(word))
1353
- at++;
1354
- at++;
1355
- }
1356
- const last = positionals.at(-1);
1357
- if (typed.length < positionals.length)
1358
- return { name: positionals[typed.length], typed };
1359
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1573
+ // ../kit/src/chart.ts
1574
+ init_format();
1575
+ init_mode();
1576
+ init_style();
1577
+ init_theme();
1578
+ // ../kit/src/ci.ts
1579
+ init_args();
1580
+ init_format();
1581
+
1582
+ // ../kit/src/progress.ts
1583
+ init_format();
1584
+ import process12 from "process";
1585
+
1586
+ // ../kit/src/process.ts
1587
+ import { readFileSync as readFileSync4 } from "fs";
1588
+ import { constants } from "os";
1589
+ import process11 from "process";
1590
+ var KILL_GRACE_MS = 2000;
1591
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1592
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
1593
+ function exitCodeOf(code, signal) {
1594
+ if (code !== null)
1595
+ return code;
1596
+ if (typeof signal === "number")
1597
+ return 128 + signal;
1598
+ return signal === null ? 129 : 128 + constants.signals[signal];
1360
1599
  }
1361
- async function leafCandidates(run, words) {
1362
- const completing = await completingOf(run);
1363
- if ((words.at(-1) ?? "").startsWith("-"))
1364
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1365
- const flag = words.at(-2);
1366
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1367
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1368
- if (option?.type === "string") {
1369
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1370
- return values === undefined ? [FILES] : values.map(candidateLine);
1600
+ function groupsOf(pid) {
1601
+ try {
1602
+ const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
1603
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
1604
+ return { group: Number(fields[2]), foreground: Number(fields[5]) };
1605
+ } catch {
1606
+ return;
1371
1607
  }
1372
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1373
- return values === undefined ? [FILES] : values.map(candidateLine);
1374
1608
  }
1375
- var COMPLETIONS = "--completions";
1376
- function flagValue([flag = "", ...rest]) {
1377
- return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1609
+ function heardTheTerminal(child) {
1610
+ if (child.pid === undefined)
1611
+ return false;
1612
+ const own = groupsOf("self");
1613
+ return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
1378
1614
  }
1379
- function printCompletionScript(name, args) {
1380
- const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1381
- if (shell === undefined || args.length !== 1) {
1382
- printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1383
- return 2;
1615
+ function holdSignals(cleanup) {
1616
+ let received;
1617
+ let child;
1618
+ const held = {
1619
+ get signal() {
1620
+ return received;
1621
+ },
1622
+ forward: (to) => {
1623
+ child = to;
1624
+ },
1625
+ release: () => {
1626
+ for (const signal of SIGNALS)
1627
+ process11.off(signal, onSignal);
1628
+ }
1629
+ };
1630
+ function onSignal(signal) {
1631
+ received = signal;
1632
+ if (child !== undefined) {
1633
+ if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
1634
+ child.kill(signal);
1635
+ return;
1636
+ }
1637
+ if (cleanup === undefined)
1638
+ return;
1639
+ held.release();
1640
+ cleanup(signal);
1641
+ process11.kill(process11.pid, signal);
1384
1642
  }
1385
- console.log(completionScript(shell, [name]).trimEnd());
1386
- return 0;
1387
- }
1388
- async function printCandidates(found) {
1389
- for (const line of await found)
1390
- console.log(line);
1391
- return 0;
1643
+ for (const signal of SIGNALS)
1644
+ process11.on(signal, onSignal);
1645
+ return held;
1392
1646
  }
1393
- function packageVersion(entry = Bun.main) {
1394
- let resolved = entry;
1395
- try {
1396
- resolved = realpathSync2(entry);
1397
- } catch {}
1398
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1647
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
1648
+ const chunks = [];
1649
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
1650
+ 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 } : {} });
1651
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
1652
+ const timers = [];
1653
+ const killGroup = (killing) => {
1654
+ if (state.done)
1655
+ return;
1399
1656
  try {
1400
- const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1401
- if (typeof version === "string")
1402
- return version;
1657
+ if (grouped)
1658
+ process11.kill(-proc.pid, killing);
1659
+ else
1660
+ proc.kill(killing);
1403
1661
  } catch {}
1404
- if (dirname3(dir) === dir)
1405
- return "0.0.0";
1406
- }
1407
- }
1408
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1409
- if (argv[0] === COMPLETE)
1410
- return printCandidates(leafCandidates(run, argv.slice(1)));
1411
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1412
- return printCompletionScript(name, flagValue(argv));
1413
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1414
- console.log(version ?? packageVersion());
1415
- return 0;
1662
+ };
1663
+ const stop = () => {
1664
+ killGroup("SIGTERM");
1665
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
1666
+ };
1667
+ const onAbort = () => stop();
1668
+ if (timeoutMs !== undefined) {
1669
+ timers.push(setTimeout(() => {
1670
+ state.timedOut = true;
1671
+ stop();
1672
+ }, timeoutMs));
1416
1673
  }
1417
- let code;
1418
- const started = performance.now();
1674
+ if (signal?.aborted === true)
1675
+ onAbort();
1676
+ else
1677
+ signal?.addEventListener("abort", onAbort, { once: true });
1678
+ onStart?.({ kill: (killing) => killGroup(killing) });
1679
+ const drain = async (stream, name) => {
1680
+ for await (const data of stream) {
1681
+ if (state.failure !== undefined)
1682
+ continue;
1683
+ try {
1684
+ onChunk?.({ stream: name, data });
1685
+ } catch (error) {
1686
+ state.failure = error;
1687
+ stop();
1688
+ continue;
1689
+ }
1690
+ if (state.truncated)
1691
+ continue;
1692
+ let kept = data;
1693
+ if (state.kept + data.length > maxBytes) {
1694
+ let cut = maxBytes - state.kept;
1695
+ while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
1696
+ cut--;
1697
+ kept = data.subarray(0, cut);
1698
+ state.truncated = true;
1699
+ }
1700
+ state.kept += kept.length;
1701
+ if (kept.length > 0)
1702
+ chunks.push({ stream: name, data: kept });
1703
+ }
1704
+ };
1419
1705
  try {
1420
- code = await run(argv);
1421
- } catch (error) {
1422
- code = reportThrown(name, error, redact, wantsJson(argv));
1706
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
1707
+ await proc.exited;
1708
+ } finally {
1709
+ state.done = true;
1710
+ for (const timer of timers)
1711
+ clearTimeout(timer);
1712
+ signal?.removeEventListener("abort", onAbort);
1423
1713
  }
1424
- notifyEnd(name, code, performance.now() - started);
1425
- if (usage !== false) {
1426
- try {
1427
- recordUsage(usageEntry(name, undefined, argv, code));
1428
- } catch {}
1714
+ if (state.failure !== undefined)
1715
+ throw state.failure;
1716
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
1717
+ let output;
1718
+ let text;
1719
+ let stdout;
1720
+ return {
1721
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
1722
+ chunks,
1723
+ timedOut: state.timedOut,
1724
+ truncated: state.truncated,
1725
+ get output() {
1726
+ return output ??= joined();
1727
+ },
1728
+ get text() {
1729
+ return text ??= (output ??= joined()).toString();
1730
+ },
1731
+ get stdout() {
1732
+ return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1733
+ }
1734
+ };
1735
+ }
1736
+
1737
+ // ../kit/src/progress.ts
1738
+ init_style();
1739
+ init_theme();
1740
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1741
+ var FRAME_MS = 200;
1742
+ var BAR_WIDTH = 20;
1743
+ var CLEAR_BELOW = "\r\x1B[J";
1744
+ var ESC = String.fromCharCode(27);
1745
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1746
+ var RESET_STYLE = `${ESC}[0m`;
1747
+ var CTRL_C = 3;
1748
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1749
+ var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
1750
+ function liveRegion(render, stream = process12.stderr, env = process12.env) {
1751
+ if (!takesControlCodes(stream, env))
1752
+ return { redraw: () => {
1753
+ return;
1754
+ }, print: (text) => void stream.write(`${text}
1755
+ `), stop: () => {
1756
+ return;
1757
+ }, pause: () => () => {
1758
+ return;
1759
+ } };
1760
+ const write = stream.write.bind(stream);
1761
+ let frame = 0;
1762
+ let drawn = false;
1763
+ let paused = false;
1764
+ let stopped = false;
1765
+ const columns = () => {
1766
+ const now = stream.getWindowSize?.()[0] ?? stream.columns;
1767
+ return now === undefined || now === 0 ? 80 : now;
1768
+ };
1769
+ const clear = () => {
1770
+ if (drawn)
1771
+ write(CLEAR_BELOW);
1772
+ drawn = false;
1773
+ };
1774
+ const draw = () => {
1775
+ if (paused)
1776
+ return;
1777
+ const width = columns() - 1;
1778
+ const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
1779
+ const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
1780
+ if (lines.length === 0) {
1781
+ clear();
1782
+ return;
1783
+ }
1784
+ write(`${CLEAR_BELOW}${lines.join(`
1785
+ `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
1786
+ drawn = true;
1787
+ };
1788
+ let timer = setInterval(draw, FRAME_MS);
1789
+ stream.on?.("resize", draw);
1790
+ let restore = interceptOutput(clear);
1791
+ let release = swallowInput();
1792
+ const onExit = () => {
1793
+ clear();
1794
+ release();
1795
+ };
1796
+ const signals = holdSignals(stop);
1797
+ function stop() {
1798
+ stopped = true;
1799
+ clearInterval(timer);
1800
+ stream.off?.("resize", draw);
1801
+ clear();
1802
+ restore();
1803
+ release();
1804
+ process12.off("exit", onExit);
1805
+ signals.release();
1429
1806
  }
1430
- return code;
1807
+ function pause() {
1808
+ if (paused || stopped)
1809
+ return () => {
1810
+ return;
1811
+ };
1812
+ paused = true;
1813
+ clearInterval(timer);
1814
+ stream.off?.("resize", draw);
1815
+ clear();
1816
+ restore();
1817
+ release();
1818
+ return () => {
1819
+ if (!paused || stopped)
1820
+ return;
1821
+ paused = false;
1822
+ timer = setInterval(draw, FRAME_MS);
1823
+ timer.unref();
1824
+ stream.on?.("resize", draw);
1825
+ restore = interceptOutput(clear);
1826
+ release = swallowInput();
1827
+ draw();
1828
+ };
1829
+ }
1830
+ timer.unref();
1831
+ process12.on("exit", onExit);
1832
+ return {
1833
+ redraw: draw,
1834
+ print: (text) => {
1835
+ clear();
1836
+ write(`${text}
1837
+ `);
1838
+ draw();
1839
+ },
1840
+ stop,
1841
+ pause
1842
+ };
1431
1843
  }
1432
- // ../kit/src/folders.ts
1433
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1434
- // ../kit/src/secrets.ts
1435
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1436
- // ../kit/src/sessions.ts
1437
- var {Glob } = globalThis.Bun;
1438
- var SESSION_FILES = new Glob("*.json");
1439
- var ACCOUNT_DIRS = new Glob("*/sessions");
1440
- // ../kit/src/watch.ts
1441
- import process16 from "process";
1442
- import { format } from "util";
1443
- var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1444
- var DEFAULT_SECONDS = 2;
1445
- var ATTACHED_SHORT = /^-w./;
1446
- var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
1447
- function watchOption(what) {
1448
- return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
1844
+ function progressLine(stream = process12.stderr, env = process12.env) {
1845
+ const colors = paint(stream, env);
1846
+ const write = stream.write.bind(stream);
1847
+ const begun = performance.now();
1848
+ let started = begun;
1849
+ let current;
1850
+ const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
1851
+ const end = (line) => {
1852
+ region.stop();
1853
+ write(`${line}
1854
+ `);
1855
+ };
1856
+ return {
1857
+ update: (progress) => {
1858
+ const step = current?.step;
1859
+ current = progress;
1860
+ if (progress.step !== step) {
1861
+ started = performance.now();
1862
+ region.redraw();
1863
+ }
1864
+ },
1865
+ stop: region.stop,
1866
+ pause: region.pause,
1867
+ done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
1868
+ failed: (text) => end(marked("problem", text, stream, undefined, env))
1869
+ };
1870
+ }
1871
+ function progressParts({ step, done, total, unit }, spinner, ms) {
1872
+ const { theme } = activeTheme();
1873
+ const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
1874
+ if (total !== undefined && total > 0) {
1875
+ const counted = Math.min(done ?? 0, total);
1876
+ const filled = Math.round(counted / total * BAR_WIDTH);
1877
+ 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 });
1878
+ }
1879
+ parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
1880
+ return parts;
1449
1881
  }
1450
- function withoutWatch(args) {
1451
- const rest = [];
1452
- for (let at = 0;at < args.length; at++) {
1453
- const arg = args[at];
1454
- if (arg === "--watch" || arg === "-w") {
1455
- if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
1456
- at++;
1457
- } else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
1458
- rest.push(arg);
1882
+ function plain(text) {
1883
+ return text;
1884
+ }
1885
+ function tintedParts(parts, colors) {
1886
+ return parts.map(({ text, tint }) => tint(colors)(text)).join("");
1887
+ }
1888
+ function cutToWidth(line, width) {
1889
+ if (Bun.stringWidth(line) <= width)
1890
+ return line;
1891
+ let room = width;
1892
+ let kept = "";
1893
+ let index = 0;
1894
+ let linked = false;
1895
+ while (index < line.length) {
1896
+ ESCAPE_CODE.lastIndex = index;
1897
+ const escape = ESCAPE_CODE.exec(line);
1898
+ if (escape !== null) {
1899
+ kept += escape[0];
1900
+ linked ||= escape[0].startsWith(`${ESC}]`);
1901
+ index = ESCAPE_CODE.lastIndex;
1902
+ continue;
1459
1903
  }
1904
+ const char = String.fromCodePoint(line.codePointAt(index));
1905
+ const columns = Bun.stringWidth(char);
1906
+ if (columns > room)
1907
+ break;
1908
+ kept += char;
1909
+ room -= columns;
1910
+ index += char.length;
1460
1911
  }
1461
- return rest;
1912
+ return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1462
1913
  }
1463
- async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1464
- const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1465
- if (!takesControlCodes(stream))
1466
- badUsage("--watch redraws the screen, so it needs a terminal");
1467
- let code = 0;
1468
- for (let round = 0;round < rounds; round++) {
1469
- const held = [];
1470
- const { log, info } = console;
1471
- const write = process16.stdout.write.bind(process16.stdout);
1472
- const hold = (...parts) => void held.push(`${format(...parts)}
1473
- `);
1474
- console.log = hold;
1475
- console.info = hold;
1476
- process16.stdout.write = (text) => {
1477
- held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1478
- return true;
1914
+ function swallowInput() {
1915
+ const input = process12.stdin;
1916
+ if (!input.isTTY)
1917
+ return () => {
1918
+ return;
1919
+ };
1920
+ const onData = (data) => {
1921
+ if (data.includes(CTRL_C))
1922
+ process12.kill(process12.pid, "SIGINT");
1923
+ };
1924
+ input.setRawMode(true);
1925
+ input.on("data", onData);
1926
+ input.resume();
1927
+ let released = false;
1928
+ return () => {
1929
+ if (released)
1930
+ return;
1931
+ released = true;
1932
+ input.off("data", onData);
1933
+ input.pause();
1934
+ input.setRawMode(false);
1935
+ };
1936
+ }
1937
+ function interceptOutput(clear) {
1938
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1939
+ const wrapped = targets.map(([target, name]) => {
1940
+ const original = Reflect.get(target, name);
1941
+ const wrapper = (...args) => {
1942
+ clear();
1943
+ return original.apply(target, args);
1479
1944
  };
1945
+ Reflect.set(target, name, wrapper);
1946
+ return { target, name, original, wrapper };
1947
+ });
1948
+ return () => {
1949
+ for (const { target, name, original, wrapper } of wrapped) {
1950
+ if (Reflect.get(target, name) === wrapper)
1951
+ Reflect.set(target, name, original);
1952
+ }
1953
+ };
1954
+ }
1955
+
1956
+ // ../kit/src/ci.ts
1957
+ init_style();
1958
+
1959
+ // ../kit/src/tool.ts
1960
+ init_format();
1961
+ // ../kit/src/cli.ts
1962
+ init_args();
1963
+ import { readFileSync as readFileSync6, realpathSync as realpathSync2 } from "fs";
1964
+ import { dirname as dirname4, join as join8 } from "path";
1965
+ import process19 from "process";
1966
+
1967
+ // ../kit/src/askpass.ts
1968
+ import { chmodSync, mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
1969
+ import { tmpdir } from "os";
1970
+ import { join as join6 } from "path";
1971
+ import process16 from "process";
1972
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1973
+ var ECHOED = /username|yes\/no/i;
1974
+ var quoted = (text) => `'${text.replaceAll("'", `'\\''`)}'`;
1975
+ function askpass(pause = () => () => {
1976
+ return;
1977
+ }) {
1978
+ if (process16.stdin.isTTY !== true || process16.stderr.isTTY !== true || process16.argv[1] === undefined)
1979
+ return;
1980
+ const dir = mkdtempSync(join6(tmpdir(), "kaynooo-askpass-"));
1981
+ const socketPath = join6(dir, "socket");
1982
+ const script = join6(dir, "askpass");
1983
+ let turn = Promise.resolve();
1984
+ const answer = async ({ prompt, notice }) => {
1985
+ const resume = pause();
1480
1986
  try {
1481
- code = await step();
1987
+ if (notice === true) {
1988
+ process16.stderr.write(`${prompt.trim()}
1989
+ `);
1990
+ return {};
1991
+ }
1992
+ await Promise.resolve().then(() => init_prompt());
1993
+ return { answer: await input2(prompt.trim(), { mask: !ECHOED.test(prompt) }) };
1482
1994
  } finally {
1483
- console.log = log;
1484
- console.info = info;
1485
- process16.stdout.write = write;
1995
+ resume();
1486
1996
  }
1487
- stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1488
- await sleep(interval);
1489
- }
1490
- return code;
1491
- }
1492
- // ../kit/src/workspace-root.ts
1493
- import { homedir as homedir4 } from "os";
1494
- import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1495
- import process17 from "process";
1496
- function expandHome(path, home) {
1497
- if (path === "~")
1498
- return home;
1499
- return path.startsWith("~/") ? join6(home, path.slice(2)) : path;
1500
- }
1501
- function configured(env, home) {
1502
- const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1503
- return typeof folder === "string" && folder !== "" ? folder : undefined;
1997
+ };
1998
+ const respond = async (socket, request) => {
1999
+ const { promise, resolve } = Promise.withResolvers();
2000
+ const previous = turn;
2001
+ let reply = {};
2002
+ turn = promise;
2003
+ await previous;
2004
+ try {
2005
+ reply = await answer(request);
2006
+ } catch {} finally {
2007
+ socket.end(`${JSON.stringify(reply)}
2008
+ `);
2009
+ resolve();
2010
+ }
2011
+ };
2012
+ const server = Bun.listen({
2013
+ unix: socketPath,
2014
+ socket: {
2015
+ open: (socket) => {
2016
+ socket.data = { buffered: "" };
2017
+ },
2018
+ data: (socket, chunk) => {
2019
+ const before = socket.data.buffered;
2020
+ socket.data.buffered += chunk.toString();
2021
+ if (before.includes(`
2022
+ `) || !socket.data.buffered.includes(`
2023
+ `))
2024
+ return;
2025
+ respond(socket, JSON.parse(socket.data.buffered));
2026
+ }
2027
+ }
2028
+ });
2029
+ writeFileSync2(script, `#!/bin/sh
2030
+ ${SOCKET_VARIABLE}=${quoted(socketPath)} exec ${quoted(process16.execPath)} --no-env-file --config=/dev/null ${quoted(process16.argv[1])} "$@"
2031
+ `);
2032
+ chmodSync(script, 448);
2033
+ return {
2034
+ env: { GIT_ASKPASS: script, SSH_ASKPASS: script, SSH_ASKPASS_REQUIRE: "force" },
2035
+ close: () => {
2036
+ server.stop(true);
2037
+ rmSync(dir, { recursive: true, force: true });
2038
+ }
2039
+ };
1504
2040
  }
1505
- function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1506
- const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1507
- return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
2041
+ async function askpassClient(argv) {
2042
+ const socketPath = process16.env[SOCKET_VARIABLE];
2043
+ if (socketPath === undefined)
2044
+ return;
2045
+ const request = { prompt: argv[0] ?? "", ...process16.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
2046
+ const { promise, resolve } = Promise.withResolvers();
2047
+ let received = "";
2048
+ try {
2049
+ await Bun.connect({
2050
+ unix: socketPath,
2051
+ socket: {
2052
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
2053
+ `),
2054
+ data: (_, chunk) => {
2055
+ received += chunk.toString();
2056
+ },
2057
+ close: () => resolve(received),
2058
+ error: () => resolve("")
2059
+ }
2060
+ });
2061
+ } catch {
2062
+ return 1;
2063
+ }
2064
+ const reply = await promise;
2065
+ if (reply === "")
2066
+ return 1;
2067
+ const { answer } = JSON.parse(reply);
2068
+ if (request.notice === true)
2069
+ return 0;
2070
+ if (answer === undefined)
2071
+ return 1;
2072
+ process16.stdout.write(`${answer}
2073
+ `);
2074
+ return 0;
1508
2075
  }
1509
- // src/branch.ts
1510
- import { basename } from "path";
1511
- import process22 from "process";
1512
2076
 
1513
- // ../kit/src/picker/line.ts
1514
- var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1515
- var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1516
- var FORWARD_KILLS = new Set(["killnext", "killend"]);
1517
- function isEditKey(key) {
1518
- return EDIT_KEYS.has(key);
2077
+ // ../kit/src/completions.ts
2078
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
2079
+ 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'
2080
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
2081
+ set -l current (commandline -ct)
2082
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
2083
+ if test "$line" = __files__
2084
+ __fish_complete_path $current
2085
+ else
2086
+ echo $line
2087
+ end
2088
+ end
2089
+ end`;
2090
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
2091
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
2092
+ local -a lines
2093
+ COMPREPLY=()
2094
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
2095
+ for line in "\${lines[@]}"; do
2096
+ if [[ $line == __files__ ]]; then
2097
+ COMPREPLY+=($(compgen -f -- "$cur"))
2098
+ else
2099
+ words+="\${line%%$'\\t'*}"$'\\n'
2100
+ fi
2101
+ done
2102
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
2103
+ }`;
2104
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
2105
+ local line
2106
+ local -a described plain
2107
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
2108
+ if [[ $line == __files__ ]]; then
2109
+ _files
2110
+ elif [[ $line == *$'\\t'* ]]; then
2111
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
2112
+ else
2113
+ plain+=("$line")
2114
+ fi
2115
+ done
2116
+ (( \${#described} )) && _describe -V value described
2117
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
2118
+ return 0
2119
+ }`;
2120
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
2121
+ if (shell === "fish")
2122
+ return `${header}
2123
+ ${FISH_FUNCTION}
2124
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
2125
+ `).join("")}`;
2126
+ if (shell === "bash")
2127
+ return `${header}
2128
+ ${BASH_FUNCTION}
2129
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
2130
+ `;
2131
+ return `${header}
2132
+ ${ZSH_FUNCTION}
2133
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
2134
+ `;
1519
2135
  }
1520
- function endsKills(key) {
1521
- return typeof key !== "object" && !isEditKey(key);
2136
+
2137
+ // ../kit/src/notify.ts
2138
+ init_format();
2139
+ init_mode();
2140
+ import process17 from "process";
2141
+ var NOTIFY_AFTER_MS = 1e4;
2142
+ var CANCELLED = 130;
2143
+ function base64(text) {
2144
+ return Buffer.from(text).toString("base64");
1522
2145
  }
1523
- var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1524
- var SPACE = /\s/;
1525
- function isWord(char) {
1526
- return char !== undefined && WORD_CHARACTER.test(char);
2146
+ function notification(title, body, env = process17.env) {
2147
+ const id = `kit${process17.pid}`;
2148
+ 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\\`];
2149
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1527
2150
  }
1528
- function wordStart(chars, from) {
1529
- let at = from;
1530
- while (at > 0 && !isWord(chars[at - 1]))
1531
- at--;
1532
- while (at > 0 && isWord(chars[at - 1]))
1533
- at--;
1534
- return at;
2151
+ function notifyEnd(command, code, ms, { stream = process17.stderr, env = process17.env } = {}) {
2152
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
2153
+ return;
2154
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1535
2155
  }
1536
- function wordEnd(chars, from) {
1537
- let at = from;
1538
- while (at < chars.length && !isWord(chars[at]))
1539
- at++;
1540
- while (at < chars.length && isWord(chars[at]))
1541
- at++;
1542
- return at;
2156
+
2157
+ // ../kit/src/cli.ts
2158
+ init_style();
2159
+ init_text2();
2160
+
2161
+ // ../kit/src/usage.ts
2162
+ import { appendFileSync, mkdirSync as mkdirSync2 } from "fs";
2163
+ import { homedir as homedir4 } from "os";
2164
+ import { dirname as dirname3, join as join7 } from "path";
2165
+ import process18 from "process";
2166
+
2167
+ // ../kit/src/logs.ts
2168
+ init_user_config();
2169
+ var DAY_MS = 24 * 60 * 60 * 1000;
2170
+ var CLI_FOLDER = "kaynooo-cli";
2171
+
2172
+ // ../kit/src/usage.ts
2173
+ init_user_config();
2174
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
2175
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
2176
+ var LONGEST_NAME = 40;
2177
+ var usageError;
2178
+ function noteUsageError(message) {
2179
+ usageError = message;
1543
2180
  }
1544
- function spacedStart(chars, from) {
1545
- let at = from;
1546
- while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
1547
- at--;
1548
- while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
1549
- at--;
1550
- return at;
2181
+ function stateHome(env = process18.env) {
2182
+ return xdgFolder(env.XDG_STATE_HOME, join7(homedir4(), ".local", "state"));
1551
2183
  }
1552
- function cut(chars, from, to) {
1553
- return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
2184
+ function usagePath(env = process18.env) {
2185
+ return join7(stateHome(env), CLI_FOLDER, "usage.jsonl");
1554
2186
  }
1555
- function insert(chars, at, text) {
1556
- const typed = [...text];
1557
- return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
2187
+ function usageRecorded(env = process18.env) {
2188
+ const off = env.KAYNOOO_CLI_NO_USAGE;
2189
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1558
2190
  }
1559
- function editLine(line, key) {
1560
- const { killed = "", chained = false } = line;
1561
- const chars = [...line.text];
1562
- const at = Math.min(Math.max(line.caret, 0), chars.length);
1563
- const edited = edit(chars, at, key, killed);
1564
- if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1565
- return line.killed === undefined ? edited : { ...edited, killed };
1566
- const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1567
- if (taken === "")
1568
- return { ...edited, killed, chained };
1569
- if (!chained)
1570
- return { ...edited, killed: taken, chained: true };
1571
- return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
2191
+ function flagNames(argv) {
2192
+ const end = argv.indexOf("--");
2193
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
2194
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1572
2195
  }
1573
- function edit(chars, at, key, killed) {
1574
- const text = chars.join("");
1575
- if (typeof key === "object")
1576
- return insert(chars, at, key.text);
1577
- switch (key) {
1578
- case "left":
1579
- return { text, caret: Math.max(at - 1, 0) };
1580
- case "right":
1581
- return { text, caret: Math.min(at + 1, chars.length) };
1582
- case "wordleft":
1583
- return { text, caret: wordStart(chars, at) };
1584
- case "wordright":
1585
- return { text, caret: wordEnd(chars, at) };
1586
- case "linestart":
1587
- return { text, caret: 0 };
1588
- case "lineend":
1589
- return { text, caret: chars.length };
1590
- case "erase":
1591
- return cut(chars, Math.max(at - 1, 0), at);
1592
- case "delete":
1593
- return cut(chars, at, Math.min(at + 1, chars.length));
1594
- case "word":
1595
- return cut(chars, spacedStart(chars, at), at);
1596
- case "killword":
1597
- return cut(chars, wordStart(chars, at), at);
1598
- case "killnext":
1599
- return cut(chars, at, wordEnd(chars, at));
1600
- case "clear":
1601
- return cut(chars, 0, at);
1602
- case "killend":
1603
- return cut(chars, at, chars.length);
1604
- case "yank":
1605
- return insert(chars, at, killed);
1606
- }
2196
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
2197
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
2198
+ usageError = undefined;
2199
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1607
2200
  }
1608
- function visible({ text, caret }, room) {
1609
- const chars = [...text];
1610
- const at = Math.min(Math.max(caret, 0), chars.length);
1611
- const cells = at === chars.length ? [...chars, " "] : chars;
1612
- const widths = cells.map((char) => Bun.stringWidth(char));
1613
- const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1614
- const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1615
- let start = at;
1616
- let end = at + 1;
1617
- while (start > 0 && fits(start - 1, end))
1618
- start--;
1619
- while (end < cells.length && fits(start, end + 1))
1620
- end++;
1621
- const left = start > 0 ? "\u2026" : "";
1622
- const right = end < cells.length ? "\u2026" : "";
1623
- return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
2201
+ function recordUsage(entry, env = process18.env) {
2202
+ if (!usageRecorded(env))
2203
+ return;
2204
+ try {
2205
+ const path = usagePath(env);
2206
+ mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
2207
+ appendFileSync(path, `${JSON.stringify(entry)}
2208
+ `, { mode: 384 });
2209
+ } catch {}
1624
2210
  }
1625
2211
 
1626
- // ../kit/src/picker/score.ts
1627
- var MATCH = 16;
1628
- var CONSECUTIVE = 12;
1629
- var BOUNDARY = 10;
1630
- var PREFIX = 8;
1631
- var GAP = 1;
1632
- var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1633
- var UPPER = /\p{Lu}/u;
1634
- var LOWER = /\p{Ll}/u;
1635
- var NONE = Number.NEGATIVE_INFINITY;
1636
- function startsWord(text, index) {
1637
- if (index === 0)
1638
- return true;
1639
- const before = text[index - 1];
1640
- return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
2212
+ // ../kit/src/cli.ts
2213
+ var LEVEL_OPTIONS = {
2214
+ ...OUTPUT_OPTIONS,
2215
+ help: { type: "boolean", short: "h", description: "show this help" }
2216
+ };
2217
+ var TOP_OPTIONS = {
2218
+ ...LEVEL_OPTIONS,
2219
+ version: { type: "boolean", short: "v", description: "print the version" },
2220
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
2221
+ };
2222
+ function printError(prefix, message, hint, cause) {
2223
+ const colors = paint(process19.stderr);
2224
+ const styled = takesControlCodes(process19.stderr);
2225
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
2226
+ const under = (label, text, tint) => text === undefined ? "" : `
2227
+ ${styled ? tint(label) : `${label}:`} ${text}`;
2228
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1641
2229
  }
1642
- function fuzzy(query, text) {
1643
- if (query === "")
1644
- return { score: 0, positions: [] };
1645
- const exact = query !== query.toLowerCase();
1646
- const needle = exact ? query : query.toLowerCase();
1647
- const haystack = exact ? text : text.toLowerCase();
1648
- if (haystack.length !== text.length || needle.length > haystack.length)
1649
- return;
1650
- const width = haystack.length;
1651
- const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
1652
- const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
1653
- for (let j = 0;j < needle.length; j++) {
1654
- let run = NONE;
1655
- let runAt = -1;
1656
- for (let i = j;i < width; i++) {
1657
- if (j > 0 && i - 2 >= j - 1) {
1658
- const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
1659
- if (candidate > run) {
1660
- run = candidate;
1661
- runAt = i - 2;
1662
- }
1663
- }
1664
- if (haystack[i] !== needle[j])
1665
- continue;
1666
- const here = MATCH + (startsWord(text, i) ? BOUNDARY : 0) + (i === 0 ? PREFIX : 0);
1667
- if (j === 0) {
1668
- best[0][i] = here - i * GAP;
1669
- continue;
1670
- }
1671
- const joined = best[j - 1][i - 1] + CONSECUTIVE;
1672
- const skipped = run - (i - 1) * GAP;
1673
- if (joined > NONE && joined >= skipped) {
1674
- best[j][i] = joined + here;
1675
- from[j][i] = i - 1;
1676
- } else if (skipped > NONE) {
1677
- best[j][i] = skipped + here;
1678
- from[j][i] = runAt;
1679
- }
1680
- }
1681
- }
1682
- const last = best[needle.length - 1];
1683
- let end = -1;
1684
- for (let i = 0;i < width; i++) {
1685
- if (last[i] > NONE && (end === -1 || last[i] > last[end]))
1686
- end = i;
1687
- }
1688
- if (end === -1)
1689
- return;
1690
- const positions = [];
1691
- for (let j = needle.length - 1, i = end;j >= 0; j--) {
1692
- positions.unshift(i);
1693
- i = from[j][i];
1694
- }
1695
- return { score: last[end], positions };
2230
+ function runHint(command, effect) {
2231
+ return `run \`${command}\`${effect === undefined ? "" : ` to ${effect}`}`;
1696
2232
  }
1697
- function rank(query, lines) {
1698
- if (query === "")
1699
- return lines.map((_, index) => ({ index, positions: [] }));
1700
- const found = [];
1701
- for (const [index, line] of lines.entries()) {
1702
- const match = fuzzy(query, line);
1703
- if (match !== undefined)
1704
- found.push({ index, positions: match.positions, score: match.score });
1705
- }
1706
- return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
2233
+ function printJsonError(message, hint, cause) {
2234
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1707
2235
  }
1708
-
1709
- // ../kit/src/picker/state.ts
1710
- var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1711
- var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1712
- var SGR = /^\x1B\[[0-9;]*m$/;
1713
- var RESET = /^\x1B\[0?m$/;
1714
- var COLUMN_GAP = 2;
1715
- var PASTE_START = "\x1B[200~";
1716
- var PASTE_END = "\x1B[201~";
1717
- var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1718
- var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1719
- var WHEEL_LINES = 3;
1720
- var KEYS = {
1721
- "\x1B[A": "up",
1722
- "\x1BOA": "up",
1723
- "\x10": "up",
1724
- "\x1B[B": "down",
1725
- "\x1BOB": "down",
1726
- "\x0E": "down",
1727
- "\x1B[5~": "pageup",
1728
- "\x1B[6~": "pagedown",
1729
- "\x1B[H": "home",
1730
- "\x1B[1~": "home",
1731
- "\x1BOH": "home",
1732
- "\x1B[F": "end",
1733
- "\x1B[4~": "end",
1734
- "\x1BOF": "end",
1735
- "\r": "enter",
1736
- "\n": "enter",
1737
- "\x03": "cancel",
1738
- "\x1B": "cancel",
1739
- "\x1B[D": "left",
1740
- "\x1BOD": "left",
1741
- "\x1B[C": "right",
1742
- "\x1BOC": "right",
1743
- "\x1B[1;5D": "wordleft",
1744
- "\x1B[1;3D": "wordleft",
1745
- "\x1Bb": "wordleft",
1746
- "\x1B[1;5C": "wordright",
1747
- "\x1B[1;3C": "wordright",
1748
- "\x1Bf": "wordright",
1749
- "\x01": "linestart",
1750
- "\x05": "lineend",
1751
- "\x7F": "erase",
1752
- "\x1B[3~": "delete",
1753
- "\b": "killword",
1754
- "\x1B\x7F": "killword",
1755
- "\x1B[3;5~": "killnext",
1756
- "\x1Bd": "killnext",
1757
- "\x15": "clear",
1758
- "\v": "killend",
1759
- "\x17": "word",
1760
- "\x19": "yank",
1761
- "\x1A": "suspend",
1762
- "\t": "tab",
1763
- "\x1F": "help",
1764
- "\x1BOP": "help",
1765
- "\x1B[11~": "help"
1766
- };
1767
- var CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
1768
- function repeat(value, count) {
1769
- return Array.from({ length: count }).fill(value);
2236
+ function wantsJson(argv) {
2237
+ const end = argv.indexOf("--");
2238
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1770
2239
  }
1771
- function styled(line) {
1772
- let text = "";
1773
- const styles = [];
1774
- let active = "";
1775
- let colored = false;
1776
- let last = 0;
1777
- function add(chunk) {
1778
- const flat = chunk.replace(CONTROL2, " ");
1779
- text += flat;
1780
- colored ||= active !== "" && flat !== "";
1781
- styles.push(...repeat(active, flat.length));
1782
- }
1783
- for (const found of line.matchAll(ANSI)) {
1784
- add(line.slice(last, found.index));
1785
- last = found.index + found[0].length;
1786
- if (SGR.test(found[0]))
1787
- active = RESET.test(found[0]) ? "" : active + found[0];
1788
- }
1789
- add(line.slice(last));
1790
- return { text, styles: colored ? styles : undefined };
2240
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
2241
+ if (error instanceof HelpShown)
2242
+ return 0;
2243
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
2244
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
2245
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
2246
+ if (error instanceof Exit && error.code === 2)
2247
+ noteUsageError(error.message);
2248
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
2249
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
2250
+ return error instanceof Exit ? error.code : 1;
1791
2251
  }
1792
- function lay(rows, searched) {
1793
- const parsed = rows.map((row) => row.cells.map(styled));
1794
- const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1795
- return parsed.map((cells, at) => {
1796
- let text = "";
1797
- const styles = [];
1798
- let colored = false;
1799
- let searchEnd = 0;
1800
- for (const [column, cell] of cells.entries()) {
1801
- const last = column === cells.length - 1;
1802
- const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1803
- text += shown;
1804
- colored ||= cell.styles !== undefined;
1805
- styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1806
- if (column < searched)
1807
- searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1808
- if (!last) {
1809
- const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1810
- text += " ".repeat(pad);
1811
- styles.push(...repeat("", pad));
1812
- }
1813
- }
1814
- return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1815
- });
2252
+ var COMPLETE = "__complete";
2253
+ var FILES = "__files__";
2254
+ async function completingOf(run) {
2255
+ completion.active = true;
2256
+ try {
2257
+ await run([]);
2258
+ } catch (error) {
2259
+ if (error instanceof Completing)
2260
+ return error;
2261
+ } finally {
2262
+ completion.active = false;
2263
+ }
2264
+ return new Completing({});
1816
2265
  }
1817
- function parseKeys(input, paste = { active: false }, ctrls = []) {
1818
- const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1819
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1820
- const wheel = MOUSE.exec(sequence)?.[1];
1821
- if (wheel !== undefined)
1822
- return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1823
- const named = codes.get(sequence);
1824
- const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1825
- if (sequence === PASTE_START || sequence === PASTE_END) {
1826
- paste.active = sequence === PASTE_START;
1827
- return [];
2266
+ function candidateLine(candidate) {
2267
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
2268
+ }
2269
+ function positionalBeingTyped(before, { options, positionals }) {
2270
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
2271
+ const typed = [];
2272
+ let at = 0;
2273
+ while (at < before.length) {
2274
+ const word = before[at];
2275
+ if (word === "--") {
2276
+ typed.push(...before.slice(at + 1));
2277
+ break;
1828
2278
  }
1829
- if (paste.active && (sequence === "\r" || sequence === `
1830
- `))
1831
- return [];
1832
- if (key !== undefined)
1833
- return [key];
1834
- return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1835
- });
2279
+ if (!word.startsWith("-"))
2280
+ typed.push(word);
2281
+ else if (takesValue(word))
2282
+ at++;
2283
+ at++;
2284
+ }
2285
+ const last = positionals.at(-1);
2286
+ if (typed.length < positionals.length)
2287
+ return { name: positionals[typed.length], typed };
2288
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1836
2289
  }
1837
- function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1838
- const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1839
- return withRows(state, rows);
2290
+ async function leafCandidates(run, words) {
2291
+ const completing = await completingOf(run);
2292
+ if ((words.at(-1) ?? "").startsWith("-"))
2293
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
2294
+ const flag = words.at(-2);
2295
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
2296
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
2297
+ if (option?.type === "string") {
2298
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
2299
+ return values === undefined ? [FILES] : values.map(candidateLine);
2300
+ }
2301
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
2302
+ return values === undefined ? [FILES] : values.map(candidateLine);
1840
2303
  }
1841
- function withRows(state, rows, header = state.header) {
1842
- const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1843
- const laid = lay(cells, state.searched);
1844
- const searchable = laid.map((row) => row.searchable);
1845
- const matches = rank(state.query, searchable);
1846
- return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
2304
+ var COMPLETIONS = "--completions";
2305
+ function flagValue([flag = "", ...rest]) {
2306
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1847
2307
  }
1848
- function withQuery(state, key) {
1849
- const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1850
- return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
2308
+ function printCompletionScript(name, args) {
2309
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
2310
+ if (shell === undefined || args.length !== 1) {
2311
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
2312
+ return 2;
2313
+ }
2314
+ console.log(completionScript(shell, [name]).trimEnd());
2315
+ return 0;
1851
2316
  }
1852
- function move(state, by) {
1853
- return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
2317
+ async function printCandidates(found) {
2318
+ for (const line of await found)
2319
+ console.log(line);
2320
+ return 0;
1854
2321
  }
1855
- function highlighted(state) {
1856
- return state.matches[state.cursor]?.index;
2322
+ function packageVersion(entry = Bun.main) {
2323
+ let resolved = entry;
2324
+ try {
2325
+ resolved = realpathSync2(entry);
2326
+ } catch {}
2327
+ for (let dir = dirname4(resolved);; dir = dirname4(dir)) {
2328
+ try {
2329
+ const { version } = JSON.parse(readFileSync6(join8(dir, "package.json"), "utf8"));
2330
+ if (typeof version === "string")
2331
+ return version;
2332
+ } catch {}
2333
+ if (dirname4(dir) === dir)
2334
+ return "0.0.0";
2335
+ }
1857
2336
  }
1858
- function press(state, key) {
1859
- if (state.done !== undefined)
1860
- return state;
1861
- if (state.chained && endsKills(key))
1862
- state = { ...state, chained: false };
1863
- if (state.help)
1864
- return { ...state, help: false };
1865
- if (typeof key === "object") {
1866
- if ("text" in key)
1867
- return withQuery(state, key);
1868
- return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
2337
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
2338
+ const answered = await askpassClient(argv);
2339
+ if (answered !== undefined)
2340
+ return answered;
2341
+ if (argv[0] === COMPLETE)
2342
+ return printCandidates(leafCandidates(run, argv.slice(1)));
2343
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
2344
+ return printCompletionScript(name, flagValue(argv));
2345
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
2346
+ console.log(version ?? packageVersion());
2347
+ return 0;
1869
2348
  }
1870
- if (isEditKey(key))
1871
- return withQuery(state, key);
1872
- switch (key) {
1873
- case "up":
1874
- return move(state, -1);
1875
- case "down":
1876
- return move(state, 1);
1877
- case "pageup":
1878
- return move(state, -state.page);
1879
- case "pagedown":
1880
- return move(state, state.page);
1881
- case "home":
1882
- return move(state, -state.matches.length);
1883
- case "end":
1884
- return move(state, state.matches.length);
1885
- case "cancel":
1886
- return { ...state, done: "cancel" };
1887
- case "help":
1888
- return { ...state, help: true };
1889
- case "suspend":
1890
- return state;
1891
- case "enter":
1892
- return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1893
- case "tab": {
1894
- const at = highlighted(state);
1895
- if (!state.multi || at === undefined)
1896
- return state;
1897
- const marked = new Set(state.marked);
1898
- if (!marked.delete(at))
1899
- marked.add(at);
1900
- return move({ ...state, marked }, 1);
2349
+ let code;
2350
+ const started = performance.now();
2351
+ try {
2352
+ code = await run(argv);
2353
+ } catch (error) {
2354
+ code = reportThrown(name, error, redact, wantsJson(argv));
2355
+ }
2356
+ notifyEnd(name, code, performance.now() - started);
2357
+ if (usage !== false) {
2358
+ try {
2359
+ recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
2360
+ } catch {}
2361
+ }
2362
+ return code;
2363
+ }
2364
+
2365
+ // ../kit/src/index.ts
2366
+ init_config();
2367
+
2368
+ // ../kit/src/excerpt.ts
2369
+ init_text2();
2370
+
2371
+ // ../kit/src/index.ts
2372
+ init_folders();
2373
+ init_format();
2374
+
2375
+ // ../kit/src/git.ts
2376
+ init_args();
2377
+ // ../kit/src/limit.ts
2378
+ init_args();
2379
+
2380
+ // ../kit/src/index.ts
2381
+ init_mode();
2382
+
2383
+ // ../kit/src/report.ts
2384
+ init_style();
2385
+ init_text2();
2386
+ // ../kit/src/secrets.ts
2387
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
2388
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
2389
+ // ../kit/src/sessions.ts
2390
+ var {Glob } = globalThis.Bun;
2391
+ var SESSION_FILES = new Glob("*.json");
2392
+ var ACCOUNT_DIRS = new Glob("*/sessions");
2393
+
2394
+ // ../kit/src/index.ts
2395
+ init_style();
2396
+ init_text2();
2397
+ init_theme();
2398
+ init_user_config();
2399
+
2400
+ // ../kit/src/watch.ts
2401
+ init_args();
2402
+ init_input();
2403
+ init_style();
2404
+ import process20 from "process";
2405
+ import { format } from "util";
2406
+ var CLEAR_SCREEN = "\x1B[H\x1B[2J";
2407
+ var DEFAULT_SECONDS = 2;
2408
+ var ATTACHED_SHORT = /^-w./;
2409
+ var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
2410
+ function watchOption(what) {
2411
+ return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
2412
+ }
2413
+ function withoutWatch(args) {
2414
+ const rest = [];
2415
+ for (let at = 0;at < args.length; at++) {
2416
+ const arg = args[at];
2417
+ if (arg === "--watch" || arg === "-w") {
2418
+ if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
2419
+ at++;
2420
+ } else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
2421
+ rest.push(arg);
1901
2422
  }
1902
2423
  }
2424
+ return rest;
1903
2425
  }
1904
- function chosen(state) {
1905
- if (state.marked.size > 0)
1906
- return state.rows.filter((_, index) => state.marked.has(index));
1907
- const at = highlighted(state);
1908
- return at === undefined ? [] : [state.rows[at]];
2426
+ async function watching(value, step, stream = process20.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
2427
+ const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
2428
+ if (!takesControlCodes(stream))
2429
+ badUsage("--watch redraws the screen, so it needs a terminal");
2430
+ let code = 0;
2431
+ for (let round = 0;round < rounds; round++) {
2432
+ const held = [];
2433
+ const { log, info } = console;
2434
+ const write = process20.stdout.write.bind(process20.stdout);
2435
+ const hold = (...parts) => void held.push(`${format(...parts)}
2436
+ `);
2437
+ console.log = hold;
2438
+ console.info = hold;
2439
+ process20.stdout.write = (text) => {
2440
+ held.push(typeof text === "string" ? text : Buffer.from(text).toString());
2441
+ return true;
2442
+ };
2443
+ try {
2444
+ code = await step();
2445
+ } finally {
2446
+ console.log = log;
2447
+ console.info = info;
2448
+ process20.stdout.write = write;
2449
+ }
2450
+ stream.write(`${CLEAR_SCREEN}${held.join("")}`);
2451
+ await sleep(interval);
2452
+ }
2453
+ return code;
2454
+ }
2455
+ // ../kit/src/workspace-root.ts
2456
+ init_user_config();
2457
+ import { homedir as homedir5 } from "os";
2458
+ import { dirname as dirname5, join as join9, resolve as resolve4 } from "path";
2459
+ import process21 from "process";
2460
+ function expandHome(path, home) {
2461
+ if (path === "~")
2462
+ return home;
2463
+ return path.startsWith("~/") ? join9(home, path.slice(2)) : path;
2464
+ }
2465
+ function configured(env, home) {
2466
+ const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
2467
+ return typeof folder === "string" && folder !== "" ? folder : undefined;
2468
+ }
2469
+ function workspaceRoot({ given, env = process21.env, home = homedir5() } = {}) {
2470
+ const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
2471
+ return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join9(home, "Workspace"), home));
1909
2472
  }
2473
+ // src/branch.ts
2474
+ import { basename } from "path";
2475
+ import process25 from "process";
2476
+
2477
+ // ../kit/src/picker.ts
2478
+ init_folders();
2479
+ init_state();
1910
2480
 
1911
2481
  // ../kit/src/picker/terminal.ts
2482
+ init_args();
2483
+ init_job();
2484
+ init_redraw();
2485
+ init_style();
1912
2486
  import { openSync } from "fs";
1913
- import process21 from "process";
2487
+ import process24 from "process";
1914
2488
  import tty from "tty";
1915
2489
 
1916
- // ../kit/src/job.ts
1917
- import process19 from "process";
1918
- function stopJob() {
1919
- process19.kill(0, "SIGTSTP");
1920
- }
1921
-
1922
- // ../kit/src/redraw.ts
1923
- var SYNC_START = "\x1B[?2026h";
1924
- var SYNC_END = "\x1B[?2026l";
1925
- function overwrite(lines, columns) {
1926
- return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1927
- `);
1928
- }
1929
-
1930
2490
  // ../kit/src/picker/preview.ts
1931
- import process20 from "process";
2491
+ import process23 from "process";
1932
2492
 
1933
2493
  // ../kit/src/shell.ts
1934
2494
  var SEPARATORS = new Set([`
@@ -1939,6 +2499,7 @@ var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
1939
2499
  var SAFE_WORD = /^[\w@%+=:,./-]+$/;
1940
2500
  var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
1941
2501
  var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
2502
+ var FISH_COMBINERS = new Set(["and", "or", "not"]);
1942
2503
  var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
1943
2504
  var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
1944
2505
  var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
@@ -1950,6 +2511,7 @@ var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
1950
2511
  function wrapper(short = "", long = [], operands = 0, runsString = false) {
1951
2512
  return { short, long, operands, runsString };
1952
2513
  }
2514
+ var RUNNER = { ...wrapper(), afterDashes: true };
1953
2515
  var WRAPPERS = new Map([
1954
2516
  ["command", wrapper()],
1955
2517
  ["builtin", wrapper()],
@@ -1971,7 +2533,23 @@ var WRAPPERS = new Map([
1971
2533
  ["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
1972
2534
  ["unbuffer", wrapper()],
1973
2535
  ["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
1974
- ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
2536
+ ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])],
2537
+ ["strace", wrapper("abeEIoOpPsSuUX", ["--trace", "--output", "--attach", "--string-limit", "--user", "--env", "--columns", "--trace-path", "--signal", "--status", "--summary-sort-by", "--summary-columns", "--const-print-style", "--interruptible", "--detach-on"])],
2538
+ ["ltrace", wrapper("aeFlnopsuxX", ["--output", "--user", "--library", "--config", "--align", "--indent"])],
2539
+ ["taskset", wrapper("", [], 1)],
2540
+ ["fakeroot", wrapper("lsib", ["--lib", "--faked"])],
2541
+ ["sshpass", wrapper("pfdP")],
2542
+ ["coproc", wrapper()],
2543
+ ["proxychains", wrapper("f")],
2544
+ ["proxychains4", wrapper("f")],
2545
+ ["torsocks", wrapper("upaP", ["--user", "--pass", "--address", "--port"])],
2546
+ ["chrt", wrapper("TPD", ["--sched-runtime", "--sched-period", "--sched-deadline"], 1)],
2547
+ ["unshare", wrapper("SGRw", ["--setuid", "--setgid", "--root", "--wd", "--map-user", "--map-group", "--map-users", "--map-groups", "--propagation", "--setgroups"])],
2548
+ ["nsenter", wrapper("tSG", ["--target", "--setuid", "--setgid"])],
2549
+ ["out", RUNNER],
2550
+ ["slot", RUNNER],
2551
+ ["waitfor", RUNNER],
2552
+ ["base", RUNNER]
1975
2553
  ]);
1976
2554
  function shellQuote(word) {
1977
2555
  return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
@@ -1997,7 +2575,7 @@ async function runPreview(template, line, signal, hidden = []) {
1997
2575
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1998
2576
  const stop = () => {
1999
2577
  try {
2000
- process20.kill(-proc.pid, "SIGKILL");
2578
+ process23.kill(-proc.pid, "SIGKILL");
2001
2579
  } catch {
2002
2580
  proc.kill();
2003
2581
  }
@@ -2022,7 +2600,12 @@ ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe",
2022
2600
  return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
2023
2601
  }
2024
2602
 
2603
+ // ../kit/src/picker/terminal.ts
2604
+ init_state();
2605
+
2025
2606
  // ../kit/src/picker/view.ts
2607
+ init_line();
2608
+ init_state();
2026
2609
  var MIN_HEIGHT = 4;
2027
2610
  var PREVIEW_MIN_COLUMNS = 80;
2028
2611
  var PREVIEW_MIN_ROWS = 10;
@@ -2155,7 +2738,7 @@ function openTerminal() {
2155
2738
  return fail("no terminal to read keys from (/dev/tty)");
2156
2739
  }
2157
2740
  const keys = Bun.file("/dev/tty").stream().getReader();
2158
- const out = process21.stderr;
2741
+ const out = process24.stderr;
2159
2742
  let resize;
2160
2743
  async function read(onChunk) {
2161
2744
  const decoder = new TextDecoder;
@@ -2344,9 +2927,9 @@ async function select(rows, settings, terminal = openTerminal()) {
2344
2927
  const ended = new Promise((resolve) => {
2345
2928
  finish = resolve;
2346
2929
  });
2347
- process21.once("exit", restore);
2930
+ process24.once("exit", restore);
2348
2931
  for (const signal of SIGNALS2)
2349
- process21.once(signal, stop);
2932
+ process24.once(signal, stop);
2350
2933
  try {
2351
2934
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
2352
2935
  terminal.listen(onChunk, () => draw(true));
@@ -2359,8 +2942,8 @@ async function select(rows, settings, terminal = openTerminal()) {
2359
2942
  await ended;
2360
2943
  } finally {
2361
2944
  for (const signal of SIGNALS2)
2362
- process21.off(signal, stop);
2363
- process21.off("exit", restore);
2945
+ process24.off(signal, stop);
2946
+ process24.off("exit", restore);
2364
2947
  restore();
2365
2948
  }
2366
2949
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -2372,7 +2955,9 @@ async function previewOf(preview, hidden, signal) {
2372
2955
  return [error instanceof Error ? error.message : String(error)];
2373
2956
  }
2374
2957
  }
2958
+
2375
2959
  // ../kit/src/picker.ts
2960
+ init_score();
2376
2961
  function table2(rows) {
2377
2962
  const widths = rows[0]?.cells.map((_, index) => Math.max(...rows.map((row) => Bun.stringWidth(row.cells[index])))) ?? [];
2378
2963
  return rows.map((row) => [
@@ -2407,14 +2992,14 @@ function list(rows) {
2407
2992
  }
2408
2993
 
2409
2994
  // src/branch.ts
2410
- var usage2 = `gb [branch]
2995
+ var usage2 = `gb [branch]: picks a git branch and switches to it
2411
2996
  gb -
2412
2997
  gb -c <name>
2413
2998
  gb -d <branch>
2414
2999
 
2415
- Without a branch, picks one when a terminal is attached: the branches last checked out first, as the reflog has them, then the other local ones, then the remote ones with no local branch yet. The header says where HEAD stands, each row how its branch stands against its upstream and whether it is merged into the base. enter switches to it (a remote one gets its local tracking branch), ctrl-n creates a branch named after the query, ctrl-d deletes the highlighted local branch with \`git branch -d\`, which refuses one not merged yet, and ctrl-r fetches, prunes and lists again. Without a terminal it lists the branches instead.
2416
- \`gb <branch>\` switches without the picker, a bare name finding the remote branch it would create. \`gb -\` goes back to the previous branch, \`gb -c <name>\` creates one and switches to it, \`gb -d <branch>\` deletes a local one.
2417
- A branch checked out in another worktree cannot be switched to: gb prints that worktree's path on stdout and a hint on stderr, since a command cannot change its parent shell's folder.`;
3000
+ Without a branch, on a terminal, picks one: the recently checked out first, then the other local ones, then the remote ones with no local branch yet (enter switches, ctrl-n creates, ctrl-d deletes a merged local branch with \`git branch -d\`, ctrl-r fetches and prunes); without a terminal it lists them.
3001
+ \`gb <branch>\` switches without the picker, \`gb -\` goes back to the previous branch, \`gb -c <name>\` creates one and switches to it, \`gb -d <branch>\` deletes a local one.
3002
+ A branch checked out in another worktree cannot be switched to: gb prints that worktree's path, since a command cannot change its shell's folder.`;
2418
3003
  var EXITS = [[0, "it switched, created, deleted or listed"], ["git", "the code of the git command it ran, when that failed"], [1, "there is no branch by that name or nothing was picked"], [2, "outside a git repository or a usage error"]];
2419
3004
  var options = {
2420
3005
  create: { type: "boolean", short: "c", description: "create the branch named by the rest of the line and switch to it" },
@@ -2557,7 +3142,7 @@ async function fetched() {
2557
3142
  const success = await proc.exited === 0;
2558
3143
  return header(branches(base()), read(["branch", "--show-current"]), success ? "" : "fetch failed");
2559
3144
  }
2560
- function listed2(all) {
3145
+ function listed3(all) {
2561
3146
  list([
2562
3147
  ...all.map((branch) => ({
2563
3148
  label: branch.name,
@@ -2584,7 +3169,7 @@ async function hidden(flag, rest) {
2584
3169
  return 0;
2585
3170
  }
2586
3171
  if (flag === "--list") {
2587
- listed2(load().all);
3172
+ listed3(load().all);
2588
3173
  return 0;
2589
3174
  }
2590
3175
  if (flag === "--names") {
@@ -2631,7 +3216,7 @@ async function gb(args) {
2631
3216
  if (parsed.values.json === true)
2632
3217
  printJson(all);
2633
3218
  else
2634
- console.log(table2(all.map(row)).map((line) => takesControlCodes(process22.stdout) ? line : Bun.stripANSI(line)).join(`
3219
+ console.log(table2(all.map(row)).map((line) => takesControlCodes(process25.stdout) ? line : Bun.stripANSI(line)).join(`
2635
3220
  `));
2636
3221
  return 0;
2637
3222
  }
@@ -2688,4 +3273,4 @@ async function finish(command, typed, emitting) {
2688
3273
  }
2689
3274
 
2690
3275
  // src/gb.ts
2691
- process23.exitCode = await runMain({ name: "gb", run: gb });
3276
+ process26.exitCode = await runMain({ name: "gb", run: gb });