@kaynooo/cli-check 0.20.1 → 0.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/j-cli.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/j-cli.ts
5
- import process26 from "process";
6
- // ../kit/src/args.ts
7
- import process10 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,36 +176,18 @@ 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
163
- var ENDS = new Map;
164
- var DEFAULT = {
165
- 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" },
166
- 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" },
167
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
168
- bins: {},
169
- gradient: ["#c084fc", "#67e8f9"]
170
- };
171
- 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" };
172
- 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" };
173
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
174
- var PRESETS = {
175
- default: {},
176
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
177
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
178
- ascii: { glyphs: ASCII }
179
- };
180
- 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"]);
181
- var HEX = /^#[0-9a-f]{6}$/i;
182
- var CONTROL = /\p{Cc}/u;
183
- var MAX_FILE_BYTES = 64 * 1024;
184
- var SPACES = /\s+/;
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";
185
186
  function isColorSpec(spec) {
186
187
  if (typeof spec === "number")
187
188
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
188
189
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
189
190
  }
190
- var CUBE = [0, 95, 135, 175, 215, 255];
191
191
  function cubeLevel(channel) {
192
192
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
193
193
  }
@@ -292,7 +292,6 @@ function applyFile(theme, file, where, warn) {
292
292
  function endsWalk(home) {
293
293
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
294
294
  }
295
- var warned = new Set;
296
295
  function warnOnce(message) {
297
296
  if (warned.has(message))
298
297
  return;
@@ -329,8 +328,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
329
328
  }
330
329
  return { theme, sources, preset };
331
330
  }
