@kaynooo/cli-dev 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +3 -3
  2. package/dist/cli.js +1128 -833
  3. package/package.json +5 -5
package/dist/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/cli.ts
5
- import process15 from "process";
6
- // ../kit/src/args.ts
7
- import process6 from "process";
8
- import { parseArgs } from "util";
9
-
10
- // ../kit/src/format.ts
11
- import process4 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 process3 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,32 +109,66 @@ 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
+ });
122
+
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
+ });
127
+
128
+ // ../kit/src/config.ts
129
+ var init_config = __esm(() => {
130
+ init_args();
131
+ });
132
+
133
+ // ../kit/src/user-config.ts
134
+ var init_user_config = () => {};
109
135
 
110
136
  // ../kit/src/theme.ts
111
- var ENDS = new Map;
112
- 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"]);
113
- var MAX_FILE_BYTES = 64 * 1024;
114
- var warned = new Set;
137
+ var ENDS, STYLES, MAX_FILE_BYTES, warned;
138
+ var init_theme = __esm(() => {
139
+ init_config();
140
+ init_user_config();
141
+ ENDS = new Map;
142
+ 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"]);
143
+ MAX_FILE_BYTES = 64 * 1024;
144
+ warned = new Set;
145
+ });
115
146
 
116
147
  // ../kit/src/style.ts
148
+ import process3 from "process";
117
149
  function takesControlCodes(stream, env = process3.env) {
118
150
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
119
151
  }
120
152
  function paint(stream, env = process3.env) {
121
153
  return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
122
154
  }
123
- var STATUS_WORDS = {
124
- passed: ["passed", "success", "succeeded", "ok"],
125
- failed: ["failed", "failure", "error", "errored"],
126
- running: ["running", "in_progress", "started", "holding"],
127
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
128
- skipped: ["skipped", "cancelled", "canceled", "manual"]
129
- };
130
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
155
+ var STATUS_WORDS, STATUS_OF;
156
+ var init_style = __esm(() => {
157
+ init_colors();
158
+ init_mode();
159
+ init_theme();
160
+ STATUS_WORDS = {
161
+ passed: ["passed", "success", "succeeded", "ok"],
162
+ failed: ["failed", "failure", "error", "errored"],
163
+ running: ["running", "in_progress", "started", "holding"],
164
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
165
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
166
+ };
167
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
168
+ });
131
169
 
132
170
  // ../kit/src/format.ts
