@kaynooo/cli-pick 0.11.1 → 0.11.3

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 +2 -0
  2. package/dist/pick.js +898 -689
  3. package/package.json +5 -5
package/dist/pick.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
-
4
- // src/pick.ts
5
- import process18 from "process";
6
- // ../kit/src/args.ts
7
- import process9 from "process";
8
- import { parseArgs } from "util";
9
-
10
- // ../kit/src/format.ts
11
- import process7 from "process";
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
+ };
12
14
 
13
15
  // ../kit/src/mode.ts
14
16
  import process2 from "process";
15
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
16
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
17
17
  function isSet(value) {
18
18
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
19
19
  }
@@ -27,12 +27,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
27
27
  return "terminal";
28
28
  return isSet(env.CI) ? "ci" : "pipe";
29
29
  }
30
+ var MODES, AGENT_VARIABLES;
31
+ var init_mode = __esm(() => {
32
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
33
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
34
+ });
30
35
 
31
- // ../kit/src/style.ts
32
- import process6 from "process";
33
-
34
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
35
- var G = /^[a-f0-9]+$/i;
36
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
36
37
  function b(r) {
37
38
  let e = r.startsWith("#") ? r.slice(1) : r;
38
39
  if (!G.test(e))
@@ -43,11 +44,6 @@ function b(r) {
43
44
  throw Error(`Invalid hex color length: ${e.length}`);
44
45
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
45
46
  }
46
- var 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") => {
47
- let [l, n, c] = b(r);
48
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
49
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
50
- var h = new Set(["", "1", "2", "3", "true"]);
51
47
  function C(r, e = globalThis.process?.env ?? {}) {
52
48
  if (e.FORCE_COLOR !== undefined)
53
49
  return h.has(e.FORCE_COLOR);
@@ -84,13 +80,21 @@ function f(r, e = []) {
84
80
  function Fe(r = {}) {
85
81
  return f(r);
86
82
  }
87
- var o = Fe();
83
+ var G, B, h, o;
84
+ var init_chunk_x450vn3m = __esm(() => {
85
+ G = /^[a-f0-9]+$/i;
86
+ 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") => {
87
+ let [l, n, c] = b(r);
88
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
89
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
90
+ h = new Set(["", "1", "2", "3", "true"]);
91
+ o = Fe();
92
+ });
88
93
 
89
- // ../kit/src/theme.ts
90
- import { existsSync as existsSync2, readFileSync, statSync } from "fs";
91
- import { homedir as homedir2 } from "os";
92
- import { join as join3, resolve as resolve2 } from "path";
93
- import process5 from "process";
94
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
95
+ var init_colors = __esm(() => {
96
+ init_chunk_x450vn3m();
97
+ });
94
98
 
95
99
  // ../kit/src/config.ts
96
100
  import { existsSync } from "fs";
@@ -106,6 +110,9 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
106
110
  return;
107
111
  }
108
112
  }
113
+ var init_config = __esm(() => {
114
+ init_args();
115
+ });
109
116
 
110
117
  // ../kit/src/user-config.ts
111
118
  import { homedir } from "os";
@@ -118,36 +125,18 @@ function configBase(where = {}) {
118
125
  function userConfigPath(bin, where = {}) {
119
126
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
120
127
  }
128
+ var init_user_config = () => {};
121
129
 
122
130
  // ../kit/src/theme.ts
123
- var ENDS = new Map;
124
- var DEFAULT = {
125
- colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
126
- glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
127
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
128
- bins: {},
129
- gradient: ["#c084fc", "#67e8f9"]
130
- };
131
- var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
132
- var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
133
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
134
- var PRESETS = {
135
- default: {},
136
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
137
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
138
- ascii: { glyphs: ASCII }
139
- };
140
- 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"]);
141
- var HEX = /^#[0-9a-f]{6}$/i;
142
- var CONTROL = /\p{Cc}/u;
143
- var MAX_FILE_BYTES = 64 * 1024;
144
- var SPACES = /\s+/;
131
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
132
+ import { homedir as homedir2 } from "os";
133
+ import { join as join3, resolve as resolve2 } from "path";
134
+ import process5 from "process";
145
135
  function isColorSpec(spec) {
146
136
  if (typeof spec === "number")
147
137
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
148
138
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
149
139
  }
150
- var CUBE = [0, 95, 135, 175, 215, 255];
151
140
  function cubeLevel(channel) {
152
141
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
153
142
  }
@@ -252,7 +241,6 @@ function applyFile(theme, file, where, warn) {
252
241
  function endsWalk(home) {
253
242
  return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
254
243
  }
255
- var warned = new Set;
256
244
  function warnOnce(message) {
257
245
  if (warned.has(message))
258
246
  return;
@@ -289,8 +277,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
289
277
  }
290
278
  return { theme, sources, preset };
291
279
  }
292
- var current;
293
- var currentKey = "";
294
280
  function activeTheme() {
295
281
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
296
282
  if (current === undefined || key !== currentKey) {
@@ -299,8 +285,38 @@ function activeTheme() {
299
285
  }
300
286
  return current;
301
287
  }
288
+ var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
289
+ var init_theme = __esm(() => {
290
+ init_config();
291
+ init_user_config();
292
+ ENDS = new Map;
293
+ DEFAULT = {
294
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
295
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
296
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
297
+ bins: {},
298
+ gradient: ["#c084fc", "#67e8f9"]
299
+ };
300
+ BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
301
+ MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
302
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
303
+ PRESETS = {
304
+ default: {},
305
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
306
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
307
+ ascii: { glyphs: ASCII }
308
+ };
309
+ 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"]);
310
+ HEX = /^#[0-9a-f]{6}$/i;
311
+ CONTROL = /\p{Cc}/u;
312
+ MAX_FILE_BYTES = 64 * 1024;
313
+ SPACES = /\s+/;
314
+ CUBE = [0, 95, 135, 175, 215, 255];
315
+ warned = new Set;
316
+ });
302
317
 
303
318
  // ../kit/src/style.ts
319
+ import process6 from "process";
304
320
  function takesControlCodes(stream, env = process6.env) {
305
321
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
306
322
  }
@@ -311,17 +327,23 @@ function role(name, stream, env = process6.env) {
311
327
  const colors = paint(stream, env);
312
328
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
313
329
  }
314
- var STATUS_WORDS = {
315
- passed: ["passed", "success", "succeeded", "ok"],
316
- failed: ["failed", "failure", "error", "errored"],
317
- running: ["running", "in_progress", "started", "holding"],
318
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
319
- skipped: ["skipped", "cancelled", "canceled", "manual"]
320
- };
321
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
330
+ var STATUS_WORDS, STATUS_OF;
331
+ var init_style = __esm(() => {
332
+ init_colors();
333
+ init_mode();
334
+ init_theme();
335
+ STATUS_WORDS = {
336
+ passed: ["passed", "success", "succeeded", "ok"],
337
+ failed: ["failed", "failure", "error", "errored"],
338
+ running: ["running", "in_progress", "started", "holding"],
339
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
340
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
341
+ };
342
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
343
+ });
322
344
 
323
345
  // ../kit/src/format.ts
324
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
346
+ import process7 from "process";
325
347
  function formatSeconds(total) {
326
348
  let rest = Math.max(0, Math.round(total));
327
349
  const amounts = UNITS.map(([unit, size]) => {
@@ -342,7 +364,6 @@ function upTo(text, separator) {
342
364
  const end = text.indexOf(separator);
343
365
  return end === -1 ? text : text.slice(0, end);
344
366
  }
345
- var ESCAPE = String.fromCharCode(27);
346
367
  function textWidth(text) {
347
368
  return Bun.stringWidth(text);
348
369
  }
@@ -352,14 +373,38 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
352
373
  function printJson(value) {
353
374
  console.log(jsonText(value));
354
375
  }
376
+ var UNITS, ESCAPE;
377
+ var init_format = __esm(() => {
378
+ init_mode();
379
+ init_style();
380
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
381
+ ESCAPE = String.fromCharCode(27);
382
+ });
355
383
 
356
384
  // ../kit/src/help.ts
357
385
  import process8 from "process";
358
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
359
- var USAGE_PREFIX = /^usage:\s*/i;
360
- var FULL_STOP = /\.$/;
361
386
  function usageLine(usage, colors = paint(process8.stdout)) {
362
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
387
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
388
+ `);
389
+ const blank = lines.indexOf("");
390
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
391
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
392
+ const colon = synopses[0].indexOf(": ");
393
+ const inline = synopses[0].slice(colon + 2);
394
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
395
+ if (colon !== -1)
396
+ synopses[0] = synopses[0].slice(0, colon);
397
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
398
+ `)}`;
399
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
400
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
401
+ return [head, ...lead, ...rest].join(`
402
+ `);
403
+ }
404
+ function prose(line, colors) {
405
+ if (colors.cyan("x") === "x")
406
+ return line;
407
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
363
408
  }
364
409
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
365
410
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -394,7 +439,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
394
439
  return [];
395
440
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
396
441
  }
397
- var MAX_INLINE_CHOICES = 24;
398
442
  function optionRows(options, colors = paint(process8.stdout)) {
399
443
  const rows = Object.entries(options).map(([name, option]) => {
400
444
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -409,9 +453,17 @@ function optionRows(options, colors = paint(process8.stdout)) {
409
453
  const width = Math.max(0, ...rows.map((row) => row.width));
410
454
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
411
455
  }
456
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
457
+ var init_help = __esm(() => {
458
+ init_mode();
459
+ init_style();
460
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
461
+ USAGE_PREFIX = /^usage:\s*/i;
462
+ FULL_STOP = /\.$/;
463
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
464
+ });
412
465
 
413
466
  // ../kit/src/text.ts
414
- var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
415
467
  function distance(a, b) {
416
468
  const left = [...a];
417
469
  const right = [...b];
@@ -437,40 +489,29 @@ function closest(name, names) {
437
489
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
438
490
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
439
491
  }
492
+ var ANSI;
493
+ var init_text = __esm(() => {
494
+ ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
495
+ });
496
+
497
+ // ../kit/src/input.ts
498
+ var init_input = __esm(() => {
499
+ init_args();
500
+ });
440
501
 
441
502
  // ../kit/src/args.ts
442
- var DASHES = /^-+/;
503
+ import process9 from "process";
504
+ import { parseArgs } from "util";
443
505
  function jsonOption(holds) {
444
506
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
445
507
  }
446
- class Exit extends Error {
447
- code;
448
- hint;
449
- constructor(message, code, hint) {
450
- super(message);
451
- this.code = code;
452
- this.hint = hint;
453
- }
454
- }
455
508
  function fail(message, code = 2, hint) {
456
509
  throw new Exit(message, code, hint);
457
510
  }
458
-
459
- class UsageError extends Exit {
460
- constructor(message, hint) {
461
- super(message, 2, hint);
462
- }
463
- }
464
511
  function badUsage(message) {
465
512
  throw new UsageError(message);
466
513
  }
467
514
 
468
- class HelpShown extends Exit {
469
- constructor() {
470
- super("help shown", 0);
471
- }
472
- }
473
-
474
515
  class Completing {
475
516
  options;
476
517
  positionals;
@@ -481,11 +522,6 @@ class Completing {
481
522
  this.candidates = candidates;
482
523
  }
483
524
  }
484
- var completion = { active: false };
485
- var OUTPUT_OPTIONS = {
486
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
487
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
488
- };
489
525
  function applyOutput(color, plain, env = process9.env) {
490
526
  const when = plain === true ? "never" : color ?? "auto";
491
527
  if (when === "auto")
@@ -639,7 +675,6 @@ function parseError(error) {
639
675
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
640
676
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
641
677
  }
642
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
643
678
  function nearestOption(message, options, allowNegative) {
644
679
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
645
680
  if (typed === undefined)
@@ -655,381 +690,109 @@ function nearestOption(message, options, allowNegative) {
655
690
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
656
691
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
657
692
  }
658
- // ../kit/src/argv.ts
659
- import { readFileSync as readFileSync2, realpathSync } from "fs";
660
- import { resolve as resolve3 } from "path";
661
- import process10 from "process";
662
- function commandLine() {
663
- try {
664
- return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
665
- } catch {
666
- return;
667
- }
668
- }
669
- function realPath(word) {
670
- try {
671
- return realpathSync(resolve3(word));
672
- } catch {
673
- return;
674
- }
675
- }
676
- function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
677
- const target = script === undefined ? undefined : realPath(script) ?? script;
678
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
679
- const after = at === -1 ? [] : cmdline.slice(at + 1);
680
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
681
- }
682
- // ../kit/src/progress.ts
683
- var ESC = String.fromCharCode(27);
684
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
685
- var RESET_STYLE = `${ESC}[0m`;
686
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
687
- // ../kit/src/cli.ts
688
- import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
689
- import { dirname as dirname3, join as join5 } from "path";
690
- import process13 from "process";
693
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
694
+ var init_args = __esm(() => {
695
+ init_format();
696
+ init_help();
697
+ init_text();
698
+ init_help();
699
+ init_input();
700
+ DASHES = /^-+/;
701
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
702
+ Exit = class Exit extends Error {
703
+ code;
704
+ hint;
705
+ [EXIT] = true;
706
+ constructor(message, code, hint) {
707
+ super(message);
708
+ this.code = code;
709
+ this.hint = hint;
710
+ }
711
+ static [Symbol.hasInstance](value) {
712
+ if (this !== Exit)
713
+ return Function.prototype[Symbol.hasInstance].call(this, value);
714
+ return typeof value === "object" && value !== null && value[EXIT] === true;
715
+ }
716
+ };
717
+ UsageError = class UsageError extends Exit {
718
+ constructor(message, hint) {
719
+ super(message, 2, hint);
720
+ }
721
+ };
722
+ HelpShown = class HelpShown extends Exit {
723
+ constructor() {
724
+ super("help shown", 0);
725
+ }
726
+ };
727
+ completion = { active: false };
728
+ OUTPUT_OPTIONS = {
729
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
730
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
731
+ };
732
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
733
+ });
691
734
 
692
- // ../kit/src/completions.ts
693
- var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
694
- 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'
695
- set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
696
- set -l current (commandline -ct)
697
- for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
698
- if test "$line" = __files__
699
- __fish_complete_path $current
700
- else
701
- echo $line
702
- end
703
- end
704
- end`;
705
- var BASH_FUNCTION = `__kaynooo_cli_complete() {
706
- local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
707
- local -a lines
708
- COMPREPLY=()
709
- lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
710
- for line in "\${lines[@]}"; do
711
- if [[ $line == __files__ ]]; then
712
- COMPREPLY+=($(compgen -f -- "$cur"))
713
- else
714
- words+="\${line%%$'\\t'*}"$'\\n'
715
- fi
716
- done
717
- COMPREPLY+=($(compgen -W "$words" -- "$cur"))
718
- }`;
719
- var ZSH_FUNCTION = `__kaynooo_cli_complete() {
720
- local line
721
- local -a described plain
722
- for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
723
- if [[ $line == __files__ ]]; then
724
- _files
725
- elif [[ $line == *$'\\t'* ]]; then
726
- described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
727
- else
728
- plain+=("$line")
729
- fi
730
- done
731
- (( \${#described} )) && _describe -V value described
732
- (( \${#plain} )) && compadd -- "\${plain[@]}"
733
- return 0
734
- }`;
735
- function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
736
- if (shell === "fish")
737
- return `${header}
738
- ${FISH_FUNCTION}
739
- ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
740
- `).join("")}`;
741
- if (shell === "bash")
742
- return `${header}
743
- ${BASH_FUNCTION}
744
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
745
- `;
746
- return `${header}
747
- ${ZSH_FUNCTION}
748
- compdef __kaynooo_cli_complete ${bins.join(" ")}
749
- `;
750
- }
735
+ // ../kit/src/folders.ts
736
+ var SKIPPED_FOLDERS;
737
+ var init_folders = __esm(() => {
738
+ init_user_config();
739
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
740
+ });
751
741
 
752
- // ../kit/src/notify.ts
753
- import process11 from "process";
754
- var NOTIFY_AFTER_MS = 1e4;
755
- var CANCELLED = 130;
756
- function base64(text) {
757
- return Buffer.from(text).toString("base64");
758
- }
759
- function notification(title, body, env = process11.env) {
760
- const id = `kit${process11.pid}`;
761
- 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\\`];
762
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
742
+ // ../kit/src/picker/line.ts
743
+ function isEditKey(key) {
744
+ return EDIT_KEYS.has(key);
763
745
  }
764
- function notifyEnd(command, code, ms, { stream = process11.stderr, env = process11.env } = {}) {
765
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
766
- return;
767
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
746
+ function endsKills(key) {
747
+ return typeof key !== "object" && !isEditKey(key);
768
748
  }
769
-
770
- // ../kit/src/usage.ts
771
- import { appendFileSync, mkdirSync } from "fs";
772
- import { homedir as homedir3 } from "os";
773
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
774
- import process12 from "process";
775
-
776
- // ../kit/src/logs.ts
777
- var DAY_MS = 24 * 60 * 60 * 1000;
778
- var CLI_FOLDER = "kaynooo-cli";
779
-
780
- // ../kit/src/usage.ts
781
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
782
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
783
- var LONGEST_NAME = 40;
784
- var usageError;
785
- function noteUsageError(message) {
786
- usageError = message;
749
+ function isWord(char) {
750
+ return char !== undefined && WORD_CHARACTER.test(char);
787
751
  }
788
- function stateHome(env = process12.env) {
789
- const dir = env.XDG_STATE_HOME;
790
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
752
+ function wordStart(chars, from) {
753
+ let at = from;
754
+ while (at > 0 && !isWord(chars[at - 1]))
755
+ at--;
756
+ while (at > 0 && isWord(chars[at - 1]))
757
+ at--;
758
+ return at;
791
759
  }
792
- function usagePath(env = process12.env) {
793
- return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
760
+ function wordEnd(chars, from) {
761
+ let at = from;
762
+ while (at < chars.length && !isWord(chars[at]))
763
+ at++;
764
+ while (at < chars.length && isWord(chars[at]))
765
+ at++;
766
+ return at;
794
767
  }
795
- function usageRecorded(env = process12.env) {
796
- const off = env.KAYNOOO_CLI_NO_USAGE;
797
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
768
+ function spacedStart(chars, from) {
769
+ let at = from;
770
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
771
+ at--;
772
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
773
+ at--;
774
+ return at;
798
775
  }
799
- function flagNames(argv) {
800
- const end = argv.indexOf("--");
801
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
802
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
776
+ function cut(chars, from, to) {
777
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
803
778
  }
804
- function usageEntry(bin, command, argv, code, now = new Date) {
805
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
806
- usageError = undefined;
807
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
779
+ function insert(chars, at, text) {
780
+ const typed = [...text];
781
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
808
782
  }
809
- function recordUsage(entry, env = process12.env) {
810
- if (!usageRecorded(env))
811
- return;
812
- try {
813
- const path = usagePath(env);
814
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
815
- appendFileSync(path, `${JSON.stringify(entry)}
816
- `, { mode: 384 });
817
- } catch {}
818
- }
819
-
820
- // ../kit/src/cli.ts
821
- var LEVEL_OPTIONS = {
822
- ...OUTPUT_OPTIONS,
823
- help: { type: "boolean", short: "h", description: "show this help" }
824
- };
825
- var TOP_OPTIONS = {
826
- ...LEVEL_OPTIONS,
827
- version: { type: "boolean", short: "v", description: "print the version" },
828
- completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
829
- };
830
- function printError(prefix, message, hint, cause) {
831
- const colors = paint(process13.stderr);
832
- const styled = takesControlCodes(process13.stderr);
833
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
834
- const under = (label, text, tint) => text === undefined ? "" : `
835
- ${styled ? tint(label) : `${label}:`} ${text}`;
836
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
837
- }
838
- function printJsonError(message, hint, cause) {
839
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
840
- }
841
- function wantsJson(argv) {
842
- const end = argv.indexOf("--");
843
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
844
- }
845
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
846
- if (error instanceof HelpShown)
847
- return 0;
848
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
849
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
850
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
851
- if (error instanceof Exit && error.code === 2)
852
- noteUsageError(error.message);
853
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
854
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
855
- return error instanceof Exit ? error.code : 1;
856
- }
857
- var COMPLETE = "__complete";
858
- var FILES = "__files__";
859
- async function completingOf(run) {
860
- completion.active = true;
861
- try {
862
- await run([]);
863
- } catch (error) {
864
- if (error instanceof Completing)
865
- return error;
866
- } finally {
867
- completion.active = false;
868
- }
869
- return new Completing({});
870
- }
871
- function candidateLine(candidate) {
872
- return typeof candidate === "string" ? candidate : candidate.join("\t");
873
- }
874
- function positionalBeingTyped(before, { options, positionals }) {
875
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
876
- const typed = [];
877
- let at = 0;
878
- while (at < before.length) {
879
- const word = before[at];
880
- if (word === "--") {
881
- typed.push(...before.slice(at + 1));
882
- break;
883
- }
884
- if (!word.startsWith("-"))
885
- typed.push(word);
886
- else if (takesValue(word))
887
- at++;
888
- at++;
889
- }
890
- const last = positionals.at(-1);
891
- if (typed.length < positionals.length)
892
- return { name: positionals[typed.length], typed };
893
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
894
- }
895
- async function leafCandidates(run, words) {
896
- const completing = await completingOf(run);
897
- if ((words.at(-1) ?? "").startsWith("-"))
898
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
899
- const flag = words.at(-2);
900
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
901
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
902
- if (option?.type === "string") {
903
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
904
- return values === undefined ? [FILES] : values.map(candidateLine);
905
- }
906
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
907
- return values === undefined ? [FILES] : values.map(candidateLine);
908
- }
909
- var COMPLETIONS = "--completions";
910
- function flagValue([flag = "", ...rest]) {
911
- return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
912
- }
913
- function printCompletionScript(name, args) {
914
- const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
915
- if (shell === undefined || args.length !== 1) {
916
- printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
917
- return 2;
918
- }
919
- console.log(completionScript(shell, [name]).trimEnd());
920
- return 0;
921
- }
922
- async function printCandidates(found) {
923
- for (const line of await found)
924
- console.log(line);
925
- return 0;
926
- }
927
- function packageVersion(entry = Bun.main) {
928
- let resolved = entry;
929
- try {
930
- resolved = realpathSync2(entry);
931
- } catch {}
932
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
933
- try {
934
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
935
- if (typeof version === "string")
936
- return version;
937
- } catch {}
938
- if (dirname3(dir) === dir)
939
- return "0.0.0";
940
- }
941
- }
942
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
943
- if (argv[0] === COMPLETE)
944
- return printCandidates(leafCandidates(run, argv.slice(1)));
945
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
946
- return printCompletionScript(name, flagValue(argv));
947
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
948
- console.log(version ?? packageVersion());
949
- return 0;
950
- }
951
- let code;
952
- const started = performance.now();
953
- try {
954
- code = await run(argv);
955
- } catch (error) {
956
- code = reportThrown(name, error, redact, wantsJson(argv));
957
- }
958
- notifyEnd(name, code, performance.now() - started);
959
- if (usage !== false) {
960
- try {
961
- recordUsage(usageEntry(name, undefined, argv, code));
962
- } catch {}
963
- }
964
- return code;
965
- }
966
- // ../kit/src/folders.ts
967
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
968
- // ../kit/src/secrets.ts
969
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
970
- // ../kit/src/sessions.ts
971
- var {Glob } = globalThis.Bun;
972
- var SESSION_FILES = new Glob("*.json");
973
- var ACCOUNT_DIRS = new Glob("*/sessions");
974
- // ../kit/src/picker/line.ts
975
- var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
976
- var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
977
- var FORWARD_KILLS = new Set(["killnext", "killend"]);
978
- function isEditKey(key) {
979
- return EDIT_KEYS.has(key);
980
- }
981
- function endsKills(key) {
982
- return typeof key !== "object" && !isEditKey(key);
983
- }
984
- var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
985
- var SPACE = /\s/;
986
- function isWord(char) {
987
- return char !== undefined && WORD_CHARACTER.test(char);
988
- }
989
- function wordStart(chars, from) {
990
- let at = from;
991
- while (at > 0 && !isWord(chars[at - 1]))
992
- at--;
993
- while (at > 0 && isWord(chars[at - 1]))
994
- at--;
995
- return at;
996
- }
997
- function wordEnd(chars, from) {
998
- let at = from;
999
- while (at < chars.length && !isWord(chars[at]))
1000
- at++;
1001
- while (at < chars.length && isWord(chars[at]))
1002
- at++;
1003
- return at;
1004
- }
1005
- function spacedStart(chars, from) {
1006
- let at = from;
1007
- while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
1008
- at--;
1009
- while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
1010
- at--;
1011
- return at;
1012
- }
1013
- function cut(chars, from, to) {
1014
- return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1015
- }
1016
- function insert(chars, at, text) {
1017
- const typed = [...text];
1018
- return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
1019
- }
1020
- function editLine(line, key) {
1021
- const { killed = "", chained = false } = line;
1022
- const chars = [...line.text];
1023
- const at = Math.min(Math.max(line.caret, 0), chars.length);
1024
- const edited = edit(chars, at, key, killed);
1025
- if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1026
- return line.killed === undefined ? edited : { ...edited, killed };
1027
- const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1028
- if (taken === "")
1029
- return { ...edited, killed, chained };
1030
- if (!chained)
1031
- return { ...edited, killed: taken, chained: true };
1032
- return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
783
+ function editLine(line, key) {
784
+ const { killed = "", chained = false } = line;
785
+ const chars = [...line.text];
786
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
787
+ const edited = edit(chars, at, key, killed);
788
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
789
+ return line.killed === undefined ? edited : { ...edited, killed };
790
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
791
+ if (taken === "")
792
+ return { ...edited, killed, chained };
793
+ if (!chained)
794
+ return { ...edited, killed: taken, chained: true };
795
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1033
796
  }
1034
797
  function edit(chars, at, key, killed) {
1035
798
  const text = chars.join("");
@@ -1083,17 +846,16 @@ function visible({ text, caret }, room) {
1083
846
  const right = end < cells.length ? "\u2026" : "";
1084
847
  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) };
1085
848
  }
849
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
850
+ var init_line = __esm(() => {
851
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
852
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
853
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
854
+ WORD_CHARACTER = /[\p{L}\p{N}_]/u;
855
+ SPACE = /\s/;
856
+ });
1086
857
 
1087
858
  // ../kit/src/picker/score.ts
1088
- var MATCH = 16;
1089
- var CONSECUTIVE = 12;
1090
- var BOUNDARY = 10;
1091
- var PREFIX = 8;
1092
- var GAP = 1;
1093
- var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1094
- var UPPER = /\p{Lu}/u;
1095
- var LOWER = /\p{Ll}/u;
1096
- var NONE = Number.NEGATIVE_INFINITY;
1097
859
  function startsWord(text, index) {
1098
860
  if (index === 0)
1099
861
  return true;
@@ -1166,229 +928,671 @@ function rank(query, lines) {
1166
928
  }
1167
929
  return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
1168
930
  }
931
+ var MATCH = 16, CONSECUTIVE = 12, BOUNDARY = 10, PREFIX = 8, GAP = 1, BOUNDARY_AFTER, UPPER, LOWER, NONE;
932
+ var init_score = __esm(() => {
933
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
934
+ UPPER = /\p{Lu}/u;
935
+ LOWER = /\p{Ll}/u;
936
+ NONE = Number.NEGATIVE_INFINITY;
937
+ });
1169
938
 
1170
939
  // ../kit/src/picker/state.ts
1171
- var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1172
- var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1173
- var SGR = /^\x1B\[[0-9;]*m$/;
1174
- var RESET = /^\x1B\[0?m$/;
1175
- var COLUMN_GAP = 2;
1176
- var PASTE_START = "\x1B[200~";
1177
- var PASTE_END = "\x1B[201~";
1178
- var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1179
- var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1180
- var WHEEL_LINES = 3;
1181
- var KEYS = {
1182
- "\x1B[A": "up",
1183
- "\x1BOA": "up",
1184
- "\x10": "up",
1185
- "\x1B[B": "down",
1186
- "\x1BOB": "down",
1187
- "\x0E": "down",
1188
- "\x1B[5~": "pageup",
1189
- "\x1B[6~": "pagedown",
1190
- "\x1B[H": "home",
1191
- "\x1B[1~": "home",
1192
- "\x1BOH": "home",
1193
- "\x1B[F": "end",
1194
- "\x1B[4~": "end",
1195
- "\x1BOF": "end",
1196
- "\r": "enter",
1197
- "\n": "enter",
1198
- "\x03": "cancel",
1199
- "\x1B": "cancel",
1200
- "\x1B[D": "left",
1201
- "\x1BOD": "left",
1202
- "\x1B[C": "right",
1203
- "\x1BOC": "right",
1204
- "\x1B[1;5D": "wordleft",
1205
- "\x1B[1;3D": "wordleft",
1206
- "\x1Bb": "wordleft",
1207
- "\x1B[1;5C": "wordright",
1208
- "\x1B[1;3C": "wordright",
1209
- "\x1Bf": "wordright",
1210
- "\x01": "linestart",
1211
- "\x05": "lineend",
1212
- "\x7F": "erase",
1213
- "\x1B[3~": "delete",
1214
- "\b": "killword",
1215
- "\x1B\x7F": "killword",
1216
- "\x1B[3;5~": "killnext",
1217
- "\x1Bd": "killnext",
1218
- "\x15": "clear",
1219
- "\v": "killend",
1220
- "\x17": "word",
1221
- "\x19": "yank",
1222
- "\x1A": "suspend",
1223
- "\t": "tab",
1224
- "\x1F": "help",
1225
- "\x1BOP": "help",
1226
- "\x1B[11~": "help"
1227
- };
1228
940
  function repeat(value, count) {
1229
941
  return Array.from({ length: count }).fill(value);
1230
942
  }
1231
- function styled(line) {
1232
- let text = "";
1233
- const styles = [];
1234
- let active = "";
1235
- let colored = false;
1236
- let last = 0;
1237
- function add(chunk) {
1238
- const flat = chunk.replace(CONTROL2, " ");
1239
- text += flat;
1240
- colored ||= active !== "" && flat !== "";
1241
- styles.push(...repeat(active, flat.length));
1242
- }
1243
- for (const found of line.matchAll(ANSI)) {
1244
- add(line.slice(last, found.index));
1245
- last = found.index + found[0].length;
1246
- if (SGR.test(found[0]))
1247
- active = RESET.test(found[0]) ? "" : active + found[0];
943
+ function styled(line) {
944
+ let text = "";
945
+ const styles = [];
946
+ let active = "";
947
+ let colored = false;
948
+ let last = 0;
949
+ function add(chunk) {
950
+ const flat = chunk.replace(CONTROL2, " ");
951
+ text += flat;
952
+ colored ||= active !== "" && flat !== "";
953
+ styles.push(...repeat(active, flat.length));
954
+ }
955
+ for (const found of line.matchAll(ANSI)) {
956
+ add(line.slice(last, found.index));
957
+ last = found.index + found[0].length;
958
+ if (SGR.test(found[0]))
959
+ active = RESET.test(found[0]) ? "" : active + found[0];
960
+ }
961
+ add(line.slice(last));
962
+ return { text, styles: colored ? styles : undefined };
963
+ }
964
+ function lay(rows, searched) {
965
+ const parsed = rows.map((row) => row.cells.map(styled));
966
+ const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
967
+ return parsed.map((cells, at) => {
968
+ let text = "";
969
+ const styles = [];
970
+ let colored = false;
971
+ let searchEnd = 0;
972
+ for (const [column, cell] of cells.entries()) {
973
+ const last = column === cells.length - 1;
974
+ const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
975
+ text += shown;
976
+ colored ||= cell.styles !== undefined;
977
+ styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
978
+ if (column < searched)
979
+ searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
980
+ if (!last) {
981
+ const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
982
+ text += " ".repeat(pad);
983
+ styles.push(...repeat("", pad));
984
+ }
985
+ }
986
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
987
+ });
988
+ }
989
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
990
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
991
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
992
+ const wheel = MOUSE.exec(sequence)?.[1];
993
+ if (wheel !== undefined)
994
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
995
+ const named = codes.get(sequence);
996
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
997
+ if (sequence === PASTE_START || sequence === PASTE_END) {
998
+ paste.active = sequence === PASTE_START;
999
+ return [];
1000
+ }
1001
+ if (paste.active && (sequence === "\r" || sequence === `
1002
+ `))
1003
+ return [];
1004
+ if (key !== undefined)
1005
+ return [key];
1006
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1007
+ });
1008
+ }
1009
+ function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1010
+ const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1011
+ return withRows(state, rows);
1012
+ }
1013
+ function withRows(state, rows, header = state.header) {
1014
+ const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1015
+ const laid = lay(cells, state.searched);
1016
+ const searchable = laid.map((row) => row.searchable);
1017
+ const matches = rank(state.query, searchable);
1018
+ return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
1019
+ }
1020
+ function withQuery(state, key) {
1021
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1022
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1023
+ }
1024
+ function move(state, by) {
1025
+ return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1026
+ }
1027
+ function highlighted(state) {
1028
+ return state.matches[state.cursor]?.index;
1029
+ }
1030
+ function press(state, key) {
1031
+ if (state.done !== undefined)
1032
+ return state;
1033
+ if (state.chained && endsKills(key))
1034
+ state = { ...state, chained: false };
1035
+ if (state.help)
1036
+ return { ...state, help: false };
1037
+ if (typeof key === "object") {
1038
+ if ("text" in key)
1039
+ return withQuery(state, key);
1040
+ return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1041
+ }
1042
+ if (isEditKey(key))
1043
+ return withQuery(state, key);
1044
+ switch (key) {
1045
+ case "up":
1046
+ return move(state, -1);
1047
+ case "down":
1048
+ return move(state, 1);
1049
+ case "pageup":
1050
+ return move(state, -state.page);
1051
+ case "pagedown":
1052
+ return move(state, state.page);
1053
+ case "home":
1054
+ return move(state, -state.matches.length);
1055
+ case "end":
1056
+ return move(state, state.matches.length);
1057
+ case "cancel":
1058
+ return { ...state, done: "cancel" };
1059
+ case "help":
1060
+ return { ...state, help: true };
1061
+ case "suspend":
1062
+ return state;
1063
+ case "enter":
1064
+ return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1065
+ case "tab": {
1066
+ const at = highlighted(state);
1067
+ if (!state.multi || at === undefined)
1068
+ return state;
1069
+ const marked = new Set(state.marked);
1070
+ if (!marked.delete(at))
1071
+ marked.add(at);
1072
+ return move({ ...state, marked }, 1);
1073
+ }
1074
+ }
1075
+ }
1076
+ function chosen(state) {
1077
+ if (state.marked.size > 0)
1078
+ return state.rows.filter((_, index) => state.marked.has(index));
1079
+ const at = highlighted(state);
1080
+ return at === undefined ? [] : [state.rows[at]];
1081
+ }
1082
+ var CONTROL2, IS_CONTROL, SGR, RESET, COLUMN_GAP = 2, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
1083
+ var init_state = __esm(() => {
1084
+ init_text();
1085
+ init_line();
1086
+ init_score();
1087
+ CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1088
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1089
+ SGR = /^\x1B\[[0-9;]*m$/;
1090
+ RESET = /^\x1B\[0?m$/;
1091
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1092
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1093
+ KEYS = {
1094
+ "\x1B[A": "up",
1095
+ "\x1BOA": "up",
1096
+ "\x10": "up",
1097
+ "\x1B[B": "down",
1098
+ "\x1BOB": "down",
1099
+ "\x0E": "down",
1100
+ "\x1B[5~": "pageup",
1101
+ "\x1B[6~": "pagedown",
1102
+ "\x1B[H": "home",
1103
+ "\x1B[1~": "home",
1104
+ "\x1BOH": "home",
1105
+ "\x1B[F": "end",
1106
+ "\x1B[4~": "end",
1107
+ "\x1BOF": "end",
1108
+ "\r": "enter",
1109
+ "\n": "enter",
1110
+ "\x03": "cancel",
1111
+ "\x1B": "cancel",
1112
+ "\x1B[D": "left",
1113
+ "\x1BOD": "left",
1114
+ "\x1B[C": "right",
1115
+ "\x1BOC": "right",
1116
+ "\x1B[1;5D": "wordleft",
1117
+ "\x1B[1;3D": "wordleft",
1118
+ "\x1Bb": "wordleft",
1119
+ "\x1B[1;5C": "wordright",
1120
+ "\x1B[1;3C": "wordright",
1121
+ "\x1Bf": "wordright",
1122
+ "\x01": "linestart",
1123
+ "\x05": "lineend",
1124
+ "\x7F": "erase",
1125
+ "\x1B[3~": "delete",
1126
+ "\b": "killword",
1127
+ "\x1B\x7F": "killword",
1128
+ "\x1B[3;5~": "killnext",
1129
+ "\x1Bd": "killnext",
1130
+ "\x15": "clear",
1131
+ "\v": "killend",
1132
+ "\x17": "word",
1133
+ "\x19": "yank",
1134
+ "\x1A": "suspend",
1135
+ "\t": "tab",
1136
+ "\x1F": "help",
1137
+ "\x1BOP": "help",
1138
+ "\x1B[11~": "help"
1139
+ };
1140
+ });
1141
+
1142
+ // ../kit/src/job.ts
1143
+ import process16 from "process";
1144
+ function stopJob() {
1145
+ process16.kill(0, "SIGTSTP");
1146
+ }
1147
+ var init_job = () => {};
1148
+
1149
+ // ../kit/src/redraw.ts
1150
+ function overwrite(lines, columns) {
1151
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1152
+ `);
1153
+ }
1154
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
1155
+ var init_redraw = __esm(() => {
1156
+ init_format();
1157
+ });
1158
+
1159
+ // src/pick.ts
1160
+ import process19 from "process";
1161
+
1162
+ // ../kit/src/index.ts
1163
+ init_args();
1164
+
1165
+ // ../kit/src/argv.ts
1166
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
1167
+ import { resolve as resolve3 } from "path";
1168
+ import process10 from "process";
1169
+ function commandLine() {
1170
+ try {
1171
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
1172
+ } catch {
1173
+ return;
1174
+ }
1175
+ }
1176
+ function realPath(word) {
1177
+ try {
1178
+ return realpathSync(resolve3(word));
1179
+ } catch {
1180
+ return;
1181
+ }
1182
+ }
1183
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
1184
+ const target = script === undefined ? undefined : realPath(script) ?? script;
1185
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
1186
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
1187
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
1188
+ }
1189
+ // ../kit/src/chart.ts
1190
+ init_format();
1191
+ init_mode();
1192
+ init_style();
1193
+ init_theme();
1194
+ // ../kit/src/ci.ts
1195
+ init_args();
1196
+ init_format();
1197
+
1198
+ // ../kit/src/progress.ts
1199
+ init_format();
1200
+ init_style();
1201
+ init_theme();
1202
+ var ESC = String.fromCharCode(27);
1203
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1204
+ var RESET_STYLE = `${ESC}[0m`;
1205
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1206
+
1207
+ // ../kit/src/ci.ts
1208
+ init_style();
1209
+
1210
+ // ../kit/src/tool.ts
1211
+ init_format();
1212
+ // ../kit/src/cli.ts
1213
+ init_args();
1214
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
1215
+ import { dirname as dirname3, join as join5 } from "path";
1216
+ import process14 from "process";
1217
+
1218
+ // ../kit/src/askpass.ts
1219
+ import process11 from "process";
1220
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1221
+ async function askpassClient(argv) {
1222
+ const socketPath = process11.env[SOCKET_VARIABLE];
1223
+ if (socketPath === undefined)
1224
+ return;
1225
+ const request = { prompt: argv[0] ?? "", ...process11.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1226
+ const { promise, resolve } = Promise.withResolvers();
1227
+ let received = "";
1228
+ try {
1229
+ await Bun.connect({
1230
+ unix: socketPath,
1231
+ socket: {
1232
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1233
+ `),
1234
+ data: (_, chunk) => {
1235
+ received += chunk.toString();
1236
+ },
1237
+ close: () => resolve(received),
1238
+ error: () => resolve("")
1239
+ }
1240
+ });
1241
+ } catch {
1242
+ return 1;
1243
+ }
1244
+ const reply = await promise;
1245
+ if (reply === "")
1246
+ return 1;
1247
+ const { answer } = JSON.parse(reply);
1248
+ if (request.notice === true)
1249
+ return 0;
1250
+ if (answer === undefined)
1251
+ return 1;
1252
+ process11.stdout.write(`${answer}
1253
+ `);
1254
+ return 0;
1255
+ }
1256
+
1257
+ // ../kit/src/completions.ts
1258
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1259
+ 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'
1260
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1261
+ set -l current (commandline -ct)
1262
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1263
+ if test "$line" = __files__
1264
+ __fish_complete_path $current
1265
+ else
1266
+ echo $line
1267
+ end
1268
+ end
1269
+ end`;
1270
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1271
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1272
+ local -a lines
1273
+ COMPREPLY=()
1274
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1275
+ for line in "\${lines[@]}"; do
1276
+ if [[ $line == __files__ ]]; then
1277
+ COMPREPLY+=($(compgen -f -- "$cur"))
1278
+ else
1279
+ words+="\${line%%$'\\t'*}"$'\\n'
1280
+ fi
1281
+ done
1282
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1283
+ }`;
1284
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1285
+ local line
1286
+ local -a described plain
1287
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1288
+ if [[ $line == __files__ ]]; then
1289
+ _files
1290
+ elif [[ $line == *$'\\t'* ]]; then
1291
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1292
+ else
1293
+ plain+=("$line")
1294
+ fi
1295
+ done
1296
+ (( \${#described} )) && _describe -V value described
1297
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1298
+ return 0
1299
+ }`;
1300
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1301
+ if (shell === "fish")
1302
+ return `${header}
1303
+ ${FISH_FUNCTION}
1304
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1305
+ `).join("")}`;
1306
+ if (shell === "bash")
1307
+ return `${header}
1308
+ ${BASH_FUNCTION}
1309
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1310
+ `;
1311
+ return `${header}
1312
+ ${ZSH_FUNCTION}
1313
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1314
+ `;
1315
+ }
1316
+
1317
+ // ../kit/src/notify.ts
1318
+ init_format();
1319
+ init_mode();
1320
+ import process12 from "process";
1321
+ var NOTIFY_AFTER_MS = 1e4;
1322
+ var CANCELLED = 130;
1323
+ function base64(text) {
1324
+ return Buffer.from(text).toString("base64");
1325
+ }
1326
+ function notification(title, body, env = process12.env) {
1327
+ const id = `kit${process12.pid}`;
1328
+ 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\\`];
1329
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1330
+ }
1331
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
1332
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1333
+ return;
1334
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1335
+ }
1336
+
1337
+ // ../kit/src/cli.ts
1338
+ init_style();
1339
+ init_text();
1340
+
1341
+ // ../kit/src/usage.ts
1342
+ import { appendFileSync, mkdirSync } from "fs";
1343
+ import { homedir as homedir3 } from "os";
1344
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1345
+ import process13 from "process";
1346
+
1347
+ // ../kit/src/logs.ts
1348
+ var DAY_MS = 24 * 60 * 60 * 1000;
1349
+ var CLI_FOLDER = "kaynooo-cli";
1350
+
1351
+ // ../kit/src/usage.ts
1352
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1353
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1354
+ var LONGEST_NAME = 40;
1355
+ var usageError;
1356
+ function noteUsageError(message) {
1357
+ usageError = message;
1358
+ }
1359
+ function stateHome(env = process13.env) {
1360
+ const dir = env.XDG_STATE_HOME;
1361
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1362
+ }
1363
+ function usagePath(env = process13.env) {
1364
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1365
+ }
1366
+ function usageRecorded(env = process13.env) {
1367
+ const off = env.KAYNOOO_CLI_NO_USAGE;
1368
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1369
+ }
1370
+ function flagNames(argv) {
1371
+ const end = argv.indexOf("--");
1372
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1373
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1374
+ }
1375
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1376
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1377
+ usageError = undefined;
1378
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1379
+ }
1380
+ function recordUsage(entry, env = process13.env) {
1381
+ if (!usageRecorded(env))
1382
+ return;
1383
+ try {
1384
+ const path = usagePath(env);
1385
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1386
+ appendFileSync(path, `${JSON.stringify(entry)}
1387
+ `, { mode: 384 });
1388
+ } catch {}
1389
+ }
1390
+
1391
+ // ../kit/src/cli.ts
1392
+ var LEVEL_OPTIONS = {
1393
+ ...OUTPUT_OPTIONS,
1394
+ help: { type: "boolean", short: "h", description: "show this help" }
1395
+ };
1396
+ var TOP_OPTIONS = {
1397
+ ...LEVEL_OPTIONS,
1398
+ version: { type: "boolean", short: "v", description: "print the version" },
1399
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1400
+ };
1401
+ function printError(prefix, message, hint, cause) {
1402
+ const colors = paint(process14.stderr);
1403
+ const styled = takesControlCodes(process14.stderr);
1404
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1405
+ const under = (label, text, tint) => text === undefined ? "" : `
1406
+ ${styled ? tint(label) : `${label}:`} ${text}`;
1407
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1408
+ }
1409
+ function printJsonError(message, hint, cause) {
1410
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1411
+ }
1412
+ function wantsJson(argv) {
1413
+ const end = argv.indexOf("--");
1414
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1415
+ }
1416
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
1417
+ if (error instanceof HelpShown)
1418
+ return 0;
1419
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1420
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1421
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1422
+ if (error instanceof Exit && error.code === 2)
1423
+ noteUsageError(error.message);
1424
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1425
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1426
+ return error instanceof Exit ? error.code : 1;
1427
+ }
1428
+ var COMPLETE = "__complete";
1429
+ var FILES = "__files__";
1430
+ async function completingOf(run) {
1431
+ completion.active = true;
1432
+ try {
1433
+ await run([]);
1434
+ } catch (error) {
1435
+ if (error instanceof Completing)
1436
+ return error;
1437
+ } finally {
1438
+ completion.active = false;
1248
1439
  }
1249
- add(line.slice(last));
1250
- return { text, styles: colored ? styles : undefined };
1440
+ return new Completing({});
1251
1441
  }
1252
- function lay(rows, searched) {
1253
- const parsed = rows.map((row) => row.cells.map(styled));
1254
- const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1255
- return parsed.map((cells, at) => {
1256
- let text = "";
1257
- const styles = [];
1258
- let colored = false;
1259
- let searchEnd = 0;
1260
- for (const [column, cell] of cells.entries()) {
1261
- const last = column === cells.length - 1;
1262
- const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1263
- text += shown;
1264
- colored ||= cell.styles !== undefined;
1265
- styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1266
- if (column < searched)
1267
- searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1268
- if (!last) {
1269
- const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1270
- text += " ".repeat(pad);
1271
- styles.push(...repeat("", pad));
1272
- }
1273
- }
1274
- return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1275
- });
1442
+ function candidateLine(candidate) {
1443
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1276
1444
  }
1277
- function parseKeys(input, paste = { active: false }, ctrls = []) {
1278
- const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1279
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1280
- const wheel = MOUSE.exec(sequence)?.[1];
1281
- if (wheel !== undefined)
1282
- return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1283
- const named = codes.get(sequence);
1284
- const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1285
- if (sequence === PASTE_START || sequence === PASTE_END) {
1286
- paste.active = sequence === PASTE_START;
1287
- return [];
1445
+ function positionalBeingTyped(before, { options, positionals }) {
1446
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1447
+ const typed = [];
1448
+ let at = 0;
1449
+ while (at < before.length) {
1450
+ const word = before[at];
1451
+ if (word === "--") {
1452
+ typed.push(...before.slice(at + 1));
1453
+ break;
1288
1454
  }
1289
- if (paste.active && (sequence === "\r" || sequence === `
1290
- `))
1291
- return [];
1292
- if (key !== undefined)
1293
- return [key];
1294
- return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1295
- });
1455
+ if (!word.startsWith("-"))
1456
+ typed.push(word);
1457
+ else if (takesValue(word))
1458
+ at++;
1459
+ at++;
1460
+ }
1461
+ const last = positionals.at(-1);
1462
+ if (typed.length < positionals.length)
1463
+ return { name: positionals[typed.length], typed };
1464
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1296
1465
  }
1297
- function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1298
- const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1299
- return withRows(state, rows);
1466
+ async function leafCandidates(run, words) {
1467
+ const completing = await completingOf(run);
1468
+ if ((words.at(-1) ?? "").startsWith("-"))
1469
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1470
+ const flag = words.at(-2);
1471
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1472
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1473
+ if (option?.type === "string") {
1474
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1475
+ return values === undefined ? [FILES] : values.map(candidateLine);
1476
+ }
1477
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1478
+ return values === undefined ? [FILES] : values.map(candidateLine);
1300
1479
  }
1301
- function withRows(state, rows, header = state.header) {
1302
- const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1303
- const laid = lay(cells, state.searched);
1304
- const searchable = laid.map((row) => row.searchable);
1305
- const matches = rank(state.query, searchable);
1306
- return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
1480
+ var COMPLETIONS = "--completions";
1481
+ function flagValue([flag = "", ...rest]) {
1482
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1307
1483
  }
1308
- function withQuery(state, key) {
1309
- const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1310
- return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1484
+ function printCompletionScript(name, args) {
1485
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1486
+ if (shell === undefined || args.length !== 1) {
1487
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1488
+ return 2;
1489
+ }
1490
+ console.log(completionScript(shell, [name]).trimEnd());
1491
+ return 0;
1311
1492
  }
1312
- function move(state, by) {
1313
- return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1493
+ async function printCandidates(found) {
1494
+ for (const line of await found)
1495
+ console.log(line);
1496
+ return 0;
1314
1497
  }
1315
- function highlighted(state) {
1316
- return state.matches[state.cursor]?.index;
1498
+ function packageVersion(entry = Bun.main) {
1499
+ let resolved = entry;
1500
+ try {
1501
+ resolved = realpathSync2(entry);
1502
+ } catch {}
1503
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1504
+ try {
1505
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1506
+ if (typeof version === "string")
1507
+ return version;
1508
+ } catch {}
1509
+ if (dirname3(dir) === dir)
1510
+ return "0.0.0";
1511
+ }
1317
1512
  }
1318
- function press(state, key) {
1319
- if (state.done !== undefined)
1320
- return state;
1321
- if (state.chained && endsKills(key))
1322
- state = { ...state, chained: false };
1323
- if (state.help)
1324
- return { ...state, help: false };
1325
- if (typeof key === "object") {
1326
- if ("text" in key)
1327
- return withQuery(state, key);
1328
- return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1513
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1514
+ const answered = await askpassClient(argv);
1515
+ if (answered !== undefined)
1516
+ return answered;
1517
+ if (argv[0] === COMPLETE)
1518
+ return printCandidates(leafCandidates(run, argv.slice(1)));
1519
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1520
+ return printCompletionScript(name, flagValue(argv));
1521
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1522
+ console.log(version ?? packageVersion());
1523
+ return 0;
1329
1524
  }
1330
- if (isEditKey(key))
1331
- return withQuery(state, key);
1332
- switch (key) {
1333
- case "up":
1334
- return move(state, -1);
1335
- case "down":
1336
- return move(state, 1);
1337
- case "pageup":
1338
- return move(state, -state.page);
1339
- case "pagedown":
1340
- return move(state, state.page);
1341
- case "home":
1342
- return move(state, -state.matches.length);
1343
- case "end":
1344
- return move(state, state.matches.length);
1345
- case "cancel":
1346
- return { ...state, done: "cancel" };
1347
- case "help":
1348
- return { ...state, help: true };
1349
- case "suspend":
1350
- return state;
1351
- case "enter":
1352
- return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1353
- case "tab": {
1354
- const at = highlighted(state);
1355
- if (!state.multi || at === undefined)
1356
- return state;
1357
- const marked = new Set(state.marked);
1358
- if (!marked.delete(at))
1359
- marked.add(at);
1360
- return move({ ...state, marked }, 1);
1361
- }
1525
+ let code;
1526
+ const started = performance.now();
1527
+ try {
1528
+ code = await run(argv);
1529
+ } catch (error) {
1530
+ code = reportThrown(name, error, redact, wantsJson(argv));
1362
1531
  }
1532
+ notifyEnd(name, code, performance.now() - started);
1533
+ if (usage !== false) {
1534
+ try {
1535
+ recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
1536
+ } catch {}
1537
+ }
1538
+ return code;
1363
1539
  }
1364
- function chosen(state) {
1365
- if (state.marked.size > 0)
1366
- return state.rows.filter((_, index) => state.marked.has(index));
1367
- const at = highlighted(state);
1368
- return at === undefined ? [] : [state.rows[at]];
1369
- }
1540
+
1541
+ // ../kit/src/index.ts
1542
+ init_config();
1543
+
1544
+ // ../kit/src/excerpt.ts
1545
+ init_text();
1546
+
1547
+ // ../kit/src/index.ts
1548
+ init_folders();
1549
+ init_format();
1550
+
1551
+ // ../kit/src/git.ts
1552
+ init_args();
1553
+ // ../kit/src/limit.ts
1554
+ init_args();
1555
+
1556
+ // ../kit/src/index.ts
1557
+ init_mode();
1558
+
1559
+ // ../kit/src/report.ts
1560
+ init_style();
1561
+ init_text();
1562
+ // ../kit/src/secrets.ts
1563
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1564
+ // ../kit/src/sessions.ts
1565
+ var {Glob } = globalThis.Bun;
1566
+ var SESSION_FILES = new Glob("*.json");
1567
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1568
+
1569
+ // ../kit/src/index.ts
1570
+ init_style();
1571
+ init_text();
1572
+ init_theme();
1573
+ init_user_config();
1574
+
1575
+ // ../kit/src/watch.ts
1576
+ init_args();
1577
+ init_input();
1578
+ init_style();
1579
+ // ../kit/src/workspace-root.ts
1580
+ init_user_config();
1581
+ // ../kit/src/picker.ts
1582
+ init_folders();
1583
+ init_state();
1370
1584
 
1371
1585
  // ../kit/src/picker/terminal.ts
1586
+ init_args();
1587
+ init_job();
1588
+ init_redraw();
1589
+ init_style();
1372
1590
  import { openSync } from "fs";
1373
- import process17 from "process";
1591
+ import process18 from "process";
1374
1592
  import tty from "tty";
1375
1593
 
1376
- // ../kit/src/job.ts
1377
- import process15 from "process";
1378
- function stopJob() {
1379
- process15.kill(0, "SIGTSTP");
1380
- }
1381
-
1382
- // ../kit/src/redraw.ts
1383
- var SYNC_START = "\x1B[?2026h";
1384
- var SYNC_END = "\x1B[?2026l";
1385
- function overwrite(lines, columns) {
1386
- return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1387
- `);
1388
- }
1389
-
1390
1594
  // ../kit/src/picker/preview.ts
1391
- import process16 from "process";
1595
+ import process17 from "process";
1392
1596
 
1393
1597
  // ../kit/src/shell.ts
1394
1598
  var SEPARATORS = new Set([`
@@ -1457,7 +1661,7 @@ async function runPreview(template, line, signal, hidden = []) {
1457
1661
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1458
1662
  const stop = () => {
1459
1663
  try {
1460
- process16.kill(-proc.pid, "SIGKILL");
1664
+ process17.kill(-proc.pid, "SIGKILL");
1461
1665
  } catch {
1462
1666
  proc.kill();
1463
1667
  }
@@ -1482,7 +1686,12 @@ ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe",
1482
1686
  return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
1483
1687
  }
1484
1688
 
1689
+ // ../kit/src/picker/terminal.ts
1690
+ init_state();
1691
+
1485
1692
  // ../kit/src/picker/view.ts
1693
+ init_line();
1694
+ init_state();
1486
1695
  var MIN_HEIGHT = 4;
1487
1696
  var PREVIEW_MIN_COLUMNS = 80;
1488
1697
  var PREVIEW_MIN_ROWS = 10;
@@ -1616,7 +1825,7 @@ function openTerminal() {
1616
1825
  return fail("no terminal to read keys from (/dev/tty)");
1617
1826
  }
1618
1827
  const keys = Bun.file("/dev/tty").stream().getReader();
1619
- const out = process17.stderr;
1828
+ const out = process18.stderr;
1620
1829
  let resize;
1621
1830
  async function read(onChunk) {
1622
1831
  const decoder = new TextDecoder;
@@ -1805,9 +2014,9 @@ async function select(rows, settings, terminal = openTerminal()) {
1805
2014
  const ended = new Promise((resolve) => {
1806
2015
  finish = resolve;
1807
2016
  });
1808
- process17.once("exit", restore);
2017
+ process18.once("exit", restore);
1809
2018
  for (const signal of SIGNALS)
1810
- process17.once(signal, stop);
2019
+ process18.once(signal, stop);
1811
2020
  try {
1812
2021
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1813
2022
  terminal.listen(onChunk, () => draw(true));
@@ -1820,8 +2029,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1820
2029
  await ended;
1821
2030
  } finally {
1822
2031
  for (const signal of SIGNALS)
1823
- process17.off(signal, stop);
1824
- process17.off("exit", restore);
2032
+ process18.off(signal, stop);
2033
+ process18.off("exit", restore);
1825
2034
  restore();
1826
2035
  }
1827
2036
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1833,6 +2042,10 @@ async function previewOf(preview, hidden, signal) {
1833
2042
  return [error instanceof Error ? error.message : String(error)];
1834
2043
  }
1835
2044
  }
2045
+
2046
+ // ../kit/src/picker.ts
2047
+ init_score();
2048
+
1836
2049
  // src/fields.ts
1837
2050
  var INDEX = /^-?\d+$/;
1838
2051
  function splitFields(line, delimiter) {
@@ -1874,14 +2087,10 @@ function pickFields(line, select, delimiter) {
1874
2087
  // src/pick.ts
1875
2088
  var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
1876
2089
 
1877
- Type to filter: the query matches as a subsequence, best matches first (a word start, a run of characters or a prefix scores higher; a lowercase query ignores case, an uppercase letter makes it exact). Up and down or ctrl-p and ctrl-n move, enter picks, esc and ctrl-c cancel, left, right, ctrl-a and ctrl-e move in the query (ctrl or alt for a word), ctrl-u and ctrl-k erase back to its start and on to its end, ctrl-y puts back what they erased, ctrl-z suspends, ctrl-/ or f1 shows the keys.
1878
- The keys are read from the terminal and the selector is drawn on stderr, so \`pick\` in a pipe or a command substitution prints only the choice. With --multi, tab marks the highlighted line and enter prints the marked lines in input order (the highlighted one when none is marked).
1879
- --preview runs a command for the highlighted line, \`{}\` standing for it shell-quoted, in a pane on the right when the terminal is at least 80 columns wide; its output is cut at 64 KiB and 200 lines.
1880
-
1881
- --delimiter splits each line into fields (a regex, whitespace by default), --nth names the fields the query is matched against and --with-nth the ones shown, in fzf's syntax: 1-based, \`-1\` the last, \`2..\`, \`..3\`, \`2..4\`, comma-separated. The printed line is always the whole input line. --read0 reads NUL-separated lines and --print0 ends each printed one with NUL.
1882
- --filter takes the query and prints every match best first with no terminal; --select-1 prints the only match without opening the selector, --exit-0 exits 1 at once when nothing matches.
1883
-
1884
- Without a terminal on stderr there is nobody to choose: it prints the best line the query matches, as the selector would rank it, or every match best first with --multi.`;
2090
+ Type to filter: the query matches as a subsequence, best matches first, and ctrl-/ or f1 shows the keys; enter picks, esc and ctrl-c cancel.
2091
+ The keys are read from the terminal and the selector is drawn on stderr, so \`pick\` in a pipe or a command substitution prints only the choice. With --multi, tab marks lines and enter prints them in input order.
2092
+ --delimiter, --nth and --with-nth split lines into fields in fzf's syntax, and the printed line is always the whole input line.
2093
+ Without a terminal on stderr it prints the best match, or every match with --multi.`;
1885
2094
  var EXITS = [[0, "it printed a choice"], [1, "nothing matches or there are no lines"], [2, "a usage error"], [130, "cancelled"]];
1886
2095
  var OPTIONS = {
1887
2096
  multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
@@ -1904,7 +2113,7 @@ function print(chosen, json, end) {
1904
2113
  if (json)
1905
2114
  printJson({ picked: chosen });
1906
2115
  else
1907
- process18.stdout.write(chosen.map((line) => line + end).join(""));
2116
+ process19.stdout.write(chosen.map((line) => line + end).join(""));
1908
2117
  }
1909
2118
  async function main(args) {
1910
2119
  const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, replaces: "fzf for a quick choice in a pipe, select in a shell script", examples: ["git branch --format='%(refname:short)' | pick", "ls | pick --multi --preview 'head -20 {}'", "git branch | pick --filter main # every match, best first, no terminal", "ps aux | pick --with-nth 2,11.. --nth 11.. # show some fields, search others"] });
@@ -1913,7 +2122,7 @@ async function main(args) {
1913
2122
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1914
2123
  if (height === undefined)
1915
2124
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1916
- if (process18.stdin.isTTY)
2125
+ if (process19.stdin.isTTY)
1917
2126
  badUsage("pipe the lines to pick on stdin");
1918
2127
  const fieldsOf = (name) => {
1919
2128
  const text = values[name];
@@ -1939,9 +2148,9 @@ async function main(args) {
1939
2148
  const json = values.json === true;
1940
2149
  const searched = lines.map((line) => nth === undefined ? line : pickFields(line, nth, delimiter));
1941
2150
  const matching = rank(query, searched).map(({ index }) => lines[index]);
1942
- if (matching.length === 0 && (values["exit-0"] === true || values.filter !== undefined || !process18.stderr.isTTY))
2151
+ if (matching.length === 0 && (values["exit-0"] === true || values.filter !== undefined || !process19.stderr.isTTY))
1943
2152
  return 1;
1944
- if (values.filter !== undefined || !process18.stderr.isTTY) {
2153
+ if (values.filter !== undefined || !process19.stderr.isTTY) {
1945
2154
  print(values.multi === true || values.filter !== undefined ? matching : matching.slice(0, 1), json, end);
1946
2155
  return 0;
1947
2156
  }
@@ -1956,4 +2165,4 @@ async function main(args) {
1956
2165
  print(picked.rows.map((row) => row.hidden[0]), json, end);
1957
2166
  return 0;
1958
2167
  }
1959
- process18.exitCode = await runMain({ name: "pick", run: main });
2168
+ process19.exitCode = await runMain({ name: "pick", run: main });