332
- var current;
333
- var currentKey = "";
334
331
  function activeTheme() {
335
332
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
336
333
  if (current === undefined || key !== currentKey) {
@@ -339,9 +336,38 @@ function activeTheme() {
339
336
  }
340
337
  return current;
341
338
  }
339
+ var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
340
+ var init_theme = __esm(() => {
341
+ init_config();
342
+ init_user_config();
343
+ ENDS = new Map;
344
+ DEFAULT = {
345
+ 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" },
346
+ 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" },
347
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
348
+ bins: {},
349
+ gradient: ["#c084fc", "#67e8f9"]
350
+ };
351
+ 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" };
352
+ 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" };
353
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
354
+ PRESETS = {
355
+ default: {},
356
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
357
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
358
+ ascii: { glyphs: ASCII }
359
+ };
360
+ 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"]);
361
+ HEX = /^#[0-9a-f]{6}$/i;
362
+ CONTROL = /\p{Cc}/u;
363
+ MAX_FILE_BYTES = 64 * 1024;
364
+ SPACES = /\s+/;
365
+ CUBE = [0, 95, 135, 175, 215, 255];
366
+ warned = new Set;
367
+ });
342
368
 
343
369
  // ../kit/src/style.ts
344
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
370
+ import process6 from "process";
345
371
  function takesControlCodes(stream, env = process6.env) {
346
372
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
347
373
  }
@@ -364,14 +390,6 @@ function role(name, stream, env = process6.env) {
364
390
  const colors = paint(stream, env);
365
391
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
366
392
  }
367
- var STATUS_WORDS = {
368
- passed: ["passed", "success", "succeeded", "ok"],
369
- failed: ["failed", "failure", "error", "errored"],
370
- running: ["running", "in_progress", "started", "holding"],
371
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
372
- skipped: ["skipped", "cancelled", "canceled", "manual"]
373
- };
374
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
375
393
  function header(bin, context, stream, env = process6.env) {
376
394
  if (!takesControlCodes(stream, env))
377
395
  return "";
@@ -382,9 +400,24 @@ function header(bin, context, stream, env = process6.env) {
382
400
  const accent = tinted(typeof spec === "string" && spec.split(" ").includes("bold") ? colors : colors.bold, spec, env);
383
401
  return `${accent(bin)}${context === undefined ? "" : colors.dim(` \u203A ${context}`)}`;
384
402
  }
403
+ var MARK_WORDS, STATUS_WORDS, STATUS_OF;
404
+ var init_style = __esm(() => {
405
+ init_colors();
406
+ init_mode();
407
+ init_theme();
408
+ MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
409
+ STATUS_WORDS = {
410
+ passed: ["passed", "success", "succeeded", "ok"],
411
+ failed: ["failed", "failure", "error", "errored"],
412
+ running: ["running", "in_progress", "started", "holding"],
413
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
414
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
415
+ };
416
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
417
+ });
385
418
 
386
419
  // ../kit/src/format.ts
387
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
420
+ import process7 from "process";
388
421
  function formatSeconds(total) {
389
422
  let rest = Math.max(0, Math.round(total));
390
423
  const amounts = UNITS.map(([unit, size]) => {
@@ -406,10 +439,8 @@ function upTo(text, separator) {
406
439
  return end === -1 ? text : text.slice(0, end);
407
440
  }
408
441
  function truncate(text, width) {
409
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
442
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
410
443
  }
411
- var LINE_BREAKS = /\s*\n\s*/g;
412
- var ESCAPE = String.fromCharCode(27);
413
444
  function textWidth(text) {
414
445
  return Bun.stringWidth(text);
415
446
  }
@@ -458,14 +489,40 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
458
489
  function printJson(value) {
459
490
  console.log(jsonText(value));
460
491
  }
492
+ var UNITS, LINE_BREAKS, ESCAPE;
493
+ var init_format = __esm(() => {
494
+ init_text();
495
+ init_mode();
496
+ init_style();
497
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
498
+ LINE_BREAKS = /\s*\n\s*/g;
499
+ ESCAPE = String.fromCharCode(27);
500
+ });
461
501
 
462
502
  // ../kit/src/help.ts
463
503
  import process8 from "process";
464
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
465
- var USAGE_PREFIX = /^usage:\s*/i;
466
- var FULL_STOP = /\.$/;
467
504
  function usageLine(usage, colors = paint(process8.stdout)) {
468
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
505
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
506
+ `);
507
+ const blank = lines.indexOf("");
508
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
509
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
510
+ const colon = synopses[0].indexOf(": ");
511
+ const inline = synopses[0].slice(colon + 2);
512
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
513
+ if (colon !== -1)
514
+ synopses[0] = synopses[0].slice(0, colon);
515
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
516
+ `)}`;
517
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
518
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
519
+ return [head, ...lead, ...rest].join(`
520
+ `);
521
+ }
522
+ function prose(line, colors) {
523
+ if (colors.cyan("x") === "x")
524
+ return line;
525
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
469
526
  }
470
527
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
471
528
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -500,7 +557,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
500
557
  return [];
501
558
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
502
559
  }
503
- var MAX_INLINE_CHOICES = 24;
504
560
  function optionRows(options, colors = paint(process8.stdout)) {
505
561
  const rows = Object.entries(options).map(([name, option]) => {
506
562
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -515,9 +571,17 @@ function optionRows(options, colors = paint(process8.stdout)) {
515
571
  const width = Math.max(0, ...rows.map((row) => row.width));
516
572
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
517
573
  }
574
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
575
+ var init_help = __esm(() => {
576
+ init_mode();
577
+ init_style();
578
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
579
+ USAGE_PREFIX = /^usage:\s*/i;
580
+ FULL_STOP = /\.$/;
581
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
582
+ });
518
583
 
519
584
  // ../kit/src/text.ts
520
- var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
521
585
  function stripAnsi(text) {
522
586
  return text.replace(ANSI, "");
523
587
  }
@@ -546,10 +610,13 @@ function closest(name, names) {
546
610
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
547
611
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
548
612
  }
613
+ var ANSI;
614
+ var init_text2 = __esm(() => {
615
+ ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
616
+ });
617
+
549
618
  // ../kit/src/input.ts
550
619
  import process9 from "process";
551
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
552
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
553
620
  function duration(value, name, fallback, unit = "s") {
554
621
  if (value === undefined)
555
622
  return fallback;
@@ -570,40 +637,26 @@ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
570
637
  fail(`no file ${path}`);
571
638
  return file.text();
572
639
  }
640
+ var DURATION, UNIT_MS;
641
+ var init_input = __esm(() => {
642
+ init_args();
643
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
644
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
645
+ });
573
646
 
574
647
  // ../kit/src/args.ts
575
- var DASHES = /^-+/;
648
+ import process10 from "process";
649
+ import { parseArgs } from "util";
576
650
  function jsonOption(holds) {
577
651
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
578
652
  }
579
- class Exit extends Error {
580
- code;
581
- hint;
582
- constructor(message, code, hint) {
583
- super(message);
584
- this.code = code;
585
- this.hint = hint;
586
- }
587
- }
588
653
  function fail(message, code = 2, hint) {
589
654
  throw new Exit(message, code, hint);
590
655
  }
591
-
592
- class UsageError extends Exit {
593
- constructor(message, hint) {
594
- super(message, 2, hint);
595
- }
596
- }
597
656
  function badUsage(message) {
598
657
  throw new UsageError(message);
599
658
  }
600
659
 
601
- class HelpShown extends Exit {
602
- constructor() {
603
- super("help shown", 0);
604
- }
605
- }
606
-
607
660
  class Completing {
608
661
  options;
609
662
  positionals;
@@ -614,11 +667,6 @@ class Completing {
614
667
  this.candidates = candidates;
615
668
  }
616
669
  }
617
- var completion = { active: false };
618
- var OUTPUT_OPTIONS = {
619
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
620
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
621
- };
622
670
  function applyOutput(color, plain, env = process10.env) {
623
671
  const when = plain === true ? "never" : color ?? "auto";
624
672
  if (when === "auto")
@@ -772,7 +820,6 @@ function parseError(error) {
772
820
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
773
821
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
774
822
  }
775
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
776
823
  function nearestOption(message, options, allowNegative) {
777
824
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
778
825
  if (typed === undefined)
@@ -788,1087 +835,1488 @@ function nearestOption(message, options, allowNegative) {
788
835
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
789
836
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
790
837
  }
791
- // ../kit/src/argv.ts
792
- import { readFileSync as readFileSync3, realpathSync } from "fs";
793
- import { resolve as resolve3 } from "path";
794
- import process11 from "process";
795
- function commandLine() {
796
- try {
797
- return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
798
- } catch {
799
- return;
800
- }
801
- }
802
- function realPath(word) {
803
- try {
804
- return realpathSync(resolve3(word));
805
- } catch {
806
- return;
807
- }
808
- }
809
- function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
810
- const target = script === undefined ? undefined : realPath(script) ?? script;
811
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
812
- const after = at === -1 ? [] : cmdline.slice(at + 1);
813
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
814
- }
815
- // ../kit/src/process.ts
816
- import { constants } from "os";
817
- import process12 from "process";
818
- var KILL_GRACE_MS = 2000;
819
- var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
820
- function exitCodeOf(code, signal) {
821
- if (code !== null)
822
- return code;
823
- if (typeof signal === "number")
824
- return 128 + signal;
825
- return signal === null ? 129 : 128 + constants.signals[signal];
826
- }
827
- function holdSignals(cleanup) {
828
- let received;
829
- let child;
830
- const held = {
831
- get signal() {
832
- return received;
833
- },
834
- forward: (to) => {
835
- child = to;
836
- },
837
- release: () => {
838
- for (const signal of SIGNALS)
839
- process12.off(signal, onSignal);
838
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
839
+ var init_args = __esm(() => {
840
+ init_format();
841
+ init_help();
842
+ init_text2();
843
+ init_help();
844
+ init_input();
845
+ DASHES = /^-+/;
846
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
847
+ Exit = class Exit extends Error {
848
+ code;
849
+ hint;
850
+ [EXIT] = true;
851
+ constructor(message, code, hint) {
852
+ super(message);
853
+ this.code = code;
854
+ this.hint = hint;
840
855
  }
841
- };
842
- function onSignal(signal) {
843
- received = signal;
844
- if (child !== undefined) {
845
- child.kill(signal);
846
- return;
856
+ static [Symbol.hasInstance](value) {
857
+ if (this !== Exit)
858
+ return Function.prototype[Symbol.hasInstance].call(this, value);
859
+ return typeof value === "object" && value !== null && value[EXIT] === true;
847
860
  }
848
- if (cleanup === undefined)
849
- return;
850
- held.release();
851
- cleanup(signal);
852
- process12.kill(process12.pid, signal);
853
- }
854
- for (const signal of SIGNALS)
855
- process12.on(signal, onSignal);
856
- return held;
857
- }
858
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
859
- const chunks = [];
860
- const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
861
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
862
- const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
863
- const timers = [];
864
- const killGroup = (killing) => {
865
- if (state.done)
866
- return;
867
- try {
868
- if (grouped)
869
- process12.kill(-proc.pid, killing);
870
- else
871
- proc.kill(killing);
872
- } catch {}
873
- };
874
- const stop = () => {
875
- killGroup("SIGTERM");
876
- timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
877
861
  };
878
- const onAbort = () => stop();
879
- if (timeoutMs !== undefined) {
880
- timers.push(setTimeout(() => {
881
- state.timedOut = true;
882
- stop();
883
- }, timeoutMs));
884
- }
885
- if (signal?.aborted === true)
886
- onAbort();
887
- else
888
- signal?.addEventListener("abort", onAbort, { once: true });
889
- onStart?.({ kill: (killing) => killGroup(killing) });
890
- const drain = async (stream, name) => {
891
- for await (const data of stream) {
892
- if (state.failure !== undefined)
893
- continue;
894
- try {
895
- onChunk?.({ stream: name, data });
896
- } catch (error) {
897
- state.failure = error;
898
- stop();
899
- continue;
900
- }
901
- if (state.kept + data.length > maxBytes) {
902
- state.truncated = true;
903
- continue;
904
- }
905
- state.kept += data.length;
906
- chunks.push({ stream: name, data });
862
+ UsageError = class UsageError extends Exit {
863
+ constructor(message, hint) {
864
+ super(message, 2, hint);
907
865
  }
908
866
  };
909
- try {
910
- await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
911
- await proc.exited;
912
- } finally {
913
- state.done = true;
914
- for (const timer of timers)
915
- clearTimeout(timer);
916
- signal?.removeEventListener("abort", onAbort);
917
- }
918
- if (state.failure !== undefined)
919
- throw state.failure;
920
- const joined = () => Buffer.concat(chunks.map(({ data }) => data));
921
- let output;
922
- let text;
923
- return {
924
- code: exitCodeOf(proc.exitCode, proc.signalCode),
925
- chunks,
926
- timedOut: state.timedOut,
927
- truncated: state.truncated,
928
- get output() {
929
- return output ??= joined();
930
- },
931
- get text() {
932
- return text ??= (output ??= joined()).toString();
867
+ HelpShown = class HelpShown extends Exit {
868
+ constructor() {
869
+ super("help shown", 0);
933
870
  }
934
871
  };
935
- }
872
+ completion = { active: false };
873
+ OUTPUT_OPTIONS = {
874
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
875
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
876
+ };
877
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
878
+ });
936
879
 
937
- // ../kit/src/progress.ts
938
- var ESC = String.fromCharCode(27);
939
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
940
- var RESET_STYLE = `${ESC}[0m`;
941
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
942
- // ../kit/src/cli.ts
943
- import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
944
- import { dirname as dirname3, join as join6 } from "path";
945
- import process16 from "process";
880
+ // ../kit/src/folders.ts
881
+ import { homedir as homedir5 } from "os";
882
+ import { join as join7 } from "path";
883
+ import process18 from "process";
884
+ function ignoredFolders(extra = [], where = {}) {
885
+ const configured = readUserConfig("config", where).ignore;
886
+ const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
887
+ return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
888
+ }
889
+ function cacheFolder({ home = homedir5(), env = process18.env } = {}) {
890
+ return xdgFolder(env.XDG_CACHE_HOME, join7(home, ".cache"));
891
+ }
892
+ var SKIPPED_FOLDERS;
893
+ var init_folders = __esm(() => {
894
+ init_user_config();
895
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
896
+ });
946
897
 
947
- // ../kit/src/completions.ts
948
- var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
949
- 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'
950
- set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
951
- set -l current (commandline -ct)
952
- for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
953
- if test "$line" = __files__
954
- __fish_complete_path $current
955
- else
956
- echo $line
957
- end
958
- end
959
- end`;
960
- var BASH_FUNCTION = `__kaynooo_cli_complete() {
961
- local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
962
- local -a lines
963
- COMPREPLY=()
964
- lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
965
- for line in "\${lines[@]}"; do
966
- if [[ $line == __files__ ]]; then
967
- COMPREPLY+=($(compgen -f -- "$cur"))
968
- else
969
- words+="\${line%%$'\\t'*}"$'\\n'
970
- fi
971
- done
972
- COMPREPLY+=($(compgen -W "$words" -- "$cur"))
973
- }`;
974
- var ZSH_FUNCTION = `__kaynooo_cli_complete() {
975
- local line
976
- local -a described plain
977
- for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
978
- if [[ $line == __files__ ]]; then
979
- _files
980
- elif [[ $line == *$'\\t'* ]]; then
981
- described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
982
- else
983
- plain+=("$line")
984
- fi
985
- done
986
- (( \${#described} )) && _describe -V value described
987
- (( \${#plain} )) && compadd -- "\${plain[@]}"
988
- return 0
989
- }`;
990
- function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
991
- if (shell === "fish")
992
- return `${header}
993
- ${FISH_FUNCTION}
994
- ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
995
- `).join("")}`;
996
- if (shell === "bash")
997
- return `${header}
998
- ${BASH_FUNCTION}
999
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
1000
- `;
1001
- return `${header}
1002
- ${ZSH_FUNCTION}
1003
- compdef __kaynooo_cli_complete ${bins.join(" ")}
1004
- `;
1005
- }
1006
-
1007
- // ../kit/src/notify.ts
1008
- import process13 from "process";
1009
- var NOTIFY_AFTER_MS = 1e4;
1010
- var CANCELLED = 130;
1011
- function base64(text) {
1012
- return Buffer.from(text).toString("base64");
898
+ // ../kit/src/picker/line.ts
899
+ function isEditKey(key) {
900
+ return EDIT_KEYS.has(key);
1013
901
  }
1014
- function notification(title, body, env = process13.env) {
1015
- const id = `kit${process13.pid}`;
1016
- 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\\`];
1017
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
902
+ function endsKills(key) {
903
+ return typeof key !== "object" && !isEditKey(key);
1018
904
  }
1019
- function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1020
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1021
- return;
1022
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
905
+ function isWord(char) {
906
+ return char !== undefined && WORD_CHARACTER.test(char);
1023
907
  }
1024
-
1025
- // ../kit/src/usage.ts
1026
- import { appendFileSync, mkdirSync } from "fs";
1027
- import { homedir as homedir4 } from "os";
1028
- import { dirname as dirname2, isAbsolute, join as join5 } from "path";
1029
- import process15 from "process";
1030
-
1031
- // ../kit/src/logs.ts
1032
- import { lstatSync, openSync } from "fs";
1033
- import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
1034
- import { homedir as homedir3, tmpdir } from "os";
1035
- import { join as join4 } from "path";
1036
- import process14 from "process";
1037
- var DAY_MS = 24 * 60 * 60 * 1000;
1038
- var CLI_FOLDER = "kaynooo-cli";
1039
- function isPrivateDirectory(path) {
1040
- try {
1041
- const info = lstatSync(path, { throwIfNoEntry: false });
1042
- return info !== undefined && info.isDirectory() && info.uid === (process14.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
1043
- } catch {
1044
- return false;
1045
- }
908
+ function wordStart(chars, from) {
909
+ let at = from;
910
+ while (at > 0 && !isWord(chars[at - 1]))
911
+ at--;
912
+ while (at > 0 && isWord(chars[at - 1]))
913
+ at--;
914
+ return at;
1046
915
  }
1047
- async function privateLogDirectory(name, env = process14.env) {
1048
- const runtime = env.XDG_RUNTIME_DIR;
1049
- const base = runtime === undefined || runtime === "" ? join4(homedir3(), ".cache", CLI_FOLDER) : join4(runtime, CLI_FOLDER);
1050
- const path = join4(base, name);
1051
- try {
1052
- await mkdir(path, { recursive: true, mode: 448 });
1053
- if (isPrivateDirectory(path))
1054
- return path;
1055
- } catch {}
1056
- return mkdtemp(join4(tmpdir(), `${name.replaceAll("/", "-")}-`));
916
+ function wordEnd(chars, from) {
917
+ let at = from;
918
+ while (at < chars.length && !isWord(chars[at]))
919
+ at++;
920
+ while (at < chars.length && isWord(chars[at]))
921
+ at++;
922
+ return at;
1057
923
  }
1058
- async function sweepLogs(dir, maxAgeMs = DAY_MS, now = Date.now()) {
1059
- let names;
1060
- try {
1061
- names = await readdir(dir);
1062
- } catch {
1063
- return;
1064
- }
1065
- for (const name of names) {
1066
- const path = join4(dir, name);
1067
- try {
1068
- const info = await stat(path);
1069
- if (info.isDirectory())
1070
- await sweepLogs(path, maxAgeMs, now);
1071
- if (now - info.mtimeMs > maxAgeMs)
1072
- await rm(path, { force: true, recursive: info.isDirectory() });
1073
- } catch {
1074
- continue;
1075
- }
1076
- }
924
+ function spacedStart(chars, from) {
925
+ let at = from;
926
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
927
+ at--;
928
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
929
+ at--;
930
+ return at;
1077
931
  }
1078
-
1079
- // ../kit/src/usage.ts
1080
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1081
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1082
- var LONGEST_NAME = 40;
1083
- var usageError;
1084
- function noteUsageError(message) {
1085
- usageError = message;
932
+ function cut2(chars, from, to) {
933
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1086
934
  }
1087
- function stateHome(env = process15.env) {
1088
- const dir = env.XDG_STATE_HOME;
1089
- return dir !== undefined && isAbsolute(dir) ? dir : join5(homedir4(), ".local", "state");
935
+ function insert(chars, at, text) {
936
+ const typed = [...text];
937
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
1090
938
  }
1091
- function usagePath(env = process15.env) {
1092
- return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
939
+ function editLine(line, key) {
940
+ const { killed = "", chained = false } = line;
941
+ const chars = [...line.text];
942
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
943
+ const edited = edit(chars, at, key, killed);
944
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
945
+ return line.killed === undefined ? edited : { ...edited, killed };
946
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
947
+ if (taken === "")
948
+ return { ...edited, killed, chained };
949
+ if (!chained)
950
+ return { ...edited, killed: taken, chained: true };
951
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1093
952
  }
1094
- function usageRecorded(env = process15.env) {
1095
- const off = env.KAYNOOO_CLI_NO_USAGE;
1096
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
953
+ function edit(chars, at, key, killed) {
954
+ const text = chars.join("");
955
+ if (typeof key === "object")
956
+ return insert(chars, at, key.text);
957
+ switch (key) {
958
+ case "left":
959
+ return { text, caret: Math.max(at - 1, 0) };
960
+ case "right":
961
+ return { text, caret: Math.min(at + 1, chars.length) };
962
+ case "wordleft":
963
+ return { text, caret: wordStart(chars, at) };
964
+ case "wordright":
965
+ return { text, caret: wordEnd(chars, at) };
966
+ case "linestart":
967
+ return { text, caret: 0 };
968
+ case "lineend":
969
+ return { text, caret: chars.length };
970
+ case "erase":
971
+ return cut2(chars, Math.max(at - 1, 0), at);
972
+ case "delete":
973
+ return cut2(chars, at, Math.min(at + 1, chars.length));
974
+ case "word":
975
+ return cut2(chars, spacedStart(chars, at), at);
976
+ case "killword":
977
+ return cut2(chars, wordStart(chars, at), at);
978
+ case "killnext":
979
+ return cut2(chars, at, wordEnd(chars, at));
980
+ case "clear":
981
+ return cut2(chars, 0, at);
982
+ case "killend":
983
+ return cut2(chars, at, chars.length);
984
+ case "yank":
985
+ return insert(chars, at, killed);
986
+ }
1097
987
  }
1098
- function flagNames(argv) {
1099
- const end = argv.indexOf("--");
1100
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1101
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
988
+ function visible({ text, caret }, room) {
989
+ const chars = [...text];
990
+ const at = Math.min(Math.max(caret, 0), chars.length);
991
+ const cells = at === chars.length ? [...chars, " "] : chars;
992
+ const widths = cells.map((char) => Bun.stringWidth(char));
993
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
994
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
995
+ let start = at;
996
+ let end = at + 1;
997
+ while (start > 0 && fits(start - 1, end))
998
+ start--;
999
+ while (end < cells.length && fits(start, end + 1))
1000
+ end++;
1001
+ const left = start > 0 ? "\u2026" : "";
1002
+ const right = end < cells.length ? "\u2026" : "";
1003
+ 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) };
1102
1004
  }
1103
- function usageEntry(bin, command, argv, code, now = new Date) {
1104
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1105
- usageError = undefined;
1106
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1005
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
1006
+ var init_line = __esm(() => {
1007
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1008
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1009
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
1010
+ WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1011
+ SPACE = /\s/;
1012
+ });
1013
+
1014
+ // ../kit/src/picker/score.ts
1015
+ function startsWord(text, index) {
1016
+ if (index === 0)
1017
+ return true;
1018
+ const before = text[index - 1];
1019
+ return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
1107
1020
  }
1108
- function recordUsage(entry, env = process15.env) {
1109
- if (!usageRecorded(env))
1021
+ function fuzzy(query, text) {
1022
+ if (query === "")
1023
+ return { score: 0, positions: [] };
1024
+ const exact = query !== query.toLowerCase();
1025
+ const needle = exact ? query : query.toLowerCase();
1026
+ const haystack = exact ? text : text.toLowerCase();
1027
+ if (haystack.length !== text.length || needle.length > haystack.length)
1110
1028
  return;
1111
- try {
1112
- const path = usagePath(env);
1113
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1114
- appendFileSync(path, `${JSON.stringify(entry)}
1115
- `, { mode: 384 });
1116
- } catch {}
1029
+ const width = haystack.length;
1030
+ const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
1031
+ const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
1032
+ for (let j = 0;j < needle.length; j++) {
1033
+ let run = NONE;
1034
+ let runAt = -1;
1035
+ for (let i = j;i < width; i++) {
1036
+ if (j > 0 && i - 2 >= j - 1) {
1037
+ const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
1038
+ if (candidate > run) {
1039
+ run = candidate;
1040
+ runAt = i - 2;
1041
+ }
1042
+ }
1043
+ if (haystack[i] !== needle[j])
1044
+ continue;
1045
+ const here = MATCH + (startsWord(text, i) ? BOUNDARY2 : 0) + (i === 0 ? PREFIX : 0);
1046
+ if (j === 0) {
1047
+ best[0][i] = here - i * GAP;
1048
+ continue;
1049
+ }
1050
+ const joined = best[j - 1][i - 1] + CONSECUTIVE;
1051
+ const skipped = run - (i - 1) * GAP;
1052
+ if (joined > NONE && joined >= skipped) {
1053
+ best[j][i] = joined + here;
1054
+ from[j][i] = i - 1;
1055
+ } else if (skipped > NONE) {
1056
+ best[j][i] = skipped + here;
1057
+ from[j][i] = runAt;
1058
+ }
1059
+ }
1060
+ }
1061
+ const last = best[needle.length - 1];
1062
+ let end = -1;
1063
+ for (let i = 0;i < width; i++) {
1064
+ if (last[i] > NONE && (end === -1 || last[i] > last[end]))
1065
+ end = i;
1066
+ }
1067
+ if (end === -1)
1068
+ return;
1069
+ const positions = [];
1070
+ for (let j = needle.length - 1, i = end;j >= 0; j--) {
1071
+ positions.unshift(i);
1072
+ i = from[j][i];
1073
+ }
1074
+ return { score: last[end], positions };
1075
+ }
1076
+ function rank(query, lines) {
1077
+ if (query === "")
1078
+ return lines.map((_, index) => ({ index, positions: [] }));
1079
+ const found = [];
1080
+ for (const [index, line] of lines.entries()) {
1081
+ const match = fuzzy(query, line);
1082
+ if (match !== undefined)
1083
+ found.push({ index, positions: match.positions, score: match.score });
1084
+ }
1085
+ return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
1117
1086
  }
1087
+ var MATCH = 16, CONSECUTIVE = 12, BOUNDARY2 = 10, PREFIX = 8, GAP = 1, BOUNDARY_AFTER, UPPER, LOWER, NONE;
1088
+ var init_score = __esm(() => {
1089
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1090
+ UPPER = /\p{Lu}/u;
1091
+ LOWER = /\p{Ll}/u;
1092
+ NONE = Number.NEGATIVE_INFINITY;
1093
+ });
1118
1094
 
1119
- // ../kit/src/cli.ts
1120
- var LEVEL_OPTIONS = {
1121
- ...OUTPUT_OPTIONS,
1122
- help: { type: "boolean", short: "h", description: "show this help" }
1123
- };
1124
- var TOP_OPTIONS = {
1125
- ...LEVEL_OPTIONS,
1126
- version: { type: "boolean", short: "v", description: "print the version" },
1127
- completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1128
- };
1129
- function printError(prefix, message, hint, cause) {
1130
- const colors = paint(process16.stderr);
1131
- const styled = takesControlCodes(process16.stderr);
1132
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1133
- const under = (label, text, tint) => text === undefined ? "" : `
1134
- ${styled ? tint(label) : `${label}:`} ${text}`;
1135
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1095
+ // ../kit/src/picker/state.ts
1096
+ function repeat(value, count) {
1097
+ return Array.from({ length: count }).fill(value);
1136
1098
  }
1137
- function printJsonError(message, hint, cause) {
1138
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1099
+ function styled(line) {
1100
+ let text = "";
1101
+ const styles = [];
1102
+ let active = "";
1103
+ let colored = false;
1104
+ let last = 0;
1105
+ function add(chunk) {
1106
+ const flat = chunk.replace(CONTROL2, " ");
1107
+ text += flat;
1108
+ colored ||= active !== "" && flat !== "";
1109
+ styles.push(...repeat(active, flat.length));
1110
+ }
1111
+ for (const found of line.matchAll(ANSI)) {
1112
+ add(line.slice(last, found.index));
1113
+ last = found.index + found[0].length;
1114
+ if (SGR.test(found[0]))
1115
+ active = RESET.test(found[0]) ? "" : active + found[0];
1116
+ }
1117
+ add(line.slice(last));
1118
+ return { text, styles: colored ? styles : undefined };
1139
1119
  }
1140
- function wantsJson(argv) {
1141
- const end = argv.indexOf("--");
1142
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1120
+ function lay(rows, searched) {
1121
+ const parsed = rows.map((row) => row.cells.map(styled));
1122
+ const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1123
+ return parsed.map((cells, at) => {
1124
+ let text = "";
1125
+ const styles = [];
1126
+ let colored = false;
1127
+ let searchEnd = 0;
1128
+ for (const [column, cell] of cells.entries()) {
1129
+ const last = column === cells.length - 1;
1130
+ const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1131
+ text += shown;
1132
+ colored ||= cell.styles !== undefined;
1133
+ styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1134
+ if (column < searched)
1135
+ searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1136
+ if (!last) {
1137
+ const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1138
+ text += " ".repeat(pad);
1139
+ styles.push(...repeat("", pad));
1140
+ }
1141
+ }
1142
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1143
+ });
1143
1144
  }
1144
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
1145
- if (error instanceof HelpShown)
1146
- return 0;
1147
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1148
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1149
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1150
- if (error instanceof Exit && error.code === 2)
1151
- noteUsageError(error.message);
1152
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1153
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1154
- return error instanceof Exit ? error.code : 1;
1145
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1146
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1147
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1148
+ const wheel = MOUSE.exec(sequence)?.[1];
1149
+ if (wheel !== undefined)
1150
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1151
+ const named = codes.get(sequence);
1152
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1153
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1154
+ paste.active = sequence === PASTE_START;
1155
+ return [];
1156
+ }
1157
+ if (paste.active && (sequence === "\r" || sequence === `
1158
+ `))
1159
+ return [];
1160
+ if (key !== undefined)
1161
+ return [key];
1162
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1163
+ });
1155
1164
  }
1156
- var COMPLETE = "__complete";
1157
- var FILES = "__files__";
1158
- async function completingOf(run) {
1159
- completion.active = true;
1160
- try {
1161
- await run([]);
1162
- } catch (error) {
1163
- if (error instanceof Completing)
1164
- return error;
1165
- } finally {
1166
- completion.active = false;
1167
- }
1168
- return new Completing({});
1165
+ function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1166
+ 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 };
1167
+ return withRows(state, rows);
1169
1168
  }
1170
- function candidateLine(candidate) {
1171
- return typeof candidate === "string" ? candidate : candidate.join("\t");
1169
+ function withRows(state, rows, header = state.header) {
1170
+ const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1171
+ const laid = lay(cells, state.searched);
1172
+ const searchable = laid.map((row) => row.searchable);
1173
+ const matches = rank(state.query, searchable);
1174
+ 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 };
1172
1175
  }
1173
- function positionalBeingTyped(before, { options, positionals }) {
1174
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1175
- const typed = [];
1176
- let at = 0;
1177
- while (at < before.length) {
1178
- const word = before[at];
1179
- if (word === "--") {
1180
- typed.push(...before.slice(at + 1));
1181
- break;
1176
+ function withQuery(state, key) {
1177
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1178
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1179
+ }
1180
+ function move(state, by) {
1181
+ return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1182
+ }
1183
+ function highlighted(state) {
1184
+ return state.matches[state.cursor]?.index;
1185
+ }
1186
+ function press(state, key) {
1187
+ if (state.done !== undefined)
1188
+ return state;
1189
+ if (state.chained && endsKills(key))
1190
+ state = { ...state, chained: false };
1191
+ if (state.help)
1192
+ return { ...state, help: false };
1193
+ if (typeof key === "object") {
1194
+ if ("text" in key)
1195
+ return withQuery(state, key);
1196
+ return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1197
+ }
1198
+ if (isEditKey(key))
1199
+ return withQuery(state, key);
1200
+ switch (key) {
1201
+ case "up":
1202
+ return move(state, -1);
1203
+ case "down":
1204
+ return move(state, 1);
1205
+ case "pageup":
1206
+ return move(state, -state.page);
1207
+ case "pagedown":
1208
+ return move(state, state.page);
1209
+ case "home":
1210
+ return move(state, -state.matches.length);
1211
+ case "end":
1212
+ return move(state, state.matches.length);
1213
+ case "cancel":
1214
+ return { ...state, done: "cancel" };
1215
+ case "help":
1216
+ return { ...state, help: true };
1217
+ case "suspend":
1218
+ return state;
1219
+ case "enter":
1220
+ return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1221
+ case "tab": {
1222
+ const at = highlighted(state);
1223
+ if (!state.multi || at === undefined)
1224
+ return state;
1225
+ const marked = new Set(state.marked);
1226
+ if (!marked.delete(at))
1227
+ marked.add(at);
1228
+ return move({ ...state, marked }, 1);
1182
1229
  }
1183
- if (!word.startsWith("-"))
1184
- typed.push(word);
1185
- else if (takesValue(word))
1186
- at++;
1187
- at++;
1188
1230
  }
1189
- const last = positionals.at(-1);
1190
- if (typed.length < positionals.length)
1191
- return { name: positionals[typed.length], typed };
1192
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1193
1231
  }
1194
- async function leafCandidates(run, words) {
1195
- const completing = await completingOf(run);
1196
- if ((words.at(-1) ?? "").startsWith("-"))
1197
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1198
- const flag = words.at(-2);
1199
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1200
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1201
- if (option?.type === "string") {
1202
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1203
- return values === undefined ? [FILES] : values.map(candidateLine);
1204
- }
1205
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1206
- return values === undefined ? [FILES] : values.map(candidateLine);
1232
+ function chosen(state) {
1233
+ if (state.marked.size > 0)
1234
+ return state.rows.filter((_, index) => state.marked.has(index));
1235
+ const at = highlighted(state);
1236
+ return at === undefined ? [] : [state.rows[at]];
1207
1237
  }
1208
- var COMPLETIONS = "--completions";
1209
- function flagValue([flag = "", ...rest]) {
1210
- return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1238
+ 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;
1239
+ var init_state = __esm(() => {
1240
+ init_text2();
1241
+ init_line();
1242
+ init_score();
1243
+ CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1244
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1245
+ SGR = /^\x1B\[[0-9;]*m$/;
1246
+ RESET = /^\x1B\[0?m$/;
1247
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1248
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1249
+ KEYS = {
1250
+ "\x1B[A": "up",
1251
+ "\x1BOA": "up",
1252
+ "\x10": "up",
1253
+ "\x1B[B": "down",
1254
+ "\x1BOB": "down",
1255
+ "\x0E": "down",
1256
+ "\x1B[5~": "pageup",
1257
+ "\x1B[6~": "pagedown",
1258
+ "\x1B[H": "home",
1259
+ "\x1B[1~": "home",
1260
+ "\x1BOH": "home",
1261
+ "\x1B[F": "end",
1262
+ "\x1B[4~": "end",
1263
+ "\x1BOF": "end",
1264
+ "\r": "enter",
1265
+ "\n": "enter",
1266
+ "\x03": "cancel",
1267
+ "\x1B": "cancel",
1268
+ "\x1B[D": "left",
1269
+ "\x1BOD": "left",
1270
+ "\x1B[C": "right",
1271
+ "\x1BOC": "right",
1272
+ "\x1B[1;5D": "wordleft",
1273
+ "\x1B[1;3D": "wordleft",
1274
+ "\x1Bb": "wordleft",
1275
+ "\x1B[1;5C": "wordright",
1276
+ "\x1B[1;3C": "wordright",
1277
+ "\x1Bf": "wordright",
1278
+ "\x01": "linestart",
1279
+ "\x05": "lineend",
1280
+ "\x7F": "erase",
1281
+ "\x1B[3~": "delete",
1282
+ "\b": "killword",
1283
+ "\x1B\x7F": "killword",
1284
+ "\x1B[3;5~": "killnext",
1285
+ "\x1Bd": "killnext",
1286
+ "\x15": "clear",
1287
+ "\v": "killend",
1288
+ "\x17": "word",
1289
+ "\x19": "yank",
1290
+ "\x1A": "suspend",
1291
+ "\t": "tab",
1292
+ "\x1F": "help",
1293
+ "\x1BOP": "help",
1294
+ "\x1B[11~": "help"
1295
+ };
1296
+ CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
1297
+ });
1298
+
1299
+ // ../kit/src/job.ts
1300
+ import process20 from "process";
1301
+ function stopJob() {
1302
+ process20.kill(0, "SIGTSTP");
1211
1303
  }
1212
- function printCompletionScript(name, args) {
1213
- const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1214
- if (shell === undefined || args.length !== 1) {
1215
- printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1216
- return 2;
1217
- }
1218
- console.log(completionScript(shell, [name]).trimEnd());
1219
- return 0;
1304
+ var init_job = () => {};
1305
+
1306
+ // ../kit/src/redraw.ts
1307
+ function overwrite(lines, columns) {
1308
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1309
+ `);
1220
1310
  }
1221
- async function printCandidates(found) {
1222
- for (const line of await found)
1223
- console.log(line);
1224
- return 0;
1311
+ function rowsTaken(lines, columns) {
1312
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1225
1313
  }
1226
- function packageVersion(entry = Bun.main) {
1227
- let resolved = entry;
1314
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
1315
+ var init_redraw = __esm(() => {
1316
+ init_format();
1317
+ });
1318
+
1319
+ // ../kit/src/answers.ts
1320
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync2 } from "fs";
1321
+ import { dirname as dirname5, join as join9 } from "path";
1322
+ function answersFile() {
1323
+ return join9(cacheFolder(), "kaynooo-cli", "answers.json");
1324
+ }
1325
+ function stored() {
1228
1326
  try {
1229
- resolved = realpathSync2(entry);
1230
- } catch {}
1231
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1232
- try {
1233
- const { version } = JSON.parse(readFileSync4(join6(dir, "package.json"), "utf8"));
1234
- if (typeof version === "string")
1235
- return version;
1236
- } catch {}
1237
- if (dirname3(dir) === dir)
1238
- return "0.0.0";
1327
+ const parsed = JSON.parse(readFileSync7(answersFile(), "utf-8"));
1328
+ if (typeof parsed !== "object" || parsed === null)
1329
+ return {};
1330
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
1331
+ } catch {
1332
+ return {};
1239
1333
  }
1240
1334
  }
1241
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1242
- if (argv[0] === COMPLETE)
1243
- return printCandidates(leafCandidates(run, argv.slice(1)));
1244
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1245
- return printCompletionScript(name, flagValue(argv));
1246
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1247
- console.log(version ?? packageVersion());
1248
- return 0;
1249
- }
1250
- let code;
1251
- const started = performance.now();
1335
+ function earlierAnswers(key) {
1336
+ return stored()[key] ?? [];
1337
+ }
1338
+ function rememberAnswer(key, answer) {
1339
+ const all = stored();
1340
+ const file = answersFile();
1341
+ all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
1252
1342
  try {
1253
- code = await run(argv);
1254
- } catch (error) {
1255
- code = reportThrown(name, error, redact, wantsJson(argv));
1343
+ mkdirSync3(dirname5(file), { recursive: true });
1344
+ writeFileSync2(file, JSON.stringify(all));
1345
+ } catch {}
1346
+ }
1347
+ var KEPT = 50;
1348
+ var init_answers = __esm(() => {
1349
+ init_folders();
1350
+ });
1351
+
1352
+ // ../kit/src/prompt.ts
1353
+ import process24 from "process";
1354
+ function readKeys(input, paste = { active: false }) {
1355
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1356
+ }
1357
+ function roomAfter(question, columns) {
1358
+ return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
1359
+ }
1360
+ function withCaret(colors, line, room, dim = false) {
1361
+ const { before, at, after } = visible(line, room);
1362
+ const tone = dim ? colors.dim : (text) => text;
1363
+ return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
1364
+ }
1365
+ function sharedStart(texts) {
1366
+ const [first = [], ...rest] = texts.map((text) => [...text]);
1367
+ let length = first.length;
1368
+ for (const chars of rest) {
1369
+ const differs = chars.findIndex((char, index) => char !== first[index]);
1370
+ length = Math.min(length, differs === -1 ? chars.length : differs);
1256
1371
  }
1257
- notifyEnd(name, code, performance.now() - started);
1258
- if (usage !== false) {
1259
- try {
1260
- recordUsage(usageEntry(name, undefined, argv, code));
1261
- } catch {}
1372
+ return first.slice(0, length).join("");
1373
+ }
1374
+ function listed2(colors, found, columns) {
1375
+ const shared = sharedStart(found);
1376
+ const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
1377
+ const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
1378
+ const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
1379
+ return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
1380
+ }
1381
+ async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
1382
+ let line = { text: "", caret: 0 };
1383
+ let invalid;
1384
+ let completions = [];
1385
+ const remembered = history === undefined || mask ? undefined : history;
1386
+ const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
1387
+ let recalled = -1;
1388
+ let draft = line;
1389
+ const taken = () => line.text === "" ? fallback ?? "" : line.text;
1390
+ const shown = () => mask ? "*".repeat([...taken()].length) : taken();
1391
+ const accepted = await ask(question, settings, (colors, state, { columns }) => {
1392
+ if (state !== "asking")
1393
+ return [answer(colors, question, state, shown())];
1394
+ const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
1395
+ return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
1396
+ }, (key) => {
1397
+ if (key === "cancel")
1398
+ return "cancel";
1399
+ invalid = undefined;
1400
+ completions = [];
1401
+ if (line.chained === true && endsKills(key))
1402
+ line = { ...line, chained: false };
1403
+ if (key === "tab") {
1404
+ const chars = [...line.text];
1405
+ const before = chars.slice(0, line.caret).join("");
1406
+ const found = complete?.(before) ?? [];
1407
+ const filled = sharedStart(found);
1408
+ if ([...filled].length > [...before].length)
1409
+ line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
1410
+ else
1411
+ completions = found;
1412
+ return;
1413
+ }
1414
+ if (key === "enter") {
1415
+ invalid = validate?.(taken());
1416
+ return invalid === undefined ? "enter" : undefined;
1417
+ }
1418
+ if (key === "up" || key === "down") {
1419
+ const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
1420
+ if (recalled === -1)
1421
+ draft = line;
1422
+ recalled = to;
1423
+ const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
1424
+ line = { ...shown, killed: line.killed ?? "" };
1425
+ return;
1426
+ }
1427
+ const edit = { home: "linestart", end: "lineend" }[key] ?? key;
1428
+ if (typeof edit === "object" || isEditKey(edit))
1429
+ line = editLine(line, edit);
1430
+ return;
1431
+ });
1432
+ if (!accepted)
1433
+ return;
1434
+ if (remembered !== undefined && taken() !== "")
1435
+ rememberAnswer(remembered, taken());
1436
+ return taken();
1437
+ }
1438
+ function answer(colors, question, state, picked) {
1439
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1440
+ }
1441
+ async function ask(question, { hint, terminal = process24 }, render, press) {
1442
+ const { stdin, stderr } = terminal;
1443
+ if (!isInteractive(terminal))
1444
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1445
+ const colors = paint(stderr);
1446
+ let current = "asking";
1447
+ let outcome;
1448
+ const columns = () => stderr.columns || 80;
1449
+ const draw = (state, last = false) => {
1450
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1451
+ const rows = rowsTaken(frame, columns());
1452
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1453
+ current = state;
1454
+ };
1455
+ const redraw = () => draw(current);
1456
+ const paste = { active: false };
1457
+ const stop = terminal.stop ?? (terminal === process24 ? stopJob : undefined);
1458
+ const suspend = () => {
1459
+ if (stop === undefined)
1460
+ return;
1461
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1462
+ stdin.setRawMode(false);
1463
+ stop();
1464
+ stdin.setRawMode(true);
1465
+ stderr.write("\x1B[?25l\x1B[?2004h");
1466
+ };
1467
+ try {
1468
+ stderr.on?.("resize", redraw);
1469
+ stdin.setRawMode(true);
1470
+ stdin.resume();
1471
+ stderr.write("\x1B[?25l\x1B[?2004h");
1472
+ draw("asking");
1473
+ return await new Promise((resolve) => {
1474
+ function onData(data) {
1475
+ for (const key of readKeys(data.toString(), paste)) {
1476
+ if (key === "suspend") {
1477
+ suspend();
1478
+ continue;
1479
+ }
1480
+ const pressed = press(key);
1481
+ if (pressed !== undefined) {
1482
+ settle(pressed);
1483
+ return;
1484
+ }
1485
+ }
1486
+ draw("asking");
1487
+ }
1488
+ function onEnd() {
1489
+ settle("cancel");
1490
+ }
1491
+ function settle(settled) {
1492
+ outcome = settled;
1493
+ stdin.off("data", onData);
1494
+ stdin.off("end", onEnd);
1495
+ resolve(settled === "enter");
1496
+ }
1497
+ stdin.on("data", onData);
1498
+ stdin.on("end", onEnd);
1499
+ });
1500
+ } finally {
1501
+ stderr.off?.("resize", redraw);
1502
+ draw(outcome ?? "cancel", true);
1503
+ stderr.write(`
1504
+ \x1B[?25h\x1B[?2004l`);
1505
+ stdin.setRawMode(false);
1506
+ stdin.pause();
1262
1507
  }
1263
- return code;
1264
1508
  }
1265
- // ../kit/src/excerpt.ts
1266
- var BASH_ECHO = /^\$ /;
1267
- var DURATION2 = / \[[\d.]+m?s\]$/;
1268
- var BOUNDARY = /^(?:\((?:pass|fail|skip|todo)\) |\S+\.test\.[jt]sx?:$)/;
1269
- var BUN_TEST_SUMMARY = /^\s*\d+ (?:pass|fail|skip|todo)$|^Ran \d+ tests?/;
1270
- var BUN_CHECK_BLOCK = /<error file=[\s\S]*?<\/error>/g;
1271
- var BUN_CHECK_SOURCE = /<source>[\s\S]*?<\/source>\n?/g;
1272
- var BUN_CHECK_ATTRIBUTE = /(\w+)="([^"]*)"/g;
1273
- var BUN_CHECK_SUMMARY = /^Found \d+ errors?/;
1274
- var TSC_ERROR = /\berror TS\d+/;
1275
- var TSC_CONTINUATION = /^\s{2,}\S/;
1276
- var TSC_FRAME = /^\s*[~^|]/;
1277
- var TSC_SUMMARY = /^Found \d+ errors?/;
1278
- var ESLINT_PROBLEM = /^\s+\d+:\d+\s+(?:error|warning)\s/;
1279
- var ESLINT_SUMMARY = /^(?:\u2716 )?\d+ problems? \(/;
1280
- var PHPSTAN_TABLE = /^\s*-{3,} -{3,}/;
1281
- var PHPSTAN_NOISE = /^\s*\[OK\]/;
1282
- var PHP_FAILURES = /^(?:There w(?:as|ere) \d+ (?:failure|error|risky|warning)|\s+(?:FAIL|FAILED)\s+\S|In \S+\.php line \d+:$)/;
1283
- var VITEST_FAIL_LINE = /^ FAIL {2}\S/;
1284
- var PLAYWRIGHT_FAIL_LINE = /^ {2}1\) .+:\d+:\d+ \u203A .+ \u2500+$/;
1285
- var CS_FIXER_LINE = /^\s+\d+\) \S.*\.php(?: \(.+\))?$/;
1286
- var CS_FIXER_TOTAL = /^Found \d+ of \d+ files/;
1287
- var MAX_TESTS = 10;
1288
- var MAX_LINES = 100;
1289
- var TAIL = 30;
1290
- var bunTest = (lines) => {
1291
- const seen = new Set;
1292
- const blocks = [];
1293
- for (const [index, line] of lines.entries()) {
1294
- const name = line.replace(DURATION2, "");
1295
- if (!line.startsWith("(fail) ") || seen.has(name))
1296
- continue;
1297
- seen.add(name);
1298
- if (blocks.length < MAX_TESTS)
1299
- blocks.push(lines.slice(lines.findLastIndex((text, at) => at < index && BOUNDARY.test(text)) + 1, index + 1).join(`
1300
- `).trim());
1509
+ var PROMPT_KEYS, MAX_LISTED = 12;
1510
+ var init_prompt = __esm(() => {
1511
+ init_answers();
1512
+ init_args();
1513
+ init_format();
1514
+ init_job();
1515
+ init_mode();
1516
+ init_line();
1517
+ init_state();
1518
+ init_redraw();
1519
+ init_style();
1520
+ PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1521
+ });
1522
+
1523
+ // src/j-cli.ts
1524
+ import process27 from "process";
1525
+
1526
+ // ../kit/src/index.ts
1527
+ init_args();
1528
+
1529
+ // ../kit/src/argv.ts
1530
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
1531
+ import { resolve as resolve3 } from "path";
1532
+ import process11 from "process";
1533
+ function commandLine() {
1534
+ try {
1535
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
1536
+ } catch {
1537
+ return;
1301
1538
  }
1302
- if (blocks.length === 0)
1539
+ }
1540
+ function realPath(word) {
1541
+ try {
1542
+ return realpathSync(resolve3(word));
1543
+ } catch {
1303
1544
  return;
1304
- if (seen.size > MAX_TESTS)
1305
- blocks.push(`and ${seen.size - MAX_TESTS} more failed tests`);
1306
- return [...blocks.join(`
1545
+ }
1546
+ }
1547
+ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
1548
+ const target = script === undefined ? undefined : realPath(script) ?? script;
1549
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
1550
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
1551
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
1552
+ }
1553
+ // ../kit/src/chart.ts
1554
+ init_format();
1555
+ init_mode();
1556
+ init_style();
1557
+ init_theme();
1558
+ // ../kit/src/ci.ts
1559
+ init_args();
1560
+ init_format();
1307
1561
 
1308
- `).split(`
1309
- `), "", ...lines.filter((line) => BUN_TEST_SUMMARY.test(line)).map((line) => line.trim())];
1310
- };
1311
- var bunCheck = (lines) => {
1312
- const text = lines.join(`
1313
- `);
1314
- const blocks = text.match(BUN_CHECK_BLOCK);
1315
- if (blocks === null)
1562
+ // ../kit/src/progress.ts
1563
+ init_format();
1564
+
1565
+ // ../kit/src/process.ts
1566
+ import { readFileSync as readFileSync4 } from "fs";
1567
+ import { constants } from "os";
1568
+ import process12 from "process";
1569
+ var KILL_GRACE_MS = 2000;
1570
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1571
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
1572
+ function exitCodeOf(code, signal) {
1573
+ if (code !== null)
1574
+ return code;
1575
+ if (typeof signal === "number")
1576
+ return 128 + signal;
1577
+ return signal === null ? 129 : 128 + constants.signals[signal];
1578
+ }
1579
+ function groupsOf(pid) {
1580
+ try {
1581
+ const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
1582
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
1583
+ return { group: Number(fields[2]), foreground: Number(fields[5]) };
1584
+ } catch {
1316
1585
  return;
1317
- const errors = blocks.map((block) => {
1318
- const { file, line, column, code, message } = bunCheckFields(block);
1319
- return `${file}:${line}:${column} ${code}: ${message}`;
1320
- });
1321
- return [...errors, ...lines.filter((line) => BUN_CHECK_SUMMARY.test(line))];
1322
- };
1323
- function bunCheckFields(block) {
1324
- const attributes = Object.fromEntries([...block.slice(0, block.indexOf(`
1325
- `)).matchAll(BUN_CHECK_ATTRIBUTE)].map((match) => [match[1] ?? "", match[2] ?? ""]));
1326
- return {
1327
- file: attributes.file ?? "",
1328
- line: attributes.line ?? "",
1329
- column: attributes.column ?? "",
1330
- code: attributes.code ?? "",
1331
- message: block.replace(BUN_CHECK_SOURCE, "").split(`
1332
- `).slice(1, -1).join(`
1333
- `).trim()
1334
- };
1586
+ }
1335
1587
  }
1336
- var tsc = (lines) => {
1337
- const kept = [];
1338
- let inError = false;
1339
- for (const line of lines) {
1340
- if (TSC_ERROR.test(line)) {
1341
- inError = true;
1342
- kept.push(line);
1343
- } else if (TSC_SUMMARY.test(line)) {
1344
- inError = false;
1345
- kept.push(line);
1346
- } else if (inError && TSC_CONTINUATION.test(line) && !TSC_FRAME.test(line)) {
1347
- kept.push(line);
1348
- } else {
1349
- inError = false;
1588
+ function heardTheTerminal(child) {
1589
+ if (child.pid === undefined)
1590
+ return false;
1591
+ const own = groupsOf("self");
1592
+ return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
1593
+ }
1594
+ function holdSignals(cleanup) {
1595
+ let received;
1596
+ let child;
1597
+ const held = {
1598
+ get signal() {
1599
+ return received;
1600
+ },
1601
+ forward: (to) => {
1602
+ child = to;
1603
+ },
1604
+ release: () => {
1605
+ for (const signal of SIGNALS)
1606
+ process12.off(signal, onSignal);
1350
1607
  }
1608
+ };
1609
+ function onSignal(signal) {
1610
+ received = signal;
1611
+ if (child !== undefined) {
1612
+ if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
1613
+ child.kill(signal);
1614
+ return;
1615
+ }
1616
+ if (cleanup === undefined)
1617
+ return;
1618
+ held.release();
1619
+ cleanup(signal);
1620
+ process12.kill(process12.pid, signal);
1351
1621
  }
1352
- return kept.some((line) => TSC_ERROR.test(line)) ? kept : undefined;
1353
- };
1354
- var eslint = (lines) => {
1355
- const kept = [];
1356
- let file = "";
1357
- let shown = "";
1358
- for (const line of lines) {
1359
- if (ESLINT_PROBLEM.test(line)) {
1360
- if (file !== shown) {
1361
- kept.push(file);
1362
- shown = file;
1622
+ for (const signal of SIGNALS)
1623
+ process12.on(signal, onSignal);
1624
+ return held;
1625
+ }
1626
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
1627
+ const chunks = [];
1628
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
1629
+ 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 } : {} });
1630
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
1631
+ const timers = [];
1632
+ const killGroup = (killing) => {
1633
+ if (state.done)
1634
+ return;
1635
+ try {
1636
+ if (grouped)
1637
+ process12.kill(-proc.pid, killing);
1638
+ else
1639
+ proc.kill(killing);
1640
+ } catch {}
1641
+ };
1642
+ const stop = () => {
1643
+ killGroup("SIGTERM");
1644
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
1645
+ };
1646
+ const onAbort = () => stop();
1647
+ if (timeoutMs !== undefined) {
1648
+ timers.push(setTimeout(() => {
1649
+ state.timedOut = true;
1650
+ stop();
1651
+ }, timeoutMs));
1652
+ }
1653
+ if (signal?.aborted === true)
1654
+ onAbort();
1655
+ else
1656
+ signal?.addEventListener("abort", onAbort, { once: true });
1657
+ onStart?.({ kill: (killing) => killGroup(killing) });
1658
+ const drain = async (stream, name) => {
1659
+ for await (const data of stream) {
1660
+ if (state.failure !== undefined)
1661
+ continue;
1662
+ try {
1663
+ onChunk?.({ stream: name, data });
1664
+ } catch (error) {
1665
+ state.failure = error;
1666
+ stop();
1667
+ continue;
1363
1668
  }
1364
- kept.push(line);
1365
- } else if (ESLINT_SUMMARY.test(line)) {
1366
- kept.push(line);
1367
- } else if (line.trim() !== "") {
1368
- file = line;
1669
+ if (state.truncated)
1670
+ continue;
1671
+ let kept = data;
1672
+ if (state.kept + data.length > maxBytes) {
1673
+ let cut = maxBytes - state.kept;
1674
+ while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
1675
+ cut--;
1676
+ kept = data.subarray(0, cut);
1677
+ state.truncated = true;
1678
+ }
1679
+ state.kept += kept.length;
1680
+ if (kept.length > 0)
1681
+ chunks.push({ stream: name, data: kept });
1369
1682
  }
1683
+ };
1684
+ try {
1685
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
1686
+ await proc.exited;
1687
+ } finally {
1688
+ state.done = true;
1689
+ for (const timer of timers)
1690
+ clearTimeout(timer);
1691
+ signal?.removeEventListener("abort", onAbort);
1370
1692
  }
1371
- return kept.some((line) => ESLINT_PROBLEM.test(line)) ? kept : undefined;
1372
- };
1373
- var phpstan = (lines) => {
1374
- const start = lines.findIndex((line) => PHPSTAN_TABLE.test(line));
1375
- return start === -1 ? undefined : lines.slice(start).filter((line) => !PHPSTAN_NOISE.test(line));
1376
- };
1377
- var php = (lines) => {
1378
- const start = lines.findIndex((line) => PHP_FAILURES.test(line));
1379
- return start === -1 ? undefined : lines.slice(start);
1380
- };
1381
- var vitest = (lines) => {
1382
- const start = lines.findIndex((line) => VITEST_FAIL_LINE.test(line));
1383
- return start === -1 ? undefined : lines.slice(start);
1384
- };
1385
- var playwright = (lines) => {
1386
- const start = lines.findIndex((line) => PLAYWRIGHT_FAIL_LINE.test(line));
1387
- return start === -1 ? undefined : lines.slice(start);
1388
- };
1389
- var phpCsFixer = (lines) => {
1390
- const files = lines.filter((line) => CS_FIXER_LINE.test(line) || CS_FIXER_TOTAL.test(line));
1391
- return files.some((line) => CS_FIXER_LINE.test(line)) ? files : undefined;
1392
- };
1393
- var PARSERS = [bunTest, bunCheck, tsc, eslint, vitest, playwright, phpCsFixer, phpstan, php];
1394
- function squeeze(lines) {
1395
- const out = [];
1396
- for (const line of lines.map((text) => text.trimEnd())) {
1397
- if (line !== "" || out.at(-1) !== "")
1398
- out.push(line);
1399
- }
1400
- while (out.at(-1) === "")
1401
- out.pop();
1402
- return out;
1693
+ if (state.failure !== undefined)
1694
+ throw state.failure;
1695
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
1696
+ let output;
1697
+ let text;
1698
+ let stdout;
1699
+ return {
1700
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
1701
+ chunks,
1702
+ timedOut: state.timedOut,
1703
+ truncated: state.truncated,
1704
+ get output() {
1705
+ return output ??= joined();
1706
+ },
1707
+ get text() {
1708
+ return text ??= (output ??= joined()).toString();
1709
+ },
1710
+ get stdout() {
1711
+ return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1712
+ }
1713
+ };
1403
1714
  }
1404
- function cut(shown) {
1405
- return shown.length > MAX_LINES ? [...shown.slice(0, MAX_LINES), `... ${shown.length - MAX_LINES} more lines`].join(`
1406
- `) : shown.join(`
1715
+
1716
+ // ../kit/src/progress.ts
1717
+ init_style();
1718
+ init_theme();
1719
+ var ESC = String.fromCharCode(27);
1720
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1721
+ var RESET_STYLE = `${ESC}[0m`;
1722
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1723
+
1724
+ // ../kit/src/ci.ts
1725
+ init_style();
1726
+
1727
+ // ../kit/src/tool.ts
1728
+ init_format();
1729
+ // ../kit/src/cli.ts
1730
+ init_args();
1731
+ import { readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
1732
+ import { dirname as dirname3, join as join6 } from "path";
1733
+ import process17 from "process";
1734
+
1735
+ // ../kit/src/askpass.ts
1736
+ import process13 from "process";
1737
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1738
+ async function askpassClient(argv) {
1739
+ const socketPath = process13.env[SOCKET_VARIABLE];
1740
+ if (socketPath === undefined)
1741
+ return;
1742
+ const request = { prompt: argv[0] ?? "", ...process13.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1743
+ const { promise, resolve } = Promise.withResolvers();
1744
+ let received = "";
1745
+ try {
1746
+ await Bun.connect({
1747
+ unix: socketPath,
1748
+ socket: {
1749
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1750
+ `),
1751
+ data: (_, chunk) => {
1752
+ received += chunk.toString();
1753
+ },
1754
+ close: () => resolve(received),
1755
+ error: () => resolve("")
1756
+ }
1757
+ });
1758
+ } catch {
1759
+ return 1;
1760
+ }
1761
+ const reply = await promise;
1762
+ if (reply === "")
1763
+ return 1;
1764
+ const { answer } = JSON.parse(reply);
1765
+ if (request.notice === true)
1766
+ return 0;
1767
+ if (answer === undefined)
1768
+ return 1;
1769
+ process13.stdout.write(`${answer}
1407
1770
  `);
1771
+ return 0;
1408
1772
  }
1409
- function recognised(lines, parsers) {
1410
- return parsers.map((parser) => parser(lines)).find((result) => result !== undefined && result.some((line) => line.trim() !== ""));
1773
+
1774
+ // ../kit/src/completions.ts
1775
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1776
+ 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'
1777
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1778
+ set -l current (commandline -ct)
1779
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1780
+ if test "$line" = __files__
1781
+ __fish_complete_path $current
1782
+ else
1783
+ echo $line
1784
+ end
1785
+ end
1786
+ end`;
1787
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1788
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1789
+ local -a lines
1790
+ COMPREPLY=()
1791
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1792
+ for line in "\${lines[@]}"; do
1793
+ if [[ $line == __files__ ]]; then
1794
+ COMPREPLY+=($(compgen -f -- "$cur"))
1795
+ else
1796
+ words+="\${line%%$'\\t'*}"$'\\n'
1797
+ fi
1798
+ done
1799
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1800
+ }`;
1801
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1802
+ local line
1803
+ local -a described plain
1804
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1805
+ if [[ $line == __files__ ]]; then
1806
+ _files
1807
+ elif [[ $line == *$'\\t'* ]]; then
1808
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1809
+ else
1810
+ plain+=("$line")
1811
+ fi
1812
+ done
1813
+ (( \${#described} )) && _describe -V value described
1814
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1815
+ return 0
1816
+ }`;
1817
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1818
+ if (shell === "fish")
1819
+ return `${header}
1820
+ ${FISH_FUNCTION}
1821
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1822
+ `).join("")}`;
1823
+ if (shell === "bash")
1824
+ return `${header}
1825
+ ${BASH_FUNCTION}
1826
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1827
+ `;
1828
+ return `${header}
1829
+ ${ZSH_FUNCTION}
1830
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1831
+ `;
1411
1832
  }
1412
- function failureExcerpt(output) {
1413
- const lines = stripAnsi(output).split(`
1414
- `);
1415
- if (BASH_ECHO.test(lines[0] ?? ""))
1416
- lines.shift();
1417
- return cut(squeeze(recognised(lines, PARSERS) ?? lines.slice(-TAIL)));
1833
+
1834
+ // ../kit/src/notify.ts
1835
+ init_format();
1836
+ init_mode();
1837
+ import process14 from "process";
1838
+ var NOTIFY_AFTER_MS = 1e4;
1839
+ var CANCELLED = 130;
1840
+ function base64(text) {
1841
+ return Buffer.from(text).toString("base64");
1418
1842
  }
1419
- var LOG_PATTERNS = { BASH_ECHO, DURATION: DURATION2, BOUNDARY, BUN_TEST_SUMMARY, BUN_CHECK_SUMMARY, TSC_CONTINUATION, TSC_FRAME, TSC_SUMMARY, ESLINT_PROBLEM, ESLINT_SUMMARY };
1420
- // ../kit/src/folders.ts
1421
- import { homedir as homedir5 } from "os";
1422
- import { join as join7 } from "path";
1423
- import process17 from "process";
1424
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1425
- function ignoredFolders(extra = [], where = {}) {
1426
- const configured = readUserConfig("config", where).ignore;
1427
- const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1428
- return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1843
+ function notification(title, body, env = process14.env) {
1844
+ const id = `kit${process14.pid}`;
1845
+ 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\\`];
1846
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1429
1847
  }
1430
- function cacheFolder({ home = homedir5(), env = process17.env } = {}) {
1431
- return env.XDG_CACHE_HOME ?? join7(home, ".cache");
1848
+ function notifyEnd(command, code, ms, { stream = process14.stderr, env = process14.env } = {}) {
1849
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1850
+ return;
1851
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1432
1852
  }
1433
- // ../kit/src/secrets.ts
1434
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1435
- // ../kit/src/sessions.ts
1436
- var {Glob } = globalThis.Bun;
1437
- var SESSION_FILES = new Glob("*.json");
1438
- var ACCOUNT_DIRS = new Glob("*/sessions");
1439
- // package.json
1440
- var version = "0.20.1";
1441
1853
 
1442
- // src/j.ts
1443
- import process25 from "process";
1854
+ // ../kit/src/cli.ts
1855
+ init_style();
1856
+ init_text2();
1444
1857
 
1445
- // ../kit/src/picker.ts
1446
- import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync } from "fs";
1447
- import { dirname as dirname4, join as join8 } from "path";
1448
- import process22 from "process";
1858
+ // ../kit/src/usage.ts
1859
+ import { appendFileSync, mkdirSync } from "fs";
1860
+ import { homedir as homedir4 } from "os";
1861
+ import { dirname as dirname2, join as join5 } from "path";
1862
+ import process16 from "process";
1449
1863
 
1450
- // ../kit/src/picker/line.ts
1451
- var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1452
- var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1453
- var FORWARD_KILLS = new Set(["killnext", "killend"]);
1454
- function isEditKey(key) {
1455
- return EDIT_KEYS.has(key);
1456
- }
1457
- function endsKills(key) {
1458
- return typeof key !== "object" && !isEditKey(key);
1459
- }
1460
- var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1461
- var SPACE = /\s/;
1462
- function isWord(char) {
1463
- return char !== undefined && WORD_CHARACTER.test(char);
1464
- }
1465
- function wordStart(chars, from) {
1466
- let at = from;
1467
- while (at > 0 && !isWord(chars[at - 1]))
1468
- at--;
1469
- while (at > 0 && isWord(chars[at - 1]))
1470
- at--;
1471
- return at;
1472
- }
1473
- function wordEnd(chars, from) {
1474
- let at = from;
1475
- while (at < chars.length && !isWord(chars[at]))
1476
- at++;
1477
- while (at < chars.length && isWord(chars[at]))
1478
- at++;
1479
- return at;
1480
- }
1481
- function spacedStart(chars, from) {
1482
- let at = from;
1483
- while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
1484
- at--;
1485
- while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
1486
- at--;
1487
- return at;
1488
- }
1489
- function cut2(chars, from, to) {
1490
- return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1491
- }
1492
- function insert(chars, at, text) {
1493
- const typed = [...text];
1494
- return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
1495
- }
1496
- function editLine(line, key) {
1497
- const { killed = "", chained = false } = line;
1498
- const chars = [...line.text];
1499
- const at = Math.min(Math.max(line.caret, 0), chars.length);
1500
- const edited = edit(chars, at, key, killed);
1501
- if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1502
- return line.killed === undefined ? edited : { ...edited, killed };
1503
- const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1504
- if (taken === "")
1505
- return { ...edited, killed, chained };
1506
- if (!chained)
1507
- return { ...edited, killed: taken, chained: true };
1508
- return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1509
- }
1510
- function edit(chars, at, key, killed) {
1511
- const text = chars.join("");
1512
- if (typeof key === "object")
1513
- return insert(chars, at, key.text);
1514
- switch (key) {
1515
- case "left":
1516
- return { text, caret: Math.max(at - 1, 0) };
1517
- case "right":
1518
- return { text, caret: Math.min(at + 1, chars.length) };
1519
- case "wordleft":
1520
- return { text, caret: wordStart(chars, at) };
1521
- case "wordright":
1522
- return { text, caret: wordEnd(chars, at) };
1523
- case "linestart":
1524
- return { text, caret: 0 };
1525
- case "lineend":
1526
- return { text, caret: chars.length };
1527
- case "erase":
1528
- return cut2(chars, Math.max(at - 1, 0), at);
1529
- case "delete":
1530
- return cut2(chars, at, Math.min(at + 1, chars.length));
1531
- case "word":
1532
- return cut2(chars, spacedStart(chars, at), at);
1533
- case "killword":
1534
- return cut2(chars, wordStart(chars, at), at);
1535
- case "killnext":
1536
- return cut2(chars, at, wordEnd(chars, at));
1537
- case "clear":
1538
- return cut2(chars, 0, at);
1539
- case "killend":
1540
- return cut2(chars, at, chars.length);
1541
- case "yank":
1542
- return insert(chars, at, killed);
1543
- }
1544
- }
1545
- function visible({ text, caret }, room) {
1546
- const chars = [...text];
1547
- const at = Math.min(Math.max(caret, 0), chars.length);
1548
- const cells = at === chars.length ? [...chars, " "] : chars;
1549
- const widths = cells.map((char) => Bun.stringWidth(char));
1550
- const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1551
- const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1552
- let start = at;
1553
- let end = at + 1;
1554
- while (start > 0 && fits(start - 1, end))
1555
- start--;
1556
- while (end < cells.length && fits(start, end + 1))
1557
- end++;
1558
- const left = start > 0 ? "\u2026" : "";
1559
- const right = end < cells.length ? "\u2026" : "";
1560
- 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) };
1864
+ // ../kit/src/logs.ts
1865
+ init_user_config();
1866
+ import { lstatSync, openSync } from "fs";
1867
+ import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
1868
+ import { homedir as homedir3, tmpdir } from "os";
1869
+ import { join as join4 } from "path";
1870
+ import process15 from "process";
1871
+ var DAY_MS = 24 * 60 * 60 * 1000;
1872
+ var CLI_FOLDER = "kaynooo-cli";
1873
+ function isPrivateDirectory(path) {
1874
+ try {
1875
+ const info = lstatSync(path, { throwIfNoEntry: false });
1876
+ return info !== undefined && info.isDirectory() && info.uid === (process15.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
1877
+ } catch {
1878
+ return false;
1879
+ }
1561
1880
  }
1562
-
1563
- // ../kit/src/picker/score.ts
1564
- var MATCH = 16;
1565
- var CONSECUTIVE = 12;
1566
- var BOUNDARY2 = 10;
1567
- var PREFIX = 8;
1568
- var GAP = 1;
1569
- var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1570
- var UPPER = /\p{Lu}/u;
1571
- var LOWER = /\p{Ll}/u;
1572
- var NONE = Number.NEGATIVE_INFINITY;
1573
- function startsWord(text, index) {
1574
- if (index === 0)
1575
- return true;
1576
- const before = text[index - 1];
1577
- return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
1881
+ async function privateLogDirectory(name, env = process15.env) {
1882
+ const path = join4(xdgFolder(env.XDG_RUNTIME_DIR, join4(homedir3(), ".cache")), CLI_FOLDER, name);
1883
+ try {
1884
+ await mkdir(path, { recursive: true, mode: 448 });
1885
+ if (isPrivateDirectory(path))
1886
+ return path;
1887
+ } catch {}
1888
+ return mkdtemp(join4(tmpdir(), `${name.replaceAll("/", "-")}-`));
1578
1889
  }
1579
- function fuzzy(query, text) {
1580
- if (query === "")
1581
- return { score: 0, positions: [] };
1582
- const exact = query !== query.toLowerCase();
1583
- const needle = exact ? query : query.toLowerCase();
1584
- const haystack = exact ? text : text.toLowerCase();
1585
- if (haystack.length !== text.length || needle.length > haystack.length)
1890
+ async function sweepLogs(dir, maxAgeMs = DAY_MS, now = Date.now()) {
1891
+ let names;
1892
+ try {
1893
+ names = await readdir(dir);
1894
+ } catch {
1586
1895
  return;
1587
- const width = haystack.length;
1588
- const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
1589
- const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
1590
- for (let j = 0;j < needle.length; j++) {
1591
- let run = NONE;
1592
- let runAt = -1;
1593
- for (let i = j;i < width; i++) {
1594
- if (j > 0 && i - 2 >= j - 1) {
1595
- const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
1596
- if (candidate > run) {
1597
- run = candidate;
1598
- runAt = i - 2;
1599
- }
1600
- }
1601
- if (haystack[i] !== needle[j])
1602
- continue;
1603
- const here = MATCH + (startsWord(text, i) ? BOUNDARY2 : 0) + (i === 0 ? PREFIX : 0);
1604
- if (j === 0) {
1605
- best[0][i] = here - i * GAP;
1606
- continue;
1607
- }
1608
- const joined = best[j - 1][i - 1] + CONSECUTIVE;
1609
- const skipped = run - (i - 1) * GAP;
1610
- if (joined > NONE && joined >= skipped) {
1611
- best[j][i] = joined + here;
1612
- from[j][i] = i - 1;
1613
- } else if (skipped > NONE) {
1614
- best[j][i] = skipped + here;
1615
- from[j][i] = runAt;
1616
- }
1617
- }
1618
- }
1619
- const last = best[needle.length - 1];
1620
- let end = -1;
1621
- for (let i = 0;i < width; i++) {
1622
- if (last[i] > NONE && (end === -1 || last[i] > last[end]))
1623
- end = i;
1624
1896
  }
1625
- if (end === -1)
1626
- return;
1627
- const positions = [];
1628
- for (let j = needle.length - 1, i = end;j >= 0; j--) {
1629
- positions.unshift(i);
1630
- i = from[j][i];
1897
+ for (const name of names) {
1898
+ const path = join4(dir, name);
1899
+ try {
1900
+ const info = await stat(path);
1901
+ if (info.isDirectory())
1902
+ await sweepLogs(path, maxAgeMs, now);
1903
+ if (now - info.mtimeMs > maxAgeMs)
1904
+ await rm(path, { force: true, recursive: info.isDirectory() });
1905
+ } catch {
1906
+ continue;
1907
+ }
1631
1908
  }
1632
- return { score: last[end], positions };
1633
1909
  }
1634
- function rank(query, lines) {
1635
- if (query === "")
1636
- return lines.map((_, index) => ({ index, positions: [] }));
1637
- const found = [];
1638
- for (const [index, line] of lines.entries()) {
1639
- const match = fuzzy(query, line);
1640
- if (match !== undefined)
1641
- found.push({ index, positions: match.positions, score: match.score });
1642
- }
1643
- return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
1910
+
1911
+ // ../kit/src/usage.ts
1912
+ init_user_config();
1913
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1914
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1915
+ var LONGEST_NAME = 40;
1916
+ var usageError;
1917
+ function noteUsageError(message) {
1918
+ usageError = message;
1919
+ }
1920
+ function stateHome(env = process16.env) {
1921
+ return xdgFolder(env.XDG_STATE_HOME, join5(homedir4(), ".local", "state"));
1922
+ }
1923
+ function usagePath(env = process16.env) {
1924
+ return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
1925
+ }
1926
+ function usageRecorded(env = process16.env) {
1927
+ const off = env.KAYNOOO_CLI_NO_USAGE;
1928
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1929
+ }
1930
+ function flagNames(argv) {
1931
+ const end = argv.indexOf("--");
1932
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1933
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1934
+ }
1935
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1936
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1937
+ usageError = undefined;
1938
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1939
+ }
1940
+ function recordUsage(entry, env = process16.env) {
1941
+ if (!usageRecorded(env))
1942
+ return;
1943
+ try {
1944
+ const path = usagePath(env);
1945
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1946
+ appendFileSync(path, `${JSON.stringify(entry)}
1947
+ `, { mode: 384 });
1948
+ } catch {}
1644
1949
  }
1645
1950
 
1646
- // ../kit/src/picker/state.ts
1647
- var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1648
- var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1649
- var SGR = /^\x1B\[[0-9;]*m$/;
1650
- var RESET = /^\x1B\[0?m$/;
1651
- var COLUMN_GAP = 2;
1652
- var PASTE_START = "\x1B[200~";
1653
- var PASTE_END = "\x1B[201~";
1654
- var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1655
- var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1656
- var WHEEL_LINES = 3;
1657
- var KEYS = {
1658
- "\x1B[A": "up",
1659
- "\x1BOA": "up",
1660
- "\x10": "up",
1661
- "\x1B[B": "down",
1662
- "\x1BOB": "down",
1663
- "\x0E": "down",
1664
- "\x1B[5~": "pageup",
1665
- "\x1B[6~": "pagedown",
1666
- "\x1B[H": "home",
1667
- "\x1B[1~": "home",
1668
- "\x1BOH": "home",
1669
- "\x1B[F": "end",
1670
- "\x1B[4~": "end",
1671
- "\x1BOF": "end",
1672
- "\r": "enter",
1673
- "\n": "enter",
1674
- "\x03": "cancel",
1675
- "\x1B": "cancel",
1676
- "\x1B[D": "left",
1677
- "\x1BOD": "left",
1678
- "\x1B[C": "right",
1679
- "\x1BOC": "right",
1680
- "\x1B[1;5D": "wordleft",
1681
- "\x1B[1;3D": "wordleft",
1682
- "\x1Bb": "wordleft",
1683
- "\x1B[1;5C": "wordright",
1684
- "\x1B[1;3C": "wordright",
1685
- "\x1Bf": "wordright",
1686
- "\x01": "linestart",
1687
- "\x05": "lineend",
1688
- "\x7F": "erase",
1689
- "\x1B[3~": "delete",
1690
- "\b": "killword",
1691
- "\x1B\x7F": "killword",
1692
- "\x1B[3;5~": "killnext",
1693
- "\x1Bd": "killnext",
1694
- "\x15": "clear",
1695
- "\v": "killend",
1696
- "\x17": "word",
1697
- "\x19": "yank",
1698
- "\x1A": "suspend",
1699
- "\t": "tab",
1700
- "\x1F": "help",
1701
- "\x1BOP": "help",
1702
- "\x1B[11~": "help"
1951
+ // ../kit/src/cli.ts
1952
+ var LEVEL_OPTIONS = {
1953
+ ...OUTPUT_OPTIONS,
1954
+ help: { type: "boolean", short: "h", description: "show this help" }
1703
1955
  };
1704
- var CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
1705
- function repeat(value, count) {
1706
- return Array.from({ length: count }).fill(value);
1956
+ var TOP_OPTIONS = {
1957
+ ...LEVEL_OPTIONS,
1958
+ version: { type: "boolean", short: "v", description: "print the version" },
1959
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1960
+ };
1961
+ function printError(prefix, message, hint, cause) {
1962
+ const colors = paint(process17.stderr);
1963
+ const styled = takesControlCodes(process17.stderr);
1964
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1965
+ const under = (label, text, tint) => text === undefined ? "" : `
1966
+ ${styled ? tint(label) : `${label}:`} ${text}`;
1967
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1707
1968
  }
1708
- function styled(line) {
1709
- let text = "";
1710
- const styles = [];
1711
- let active = "";
1712
- let colored = false;
1713
- let last = 0;
1714
- function add(chunk) {
1715
- const flat = chunk.replace(CONTROL2, " ");
1716
- text += flat;
1717
- colored ||= active !== "" && flat !== "";
1718
- styles.push(...repeat(active, flat.length));
1719
- }
1720
- for (const found of line.matchAll(ANSI)) {
1721
- add(line.slice(last, found.index));
1722
- last = found.index + found[0].length;
1723
- if (SGR.test(found[0]))
1724
- active = RESET.test(found[0]) ? "" : active + found[0];
1969
+ function printJsonError(message, hint, cause) {
1970
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1971
+ }
1972
+ function wantsJson(argv) {
1973
+ const end = argv.indexOf("--");
1974
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1975
+ }
1976
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
1977
+ if (error instanceof HelpShown)
1978
+ return 0;
1979
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1980
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1981
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1982
+ if (error instanceof Exit && error.code === 2)
1983
+ noteUsageError(error.message);
1984
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1985
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1986
+ return error instanceof Exit ? error.code : 1;
1987
+ }
1988
+ var COMPLETE = "__complete";
1989
+ var FILES = "__files__";
1990
+ async function completingOf(run) {
1991
+ completion.active = true;
1992
+ try {
1993
+ await run([]);
1994
+ } catch (error) {
1995
+ if (error instanceof Completing)
1996
+ return error;
1997
+ } finally {
1998
+ completion.active = false;
1725
1999
  }
1726
- add(line.slice(last));
1727
- return { text, styles: colored ? styles : undefined };
2000
+ return new Completing({});
1728
2001
  }
1729
- function lay(rows, searched) {
1730
- const parsed = rows.map((row) => row.cells.map(styled));
1731
- const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1732
- return parsed.map((cells, at) => {
1733
- let text = "";
1734
- const styles = [];
1735
- let colored = false;
1736
- let searchEnd = 0;
1737
- for (const [column, cell] of cells.entries()) {
1738
- const last = column === cells.length - 1;
1739
- const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1740
- text += shown;
1741
- colored ||= cell.styles !== undefined;
1742
- styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1743
- if (column < searched)
1744
- searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1745
- if (!last) {
1746
- const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1747
- text += " ".repeat(pad);
1748
- styles.push(...repeat("", pad));
1749
- }
2002
+ function candidateLine(candidate) {
2003
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
2004
+ }
2005
+ function positionalBeingTyped(before, { options, positionals }) {
2006
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
2007
+ const typed = [];
2008
+ let at = 0;
2009
+ while (at < before.length) {
2010
+ const word = before[at];
2011
+ if (word === "--") {
2012
+ typed.push(...before.slice(at + 1));
2013
+ break;
1750
2014
  }
1751
- return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1752
- });
2015
+ if (!word.startsWith("-"))
2016
+ typed.push(word);
2017
+ else if (takesValue(word))
2018
+ at++;
2019
+ at++;
2020
+ }
2021
+ const last = positionals.at(-1);
2022
+ if (typed.length < positionals.length)
2023
+ return { name: positionals[typed.length], typed };
2024
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
2025
+ }
2026
+ async function leafCandidates(run, words) {
2027
+ const completing = await completingOf(run);
2028
+ if ((words.at(-1) ?? "").startsWith("-"))
2029
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
2030
+ const flag = words.at(-2);
2031
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
2032
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
2033
+ if (option?.type === "string") {
2034
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
2035
+ return values === undefined ? [FILES] : values.map(candidateLine);
2036
+ }
2037
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
2038
+ return values === undefined ? [FILES] : values.map(candidateLine);
1753
2039
  }
1754
- function parseKeys(input, paste = { active: false }, ctrls = []) {
1755
- const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1756
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1757
- const wheel = MOUSE.exec(sequence)?.[1];
1758
- if (wheel !== undefined)
1759
- return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1760
- const named = codes.get(sequence);
1761
- const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1762
- if (sequence === PASTE_START || sequence === PASTE_END) {
1763
- paste.active = sequence === PASTE_START;
1764
- return [];
1765
- }
1766
- if (paste.active && (sequence === "\r" || sequence === `
1767
- `))
1768
- return [];
1769
- if (key !== undefined)
1770
- return [key];
1771
- return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1772
- });
2040
+ var COMPLETIONS = "--completions";
2041
+ function flagValue([flag = "", ...rest]) {
2042
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1773
2043
  }
1774
- function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1775
- 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 };
1776
- return withRows(state, rows);
2044
+ function printCompletionScript(name, args) {
2045
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
2046
+ if (shell === undefined || args.length !== 1) {
2047
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
2048
+ return 2;
2049
+ }
2050
+ console.log(completionScript(shell, [name]).trimEnd());
2051
+ return 0;
1777
2052
  }
1778
- function withRows(state, rows, header = state.header) {
1779
- const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1780
- const laid = lay(cells, state.searched);
1781
- const searchable = laid.map((row) => row.searchable);
1782
- const matches = rank(state.query, searchable);
1783
- 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 };
2053
+ async function printCandidates(found) {
2054
+ for (const line of await found)
2055
+ console.log(line);
2056
+ return 0;
1784
2057
  }
1785
- function withQuery(state, key) {
1786
- const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1787
- return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
2058
+ function packageVersion(entry = Bun.main) {
2059
+ let resolved = entry;
2060
+ try {
2061
+ resolved = realpathSync2(entry);
2062
+ } catch {}
2063
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
2064
+ try {
2065
+ const { version } = JSON.parse(readFileSync5(join6(dir, "package.json"), "utf8"));
2066
+ if (typeof version === "string")
2067
+ return version;
2068
+ } catch {}
2069
+ if (dirname3(dir) === dir)
2070
+ return "0.0.0";
2071
+ }
1788
2072
  }
1789
- function move(state, by) {
1790
- return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
2073
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
2074
+ const answered = await askpassClient(argv);
2075
+ if (answered !== undefined)
2076
+ return answered;
2077
+ if (argv[0] === COMPLETE)
2078
+ return printCandidates(leafCandidates(run, argv.slice(1)));
2079
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
2080
+ return printCompletionScript(name, flagValue(argv));
2081
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
2082
+ console.log(version ?? packageVersion());
2083
+ return 0;
2084
+ }
2085
+ let code;
2086
+ const started = performance.now();
2087
+ try {
2088
+ code = await run(argv);
2089
+ } catch (error) {
2090
+ code = reportThrown(name, error, redact, wantsJson(argv));
2091
+ }
2092
+ notifyEnd(name, code, performance.now() - started);
2093
+ if (usage !== false) {
2094
+ try {
2095
+ recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
2096
+ } catch {}
2097
+ }
2098
+ return code;
1791
2099
  }
1792
- function highlighted(state) {
1793
- return state.matches[state.cursor]?.index;
2100
+
2101
+ // ../kit/src/index.ts
2102
+ init_config();
2103
+
2104
+ // ../kit/src/excerpt.ts
2105
+ init_text2();
2106
+ var BASH_ECHO = /^\$ /;
2107
+ var DURATION2 = / \[[\d.]+m?s\]$/;
2108
+ var BOUNDARY = /^(?:\((?:pass|fail|skip|todo)\) |\S+\.test\.[jt]sx?:$)/;
2109
+ var BUN_TEST_SUMMARY = /^\s*\d+ (?:pass|fail|skip|todo)$|^Ran \d+ tests?/;
2110
+ var BUN_CHECK_BLOCK = /<error file=[\s\S]*?<\/error>/g;
2111
+ var BUN_CHECK_SOURCE = /<source>[\s\S]*?<\/source>\n?/g;
2112
+ var BUN_CHECK_ATTRIBUTE = /(\w+)="([^"]*)"/g;
2113
+ var BUN_CHECK_SUMMARY = /^Found \d+ errors?/;
2114
+ var TSC_ERROR = /\berror TS\d+/;
2115
+ var TSC_CONTINUATION = /^\s{2,}\S/;
2116
+ var TSC_FRAME = /^\s*[~^|]/;
2117
+ var TSC_SUMMARY = /^Found \d+ errors?/;
2118
+ var ESLINT_PROBLEM = /^\s+\d+:\d+\s+(?:error|warning)\s/;
2119
+ var ESLINT_SUMMARY = /^(?:\u2716 )?\d+ problems? \(/;
2120
+ var PHPSTAN_TABLE = /^\s*-{3,} -{3,}/;
2121
+ var PHPSTAN_NOISE = /^\s*\[OK\]/;
2122
+ var PHP_FAILURES = /^(?:There w(?:as|ere) \d+ (?:failure|error|risky|warning)|\s+(?:FAIL|FAILED)\s+\S|In \S+\.php line \d+:$)/;
2123
+ var VITEST_FAIL_LINE = /^ FAIL {2}\S/;
2124
+ var PLAYWRIGHT_FAIL_LINE = /^ {2}1\) .+:\d+:\d+ \u203A .+ \u2500+$/;
2125
+ var CS_FIXER_LINE = /^\s+\d+\) \S.*\.php(?: \(.+\))?$/;
2126
+ var CS_FIXER_TOTAL = /^Found \d+ of \d+ files/;
2127
+ var MAX_TESTS = 10;
2128
+ var MAX_LINES = 100;
2129
+ var TAIL = 30;
2130
+ var bunTest = (lines) => {
2131
+ const seen = new Set;
2132
+ const blocks = [];
2133
+ for (const [index, line] of lines.entries()) {
2134
+ const name = line.replace(DURATION2, "");
2135
+ if (!line.startsWith("(fail) ") || seen.has(name))
2136
+ continue;
2137
+ seen.add(name);
2138
+ if (blocks.length < MAX_TESTS)
2139
+ blocks.push(lines.slice(lines.findLastIndex((text, at) => at < index && BOUNDARY.test(text)) + 1, index + 1).join(`
2140
+ `).trim());
2141
+ }
2142
+ if (blocks.length === 0)
2143
+ return;
2144
+ if (seen.size > MAX_TESTS)
2145
+ blocks.push(`and ${seen.size - MAX_TESTS} more failed tests`);
2146
+ return [...blocks.join(`
2147
+
2148
+ `).split(`
2149
+ `), "", ...lines.filter((line) => BUN_TEST_SUMMARY.test(line)).map((line) => line.trim())];
2150
+ };
2151
+ var bunCheck = (lines) => {
2152
+ const text = lines.join(`
2153
+ `);
2154
+ const blocks = text.match(BUN_CHECK_BLOCK);
2155
+ if (blocks === null)
2156
+ return;
2157
+ const errors = blocks.map((block) => {
2158
+ const { file, line, column, code, message } = bunCheckFields(block);
2159
+ return `${file}:${line}:${column} ${code}: ${message}`;
2160
+ });
2161
+ return [...errors, ...lines.filter((line) => BUN_CHECK_SUMMARY.test(line))];
2162
+ };
2163
+ function bunCheckFields(block) {
2164
+ const attributes = Object.fromEntries([...block.slice(0, block.indexOf(`
2165
+ `)).matchAll(BUN_CHECK_ATTRIBUTE)].map((match) => [match[1] ?? "", match[2] ?? ""]));
2166
+ return {
2167
+ file: attributes.file ?? "",
2168
+ line: attributes.line ?? "",
2169
+ column: attributes.column ?? "",
2170
+ code: attributes.code ?? "",
2171
+ message: block.replace(BUN_CHECK_SOURCE, "").split(`
2172
+ `).slice(1, -1).join(`
2173
+ `).trim()
2174
+ };
1794
2175
  }
1795
- function press(state, key) {
1796
- if (state.done !== undefined)
1797
- return state;
1798
- if (state.chained && endsKills(key))
1799
- state = { ...state, chained: false };
1800
- if (state.help)
1801
- return { ...state, help: false };
1802
- if (typeof key === "object") {
1803
- if ("text" in key)
1804
- return withQuery(state, key);
1805
- return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
2176
+ var tsc = (lines) => {
2177
+ const kept = [];
2178
+ let inError = false;
2179
+ for (const line of lines) {
2180
+ if (TSC_ERROR.test(line)) {
2181
+ inError = true;
2182
+ kept.push(line);
2183
+ } else if (TSC_SUMMARY.test(line)) {
2184
+ inError = false;
2185
+ kept.push(line);
2186
+ } else if (inError && TSC_CONTINUATION.test(line) && !TSC_FRAME.test(line)) {
2187
+ kept.push(line);
2188
+ } else {
2189
+ inError = false;
2190
+ }
1806
2191
  }
1807
- if (isEditKey(key))
1808
- return withQuery(state, key);
1809
- switch (key) {
1810
- case "up":
1811
- return move(state, -1);
1812
- case "down":
1813
- return move(state, 1);
1814
- case "pageup":
1815
- return move(state, -state.page);
1816
- case "pagedown":
1817
- return move(state, state.page);
1818
- case "home":
1819
- return move(state, -state.matches.length);
1820
- case "end":
1821
- return move(state, state.matches.length);
1822
- case "cancel":
1823
- return { ...state, done: "cancel" };
1824
- case "help":
1825
- return { ...state, help: true };
1826
- case "suspend":
1827
- return state;
1828
- case "enter":
1829
- return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1830
- case "tab": {
1831
- const at = highlighted(state);
1832
- if (!state.multi || at === undefined)
1833
- return state;
1834
- const marked = new Set(state.marked);
1835
- if (!marked.delete(at))
1836
- marked.add(at);
1837
- return move({ ...state, marked }, 1);
2192
+ return kept.some((line) => TSC_ERROR.test(line)) ? kept : undefined;
2193
+ };
2194
+ var eslint = (lines) => {
2195
+ const kept = [];
2196
+ let file = "";
2197
+ let shown = "";
2198
+ for (const line of lines) {
2199
+ if (ESLINT_PROBLEM.test(line)) {
2200
+ if (file !== shown) {
2201
+ kept.push(file);
2202
+ shown = file;
2203
+ }
2204
+ kept.push(line);
2205
+ } else if (ESLINT_SUMMARY.test(line)) {
2206
+ kept.push(line);
2207
+ } else if (line.trim() !== "") {
2208
+ file = line;
1838
2209
  }
1839
2210
  }
2211
+ return kept.some((line) => ESLINT_PROBLEM.test(line)) ? kept : undefined;
2212
+ };
2213
+ var phpstan = (lines) => {
2214
+ const start = lines.findIndex((line) => PHPSTAN_TABLE.test(line));
2215
+ return start === -1 ? undefined : lines.slice(start).filter((line) => !PHPSTAN_NOISE.test(line));
2216
+ };
2217
+ var php = (lines) => {
2218
+ const start = lines.findIndex((line) => PHP_FAILURES.test(line));
2219
+ return start === -1 ? undefined : lines.slice(start);
2220
+ };
2221
+ var vitest = (lines) => {
2222
+ const start = lines.findIndex((line) => VITEST_FAIL_LINE.test(line));
2223
+ return start === -1 ? undefined : lines.slice(start);
2224
+ };
2225
+ var playwright = (lines) => {
2226
+ const start = lines.findIndex((line) => PLAYWRIGHT_FAIL_LINE.test(line));
2227
+ return start === -1 ? undefined : lines.slice(start);
2228
+ };
2229
+ var phpCsFixer = (lines) => {
2230
+ const files = lines.filter((line) => CS_FIXER_LINE.test(line) || CS_FIXER_TOTAL.test(line));
2231
+ return files.some((line) => CS_FIXER_LINE.test(line)) ? files : undefined;
2232
+ };
2233
+ var PARSERS = [bunTest, bunCheck, tsc, eslint, vitest, playwright, phpCsFixer, phpstan, php];
2234
+ function squeeze(lines) {
2235
+ const out = [];
2236
+ for (const line of lines.map((text) => text.trimEnd())) {
2237
+ if (line !== "" || out.at(-1) !== "")
2238
+ out.push(line);
2239
+ }
2240
+ while (out.at(-1) === "")
2241
+ out.pop();
2242
+ return out;
1840
2243
  }
1841
- function chosen(state) {
1842
- if (state.marked.size > 0)
1843
- return state.rows.filter((_, index) => state.marked.has(index));
1844
- const at = highlighted(state);
1845
- return at === undefined ? [] : [state.rows[at]];
2244
+ function cut(shown) {
2245
+ return shown.length > MAX_LINES ? [...shown.slice(0, MAX_LINES), `... ${shown.length - MAX_LINES} more lines`].join(`
2246
+ `) : shown.join(`
2247
+ `);
2248
+ }
2249
+ function recognised(lines, parsers) {
2250
+ return parsers.map((parser) => parser(lines)).find((result) => result !== undefined && result.some((line) => line.trim() !== ""));
2251
+ }
2252
+ function failureExcerpt(output) {
2253
+ const lines = stripAnsi(output).split(`
2254
+ `);
2255
+ if (BASH_ECHO.test(lines[0] ?? ""))
2256
+ lines.shift();
2257
+ return cut(squeeze(recognised(lines, PARSERS) ?? lines.slice(-TAIL)));
1846
2258
  }
2259
+ var LOG_PATTERNS = { BASH_ECHO, DURATION: DURATION2, BOUNDARY, BUN_TEST_SUMMARY, BUN_CHECK_SUMMARY, TSC_CONTINUATION, TSC_FRAME, TSC_SUMMARY, ESLINT_PROBLEM, ESLINT_SUMMARY };
2260
+
2261
+ // ../kit/src/index.ts
2262
+ init_folders();
2263
+ init_format();
2264
+
2265
+ // ../kit/src/git.ts
2266
+ init_args();
2267
+ // ../kit/src/limit.ts
2268
+ init_args();
2269
+
2270
+ // ../kit/src/index.ts
2271
+ init_mode();
2272
+
2273
+ // ../kit/src/report.ts
2274
+ init_style();
2275
+ init_text2();
2276
+ // ../kit/src/secrets.ts
2277
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
2278
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
2279
+ // ../kit/src/sessions.ts
2280
+ var {Glob } = globalThis.Bun;
2281
+ var SESSION_FILES = new Glob("*.json");
2282
+ var ACCOUNT_DIRS = new Glob("*/sessions");
2283
+
2284
+ // ../kit/src/index.ts
2285
+ init_style();
2286
+ init_text2();
2287
+ init_theme();
2288
+ init_user_config();
2289
+
2290
+ // ../kit/src/watch.ts
2291
+ init_args();
2292
+ init_input();
2293
+ init_style();
2294
+ // ../kit/src/workspace-root.ts
2295
+ init_user_config();
2296
+ // package.json
2297
+ var version = "0.21.2";
2298
+
2299
+ // src/j.ts
2300
+ import process26 from "process";
2301
+
2302
+ // ../kit/src/picker.ts
2303
+ init_folders();
2304
+ init_state();
2305
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync6, writeFileSync } from "fs";
2306
+ import { dirname as dirname4, join as join8 } from "path";
2307
+ import process23 from "process";
1847
2308
 
1848
2309
  // ../kit/src/picker/terminal.ts
2310
+ init_args();
2311
+ init_job();
2312
+ init_redraw();
2313
+ init_style();
1849
2314
  import { openSync as openSync2 } from "fs";
1850
- import process21 from "process";
2315
+ import process22 from "process";
1851
2316
  import tty from "tty";
1852
2317
 
1853
- // ../kit/src/job.ts
1854
- import process19 from "process";
1855
- function stopJob() {
1856
- process19.kill(0, "SIGTSTP");
1857
- }
1858
-
1859
- // ../kit/src/redraw.ts
1860
- var SYNC_START = "\x1B[?2026h";
1861
- var SYNC_END = "\x1B[?2026l";
1862
- function overwrite(lines, columns) {
1863
- return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1864
- `);
1865
- }
1866
- function rowsTaken(lines, columns) {
1867
- return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1868
- }
1869
-
1870
2318
  // ../kit/src/picker/preview.ts
1871
- import process20 from "process";
2319
+ import process21 from "process";
1872
2320
 
1873
2321
  // ../kit/src/shell.ts
1874
2322
  var SEPARATORS = new Set([`
@@ -1879,6 +2327,7 @@ var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
1879
2327
  var SAFE_WORD = /^[\w@%+=:,./-]+$/;
1880
2328
  var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
1881
2329
  var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
2330
+ var FISH_COMBINERS = new Set(["and", "or", "not"]);
1882
2331
  var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
1883
2332
  var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
1884
2333
  var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
@@ -1890,6 +2339,7 @@ var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
1890
2339
  function wrapper(short = "", long = [], operands = 0, runsString = false) {
1891
2340
  return { short, long, operands, runsString };
1892
2341
  }
2342
+ var RUNNER = { ...wrapper(), afterDashes: true };
1893
2343
  var WRAPPERS = new Map([
1894
2344
  ["command", wrapper()],
1895
2345
  ["builtin", wrapper()],
@@ -1911,7 +2361,23 @@ var WRAPPERS = new Map([
1911
2361
  ["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
1912
2362
  ["unbuffer", wrapper()],
1913
2363
  ["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
1914
- ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
2364
+ ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])],
2365
+ ["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"])],
2366
+ ["ltrace", wrapper("aeFlnopsuxX", ["--output", "--user", "--library", "--config", "--align", "--indent"])],
2367
+ ["taskset", wrapper("", [], 1)],
2368
+ ["fakeroot", wrapper("lsib", ["--lib", "--faked"])],
2369
+ ["sshpass", wrapper("pfdP")],
2370
+ ["coproc", wrapper()],
2371
+ ["proxychains", wrapper("f")],
2372
+ ["proxychains4", wrapper("f")],
2373
+ ["torsocks", wrapper("upaP", ["--user", "--pass", "--address", "--port"])],
2374
+ ["chrt", wrapper("TPD", ["--sched-runtime", "--sched-period", "--sched-deadline"], 1)],
2375
+ ["unshare", wrapper("SGRw", ["--setuid", "--setgid", "--root", "--wd", "--map-user", "--map-group", "--map-users", "--map-groups", "--propagation", "--setgroups"])],
2376
+ ["nsenter", wrapper("tSG", ["--target", "--setuid", "--setgid"])],
2377
+ ["out", RUNNER],
2378
+ ["slot", RUNNER],
2379
+ ["waitfor", RUNNER],
2380
+ ["base", RUNNER]
1915
2381
  ]);
1916
2382
  function shellQuote(word) {
1917
2383
  return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
@@ -1937,7 +2403,7 @@ async function runPreview(template, line, signal, hidden = []) {
1937
2403
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1938
2404
  const stop = () => {
1939
2405
  try {
1940
- process20.kill(-proc.pid, "SIGKILL");
2406
+ process21.kill(-proc.pid, "SIGKILL");
1941
2407
  } catch {
1942
2408
  proc.kill();
1943
2409
  }
@@ -1962,7 +2428,12 @@ ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe",
1962
2428
  return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
1963
2429
  }
1964
2430
 
2431
+ // ../kit/src/picker/terminal.ts
2432
+ init_state();
2433
+
1965
2434
  // ../kit/src/picker/view.ts
2435
+ init_line();
2436
+ init_state();
1966
2437
  var MIN_HEIGHT = 4;
1967
2438
  var PREVIEW_MIN_COLUMNS = 80;
1968
2439
  var PREVIEW_MIN_ROWS = 10;
@@ -2095,7 +2566,7 @@ function openTerminal() {
2095
2566
  return fail("no terminal to read keys from (/dev/tty)");
2096
2567
  }
2097
2568
  const keys = Bun.file("/dev/tty").stream().getReader();
2098
- const out = process21.stderr;
2569
+ const out = process22.stderr;
2099
2570
  let resize;
2100
2571
  async function read(onChunk) {
2101
2572
  const decoder = new TextDecoder;
@@ -2284,9 +2755,9 @@ async function select(rows, settings, terminal = openTerminal()) {
2284
2755
  const ended = new Promise((resolve) => {
2285
2756
  finish = resolve;
2286
2757
  });
2287
- process21.once("exit", restore);
2758
+ process22.once("exit", restore);
2288
2759
  for (const signal of SIGNALS2)
2289
- process21.once(signal, stop);
2760
+ process22.once(signal, stop);
2290
2761
  try {
2291
2762
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
2292
2763
  terminal.listen(onChunk, () => draw(true));
@@ -2299,8 +2770,8 @@ async function select(rows, settings, terminal = openTerminal()) {
2299
2770
  await ended;
2300
2771
  } finally {
2301
2772
  for (const signal of SIGNALS2)
2302
- process21.off(signal, stop);
2303
- process21.off("exit", restore);
2773
+ process22.off(signal, stop);
2774
+ process22.off("exit", restore);
2304
2775
  restore();
2305
2776
  }
2306
2777
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -2314,6 +2785,7 @@ async function previewOf(preview, hidden, signal) {
2314
2785
  }
2315
2786
 
2316
2787
  // ../kit/src/picker.ts
2788
+ init_score();
2317
2789
  var REMEMBERED = 20;
2318
2790
  async function pick(rows, options) {
2319
2791
  const height = parseHeight(options.height ?? "100%");
@@ -2336,18 +2808,18 @@ function historyFile(name) {
2336
2808
  function history(name) {
2337
2809
  try {
2338
2810
  const file = historyFile(name);
2339
- return existsSync4(file) ? JSON.parse(readFileSync5(file, "utf-8")) : {};
2811
+ return existsSync4(file) ? JSON.parse(readFileSync6(file, "utf-8")) : {};
2340
2812
  } catch {
2341
2813
  return {};
2342
2814
  }
2343
2815
  }
2344
2816
  function runs(name) {
2345
- return history(name)[process22.cwd()] ?? [];
2817
+ return history(name)[process23.cwd()] ?? [];
2346
2818
  }
2347
2819
  function record(name, run) {
2348
2820
  const all = history(name);
2349
2821
  const file = historyFile(name);
2350
- all[process22.cwd()] = [run, ...(all[process22.cwd()] ?? []).filter((earlier) => earlier.id !== run.id)].slice(0, REMEMBERED);
2822
+ all[process23.cwd()] = [run, ...(all[process23.cwd()] ?? []).filter((earlier) => earlier.id !== run.id)].slice(0, REMEMBERED);
2351
2823
  mkdirSync2(dirname4(file), { recursive: true });
2352
2824
  writeFileSync(file, JSON.stringify(all));
2353
2825
  }
@@ -2370,203 +2842,14 @@ function list(rows) {
2370
2842
  console.log(JSON.stringify(rows));
2371
2843
  }
2372
2844
 
2373
- // ../kit/src/prompt.ts
2374
- import process23 from "process";
2375
-
2376
- // ../kit/src/answers.ts
2377
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "fs";
2378
- import { dirname as dirname5, join as join9 } from "path";
2379
- var KEPT = 50;
2380
- function answersFile() {
2381
- return join9(cacheFolder(), "kaynooo-cli", "answers.json");
2382
- }
2383
- function stored() {
2384
- try {
2385
- const parsed = JSON.parse(readFileSync6(answersFile(), "utf-8"));
2386
- if (typeof parsed !== "object" || parsed === null)
2387
- return {};
2388
- return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
2389
- } catch {
2390
- return {};
2391
- }
2392
- }
2393
- function earlierAnswers(key) {
2394
- return stored()[key] ?? [];
2395
- }
2396
- function rememberAnswer(key, answer) {
2397
- const all = stored();
2398
- const file = answersFile();
2399
- all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
2400
- try {
2401
- mkdirSync3(dirname5(file), { recursive: true });
2402
- writeFileSync2(file, JSON.stringify(all));
2403
- } catch {}
2404
- }
2405
-
2406
- // ../kit/src/prompt.ts
2407
- var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
2408
- var MAX_LISTED = 12;
2409
- function readKeys(input, paste = { active: false }) {
2410
- return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
2411
- }
2412
- function roomAfter(question, columns) {
2413
- return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
2414
- }
2415
- function withCaret(colors, line, room, dim = false) {
2416
- const { before, at, after } = visible(line, room);
2417
- const tone = dim ? colors.dim : (text) => text;
2418
- return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
2419
- }
2420
- function sharedStart(texts) {
2421
- const [first = [], ...rest] = texts.map((text) => [...text]);
2422
- let length = first.length;
2423
- for (const chars of rest) {
2424
- const differs = chars.findIndex((char, index) => char !== first[index]);
2425
- length = Math.min(length, differs === -1 ? chars.length : differs);
2426
- }
2427
- return first.slice(0, length).join("");
2428
- }
2429
- function listed2(colors, found, columns) {
2430
- const shared = sharedStart(found);
2431
- const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
2432
- const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
2433
- const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
2434
- return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
2435
- }
2436
- async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
2437
- let line = { text: "", caret: 0 };
2438
- let invalid;
2439
- let completions = [];
2440
- const remembered = history === undefined || mask ? undefined : history;
2441
- const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
2442
- let recalled = -1;
2443
- let draft = line;
2444
- const taken = () => line.text === "" ? fallback ?? "" : line.text;
2445
- const shown = () => mask ? "*".repeat([...taken()].length) : taken();
2446
- const accepted = await ask(question, settings, (colors, state, { columns }) => {
2447
- if (state !== "asking")
2448
- return [answer(colors, question, state, shown())];
2449
- const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
2450
- return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
2451
- }, (key) => {
2452
- if (key === "cancel")
2453
- return "cancel";
2454
- invalid = undefined;
2455
- completions = [];
2456
- if (line.chained === true && endsKills(key))
2457
- line = { ...line, chained: false };
2458
- if (key === "tab") {
2459
- const chars = [...line.text];
2460
- const before = chars.slice(0, line.caret).join("");
2461
- const found = complete?.(before) ?? [];
2462
- const filled = sharedStart(found);
2463
- if ([...filled].length > [...before].length)
2464
- line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
2465
- else
2466
- completions = found;
2467
- return;
2468
- }
2469
- if (key === "enter") {
2470
- invalid = validate?.(taken());
2471
- return invalid === undefined ? "enter" : undefined;
2472
- }
2473
- if (key === "up" || key === "down") {
2474
- const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
2475
- if (recalled === -1)
2476
- draft = line;
2477
- recalled = to;
2478
- const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
2479
- line = { ...shown, killed: line.killed ?? "" };
2480
- return;
2481
- }
2482
- const edit = { home: "linestart", end: "lineend" }[key] ?? key;
2483
- if (typeof edit === "object" || isEditKey(edit))
2484
- line = editLine(line, edit);
2485
- return;
2486
- });
2487
- if (!accepted)
2488
- return;
2489
- if (remembered !== undefined && taken() !== "")
2490
- rememberAnswer(remembered, taken());
2491
- return taken();
2492
- }
2493
- function answer(colors, question, state, picked) {
2494
- return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
2495
- }
2496
- async function ask(question, { hint, terminal = process23 }, render, press) {
2497
- const { stdin, stderr } = terminal;
2498
- if (!isInteractive(terminal))
2499
- fail(`cannot ask "${question}" off a terminal`, 2, hint);
2500
- const colors = paint(stderr);
2501
- let current = "asking";
2502
- let outcome;
2503
- const columns = () => stderr.columns || 80;
2504
- const draw = (state, last = false) => {
2505
- const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
2506
- const rows = rowsTaken(frame, columns());
2507
- stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
2508
- current = state;
2509
- };
2510
- const redraw = () => draw(current);
2511
- const paste = { active: false };
2512
- const stop = terminal.stop ?? (terminal === process23 ? stopJob : undefined);
2513
- const suspend = () => {
2514
- if (stop === undefined)
2515
- return;
2516
- stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
2517
- stdin.setRawMode(false);
2518
- stop();
2519
- stdin.setRawMode(true);
2520
- stderr.write("\x1B[?25l\x1B[?2004h");
2521
- };
2522
- try {
2523
- stderr.on?.("resize", redraw);
2524
- stdin.setRawMode(true);
2525
- stdin.resume();
2526
- stderr.write("\x1B[?25l\x1B[?2004h");
2527
- draw("asking");
2528
- return await new Promise((resolve) => {
2529
- function onData(data) {
2530
- for (const key of readKeys(data.toString(), paste)) {
2531
- if (key === "suspend") {
2532
- suspend();
2533
- continue;
2534
- }
2535
- const pressed = press(key);
2536
- if (pressed !== undefined) {
2537
- settle(pressed);
2538
- return;
2539
- }
2540
- }
2541
- draw("asking");
2542
- }
2543
- function onEnd() {
2544
- settle("cancel");
2545
- }
2546
- function settle(settled) {
2547
- outcome = settled;
2548
- stdin.off("data", onData);
2549
- stdin.off("end", onEnd);
2550
- resolve(settled === "enter");
2551
- }
2552
- stdin.on("data", onData);
2553
- stdin.on("end", onEnd);
2554
- });
2555
- } finally {
2556
- stderr.off?.("resize", redraw);
2557
- draw(outcome ?? "cancel", true);
2558
- stderr.write(`
2559
- \x1B[?25h\x1B[?2004l`);
2560
- stdin.setRawMode(false);
2561
- stdin.pause();
2562
- }
2563
- }
2845
+ // src/j.ts
2846
+ init_prompt();
2564
2847
 
2565
2848
  // src/job-picker.ts
2566
- import process24 from "process";
2849
+ import process25 from "process";
2567
2850
 
2568
2851
  // src/jobs.ts
2569
- import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync7 } from "fs";
2852
+ import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync8 } from "fs";
2570
2853
  import { dirname as dirname6, join as join11, resolve as resolvePath } from "path";
2571
2854
 
2572
2855
  // src/steps.ts
@@ -2822,7 +3105,7 @@ function make(dir) {
2822
3105
  const file = MAKEFILES.find((name) => existsSync5(join11(dir, name)));
2823
3106
  if (file === undefined)
2824
3107
  return [];
2825
- const source = readFileSync7(join11(dir, file), "utf-8");
3108
+ const source = readFileSync8(join11(dir, file), "utf-8");
2826
3109
  return build({ kind: "make", tag: "make", runner: ["make"], separated: false, dir }, targets2(source).map((target) => ({ ...target, body: show(source, target.name) })));
2827
3110
  }
2828
3111
  function manager(dir, manifest) {
@@ -2845,7 +3128,7 @@ function packageScripts(dir, here) {
2845
3128
  const file = locate(dir, here, ["package.json"]);
2846
3129
  if (file === undefined)
2847
3130
  return [];
2848
- const manifest = JSON.parse(readFileSync7(file, "utf-8"));
3131
+ const manifest = JSON.parse(readFileSync8(file, "utf-8"));
2849
3132
  const tool = manager(dirname6(file), manifest);
2850
3133
  const items = Object.entries(table2(manifest.scripts)).map(([name, command]) => ({ name, body: text2(command) }));
2851
3134
  return build({ kind: "package", tag: tool, runner: [tool, "run"], separated: tool === "npm", dir: dirname6(file) }, items);
@@ -2854,7 +3137,7 @@ function composer(dir, here) {
2854
3137
  const file = locate(dir, here, ["composer.json"]);
2855
3138
  if (file === undefined)
2856
3139
  return [];
2857
- const manifest = JSON.parse(readFileSync7(file, "utf-8"));
3140
+ const manifest = JSON.parse(readFileSync8(file, "utf-8"));
2858
3141
  const descriptions = table2(manifest["scripts-descriptions"]);
2859
3142
  const items = Object.entries(table2(manifest.scripts)).map(([name, command]) => ({ name, doc: field(descriptions, name), body: text2(command) }));
2860
3143
  return build({ kind: "composer", tag: "composer", runner: ["composer", "run"], separated: true, dir: dirname6(file) }, items);
@@ -2863,7 +3146,7 @@ function deno(dir, here) {
2863
3146
  const file = locate(dir, here, ["deno.json", "deno.jsonc"]);
2864
3147
  if (file === undefined)
2865
3148
  return [];
2866
- const manifest = Bun.JSONC.parse(readFileSync7(file, "utf-8"));
3149
+ const manifest = Bun.JSONC.parse(readFileSync8(file, "utf-8"));
2867
3150
  const items = Object.entries(table2(manifest.tasks)).map(([name, task]) => ({ name, doc: field(task, "description"), body: field(task, "command") ?? text2(task) }));
2868
3151
  return build({ kind: "deno", tag: "deno", runner: ["deno", "task"], separated: false, dir: dirname6(file) }, items);
2869
3152
  }
@@ -2871,7 +3154,7 @@ function taskfile(dir, here) {
2871
3154
  const file = locate(dir, here, TASKFILES);
2872
3155
  if (file === undefined)
2873
3156
  return [];
2874
- const tasks = table2(Bun.YAML.parse(readFileSync7(file, "utf-8"))?.tasks);
3157
+ const tasks = table2(Bun.YAML.parse(readFileSync8(file, "utf-8"))?.tasks);
2875
3158
  const items = Object.entries(tasks).filter(([, task]) => !(task !== null && typeof task === "object" && task.internal === true)).map(([name, task]) => ({ name, doc: field(task, "desc") ?? field(task, "summary"), body: text2(task) }));
2876
3159
  return build({ kind: "task", tag: "task", runner: ["task"], separated: true, dir: dirname6(file) }, items);
2877
3160
  }
@@ -2890,7 +3173,7 @@ function pyproject(dir, here) {
2890
3173
  const file = locate(dir, here, ["pyproject.toml"]);
2891
3174
  if (file === undefined)
2892
3175
  return [];
2893
- const manifest = Bun.TOML.parse(readFileSync7(file, "utf-8"));
3176
+ const manifest = Bun.TOML.parse(readFileSync8(file, "utf-8"));
2894
3177
  const tool = table2(manifest.tool);
2895
3178
  const project = table2(manifest.project);
2896
3179
  const uv = locate(dirname6(file), true, ["uv.lock"]) !== undefined;
@@ -2922,9 +3205,9 @@ function readOr(read, fallback) {
2922
3205
  }
2923
3206
  }
2924
3207
  function workspaces() {
2925
- const manifest = readOr(() => JSON.parse(readFileSync7("package.json", "utf-8")), {});
3208
+ const manifest = readOr(() => JSON.parse(readFileSync8("package.json", "utf-8")), {});
2926
3209
  const declared = Array.isArray(manifest.workspaces) ? manifest.workspaces : table2(manifest.workspaces).packages;
2927
- const pnpm = readOr(() => table2(Bun.YAML.parse(readFileSync7("pnpm-workspace.yaml", "utf-8"))).packages, undefined);
3210
+ const pnpm = readOr(() => table2(Bun.YAML.parse(readFileSync8("pnpm-workspace.yaml", "utf-8"))).packages, undefined);
2928
3211
  const patterns = [declared, pnpm].flatMap((value) => Array.isArray(value) ? value.filter((pattern) => typeof pattern === "string") : []);
2929
3212
  const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => new Bun.Glob(pattern.slice(1)));
2930
3213
  return patterns.filter((pattern) => !pattern.startsWith("!")).flatMap((pattern) => [...new Bun.Glob(`${pattern.replace(TRAILING_SLASHES, "")}/package.json`).scanSync({ cwd: "." })].map((file) => dirname6(file))).filter((dir) => !dir.split("/").includes("node_modules") && !excluded.some((glob) => glob.match(dir)));
@@ -2983,7 +3266,7 @@ function labelled(entries) {
2983
3266
  return new Set(entries.map((entry) => entry.tag)).size > 1;
2984
3267
  }
2985
3268
  function row(entry, labels, signed) {
2986
- const colors = paint(process24.stderr);
3269
+ const colors = paint(process25.stderr);
2987
3270
  const keyed = entry.dir === "." ? entry.name : `${colors.dim(`${entry.dir}/`)}${entry.name}`;
2988
3271
  return {
2989
3272
  hidden: [entry.kind, entry.dir, entry.name, id(entry)],
@@ -2997,7 +3280,7 @@ async function pickJob(entries, narrowed = false) {
2997
3280
  prompt: `${[...new Set(entries.map((entry) => entry.tag))].join("/")}> `,
2998
3281
  searched: labels ? 2 : 1,
2999
3282
  ...narrowed ? { height: heightFor(entries.length) } : {},
3000
- preview: `${process24.execPath} ${process24.argv[1]} --show {1} {2} {3}`
3283
+ preview: `${process25.execPath} ${process25.argv[1]} --show {1} {2} {3}`
3001
3284
  });
3002
3285
  return entries.find((candidate) => id(candidate) === picked?.hidden[3]);
3003
3286
  }
@@ -3006,10 +3289,9 @@ async function pickJob(entries, narrowed = false) {
3006
3289
  var usage2 = `j [name] [args...]
3007
3290
  j -
3008
3291
 
3009
- Without a name, picks a recipe, target, script or task of this folder, its parents and its child folders when a terminal is attached, and runs it. The ones run last come first, per folder. Without a terminal it lists them instead.
3010
- \`j -\` runs the last one again with the same arguments, \`j <name> [args...]\` runs without the picker, the words after the name filling the parameters in order and the required ones left being asked for.
3011
- The sources are a Justfile, a Makefile, the scripts of a package.json (through its package manager), composer.json scripts, deno tasks, a Taskfile, mise tasks and a pyproject (poe tasks and entry points).
3012
- A name is the key behind the folder it runs from, \`api/test\`, bare for this folder. A name several entries share offers them, unless it comes qualified by its runner: \`just:check\`, \`bun:api/test\`.`;
3292
+ Without a name, picks a recipe, script or task of this folder, its parents and its child folders and runs it, the ones run last first; without a terminal it lists them instead.
3293
+ \`j -\` runs the last one again with the same arguments, \`j <name> [args...]\` runs without the picker, the words after the name filling the parameters in order.
3294
+ The sources are a Justfile, a Makefile, package.json and composer.json scripts, deno tasks, a Taskfile, mise tasks and a pyproject; a name several share offers them, unless qualified by its runner (\`just:check\`).`;
3013
3295
  var EXITS = [["its own", "the code of the command it ran"], [1, "there is nothing to run here or nothing by that name"]];
3014
3296
  var options = {
3015
3297
  json: jsonOption("[{ id, key, runner, dir, name, doc, parameters }]")
@@ -3018,7 +3300,7 @@ function preview(kind, dir, name) {
3018
3300
  const entry = readKind(kind, dir).find((candidate) => candidate.name === name);
3019
3301
  if (entry === undefined)
3020
3302
  return;
3021
- const colors = paint(process25.stdout);
3303
+ const colors = paint(process26.stdout);
3022
3304
  console.log(`${colors.dim(`$ ${dir === "." ? "" : `env -C ${dir} `}`)}${colors.bold([...entry.runner, entry.name].join(" "))}
3023
3305
  `);
3024
3306
  if (entry.body !== undefined)
@@ -3051,7 +3333,7 @@ function listed3(found) {
3051
3333
  }));
3052
3334
  }
3053
3335
  function listing(found) {
3054
- const colors = paint(process25.stdout);
3336
+ const colors = paint(process26.stdout);
3055
3337
  const labels = labelled(found);
3056
3338
  return table(found.map((entry) => [...labels ? [entry.tag] : [], key(entry), signature(entry), colors.dim(entry.doc ?? "")]));
3057
3339
  }
@@ -3152,4 +3434,4 @@ async function j2(argv) {
3152
3434
  }
3153
3435
 
3154
3436
  // src/j-cli.ts
3155
- process26.exitCode = await runMain({ name: "j", version, run: j2 });
3437
+ process27.exitCode = await runMain({ name: "j", version, run: j2 });