133
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
171
+ import process4 from "process";
134
172
  function formatSeconds(total) {
135
173
  let rest = Math.max(0, Math.round(total));
136
174
  const amounts = UNITS.map(([unit, size]) => {
@@ -152,9 +190,8 @@ function upTo(text, separator) {
152
190
  return end === -1 ? text : text.slice(0, end);
153
191
  }
154
192
  function truncate(text, width) {
155
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
193
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
156
194
  }
157
- var ESCAPE = String.fromCharCode(27);
158
195
  function textWidth(text) {
159
196
  return Bun.stringWidth(text);
160
197
  }
@@ -164,12 +201,17 @@ function jsonText(value, replacer, { stream = process4.stdout, env = process4.en
164
201
  function printJson(value) {
165
202
  console.log(jsonText(value));
166
203
  }
204
+ var UNITS, ESCAPE;
205
+ var init_format = __esm(() => {
206
+ init_text();
207
+ init_mode();
208
+ init_style();
209
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
210
+ ESCAPE = String.fromCharCode(27);
211
+ });
167
212
 
168
213
  // ../kit/src/help.ts
169
214
  import process5 from "process";
170
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
171
- var USAGE_PREFIX = /^usage:\s*/i;
172
- var FULL_STOP = /\.$/;
173
215
  function usageLine(usage, colors = paint(process5.stdout)) {
174
216
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
175
217
  }
@@ -206,7 +248,6 @@ function exampleRows(examples, colors = paint(process5.stdout)) {
206
248
  return [];
207
249
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
208
250
  }
209
- var MAX_INLINE_CHOICES = 24;
210
251
  function optionRows(options, colors = paint(process5.stdout)) {
211
252
  const rows = Object.entries(options).map(([name, option]) => {
212
253
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -221,6 +262,14 @@ function optionRows(options, colors = paint(process5.stdout)) {
221
262
  const width = Math.max(0, ...rows.map((row) => row.width));
222
263
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
223
264
  }
265
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, MAX_INLINE_CHOICES = 24;
266
+ var init_help = __esm(() => {
267
+ init_mode();
268
+ init_style();
269
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
270
+ USAGE_PREFIX = /^usage:\s*/i;
271
+ FULL_STOP = /\.$/;
272
+ });
224
273
 
225
274
  // ../kit/src/text.ts
226
275
  function distance(a, b) {
@@ -248,9 +297,10 @@ function closest(name, names) {
248
297
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
249
298
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
250
299
  }
300
+ var init_text2 = () => {};
301
+
251
302
  // ../kit/src/input.ts
252
303
  import { fstatSync } from "fs";
253
- var WHOLE = /^\d+$/;
254
304
  function wholeNumber(value, name, fallback, min = 1) {
255
305
  if (value === undefined)
256
306
  return fallback;
@@ -263,40 +313,28 @@ function isStdinPiped() {
263
313
  const stat = fstatSync(0);
264
314
  return stat.isFIFO() || stat.isFile();
265
315
  }
316
+ var WHOLE;
317
+ var init_input = __esm(() => {
318
+ init_args();
319
+ WHOLE = /^\d+$/;
320
+ });
266
321
 
267
322
  // ../kit/src/args.ts
268
- var DASHES = /^-+/;
323
+ import process6 from "process";
324
+ import { parseArgs } from "util";
269
325
  function jsonOption(holds) {
270
326
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
271
327
  }
272
- class Exit extends Error {
273
- code;
274
- hint;
275
- constructor(message, code, hint) {
276
- super(message);
277
- this.code = code;
278
- this.hint = hint;
279
- }
328
+ function copyOption(what) {
329
+ return { type: "boolean", description: `also copy ${what} to the clipboard` };
280
330
  }
281
331
  function fail(message, code = 2, hint) {
282
332
  throw new Exit(message, code, hint);
283
333
  }
284
-
285
- class UsageError extends Exit {
286
- constructor(message, hint) {
287
- super(message, 2, hint);
288
- }
289
- }
290
334
  function badUsage(message) {
291
335
  throw new UsageError(message);
292
336
  }
293
337
 
294
- class HelpShown extends Exit {
295
- constructor() {
296
- super("help shown", 0);
297
- }
298
- }
299
-
300
338
  class Completing {
301
339
  options;
302
340
  positionals;
@@ -307,11 +345,6 @@ class Completing {
307
345
  this.candidates = candidates;
308
346
  }
309
347
  }
310
- var completion = { active: false };
311
- var OUTPUT_OPTIONS = {
312
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
313
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
314
- };
315
348
  function applyOutput(color, plain, env = process6.env) {
316
349
  const when = plain === true ? "never" : color ?? "auto";
317
350
  if (when === "auto")
@@ -465,7 +498,6 @@ function parseError(error) {
465
498
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
466
499
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
467
500
  }
468
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
469
501
  function nearestOption(message, options, allowNegative) {
470
502
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
471
503
  if (typed === undefined)
@@ -481,832 +513,1095 @@ function nearestOption(message, options, allowNegative) {
481
513
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
482
514
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
483
515
  }
484
- // ../kit/src/argv.ts
485
- import { readFileSync, realpathSync } from "fs";
486
- import { resolve } from "path";
487
- import process7 from "process";
488
- function commandLine() {
489
- try {
490
- return readFileSync("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
491
- } catch {
492
- return;
493
- }
516
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
517
+ var init_args = __esm(() => {
518
+ init_format();
519
+ init_help();
520
+ init_text2();
521
+ init_help();
522
+ init_input();
523
+ DASHES = /^-+/;
524
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
525
+ Exit = class Exit extends Error {
526
+ code;
527
+ hint;
528
+ [EXIT] = true;
529
+ constructor(message, code, hint) {
530
+ super(message);
531
+ this.code = code;
532
+ this.hint = hint;
533
+ }
534
+ static [Symbol.hasInstance](value) {
535
+ if (this !== Exit)
536
+ return Function.prototype[Symbol.hasInstance].call(this, value);
537
+ return typeof value === "object" && value !== null && value[EXIT] === true;
538
+ }
539
+ };
540
+ UsageError = class UsageError extends Exit {
541
+ constructor(message, hint) {
542
+ super(message, 2, hint);
543
+ }
544
+ };
545
+ HelpShown = class HelpShown extends Exit {
546
+ constructor() {
547
+ super("help shown", 0);
548
+ }
549
+ };
550
+ completion = { active: false };
551
+ OUTPUT_OPTIONS = {
552
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
553
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
554
+ };
555
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
556
+ });
557
+
558
+ // ../kit/src/folders.ts
559
+ import { homedir as homedir2 } from "os";
560
+ import { join as join3 } from "path";
561
+ import process12 from "process";
562
+ function cacheFolder({ home = homedir2(), env = process12.env } = {}) {
563
+ return env.XDG_CACHE_HOME ?? join3(home, ".cache");
494
564
  }
495
- function realPath(word) {
565
+ var SKIPPED_FOLDERS;
566
+ var init_folders = __esm(() => {
567
+ init_user_config();
568
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
569
+ });
570
+
571
+ // ../kit/src/answers.ts
572
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
573
+ import { dirname as dirname3, join as join4 } from "path";
574
+ function answersFile() {
575
+ return join4(cacheFolder(), "kaynooo-cli", "answers.json");
576
+ }
577
+ function stored() {
496
578
  try {
497
- return realpathSync(resolve(word));
579
+ const parsed = JSON.parse(readFileSync3(answersFile(), "utf-8"));
580
+ if (typeof parsed !== "object" || parsed === null)
581
+ return {};
582
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
498
583
  } catch {
499
- return;
584
+ return {};
500
585
  }
501
586
  }
502
- function scriptArgs(argv = process7.argv.slice(2), cmdline = commandLine(), script = process7.argv[1]) {
503
- const target = script === undefined ? undefined : realPath(script) ?? script;
504
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve(word) === script || realPath(word) === target));
505
- const after = at === -1 ? [] : cmdline.slice(at + 1);
506
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
507
- }
508
- // ../kit/src/process.ts
509
- var CLIPBOARDS = [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"], ["pbcopy"], ["clip.exe"]];
510
- async function copyText(text, which = Bun.which) {
511
- for (const [command, ...args] of CLIPBOARDS) {
512
- const found = which(command);
513
- if (found !== null && await pipeInto([found, ...args], text))
514
- return true;
515
- }
516
- return false;
587
+ function earlierAnswers(key) {
588
+ return stored()[key] ?? [];
517
589
  }
518
- async function pipeInto(argv, text) {
590
+ function rememberAnswer(key, answer) {
591
+ const all = stored();
592
+ const file = answersFile();
593
+ all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
519
594
  try {
520
- const copy = Bun.spawn(argv, { stdin: new Blob([text]), stdout: "ignore", stderr: "ignore" });
521
- return await copy.exited === 0;
522
- } catch {
523
- return false;
524
- }
595
+ mkdirSync2(dirname3(file), { recursive: true });
596
+ writeFileSync(file, JSON.stringify(all));
597
+ } catch {}
525
598
  }
599
+ var KEPT = 50;
600
+ var init_answers = __esm(() => {
601
+ init_folders();
602
+ });
526
603
 
527
- // ../kit/src/progress.ts
528
- var ESC = String.fromCharCode(27);
529
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
530
- var RESET_STYLE = `${ESC}[0m`;
531
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
532
- // ../kit/src/cli.ts
533
- import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
534
- import { dirname as dirname2, join as join2 } from "path";
535
- import process10 from "process";
536
-
537
- // ../kit/src/notify.ts
538
- import process8 from "process";
539
- var NOTIFY_AFTER_MS = 1e4;
540
- var CANCELLED = 130;
541
- function base64(text) {
542
- return Buffer.from(text).toString("base64");
543
- }
544
- function notification(title, body, env = process8.env) {
545
- const id = `kit${process8.pid}`;
546
- 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\\`];
547
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
548
- }
549
- function notifyEnd(command, code, ms, { stream = process8.stderr, env = process8.env } = {}) {
550
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
551
- return;
552
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
604
+ // ../kit/src/job.ts
605
+ import process14 from "process";
606
+ function stopJob() {
607
+ process14.kill(0, "SIGTSTP");
553
608
  }
609
+ var init_job = () => {};
554
610
 
555
- // ../kit/src/usage.ts
556
- import { appendFileSync, mkdirSync } from "fs";
557
- import { homedir } from "os";
558
- import { dirname, isAbsolute, join } from "path";
559
- import process9 from "process";
560
-
561
- // ../kit/src/logs.ts
562
- var DAY_MS = 24 * 60 * 60 * 1000;
563
- var CLI_FOLDER = "kaynooo-cli";
564
-
565
- // ../kit/src/usage.ts
566
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
567
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
568
- var LONGEST_NAME = 40;
569
- var usageError;
570
- function noteUsageError(message) {
571
- usageError = message;
572
- }
573
- function stateHome(env = process9.env) {
574
- const dir = env.XDG_STATE_HOME;
575
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
576
- }
577
- function usagePath(env = process9.env) {
578
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
579
- }
580
- function usageRecorded(env = process9.env) {
581
- const off = env.KAYNOOO_CLI_NO_USAGE;
582
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
611
+ // ../kit/src/picker/line.ts
612
+ function isEditKey(key) {
613
+ return EDIT_KEYS.has(key);
583
614
  }
584
- function flagNames(argv) {
585
- const end = argv.indexOf("--");
586
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
587
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
615
+ function endsKills(key) {
616
+ return typeof key !== "object" && !isEditKey(key);
588
617
  }
589
- function usageEntry(bin, command, argv, code, now = new Date) {
590
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
591
- usageError = undefined;
592
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
618
+ function isWord(char) {
619
+ return char !== undefined && WORD_CHARACTER.test(char);
593
620
  }
594
- function recordUsage(entry, env = process9.env) {
595
- if (!usageRecorded(env))
596
- return;
597
- try {
598
- const path = usagePath(env);
599
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
600
- appendFileSync(path, `${JSON.stringify(entry)}
601
- `, { mode: 384 });
602
- } catch {}
621
+ function wordStart(chars, from) {
622
+ let at = from;
623
+ while (at > 0 && !isWord(chars[at - 1]))
624
+ at--;
625
+ while (at > 0 && isWord(chars[at - 1]))
626
+ at--;
627
+ return at;
603
628
  }
604
-
605
- // ../kit/src/cli.ts
606
- var LEVEL_OPTIONS = {
607
- ...OUTPUT_OPTIONS,
608
- help: { type: "boolean", short: "h", description: "show this help" }
609
- };
610
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
611
- async function commandRows(all, colors) {
612
- const commands = shown(all);
613
- const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
614
- const groups = new Map([["Commands:", []]]);
615
- const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
616
- for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
617
- const heading = group === undefined ? "Commands:" : `${group}:`;
618
- const rows = groups.get(heading) ?? [];
619
- rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
620
- groups.set(heading, rows);
621
- }
622
- return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
629
+ function wordEnd(chars, from) {
630
+ let at = from;
631
+ while (at < chars.length && !isWord(chars[at]))
632
+ at++;
633
+ while (at < chars.length && isWord(chars[at]))
634
+ at++;
635
+ return at;
623
636
  }
624
- function shown(commands) {
625
- return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
637
+ function spacedStart(chars, from) {
638
+ let at = from;
639
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
640
+ at--;
641
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
642
+ at--;
643
+ return at;
626
644
  }
627
- function takeOutputFlags(argv) {
628
- let index = 0;
629
- for (;index < argv.length; index++) {
630
- const word = argv[index];
631
- if (word === "--plain")
632
- applyOutput(undefined, true);
633
- else if (word.startsWith("--color="))
634
- applyOutput(word.slice("--color=".length), undefined);
635
- else if (word === "--color" && argv[index + 1] !== undefined)
636
- applyOutput(argv[++index], undefined);
637
- else
638
- break;
639
- }
640
- return argv.slice(index);
645
+ function cut(chars, from, to) {
646
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
641
647
  }
642
- async function resolveSummary(summary) {
643
- return typeof summary === "string" ? summary : summary();
648
+ function insert(chars, at, text) {
649
+ const typed = [...text];
650
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
644
651
  }
645
- function scopeOf(commands, extra, aliases) {
646
- return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
652
+ function editLine(line, key) {
653
+ const { killed = "", chained = false } = line;
654
+ const chars = [...line.text];
655
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
656
+ const edited = edit(chars, at, key, killed);
657
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
658
+ return line.killed === undefined ? edited : { ...edited, killed };
659
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
660
+ if (taken === "")
661
+ return { ...edited, killed, chained };
662
+ if (!chained)
663
+ return { ...edited, killed: taken, chained: true };
664
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
647
665
  }
648
- async function expand(scope, words) {
649
- if (scope.lazy.length === 0)
650
- return scope;
651
- const commands = { ...scope.commands };
652
- for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
653
- for (const [name, command] of Object.entries(added))
654
- commands[name] ??= command;
666
+ function edit(chars, at, key, killed) {
667
+ const text = chars.join("");
668
+ if (typeof key === "object")
669
+ return insert(chars, at, key.text);
670
+ switch (key) {
671
+ case "left":
672
+ return { text, caret: Math.max(at - 1, 0) };
673
+ case "right":
674
+ return { text, caret: Math.min(at + 1, chars.length) };
675
+ case "wordleft":
676
+ return { text, caret: wordStart(chars, at) };
677
+ case "wordright":
678
+ return { text, caret: wordEnd(chars, at) };
679
+ case "linestart":
680
+ return { text, caret: 0 };
681
+ case "lineend":
682
+ return { text, caret: chars.length };
683
+ case "erase":
684
+ return cut(chars, Math.max(at - 1, 0), at);
685
+ case "delete":
686
+ return cut(chars, at, Math.min(at + 1, chars.length));
687
+ case "word":
688
+ return cut(chars, spacedStart(chars, at), at);
689
+ case "killword":
690
+ return cut(chars, wordStart(chars, at), at);
691
+ case "killnext":
692
+ return cut(chars, at, wordEnd(chars, at));
693
+ case "clear":
694
+ return cut(chars, 0, at);
695
+ case "killend":
696
+ return cut(chars, at, chars.length);
697
+ case "yank":
698
+ return insert(chars, at, killed);
655
699
  }
656
- return { ...scope, commands, lazy: [] };
657
- }
658
- async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
659
- const colors = paint(stream);
660
- const prefix = path.join(" ");
661
- const summary = await resolveSummary(lazySummary);
662
- if (wantsHelpJson())
663
- return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
664
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
665
- const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
666
- const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
667
- return [
668
- header(colors, summary),
669
- "",
670
- usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
671
- "",
672
- ...await commandRows(commands, colors),
673
- ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
674
- "",
675
- colors.bold("Options:"),
676
- ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
677
- ...exampleRows(examples ?? [], colors),
678
- "",
679
- `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
680
- ].join(`
681
- `);
682
- }
683
- function printError(prefix, message, hint, cause) {
684
- const colors = paint(process10.stderr);
685
- const styled = takesControlCodes(process10.stderr);
686
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
687
- const under = (label, text, tint) => text === undefined ? "" : `
688
- ${styled ? tint(label) : `${label}:`} ${text}`;
689
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
690
- }
691
- function printJsonError(message, hint, cause) {
692
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
693
700
  }
694
- function wantsJson(argv) {
695
- const end = argv.indexOf("--");
696
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
701
+ function visible({ text, caret }, room) {
702
+ const chars = [...text];
703
+ const at = Math.min(Math.max(caret, 0), chars.length);
704
+ const cells = at === chars.length ? [...chars, " "] : chars;
705
+ const widths = cells.map((char) => Bun.stringWidth(char));
706
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
707
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
708
+ let start = at;
709
+ let end = at + 1;
710
+ while (start > 0 && fits(start - 1, end))
711
+ start--;
712
+ while (end < cells.length && fits(start, end + 1))
713
+ end++;
714
+ const left = start > 0 ? "\u2026" : "";
715
+ const right = end < cells.length ? "\u2026" : "";
716
+ 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) };
697
717
  }
698
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
699
- if (error instanceof HelpShown)
700
- return 0;
701
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
702
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
703
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
704
- if (error instanceof Exit && error.code === 2)
705
- noteUsageError(error.message);
706
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
707
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
708
- return error instanceof Exit ? error.code : 1;
718
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
719
+ var init_line = __esm(() => {
720
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
721
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
722
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
723
+ WORD_CHARACTER = /[\p{L}\p{N}_]/u;
724
+ SPACE = /\s/;
725
+ });
726
+
727
+ // ../kit/src/picker/score.ts
728
+ var BOUNDARY_AFTER, NONE;
729
+ var init_score = __esm(() => {
730
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
731
+ NONE = Number.NEGATIVE_INFINITY;
732
+ });
733
+
734
+ // ../kit/src/picker/state.ts
735
+ function repeat(value, count) {
736
+ return Array.from({ length: count }).fill(value);
709
737
  }
710
- async function dispatch(level, typed, { version, redact }) {
711
- const prefix = level.path.join(" ");
712
- let argv;
713
- try {
714
- argv = takeOutputFlags(typed);
715
- } catch (error) {
716
- return reportThrown(prefix, error);
717
- }
718
- const [name, ...args] = argv;
719
- const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
720
- if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
721
- try {
722
- return await fallback.run([]);
723
- } catch (error) {
724
- return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
738
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
739
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
740
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
741
+ const wheel = MOUSE.exec(sequence)?.[1];
742
+ if (wheel !== undefined)
743
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
744
+ const named = codes.get(sequence);
745
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
746
+ if (sequence === PASTE_START || sequence === PASTE_END) {
747
+ paste.active = sequence === PASTE_START;
748
+ return [];
725
749
  }
726
- }
727
- if (name === undefined && level.path.length > 1) {
728
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stderr));
729
- return 2;
730
- }
731
- if (name === undefined || name === "help" || name === "--help" || name === "-h") {
732
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stdout));
733
- return 0;
734
- }
735
- if (level.path.length === 1 && (name === "--version" || name === "-v")) {
736
- console.log(version);
737
- return 0;
738
- }
739
- let command = level.commands[level.aliases?.[name] ?? name];
740
- let rest = args;
741
- let ran = name;
742
- if (command === undefined && level.lazy.length > 0) {
743
- level = await expand(level, [...level.path.slice(1), ...argv]);
744
- command = level.commands[level.aliases?.[name] ?? name];
745
- }
746
- if (command === undefined && level.defaultCommand !== undefined) {
747
- command = level.commands[level.defaultCommand];
748
- rest = argv;
749
- ran = level.defaultCommand;
750
- }
751
- if (command === undefined) {
752
- const meant = closest(name, Object.keys(shown(level.commands)));
753
- printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
754
- return 2;
755
- }
756
- if ("commands" in command) {
757
- const { summary } = command;
758
- return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
759
- }
760
- try {
761
- return await command.run(rest);
762
- } catch (error) {
763
- return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
764
- }
750
+ if (paste.active && (sequence === "\r" || sequence === `
751
+ `))
752
+ return [];
753
+ if (key !== undefined)
754
+ return [key];
755
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
756
+ });
765
757
  }
766
- var COMPLETE = "__complete";
767
- var FILES = "__files__";
768
- async function completingOf(run) {
769
- completion.active = true;
770
- try {
771
- await run([]);
772
- } catch (error) {
773
- if (error instanceof Completing)
774
- return error;
775
- } finally {
776
- completion.active = false;
777
- }
778
- return new Completing({});
758
+ var IS_CONTROL, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
759
+ var init_state = __esm(() => {
760
+ init_text2();
761
+ init_line();
762
+ init_score();
763
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
764
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
765
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
766
+ KEYS = {
767
+ "\x1B[A": "up",
768
+ "\x1BOA": "up",
769
+ "\x10": "up",
770
+ "\x1B[B": "down",
771
+ "\x1BOB": "down",
772
+ "\x0E": "down",
773
+ "\x1B[5~": "pageup",
774
+ "\x1B[6~": "pagedown",
775
+ "\x1B[H": "home",
776
+ "\x1B[1~": "home",
777
+ "\x1BOH": "home",
778
+ "\x1B[F": "end",
779
+ "\x1B[4~": "end",
780
+ "\x1BOF": "end",
781
+ "\r": "enter",
782
+ "\n": "enter",
783
+ "\x03": "cancel",
784
+ "\x1B": "cancel",
785
+ "\x1B[D": "left",
786
+ "\x1BOD": "left",
787
+ "\x1B[C": "right",
788
+ "\x1BOC": "right",
789
+ "\x1B[1;5D": "wordleft",
790
+ "\x1B[1;3D": "wordleft",
791
+ "\x1Bb": "wordleft",
792
+ "\x1B[1;5C": "wordright",
793
+ "\x1B[1;3C": "wordright",
794
+ "\x1Bf": "wordright",
795
+ "\x01": "linestart",
796
+ "\x05": "lineend",
797
+ "\x7F": "erase",
798
+ "\x1B[3~": "delete",
799
+ "\b": "killword",
800
+ "\x1B\x7F": "killword",
801
+ "\x1B[3;5~": "killnext",
802
+ "\x1Bd": "killnext",
803
+ "\x15": "clear",
804
+ "\v": "killend",
805
+ "\x17": "word",
806
+ "\x19": "yank",
807
+ "\x1A": "suspend",
808
+ "\t": "tab",
809
+ "\x1F": "help",
810
+ "\x1BOP": "help",
811
+ "\x1B[11~": "help"
812
+ };
813
+ });
814
+
815
+ // ../kit/src/redraw.ts
816
+ function overwrite(lines, columns) {
817
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
818
+ `);
779
819
  }
780
- async function optionsOf(run) {
781
- return (await completingOf(run)).options;
820
+ function rowsTaken(lines, columns) {
821
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
782
822
  }
783
- function candidateLine(candidate) {
784
- return typeof candidate === "string" ? candidate : candidate.join("\t");
823
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
824
+ var init_redraw = __esm(() => {
825
+ init_format();
826
+ });
827
+
828
+ // ../kit/src/prompt.ts
829
+ import process15 from "process";
830
+ function readKeys(input, paste = { active: false }) {
831
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
785
832
  }
786
- function positionalBeingTyped(before, { options, positionals }) {
787
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
788
- const typed = [];
789
- let at = 0;
790
- while (at < before.length) {
791
- const word = before[at];
792
- if (word === "--") {
793
- typed.push(...before.slice(at + 1));
794
- break;
795
- }
796
- if (!word.startsWith("-"))
797
- typed.push(word);
798
- else if (takesValue(word))
799
- at++;
800
- at++;
801
- }
802
- const last = positionals.at(-1);
803
- if (typed.length < positionals.length)
804
- return { name: positionals[typed.length], typed };
805
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
833
+ function roomAfter(question, columns) {
834
+ return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
806
835
  }
807
- async function leafCandidates(run, words) {
808
- const completing = await completingOf(run);
809
- if ((words.at(-1) ?? "").startsWith("-"))
810
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
811
- const flag = words.at(-2);
812
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
813
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
814
- if (option?.type === "string") {
815
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
816
- return values === undefined ? [FILES] : values.map(candidateLine);
836
+ function withCaret(colors, line, room, dim = false) {
837
+ const { before, at, after } = visible(line, room);
838
+ const tone = dim ? colors.dim : (text) => text;
839
+ return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
840
+ }
841
+ function sharedStart(texts) {
842
+ const [first = [], ...rest] = texts.map((text) => [...text]);
843
+ let length = first.length;
844
+ for (const chars of rest) {
845
+ const differs = chars.findIndex((char, index) => char !== first[index]);
846
+ length = Math.min(length, differs === -1 ? chars.length : differs);
817
847
  }
818
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
819
- return values === undefined ? [FILES] : values.map(candidateLine);
848
+ return first.slice(0, length).join("");
820
849
  }
821
- async function candidates(scope, defaultCommand, words, before = []) {
822
- const [word = "", ...rest] = words;
823
- const listing = rest.length === 0 && !word.startsWith("-");
824
- let { commands, aliases } = scope;
825
- let command = commands[aliases?.[word] ?? word];
826
- if (listing || command === undefined) {
827
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
828
- command = commands[aliases?.[word] ?? word];
829
- }
830
- if (listing) {
831
- const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
832
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
833
- const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
834
- const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
835
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
836
- }
837
- if (command === undefined) {
838
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
839
- return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
840
- }
841
- return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
850
+ function listed2(colors, found, columns) {
851
+ const shared = sharedStart(found);
852
+ const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
853
+ const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
854
+ const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
855
+ return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
842
856
  }
843
- async function printCandidates(found) {
844
- for (const line of await found)
845
- console.log(line);
846
- return 0;
857
+ async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
858
+ let line = { text: "", caret: 0 };
859
+ let invalid;
860
+ let completions = [];
861
+ const remembered = history === undefined || mask ? undefined : history;
862
+ const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
863
+ let recalled = -1;
864
+ let draft = line;
865
+ const taken = () => line.text === "" ? fallback ?? "" : line.text;
866
+ const shown = () => mask ? "*".repeat([...taken()].length) : taken();
867
+ const accepted = await ask(question, settings, (colors, state, { columns }) => {
868
+ if (state !== "asking")
869
+ return [answer(colors, question, state, shown())];
870
+ const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
871
+ return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
872
+ }, (key) => {
873
+ if (key === "cancel")
874
+ return "cancel";
875
+ invalid = undefined;
876
+ completions = [];
877
+ if (line.chained === true && endsKills(key))
878
+ line = { ...line, chained: false };
879
+ if (key === "tab") {
880
+ const chars = [...line.text];
881
+ const before = chars.slice(0, line.caret).join("");
882
+ const found = complete?.(before) ?? [];
883
+ const filled = sharedStart(found);
884
+ if ([...filled].length > [...before].length)
885
+ line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
886
+ else
887
+ completions = found;
888
+ return;
889
+ }
890
+ if (key === "enter") {
891
+ invalid = validate?.(taken());
892
+ return invalid === undefined ? "enter" : undefined;
893
+ }
894
+ if (key === "up" || key === "down") {
895
+ const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
896
+ if (recalled === -1)
897
+ draft = line;
898
+ recalled = to;
899
+ const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
900
+ line = { ...shown, killed: line.killed ?? "" };
901
+ return;
902
+ }
903
+ const edit = { home: "linestart", end: "lineend" }[key] ?? key;
904
+ if (typeof edit === "object" || isEditKey(edit))
905
+ line = editLine(line, edit);
906
+ return;
907
+ });
908
+ if (!accepted)
909
+ return;
910
+ if (remembered !== undefined && taken() !== "")
911
+ rememberAnswer(remembered, taken());
912
+ return taken();
847
913
  }
848
- function packageVersion(entry = Bun.main) {
849
- let resolved = entry;
914
+ function answer(colors, question, state, picked) {
915
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
916
+ }
917
+ async function ask(question, { hint, terminal = process15 }, render, press) {
918
+ const { stdin, stderr } = terminal;
919
+ if (!isInteractive(terminal))
920
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
921
+ const colors = paint(stderr);
922
+ let current = "asking";
923
+ let outcome;
924
+ const columns = () => stderr.columns || 80;
925
+ const draw = (state, last = false) => {
926
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
927
+ const rows = rowsTaken(frame, columns());
928
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
929
+ current = state;
930
+ };
931
+ const redraw = () => draw(current);
932
+ const paste = { active: false };
933
+ const stop = terminal.stop ?? (terminal === process15 ? stopJob : undefined);
934
+ const suspend = () => {
935
+ if (stop === undefined)
936
+ return;
937
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
938
+ stdin.setRawMode(false);
939
+ stop();
940
+ stdin.setRawMode(true);
941
+ stderr.write("\x1B[?25l\x1B[?2004h");
942
+ };
850
943
  try {
851
- resolved = realpathSync2(entry);
852
- } catch {}
853
- for (let dir = dirname2(resolved);; dir = dirname2(dir)) {
854
- try {
855
- const { version } = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
856
- if (typeof version === "string")
857
- return version;
858
- } catch {}
859
- if (dirname2(dir) === dir)
860
- return "0.0.0";
944
+ stderr.on?.("resize", redraw);
945
+ stdin.setRawMode(true);
946
+ stdin.resume();
947
+ stderr.write("\x1B[?25l\x1B[?2004h");
948
+ draw("asking");
949
+ return await new Promise((resolve) => {
950
+ function onData(data) {
951
+ for (const key of readKeys(data.toString(), paste)) {
952
+ if (key === "suspend") {
953
+ suspend();
954
+ continue;
955
+ }
956
+ const pressed = press(key);
957
+ if (pressed !== undefined) {
958
+ settle(pressed);
959
+ return;
960
+ }
961
+ }
962
+ draw("asking");
963
+ }
964
+ function onEnd() {
965
+ settle("cancel");
966
+ }
967
+ function settle(settled) {
968
+ outcome = settled;
969
+ stdin.off("data", onData);
970
+ stdin.off("end", onEnd);
971
+ resolve(settled === "enter");
972
+ }
973
+ stdin.on("data", onData);
974
+ stdin.on("end", onEnd);
975
+ });
976
+ } finally {
977
+ stderr.off?.("resize", redraw);
978
+ draw(outcome ?? "cancel", true);
979
+ stderr.write(`
980
+ \x1B[?25h\x1B[?2004l`);
981
+ stdin.setRawMode(false);
982
+ stdin.pause();
861
983
  }
862
984
  }
863
- async function runCli(cli, argv = scriptArgs()) {
864
- const version = cli.version ?? packageVersion();
865
- if (argv[0] === COMPLETE)
866
- return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
867
- const started = performance.now();
868
- const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
869
- const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
870
- notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
871
- if (cli.usage !== false) {
872
- try {
873
- recordUsage(usageEntry(cli.name, command, argv, code));
874
- } catch {}
985
+ var PROMPT_KEYS, MAX_LISTED = 12;
986
+ var init_prompt = __esm(() => {
987
+ init_answers();
988
+ init_args();
989
+ init_format();
990
+ init_job();
991
+ init_mode();
992
+ init_line();
993
+ init_state();
994
+ init_redraw();
995
+ init_style();
996
+ PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
997
+ });
998
+
999
+ // src/cli.ts
1000
+ import process16 from "process";
1001
+
1002
+ // ../kit/src/index.ts
1003
+ init_args();
1004
+
1005
+ // ../kit/src/argv.ts
1006
+ import { readFileSync, realpathSync } from "fs";
1007
+ import { resolve } from "path";
1008
+ import process7 from "process";
1009
+ function commandLine() {
1010
+ try {
1011
+ return readFileSync("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
1012
+ } catch {
1013
+ return;
875
1014
  }
876
- return code;
877
1015
  }
878
- function commandPath(scope, argv) {
879
- const path = [];
880
- let level = scope;
881
- for (const word of argv.filter((each) => !each.startsWith("-"))) {
882
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
883
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
884
- if (command === undefined)
885
- break;
886
- path.push(word);
887
- if (!("commands" in command))
888
- break;
889
- level = scopeOf(command.commands, command.extraCommands, command.aliases);
1016
+ function realPath(word) {
1017
+ try {
1018
+ return realpathSync(resolve(word));
1019
+ } catch {
1020
+ return;
890
1021
  }
891
- return path.length === 0 ? undefined : path.join(" ");
892
1022
  }
893
- // ../kit/src/folders.ts
894
- import { homedir as homedir2 } from "os";
895
- import { join as join3 } from "path";
896
- import process11 from "process";
897
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
898
- function cacheFolder({ home = homedir2(), env = process11.env } = {}) {
899
- return env.XDG_CACHE_HOME ?? join3(home, ".cache");
1023
+ function scriptArgs(argv = process7.argv.slice(2), cmdline = commandLine(), script = process7.argv[1]) {
1024
+ const target = script === undefined ? undefined : realPath(script) ?? script;
1025
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve(word) === script || realPath(word) === target));
1026
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
1027
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
900
1028
  }
901
- // ../kit/src/secrets.ts
902
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
903
- // ../kit/src/sessions.ts
904
- var {Glob } = globalThis.Bun;
905
- var SESSION_FILES = new Glob("*.json");
906
- var ACCOUNT_DIRS = new Glob("*/sessions");
907
- // ../kit/src/prompt.ts
908
- import process14 from "process";
1029
+ // ../kit/src/chart.ts
1030
+ init_format();
1031
+ init_mode();
1032
+ init_style();
1033
+ init_theme();
1034
+ // ../kit/src/ci.ts
1035
+ init_args();
1036
+ init_format();
909
1037
 
910
- // ../kit/src/answers.ts
911
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
912
- import { dirname as dirname3, join as join4 } from "path";
913
- var KEPT = 50;
914
- function answersFile() {
915
- return join4(cacheFolder(), "kaynooo-cli", "answers.json");
1038
+ // ../kit/src/progress.ts
1039
+ init_format();
1040
+
1041
+ // ../kit/src/process.ts
1042
+ var CLIPBOARDS = [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"], ["pbcopy"], ["clip.exe"]];
1043
+ async function copyText(text, which = Bun.which) {
1044
+ for (const [command, ...args] of CLIPBOARDS) {
1045
+ const found = which(command);
1046
+ if (found !== null && await pipeInto([found, ...args], text))
1047
+ return true;
1048
+ }
1049
+ return false;
916
1050
  }
917
- function stored() {
1051
+ async function pipeInto(argv, text) {
918
1052
  try {
919
- const parsed = JSON.parse(readFileSync3(answersFile(), "utf-8"));
920
- if (typeof parsed !== "object" || parsed === null)
921
- return {};
922
- return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
1053
+ const copy = Bun.spawn(argv, { stdin: new Blob([text]), stdout: "ignore", stderr: "ignore" });
1054
+ return await copy.exited === 0;
923
1055
  } catch {
924
- return {};
1056
+ return false;
925
1057
  }
926
1058
  }
927
- function earlierAnswers(key) {
928
- return stored()[key] ?? [];
929
- }
930
- function rememberAnswer(key, answer) {
931
- const all = stored();
932
- const file = answersFile();
933
- all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
1059
+
1060
+ // ../kit/src/progress.ts
1061
+ init_style();
1062
+ init_theme();
1063
+ var ESC = String.fromCharCode(27);
1064
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1065
+ var RESET_STYLE = `${ESC}[0m`;
1066
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1067
+
1068
+ // ../kit/src/ci.ts
1069
+ init_style();
1070
+
1071
+ // ../kit/src/tool.ts
1072
+ init_format();
1073
+ // ../kit/src/cli.ts
1074
+ init_args();
1075
+ import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
1076
+ import { dirname as dirname2, join as join2 } from "path";
1077
+ import process11 from "process";
1078
+
1079
+ // ../kit/src/askpass.ts
1080
+ import process8 from "process";
1081
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1082
+ async function askpassClient(argv) {
1083
+ const socketPath = process8.env[SOCKET_VARIABLE];
1084
+ if (socketPath === undefined)
1085
+ return;
1086
+ const request = { prompt: argv[0] ?? "", ...process8.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1087
+ const { promise, resolve } = Promise.withResolvers();
1088
+ let received = "";
934
1089
  try {
935
- mkdirSync2(dirname3(file), { recursive: true });
936
- writeFileSync(file, JSON.stringify(all));
937
- } catch {}
1090
+ await Bun.connect({
1091
+ unix: socketPath,
1092
+ socket: {
1093
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1094
+ `),
1095
+ data: (_, chunk) => {
1096
+ received += chunk.toString();
1097
+ },
1098
+ close: () => resolve(received),
1099
+ error: () => resolve("")
1100
+ }
1101
+ });
1102
+ } catch {
1103
+ return 1;
1104
+ }
1105
+ const reply = await promise;
1106
+ if (reply === "")
1107
+ return 1;
1108
+ const { answer } = JSON.parse(reply);
1109
+ if (request.notice === true)
1110
+ return 0;
1111
+ if (answer === undefined)
1112
+ return 1;
1113
+ process8.stdout.write(`${answer}
1114
+ `);
1115
+ return 0;
938
1116
  }
939
1117
 
940
- // ../kit/src/job.ts
941
- import process13 from "process";
942
- function stopJob() {
943
- process13.kill(0, "SIGTSTP");
1118
+ // ../kit/src/completions.ts
1119
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1120
+ 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'
1121
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1122
+ set -l current (commandline -ct)
1123
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1124
+ if test "$line" = __files__
1125
+ __fish_complete_path $current
1126
+ else
1127
+ echo $line
1128
+ end
1129
+ end
1130
+ end`;
1131
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1132
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1133
+ local -a lines
1134
+ COMPREPLY=()
1135
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1136
+ for line in "\${lines[@]}"; do
1137
+ if [[ $line == __files__ ]]; then
1138
+ COMPREPLY+=($(compgen -f -- "$cur"))
1139
+ else
1140
+ words+="\${line%%$'\\t'*}"$'\\n'
1141
+ fi
1142
+ done
1143
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1144
+ }`;
1145
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1146
+ local line
1147
+ local -a described plain
1148
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1149
+ if [[ $line == __files__ ]]; then
1150
+ _files
1151
+ elif [[ $line == *$'\\t'* ]]; then
1152
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1153
+ else
1154
+ plain+=("$line")
1155
+ fi
1156
+ done
1157
+ (( \${#described} )) && _describe -V value described
1158
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1159
+ return 0
1160
+ }`;
1161
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1162
+ if (shell === "fish")
1163
+ return `${header}
1164
+ ${FISH_FUNCTION}
1165
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1166
+ `).join("")}`;
1167
+ if (shell === "bash")
1168
+ return `${header}
1169
+ ${BASH_FUNCTION}
1170
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1171
+ `;
1172
+ return `${header}
1173
+ ${ZSH_FUNCTION}
1174
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1175
+ `;
944
1176
  }
945
1177
 
946
- // ../kit/src/picker/line.ts
947
- var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
948
- var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
949
- var FORWARD_KILLS = new Set(["killnext", "killend"]);
950
- function isEditKey(key) {
951
- return EDIT_KEYS.has(key);
952
- }
953
- function endsKills(key) {
954
- return typeof key !== "object" && !isEditKey(key);
1178
+ // ../kit/src/notify.ts
1179
+ init_format();
1180
+ init_mode();
1181
+ import process9 from "process";
1182
+ var NOTIFY_AFTER_MS = 1e4;
1183
+ var CANCELLED = 130;
1184
+ function base64(text) {
1185
+ return Buffer.from(text).toString("base64");
955
1186
  }
956
- var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
957
- var SPACE = /\s/;
958
- function isWord(char) {
959
- return char !== undefined && WORD_CHARACTER.test(char);
1187
+ function notification(title, body, env = process9.env) {
1188
+ const id = `kit${process9.pid}`;
1189
+ 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\\`];
1190
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
960
1191
  }
961
- function wordStart(chars, from) {
962
- let at = from;
963
- while (at > 0 && !isWord(chars[at - 1]))
964
- at--;
965
- while (at > 0 && isWord(chars[at - 1]))
966
- at--;
967
- return at;
1192
+ function notifyEnd(command, code, ms, { stream = process9.stderr, env = process9.env } = {}) {
1193
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1194
+ return;
1195
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
968
1196
  }
969
- function wordEnd(chars, from) {
970
- let at = from;
971
- while (at < chars.length && !isWord(chars[at]))
972
- at++;
973
- while (at < chars.length && isWord(chars[at]))
974
- at++;
975
- return at;
1197
+
1198
+ // ../kit/src/cli.ts
1199
+ init_style();
1200
+ init_text2();
1201
+
1202
+ // ../kit/src/usage.ts
1203
+ import { appendFileSync, mkdirSync } from "fs";
1204
+ import { homedir } from "os";
1205
+ import { dirname, isAbsolute, join } from "path";
1206
+ import process10 from "process";
1207
+
1208
+ // ../kit/src/logs.ts
1209
+ var DAY_MS = 24 * 60 * 60 * 1000;
1210
+ var CLI_FOLDER = "kaynooo-cli";
1211
+
1212
+ // ../kit/src/usage.ts
1213
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1214
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1215
+ var LONGEST_NAME = 40;
1216
+ var usageError;
1217
+ function noteUsageError(message) {
1218
+ usageError = message;
976
1219
  }
977
- function spacedStart(chars, from) {
978
- let at = from;
979
- while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
980
- at--;
981
- while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
982
- at--;
983
- return at;
1220
+ function stateHome(env = process10.env) {
1221
+ const dir = env.XDG_STATE_HOME;
1222
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
984
1223
  }
985
- function cut(chars, from, to) {
986
- return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1224
+ function usagePath(env = process10.env) {
1225
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
987
1226
  }
988
- function insert(chars, at, text) {
989
- const typed = [...text];
990
- return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
1227
+ function usageRecorded(env = process10.env) {
1228
+ const off = env.KAYNOOO_CLI_NO_USAGE;
1229
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
991
1230
  }
992
- function editLine(line, key) {
993
- const { killed = "", chained = false } = line;
994
- const chars = [...line.text];
995
- const at = Math.min(Math.max(line.caret, 0), chars.length);
996
- const edited = edit(chars, at, key, killed);
997
- if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
998
- return line.killed === undefined ? edited : { ...edited, killed };
999
- const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1000
- if (taken === "")
1001
- return { ...edited, killed, chained };
1002
- if (!chained)
1003
- return { ...edited, killed: taken, chained: true };
1004
- return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1231
+ function flagNames(argv) {
1232
+ const end = argv.indexOf("--");
1233
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1234
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1005
1235
  }
1006
- function edit(chars, at, key, killed) {
1007
- const text = chars.join("");
1008
- if (typeof key === "object")
1009
- return insert(chars, at, key.text);
1010
- switch (key) {
1011
- case "left":
1012
- return { text, caret: Math.max(at - 1, 0) };
1013
- case "right":
1014
- return { text, caret: Math.min(at + 1, chars.length) };
1015
- case "wordleft":
1016
- return { text, caret: wordStart(chars, at) };
1017
- case "wordright":
1018
- return { text, caret: wordEnd(chars, at) };
1019
- case "linestart":
1020
- return { text, caret: 0 };
1021
- case "lineend":
1022
- return { text, caret: chars.length };
1023
- case "erase":
1024
- return cut(chars, Math.max(at - 1, 0), at);
1025
- case "delete":
1026
- return cut(chars, at, Math.min(at + 1, chars.length));
1027
- case "word":
1028
- return cut(chars, spacedStart(chars, at), at);
1029
- case "killword":
1030
- return cut(chars, wordStart(chars, at), at);
1031
- case "killnext":
1032
- return cut(chars, at, wordEnd(chars, at));
1033
- case "clear":
1034
- return cut(chars, 0, at);
1035
- case "killend":
1036
- return cut(chars, at, chars.length);
1037
- case "yank":
1038
- return insert(chars, at, killed);
1039
- }
1236
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1237
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1238
+ usageError = undefined;
1239
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1040
1240
  }
1041
- function visible({ text, caret }, room) {
1042
- const chars = [...text];
1043
- const at = Math.min(Math.max(caret, 0), chars.length);
1044
- const cells = at === chars.length ? [...chars, " "] : chars;
1045
- const widths = cells.map((char) => Bun.stringWidth(char));
1046
- const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1047
- const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1048
- let start = at;
1049
- let end = at + 1;
1050
- while (start > 0 && fits(start - 1, end))
1051
- start--;
1052
- while (end < cells.length && fits(start, end + 1))
1053
- end++;
1054
- const left = start > 0 ? "\u2026" : "";
1055
- const right = end < cells.length ? "\u2026" : "";
1056
- 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) };
1241
+ function recordUsage(entry, env = process10.env) {
1242
+ if (!usageRecorded(env))
1243
+ return;
1244
+ try {
1245
+ const path = usagePath(env);
1246
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
1247
+ appendFileSync(path, `${JSON.stringify(entry)}
1248
+ `, { mode: 384 });
1249
+ } catch {}
1057
1250
  }
1058
1251
 
1059
- // ../kit/src/picker/score.ts
1060
- var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1061
- var NONE = Number.NEGATIVE_INFINITY;
1062
-
1063
- // ../kit/src/picker/state.ts
1064
- var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1065
- var PASTE_START = "\x1B[200~";
1066
- var PASTE_END = "\x1B[201~";
1067
- var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1068
- var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1069
- var WHEEL_LINES = 3;
1070
- var KEYS = {
1071
- "\x1B[A": "up",
1072
- "\x1BOA": "up",
1073
- "\x10": "up",
1074
- "\x1B[B": "down",
1075
- "\x1BOB": "down",
1076
- "\x0E": "down",
1077
- "\x1B[5~": "pageup",
1078
- "\x1B[6~": "pagedown",
1079
- "\x1B[H": "home",
1080
- "\x1B[1~": "home",
1081
- "\x1BOH": "home",
1082
- "\x1B[F": "end",
1083
- "\x1B[4~": "end",
1084
- "\x1BOF": "end",
1085
- "\r": "enter",
1086
- "\n": "enter",
1087
- "\x03": "cancel",
1088
- "\x1B": "cancel",
1089
- "\x1B[D": "left",
1090
- "\x1BOD": "left",
1091
- "\x1B[C": "right",
1092
- "\x1BOC": "right",
1093
- "\x1B[1;5D": "wordleft",
1094
- "\x1B[1;3D": "wordleft",
1095
- "\x1Bb": "wordleft",
1096
- "\x1B[1;5C": "wordright",
1097
- "\x1B[1;3C": "wordright",
1098
- "\x1Bf": "wordright",
1099
- "\x01": "linestart",
1100
- "\x05": "lineend",
1101
- "\x7F": "erase",
1102
- "\x1B[3~": "delete",
1103
- "\b": "killword",
1104
- "\x1B\x7F": "killword",
1105
- "\x1B[3;5~": "killnext",
1106
- "\x1Bd": "killnext",
1107
- "\x15": "clear",
1108
- "\v": "killend",
1109
- "\x17": "word",
1110
- "\x19": "yank",
1111
- "\x1A": "suspend",
1112
- "\t": "tab",
1113
- "\x1F": "help",
1114
- "\x1BOP": "help",
1115
- "\x1B[11~": "help"
1252
+ // ../kit/src/cli.ts
1253
+ var LEVEL_OPTIONS = {
1254
+ ...OUTPUT_OPTIONS,
1255
+ help: { type: "boolean", short: "h", description: "show this help" }
1116
1256
  };
1117
- function repeat(value, count) {
1118
- return Array.from({ length: count }).fill(value);
1119
- }
1120
- function parseKeys(input, paste = { active: false }, ctrls = []) {
1121
- const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1122
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1123
- const wheel = MOUSE.exec(sequence)?.[1];
1124
- if (wheel !== undefined)
1125
- return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1126
- const named = codes.get(sequence);
1127
- const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1128
- if (sequence === PASTE_START || sequence === PASTE_END) {
1129
- paste.active = sequence === PASTE_START;
1130
- return [];
1131
- }
1132
- if (paste.active && (sequence === "\r" || sequence === `
1133
- `))
1134
- return [];
1135
- if (key !== undefined)
1136
- return [key];
1137
- return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1138
- });
1139
- }
1140
-
1141
- // ../kit/src/redraw.ts
1142
- var SYNC_START = "\x1B[?2026h";
1143
- var SYNC_END = "\x1B[?2026l";
1144
- function overwrite(lines, columns) {
1145
- return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1146
- `);
1257
+ var TOP_OPTIONS = {
1258
+ ...LEVEL_OPTIONS,
1259
+ version: { type: "boolean", short: "v", description: "print the version" },
1260
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1261
+ };
1262
+ async function commandRows(all, colors) {
1263
+ const commands = shown(all);
1264
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
1265
+ const groups = new Map([["Commands:", []]]);
1266
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
1267
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
1268
+ const heading = group === undefined ? "Commands:" : `${group}:`;
1269
+ const rows = groups.get(heading) ?? [];
1270
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
1271
+ groups.set(heading, rows);
1272
+ }
1273
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
1147
1274
  }
1148
- function rowsTaken(lines, columns) {
1149
- return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1275
+ function shown(commands) {
1276
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
1150
1277
  }
1151
-
1152
- // ../kit/src/prompt.ts
1153
- var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1154
- var MAX_LISTED = 12;
1155
- function readKeys(input, paste = { active: false }) {
1156
- return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1278
+ function takeOutputFlags(argv) {
1279
+ let index = 0;
1280
+ for (;index < argv.length; index++) {
1281
+ const word = argv[index];
1282
+ if (word === "--plain")
1283
+ applyOutput(undefined, true);
1284
+ else if (word.startsWith("--color="))
1285
+ applyOutput(word.slice("--color=".length), undefined);
1286
+ else if (word === "--color" && argv[index + 1] !== undefined)
1287
+ applyOutput(argv[++index], undefined);
1288
+ else
1289
+ break;
1290
+ }
1291
+ return argv.slice(index);
1157
1292
  }
1158
- function roomAfter(question, columns) {
1159
- return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
1293
+ async function resolveSummary(summary) {
1294
+ return typeof summary === "string" ? summary : summary();
1160
1295
  }
1161
- function withCaret(colors, line, room, dim = false) {
1162
- const { before, at, after } = visible(line, room);
1163
- const tone = dim ? colors.dim : (text) => text;
1164
- return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
1296
+ function scopeOf(commands, extra, aliases) {
1297
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1165
1298
  }
1166
- function sharedStart(texts) {
1167
- const [first = [], ...rest] = texts.map((text) => [...text]);
1168
- let length = first.length;
1169
- for (const chars of rest) {
1170
- const differs = chars.findIndex((char, index) => char !== first[index]);
1171
- length = Math.min(length, differs === -1 ? chars.length : differs);
1299
+ async function expand(scope, words) {
1300
+ if (scope.lazy.length === 0)
1301
+ return scope;
1302
+ const commands = { ...scope.commands };
1303
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
1304
+ for (const [name, command] of Object.entries(added))
1305
+ commands[name] ??= command;
1172
1306
  }
1173
- return first.slice(0, length).join("");
1307
+ return { ...scope, commands, lazy: [] };
1174
1308
  }
1175
- function listed2(colors, found, columns) {
1176
- const shared = sharedStart(found);
1177
- const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
1178
- const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
1179
- const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
1180
- return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
1309
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
1310
+ const colors = paint(stream);
1311
+ const prefix = path.join(" ");
1312
+ const summary = await resolveSummary(lazySummary);
1313
+ if (wantsHelpJson())
1314
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
1315
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1316
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
1317
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
1318
+ return [
1319
+ header(colors, summary),
1320
+ "",
1321
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
1322
+ "",
1323
+ ...await commandRows(commands, colors),
1324
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
1325
+ "",
1326
+ colors.bold("Options:"),
1327
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
1328
+ ...exampleRows(examples ?? [], colors),
1329
+ "",
1330
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
1331
+ ].join(`
1332
+ `);
1181
1333
  }
1182
- async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
1183
- let line = { text: "", caret: 0 };
1184
- let invalid;
1185
- let completions = [];
1186
- const remembered = history === undefined || mask ? undefined : history;
1187
- const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
1188
- let recalled = -1;
1189
- let draft = line;
1190
- const taken = () => line.text === "" ? fallback ?? "" : line.text;
1191
- const shown = () => mask ? "*".repeat([...taken()].length) : taken();
1192
- const accepted = await ask(question, settings, (colors, state, { columns }) => {
1193
- if (state !== "asking")
1194
- return [answer(colors, question, state, shown())];
1195
- const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
1196
- return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
1197
- }, (key) => {
1198
- if (key === "cancel")
1199
- return "cancel";
1200
- invalid = undefined;
1201
- completions = [];
1202
- if (line.chained === true && endsKills(key))
1203
- line = { ...line, chained: false };
1204
- if (key === "tab") {
1205
- const chars = [...line.text];
1206
- const before = chars.slice(0, line.caret).join("");
1207
- const found = complete?.(before) ?? [];
1208
- const filled = sharedStart(found);
1209
- if ([...filled].length > [...before].length)
1210
- line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
1211
- else
1212
- completions = found;
1213
- return;
1214
- }
1215
- if (key === "enter") {
1216
- invalid = validate?.(taken());
1217
- return invalid === undefined ? "enter" : undefined;
1334
+ function printError(prefix, message, hint, cause) {
1335
+ const colors = paint(process11.stderr);
1336
+ const styled = takesControlCodes(process11.stderr);
1337
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1338
+ const under = (label, text, tint) => text === undefined ? "" : `
1339
+ ${styled ? tint(label) : `${label}:`} ${text}`;
1340
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1341
+ }
1342
+ function printJsonError(message, hint, cause) {
1343
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1344
+ }
1345
+ function wantsJson(argv) {
1346
+ const end = argv.indexOf("--");
1347
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1348
+ }
1349
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
1350
+ if (error instanceof HelpShown)
1351
+ return 0;
1352
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1353
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1354
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1355
+ if (error instanceof Exit && error.code === 2)
1356
+ noteUsageError(error.message);
1357
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1358
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1359
+ return error instanceof Exit ? error.code : 1;
1360
+ }
1361
+ async function dispatch(level, typed, { version, redact }) {
1362
+ const prefix = level.path.join(" ");
1363
+ let argv;
1364
+ try {
1365
+ argv = takeOutputFlags(typed);
1366
+ } catch (error) {
1367
+ return reportThrown(prefix, error);
1368
+ }
1369
+ const [name, ...args] = argv;
1370
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
1371
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
1372
+ try {
1373
+ return await fallback.run([]);
1374
+ } catch (error) {
1375
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
1218
1376
  }
1219
- if (key === "up" || key === "down") {
1220
- const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
1221
- if (recalled === -1)
1222
- draft = line;
1223
- recalled = to;
1224
- const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
1225
- line = { ...shown, killed: line.killed ?? "" };
1226
- return;
1377
+ }
1378
+ if (name === undefined && level.path.length > 1) {
1379
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stderr));
1380
+ return 2;
1381
+ }
1382
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1383
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stdout));
1384
+ return 0;
1385
+ }
1386
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1387
+ console.log(version);
1388
+ return 0;
1389
+ }
1390
+ let command = level.commands[level.aliases?.[name] ?? name];
1391
+ let rest = args;
1392
+ let ran = name;
1393
+ if (command === undefined && level.lazy.length > 0) {
1394
+ level = await expand(level, [...level.path.slice(1), ...argv]);
1395
+ command = level.commands[level.aliases?.[name] ?? name];
1396
+ }
1397
+ if (command === undefined && level.defaultCommand !== undefined) {
1398
+ command = level.commands[level.defaultCommand];
1399
+ rest = argv;
1400
+ ran = level.defaultCommand;
1401
+ }
1402
+ if (command === undefined) {
1403
+ const meant = closest(name, Object.keys(shown(level.commands)));
1404
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
1405
+ return 2;
1406
+ }
1407
+ if ("commands" in command) {
1408
+ const { summary } = command;
1409
+ return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
1410
+ }
1411
+ try {
1412
+ return await command.run(rest);
1413
+ } catch (error) {
1414
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
1415
+ }
1416
+ }
1417
+ var COMPLETE = "__complete";
1418
+ var FILES = "__files__";
1419
+ async function completingOf(run) {
1420
+ completion.active = true;
1421
+ try {
1422
+ await run([]);
1423
+ } catch (error) {
1424
+ if (error instanceof Completing)
1425
+ return error;
1426
+ } finally {
1427
+ completion.active = false;
1428
+ }
1429
+ return new Completing({});
1430
+ }
1431
+ async function optionsOf(run) {
1432
+ return (await completingOf(run)).options;
1433
+ }
1434
+ function candidateLine(candidate) {
1435
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1436
+ }
1437
+ function positionalBeingTyped(before, { options, positionals }) {
1438
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1439
+ const typed = [];
1440
+ let at = 0;
1441
+ while (at < before.length) {
1442
+ const word = before[at];
1443
+ if (word === "--") {
1444
+ typed.push(...before.slice(at + 1));
1445
+ break;
1227
1446
  }
1228
- const edit = { home: "linestart", end: "lineend" }[key] ?? key;
1229
- if (typeof edit === "object" || isEditKey(edit))
1230
- line = editLine(line, edit);
1231
- return;
1232
- });
1233
- if (!accepted)
1234
- return;
1235
- if (remembered !== undefined && taken() !== "")
1236
- rememberAnswer(remembered, taken());
1237
- return taken();
1447
+ if (!word.startsWith("-"))
1448
+ typed.push(word);
1449
+ else if (takesValue(word))
1450
+ at++;
1451
+ at++;
1452
+ }
1453
+ const last = positionals.at(-1);
1454
+ if (typed.length < positionals.length)
1455
+ return { name: positionals[typed.length], typed };
1456
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1238
1457
  }
1239
- function answer(colors, question, state, picked) {
1240
- return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1458
+ async function leafCandidates(run, words) {
1459
+ const completing = await completingOf(run);
1460
+ if ((words.at(-1) ?? "").startsWith("-"))
1461
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1462
+ const flag = words.at(-2);
1463
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1464
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1465
+ if (option?.type === "string") {
1466
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1467
+ return values === undefined ? [FILES] : values.map(candidateLine);
1468
+ }
1469
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1470
+ return values === undefined ? [FILES] : values.map(candidateLine);
1241
1471
  }
1242
- async function ask(question, { hint, terminal = process14 }, render, press) {
1243
- const { stdin, stderr } = terminal;
1244
- if (!isInteractive(terminal))
1245
- fail(`cannot ask "${question}" off a terminal`, 2, hint);
1246
- const colors = paint(stderr);
1247
- let current = "asking";
1248
- let outcome;
1249
- const columns = () => stderr.columns || 80;
1250
- const draw = (state, last = false) => {
1251
- const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1252
- const rows = rowsTaken(frame, columns());
1253
- stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1254
- current = state;
1255
- };
1256
- const redraw = () => draw(current);
1257
- const paste = { active: false };
1258
- const stop = terminal.stop ?? (terminal === process14 ? stopJob : undefined);
1259
- const suspend = () => {
1260
- if (stop === undefined)
1261
- return;
1262
- stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1263
- stdin.setRawMode(false);
1264
- stop();
1265
- stdin.setRawMode(true);
1266
- stderr.write("\x1B[?25l\x1B[?2004h");
1267
- };
1472
+ async function candidates(scope, defaultCommand, words, before = []) {
1473
+ const [word = "", ...rest] = words;
1474
+ const listing = rest.length === 0 && !word.startsWith("-");
1475
+ let { commands, aliases } = scope;
1476
+ let command = commands[aliases?.[word] ?? word];
1477
+ if (listing || command === undefined) {
1478
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
1479
+ command = commands[aliases?.[word] ?? word];
1480
+ }
1481
+ if (listing) {
1482
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1483
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1484
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1485
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1486
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1487
+ }
1488
+ if (command === undefined) {
1489
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1490
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
1491
+ }
1492
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1493
+ }
1494
+ var COMPLETIONS = "--completions";
1495
+ function flagValue([flag = "", ...rest]) {
1496
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1497
+ }
1498
+ function printCompletionScript(name, args) {
1499
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1500
+ if (shell === undefined || args.length !== 1) {
1501
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1502
+ return 2;
1503
+ }
1504
+ console.log(completionScript(shell, [name]).trimEnd());
1505
+ return 0;
1506
+ }
1507
+ async function printCandidates(found) {
1508
+ for (const line of await found)
1509
+ console.log(line);
1510
+ return 0;
1511
+ }
1512
+ function packageVersion(entry = Bun.main) {
1513
+ let resolved = entry;
1268
1514
  try {
1269
- stderr.on?.("resize", redraw);
1270
- stdin.setRawMode(true);
1271
- stdin.resume();
1272
- stderr.write("\x1B[?25l\x1B[?2004h");
1273
- draw("asking");
1274
- return await new Promise((resolve) => {
1275
- function onData(data) {
1276
- for (const key of readKeys(data.toString(), paste)) {
1277
- if (key === "suspend") {
1278
- suspend();
1279
- continue;
1280
- }
1281
- const pressed = press(key);
1282
- if (pressed !== undefined) {
1283
- settle(pressed);
1284
- return;
1285
- }
1286
- }
1287
- draw("asking");
1288
- }
1289
- function onEnd() {
1290
- settle("cancel");
1291
- }
1292
- function settle(settled) {
1293
- outcome = settled;
1294
- stdin.off("data", onData);
1295
- stdin.off("end", onEnd);
1296
- resolve(settled === "enter");
1297
- }
1298
- stdin.on("data", onData);
1299
- stdin.on("end", onEnd);
1300
- });
1301
- } finally {
1302
- stderr.off?.("resize", redraw);
1303
- draw(outcome ?? "cancel", true);
1304
- stderr.write(`
1305
- \x1B[?25h\x1B[?2004l`);
1306
- stdin.setRawMode(false);
1307
- stdin.pause();
1515
+ resolved = realpathSync2(entry);
1516
+ } catch {}
1517
+ for (let dir = dirname2(resolved);; dir = dirname2(dir)) {
1518
+ try {
1519
+ const { version } = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
1520
+ if (typeof version === "string")
1521
+ return version;
1522
+ } catch {}
1523
+ if (dirname2(dir) === dir)
1524
+ return "0.0.0";
1525
+ }
1526
+ }
1527
+ async function runCli(cli, argv = scriptArgs()) {
1528
+ const version = cli.version ?? packageVersion();
1529
+ const answered = await askpassClient(argv);
1530
+ if (answered !== undefined)
1531
+ return answered;
1532
+ if (argv[0] === COMPLETE)
1533
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1534
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1535
+ return printCompletionScript(cli.name, flagValue(argv));
1536
+ const started = performance.now();
1537
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1538
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1539
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1540
+ if (cli.usage !== false) {
1541
+ try {
1542
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1543
+ } catch {}
1308
1544
  }
1545
+ return code;
1309
1546
  }
1547
+ function commandPath(scope, argv) {
1548
+ const path = [];
1549
+ let level = scope;
1550
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
1551
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1552
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1553
+ if (command === undefined)
1554
+ break;
1555
+ path.push(word);
1556
+ if (!("commands" in command))
1557
+ break;
1558
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1559
+ }
1560
+ return path.length === 0 ? undefined : path.join(" ");
1561
+ }
1562
+
1563
+ // ../kit/src/index.ts
1564
+ init_config();
1565
+
1566
+ // ../kit/src/excerpt.ts
1567
+ init_text2();
1568
+
1569
+ // ../kit/src/index.ts
1570
+ init_folders();
1571
+ init_format();
1572
+
1573
+ // ../kit/src/git.ts
1574
+ init_args();
1575
+ // ../kit/src/limit.ts
1576
+ init_args();
1577
+
1578
+ // ../kit/src/index.ts
1579
+ init_mode();
1580
+
1581
+ // ../kit/src/report.ts
1582
+ init_style();
1583
+ init_text2();
1584
+ // ../kit/src/secrets.ts
1585
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1586
+ // ../kit/src/sessions.ts
1587
+ var {Glob } = globalThis.Bun;
1588
+ var SESSION_FILES = new Glob("*.json");
1589
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1590
+
1591
+ // ../kit/src/index.ts
1592
+ init_style();
1593
+ init_text2();
1594
+ init_theme();
1595
+ init_user_config();
1596
+
1597
+ // ../kit/src/watch.ts
1598
+ init_args();
1599
+ init_input();
1600
+ init_style();
1601
+ // ../kit/src/workspace-root.ts
1602
+ init_user_config();
1603
+ // src/cli.ts
1604
+ init_prompt();
1310
1605
 
1311
1606
  // src/encode.ts
1312
1607
  function b64Encode(bytes, url = false) {
@@ -1486,7 +1781,7 @@ var NUMBER = /^-?\d+(?:\.\d+)?$/;
1486
1781
  var MILLISECONDS_FROM = 100000000000;
1487
1782
  function instant(kind, ms, now, timeZone) {
1488
1783
  if (Number.isNaN(new Date(ms).getTime()))
1489
- throw new Error("the date is out of range");
1784
+ throw new RangeError("the date is out of range");
1490
1785
  return { kind, ...zoned(ms, timeZone), ms, seconds: Math.floor(ms / 1000), relative: relative(ms, now) };
1491
1786
  }
1492
1787
  function convert(value, { now = Date.now(), timeZone } = {}) {
@@ -1577,18 +1872,18 @@ async function bytesInput(argument, what) {
1577
1872
  return new Uint8Array(await Bun.stdin.arrayBuffer());
1578
1873
  }
1579
1874
  function printRows(rows) {
1580
- const { cyan } = paint(process15.stdout);
1875
+ const { cyan } = paint(process16.stdout);
1581
1876
  const width = Math.max(...rows.map(([label]) => label.length));
1582
1877
  for (const [label, value] of rows)
1583
1878
  console.log(`${cyan(label.padEnd(width))} ${value}`);
1584
1879
  }
1585
- var PASSWORD_USAGE = `dev password [length] [format] [-b|--bcrypt [password]]: a random password of <length> bytes (default ${DEFAULT_LENGTH}) as hex, base64 (default) or base64url
1880
+ var PASSWORD_USAGE = `dev password [length] [format] [-b|--bcrypt [password]] [--copy]: a random password of <length> bytes (default ${DEFAULT_LENGTH}) as hex, base64 (default) or base64url
1586
1881
 
1587
- Printed on stdout and copied to the clipboard when a tool for it (wl-copy, xclip, xsel, pbcopy) exists (the copy is said on stderr). With --bcrypt it is the bcrypt hash (cost 10) that prints: of the password given (- asks for it masked on a terminal, or reads it from stdin, keeping it out of the shell history), or of a generated one, which then prints on stderr and is the one copied. Bun writes bcrypt as $2b$, the hash prints with the $2y$ prefix htpasswd -B writes, the one Apache, nginx and traefik basic auth all accept.`;
1882
+ Printed on stdout; --copy also copies it to the clipboard through wl-copy, xclip, xsel or pbcopy (the copy is said on stderr). With --bcrypt it is the bcrypt hash (cost 10) that prints: of the password given (- asks for it masked on a terminal, or reads it from stdin, keeping it out of the shell history), or of a generated one, which then prints on stderr and is the one --copy copies. Bun writes bcrypt as $2b$, the hash prints with the $2y$ prefix htpasswd -B writes, the one Apache, nginx and traefik basic auth all accept.`;
1588
1883
  var PASSWORD_EXITS = [[0, "it printed the password or hash"], [2, "a usage error"], [130, "the prompt was cancelled"]];
1589
1884
  var PASSWORD_OPTIONS = {
1590
1885
  bcrypt: { type: "string", short: "b", optional: { bare: "", accepts: STDIN_OR_VALUE }, description: "print the bcrypt hash of the password given, or of a generated one" },
1591
- "no-copy": { type: "boolean", description: "leave the clipboard alone" },
1886
+ copy: copyOption("the password, or the hash of a password given"),
1592
1887
  json: jsonOption("{password?, hash?, format, bytes, copied}")
1593
1888
  };
1594
1889
  var FORMAT_NOTES = { hex: "hexadecimal", base64: "base64", base64url: "url-safe base64" };
@@ -1608,13 +1903,13 @@ async function password(args) {
1608
1903
  const given = bcrypt === "-" ? await secretInput("the password") : bcrypt;
1609
1904
  const secret = given ?? generatePassword(bytes, format);
1610
1905
  const hash = values.bcrypt === undefined ? undefined : await bcryptHash(secret);
1611
- const copied = values["no-copy"] === true ? false : await copyText(given === undefined ? secret : hash ?? secret);
1906
+ const copied = values.copy === true && await copyText(given === undefined ? secret : hash ?? secret);
1612
1907
  if (values.json === true) {
1613
1908
  printJson({ ...hash === undefined ? {} : { hash }, ...given === undefined ? { password: secret } : {}, format, bytes, copied });
1614
1909
  return 0;
1615
1910
  }
1616
1911
  if (copied)
1617
- console.error(paint(process15.stderr).dim("copied to clipboard"));
1912
+ console.error(paint(process16.stderr).dim("copied to clipboard"));
1618
1913
  if (hash !== undefined && given === undefined)
1619
1914
  console.error(secret);
1620
1915
  console.log(hash ?? secret);
@@ -1643,7 +1938,7 @@ async function jwt(args) {
1643
1938
  printJson({ header: decoded.header, payload: decoded.payload, claims, signatureBytes: decoded.signatureBytes });
1644
1939
  return 0;
1645
1940
  }
1646
- const { bold } = paint(process15.stdout);
1941
+ const { bold } = paint(process16.stdout);
1647
1942
  console.log(`${bold("header")}
1648
1943
  ${JSON.stringify(decoded.header, null, 2)}
1649
1944
 
@@ -1829,13 +2124,13 @@ async function ip(args) {
1829
2124
  }
1830
2125
  }
1831
2126
  if (import.meta.main) {
1832
- process15.exitCode = await runCli({
2127
+ process16.exitCode = await runCli({
1833
2128
  name: "dev",
1834
2129
  about: "small developer utilities: passwords and bcrypt hashes, JWTs, timestamps, UUIDs, base64, URLs and file hashes",
1835
2130
  replaces: "openssl rand, htpasswd, jwt.io, date -d, uuidgen, base64, sha256sum and one-off scripts for each",
1836
2131
  examples: ["dev password", ["dev jwt <token>", "header, payload and expiry"], ["dev ts 1700000000", "an epoch as dates"]],
1837
2132
  commands: {
1838
- password: { summary: "a random password, copied to the clipboard, or its bcrypt hash", run: password },
2133
+ password: { summary: "a random password, or its bcrypt hash", run: password },
1839
2134
  jwt: { summary: "decode a JWT without verifying it, expiry shown as dates", run: jwt },
1840
2135
  ts: { summary: "convert epochs, ISO dates and durations, local and UTC", run: ts },
1841
2136
  uuid: { summary: "random UUIDs, v4 or v7", run: async (args) => Promise.resolve(uuid(args)) },