@kaynooo/cli-pick 0.11.0 → 0.11.4

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 +1006 -679
  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,48 +110,36 @@ 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";
112
- import { join as join2 } from "path";
119
+ import { isAbsolute, join as join2 } from "path";
113
120
  import process4 from "process";
121
+ function xdgFolder(value, fallback) {
122
+ return value !== undefined && isAbsolute(value) ? value : fallback;
123
+ }
114
124
  function configBase(where = {}) {
115
125
  const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
116
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
126
+ return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
117
127
  }
118
128
  function userConfigPath(bin, where = {}) {
119
129
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
120
130
  }
131
+ var init_user_config = () => {};
121
132
 
122
133
  // ../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+/;
134
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
135
+ import { homedir as homedir2 } from "os";
136
+ import { join as join3, resolve as resolve2 } from "path";
137
+ import process5 from "process";
145
138
  function isColorSpec(spec) {
146
139
  if (typeof spec === "number")
147
140
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
148
141
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
149
142
  }
150
- var CUBE = [0, 95, 135, 175, 215, 255];
151
143
  function cubeLevel(channel) {
152
144
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
153
145
  }
@@ -252,7 +244,6 @@ function applyFile(theme, file, where, warn) {
252
244
  function endsWalk(home) {
253
245
  return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
254
246
  }
255
- var warned = new Set;
256
247
  function warnOnce(message) {
257
248
  if (warned.has(message))
258
249
  return;
@@ -289,8 +280,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
289
280
  }
290
281
  return { theme, sources, preset };
291
282
  }
292
- var current;
293
- var currentKey = "";
294
283
  function activeTheme() {
295
284
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
296
285
  if (current === undefined || key !== currentKey) {
@@ -299,8 +288,38 @@ function activeTheme() {
299
288
  }
300
289
  return current;
301
290
  }
291
+ var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
292
+ var init_theme = __esm(() => {
293
+ init_config();
294
+ init_user_config();
295
+ ENDS = new Map;
296
+ DEFAULT = {
297
+ 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" },
298
+ 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" },
299
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
300
+ bins: {},
301
+ gradient: ["#c084fc", "#67e8f9"]
302
+ };
303
+ 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" };
304
+ 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" };
305
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
306
+ PRESETS = {
307
+ default: {},
308
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
309
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
310
+ ascii: { glyphs: ASCII }
311
+ };
312
+ 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"]);
313
+ HEX = /^#[0-9a-f]{6}$/i;
314
+ CONTROL = /\p{Cc}/u;
315
+ MAX_FILE_BYTES = 64 * 1024;
316
+ SPACES = /\s+/;
317
+ CUBE = [0, 95, 135, 175, 215, 255];
318
+ warned = new Set;
319
+ });
302
320
 
303
321
  // ../kit/src/style.ts
322
+ import process6 from "process";
304
323
  function takesControlCodes(stream, env = process6.env) {
305
324
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
306
325
  }
@@ -311,17 +330,23 @@ function role(name, stream, env = process6.env) {
311
330
  const colors = paint(stream, env);
312
331
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
313
332
  }
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])));
333
+ var STATUS_WORDS, STATUS_OF;
334
+ var init_style = __esm(() => {
335
+ init_colors();
336
+ init_mode();
337
+ init_theme();
338
+ STATUS_WORDS = {
339
+ passed: ["passed", "success", "succeeded", "ok"],
340
+ failed: ["failed", "failure", "error", "errored"],
341
+ running: ["running", "in_progress", "started", "holding"],
342
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
343
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
344
+ };
345
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
346
+ });
322
347
 
323
348
  // ../kit/src/format.ts
324
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
349
+ import process7 from "process";
325
350
  function formatSeconds(total) {
326
351
  let rest = Math.max(0, Math.round(total));
327
352
  const amounts = UNITS.map(([unit, size]) => {
@@ -342,7 +367,6 @@ function upTo(text, separator) {
342
367
  const end = text.indexOf(separator);
343
368
  return end === -1 ? text : text.slice(0, end);
344
369
  }
345
- var ESCAPE = String.fromCharCode(27);
346
370
  function textWidth(text) {
347
371
  return Bun.stringWidth(text);
348
372
  }
@@ -352,14 +376,38 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
352
376
  function printJson(value) {
353
377
  console.log(jsonText(value));
354
378
  }
379
+ var UNITS, ESCAPE;
380
+ var init_format = __esm(() => {
381
+ init_mode();
382
+ init_style();
383
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
384
+ ESCAPE = String.fromCharCode(27);
385
+ });
355
386
 
356
387
  // ../kit/src/help.ts
357
388
  import process8 from "process";
358
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
359
- var USAGE_PREFIX = /^usage:\s*/i;
360
- var FULL_STOP = /\.$/;
361
389
  function usageLine(usage, colors = paint(process8.stdout)) {
362
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
390
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
391
+ `);
392
+ const blank = lines.indexOf("");
393
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
394
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
395
+ const colon = synopses[0].indexOf(": ");
396
+ const inline = synopses[0].slice(colon + 2);
397
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
398
+ if (colon !== -1)
399
+ synopses[0] = synopses[0].slice(0, colon);
400
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
401
+ `)}`;
402
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
403
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
404
+ return [head, ...lead, ...rest].join(`
405
+ `);
406
+ }
407
+ function prose(line, colors) {
408
+ if (colors.cyan("x") === "x")
409
+ return line;
410
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
363
411
  }
364
412
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
365
413
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -394,7 +442,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
394
442
  return [];
395
443
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
396
444
  }
397
- var MAX_INLINE_CHOICES = 24;
398
445
  function optionRows(options, colors = paint(process8.stdout)) {
399
446
  const rows = Object.entries(options).map(([name, option]) => {
400
447
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -409,9 +456,17 @@ function optionRows(options, colors = paint(process8.stdout)) {
409
456
  const width = Math.max(0, ...rows.map((row) => row.width));
410
457
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
411
458
  }
459
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
460
+ var init_help = __esm(() => {
461
+ init_mode();
462
+ init_style();
463
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
464
+ USAGE_PREFIX = /^usage:\s*/i;
465
+ FULL_STOP = /\.$/;
466
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
467
+ });
412
468
 
413
469
  // ../kit/src/text.ts
414
- var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
415
470
  function distance(a, b) {
416
471
  const left = [...a];
417
472
  const right = [...b];
@@ -437,40 +492,29 @@ function closest(name, names) {
437
492
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
438
493
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
439
494
  }
495
+ var ANSI;
496
+ var init_text = __esm(() => {
497
+ ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
498
+ });
499
+
500
+ // ../kit/src/input.ts
501
+ var init_input = __esm(() => {
502
+ init_args();
503
+ });
440
504
 
441
505
  // ../kit/src/args.ts
442
- var DASHES = /^-+/;
506
+ import process9 from "process";
507
+ import { parseArgs } from "util";
443
508
  function jsonOption(holds) {
444
509
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
445
510
  }
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
511
  function fail(message, code = 2, hint) {
456
512
  throw new Exit(message, code, hint);
457
513
  }
458
-
459
- class UsageError extends Exit {
460
- constructor(message, hint) {
461
- super(message, 2, hint);
462
- }
463
- }
464
514
  function badUsage(message) {
465
515
  throw new UsageError(message);
466
516
  }
467
517
 
468
- class HelpShown extends Exit {
469
- constructor() {
470
- super("help shown", 0);
471
- }
472
- }
473
-
474
518
  class Completing {
475
519
  options;
476
520
  positionals;
@@ -481,11 +525,6 @@ class Completing {
481
525
  this.candidates = candidates;
482
526
  }
483
527
  }
484
- var completion = { active: false };
485
- var OUTPUT_OPTIONS = {
486
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
487
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
488
- };
489
528
  function applyOutput(color, plain, env = process9.env) {
490
529
  const when = plain === true ? "never" : color ?? "auto";
491
530
  if (when === "auto")
@@ -639,7 +678,6 @@ function parseError(error) {
639
678
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
640
679
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
641
680
  }
642
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
643
681
  function nearestOption(message, options, allowNegative) {
644
682
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
645
683
  if (typed === undefined)
@@ -655,371 +693,177 @@ function nearestOption(message, options, allowNegative) {
655
693
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
656
694
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
657
695
  }
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";
696
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
697
+ var init_args = __esm(() => {
698
+ init_format();
699
+ init_help();
700
+ init_text();
701
+ init_help();
702
+ init_input();
703
+ DASHES = /^-+/;
704
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
705
+ Exit = class Exit extends Error {
706
+ code;
707
+ hint;
708
+ [EXIT] = true;
709
+ constructor(message, code, hint) {
710
+ super(message);
711
+ this.code = code;
712
+ this.hint = hint;
713
+ }
714
+ static [Symbol.hasInstance](value) {
715
+ if (this !== Exit)
716
+ return Function.prototype[Symbol.hasInstance].call(this, value);
717
+ return typeof value === "object" && value !== null && value[EXIT] === true;
718
+ }
719
+ };
720
+ UsageError = class UsageError extends Exit {
721
+ constructor(message, hint) {
722
+ super(message, 2, hint);
723
+ }
724
+ };
725
+ HelpShown = class HelpShown extends Exit {
726
+ constructor() {
727
+ super("help shown", 0);
728
+ }
729
+ };
730
+ completion = { active: false };
731
+ OUTPUT_OPTIONS = {
732
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
733
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
734
+ };
735
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
736
+ });
691
737
 
692
- // ../kit/src/notify.ts
693
- import process11 from "process";
694
- var NOTIFY_AFTER_MS = 1e4;
695
- var CANCELLED = 130;
696
- function base64(text) {
697
- return Buffer.from(text).toString("base64");
738
+ // ../kit/src/folders.ts
739
+ var SKIPPED_FOLDERS;
740
+ var init_folders = __esm(() => {
741
+ init_user_config();
742
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
743
+ });
744
+
745
+ // ../kit/src/picker/line.ts
746
+ function isEditKey(key) {
747
+ return EDIT_KEYS.has(key);
698
748
  }
699
- function notification(title, body, env = process11.env) {
700
- const id = `kit${process11.pid}`;
701
- 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\\`];
702
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
749
+ function endsKills(key) {
750
+ return typeof key !== "object" && !isEditKey(key);
703
751
  }
704
- function notifyEnd(command, code, ms, { stream = process11.stderr, env = process11.env } = {}) {
705
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
706
- return;
707
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
752
+ function isWord(char) {
753
+ return char !== undefined && WORD_CHARACTER.test(char);
708
754
  }
709
-
710
- // ../kit/src/usage.ts
711
- import { appendFileSync, mkdirSync } from "fs";
712
- import { homedir as homedir3 } from "os";
713
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
714
- import process12 from "process";
715
-
716
- // ../kit/src/logs.ts
717
- var DAY_MS = 24 * 60 * 60 * 1000;
718
- var CLI_FOLDER = "kaynooo-cli";
719
-
720
- // ../kit/src/usage.ts
721
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
722
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
723
- var LONGEST_NAME = 40;
724
- var usageError;
725
- function noteUsageError(message) {
726
- usageError = message;
755
+ function wordStart(chars, from) {
756
+ let at = from;
757
+ while (at > 0 && !isWord(chars[at - 1]))
758
+ at--;
759
+ while (at > 0 && isWord(chars[at - 1]))
760
+ at--;
761
+ return at;
727
762
  }
728
- function stateHome(env = process12.env) {
729
- const dir = env.XDG_STATE_HOME;
730
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
763
+ function wordEnd(chars, from) {
764
+ let at = from;
765
+ while (at < chars.length && !isWord(chars[at]))
766
+ at++;
767
+ while (at < chars.length && isWord(chars[at]))
768
+ at++;
769
+ return at;
731
770
  }
732
- function usagePath(env = process12.env) {
733
- return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
771
+ function spacedStart(chars, from) {
772
+ let at = from;
773
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
774
+ at--;
775
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
776
+ at--;
777
+ return at;
734
778
  }
735
- function usageRecorded(env = process12.env) {
736
- const off = env.KAYNOOO_CLI_NO_USAGE;
737
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
779
+ function cut(chars, from, to) {
780
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
738
781
  }
739
- function flagNames(argv) {
740
- const end = argv.indexOf("--");
741
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
742
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
782
+ function insert(chars, at, text) {
783
+ const typed = [...text];
784
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
743
785
  }
744
- function usageEntry(bin, command, argv, code, now = new Date) {
745
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
746
- usageError = undefined;
747
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
786
+ function editLine(line, key) {
787
+ const { killed = "", chained = false } = line;
788
+ const chars = [...line.text];
789
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
790
+ const edited = edit(chars, at, key, killed);
791
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
792
+ return line.killed === undefined ? edited : { ...edited, killed };
793
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
794
+ if (taken === "")
795
+ return { ...edited, killed, chained };
796
+ if (!chained)
797
+ return { ...edited, killed: taken, chained: true };
798
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
748
799
  }
749
- function recordUsage(entry, env = process12.env) {
750
- if (!usageRecorded(env))
751
- return;
752
- try {
753
- const path = usagePath(env);
754
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
755
- appendFileSync(path, `${JSON.stringify(entry)}
756
- `, { mode: 384 });
757
- } catch {}
800
+ function edit(chars, at, key, killed) {
801
+ const text = chars.join("");
802
+ if (typeof key === "object")
803
+ return insert(chars, at, key.text);
804
+ switch (key) {
805
+ case "left":
806
+ return { text, caret: Math.max(at - 1, 0) };
807
+ case "right":
808
+ return { text, caret: Math.min(at + 1, chars.length) };
809
+ case "wordleft":
810
+ return { text, caret: wordStart(chars, at) };
811
+ case "wordright":
812
+ return { text, caret: wordEnd(chars, at) };
813
+ case "linestart":
814
+ return { text, caret: 0 };
815
+ case "lineend":
816
+ return { text, caret: chars.length };
817
+ case "erase":
818
+ return cut(chars, Math.max(at - 1, 0), at);
819
+ case "delete":
820
+ return cut(chars, at, Math.min(at + 1, chars.length));
821
+ case "word":
822
+ return cut(chars, spacedStart(chars, at), at);
823
+ case "killword":
824
+ return cut(chars, wordStart(chars, at), at);
825
+ case "killnext":
826
+ return cut(chars, at, wordEnd(chars, at));
827
+ case "clear":
828
+ return cut(chars, 0, at);
829
+ case "killend":
830
+ return cut(chars, at, chars.length);
831
+ case "yank":
832
+ return insert(chars, at, killed);
833
+ }
758
834
  }
759
-
760
- // ../kit/src/cli.ts
761
- var LEVEL_OPTIONS = {
762
- ...OUTPUT_OPTIONS,
763
- help: { type: "boolean", short: "h", description: "show this help" }
764
- };
765
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
766
- function printError(prefix, message, hint, cause) {
767
- const colors = paint(process13.stderr);
768
- const styled = takesControlCodes(process13.stderr);
769
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
770
- const under = (label, text, tint) => text === undefined ? "" : `
771
- ${styled ? tint(label) : `${label}:`} ${text}`;
772
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
835
+ function visible({ text, caret }, room) {
836
+ const chars = [...text];
837
+ const at = Math.min(Math.max(caret, 0), chars.length);
838
+ const cells = at === chars.length ? [...chars, " "] : chars;
839
+ const widths = cells.map((char) => Bun.stringWidth(char));
840
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
841
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
842
+ let start = at;
843
+ let end = at + 1;
844
+ while (start > 0 && fits(start - 1, end))
845
+ start--;
846
+ while (end < cells.length && fits(start, end + 1))
847
+ end++;
848
+ const left = start > 0 ? "\u2026" : "";
849
+ const right = end < cells.length ? "\u2026" : "";
850
+ 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) };
773
851
  }
774
- function printJsonError(message, hint, cause) {
775
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
776
- }
777
- function wantsJson(argv) {
778
- const end = argv.indexOf("--");
779
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
780
- }
781
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
782
- if (error instanceof HelpShown)
783
- return 0;
784
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
785
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
786
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
787
- if (error instanceof Exit && error.code === 2)
788
- noteUsageError(error.message);
789
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
790
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
791
- return error instanceof Exit ? error.code : 1;
792
- }
793
- var COMPLETE = "__complete";
794
- var FILES = "__files__";
795
- async function completingOf(run) {
796
- completion.active = true;
797
- try {
798
- await run([]);
799
- } catch (error) {
800
- if (error instanceof Completing)
801
- return error;
802
- } finally {
803
- completion.active = false;
804
- }
805
- return new Completing({});
806
- }
807
- function candidateLine(candidate) {
808
- return typeof candidate === "string" ? candidate : candidate.join("\t");
809
- }
810
- function positionalBeingTyped(before, { options, positionals }) {
811
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
812
- const typed = [];
813
- let at = 0;
814
- while (at < before.length) {
815
- const word = before[at];
816
- if (word === "--") {
817
- typed.push(...before.slice(at + 1));
818
- break;
819
- }
820
- if (!word.startsWith("-"))
821
- typed.push(word);
822
- else if (takesValue(word))
823
- at++;
824
- at++;
825
- }
826
- const last = positionals.at(-1);
827
- if (typed.length < positionals.length)
828
- return { name: positionals[typed.length], typed };
829
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
830
- }
831
- async function leafCandidates(run, words) {
832
- const completing = await completingOf(run);
833
- if ((words.at(-1) ?? "").startsWith("-"))
834
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
835
- const flag = words.at(-2);
836
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
837
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
838
- if (option?.type === "string") {
839
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
840
- return values === undefined ? [FILES] : values.map(candidateLine);
841
- }
842
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
843
- return values === undefined ? [FILES] : values.map(candidateLine);
844
- }
845
- async function printCandidates(found) {
846
- for (const line of await found)
847
- console.log(line);
848
- return 0;
849
- }
850
- function packageVersion(entry = Bun.main) {
851
- let resolved = entry;
852
- try {
853
- resolved = realpathSync2(entry);
854
- } catch {}
855
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
856
- try {
857
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
858
- if (typeof version === "string")
859
- return version;
860
- } catch {}
861
- if (dirname3(dir) === dir)
862
- return "0.0.0";
863
- }
864
- }
865
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
866
- if (argv[0] === COMPLETE)
867
- return printCandidates(leafCandidates(run, argv.slice(1)));
868
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
869
- console.log(version ?? packageVersion());
870
- return 0;
871
- }
872
- let code;
873
- const started = performance.now();
874
- try {
875
- code = await run(argv);
876
- } catch (error) {
877
- code = reportThrown(name, error, redact, wantsJson(argv));
878
- }
879
- notifyEnd(name, code, performance.now() - started);
880
- if (usage !== false) {
881
- try {
882
- recordUsage(usageEntry(name, undefined, argv, code));
883
- } catch {}
884
- }
885
- return code;
886
- }
887
- // ../kit/src/folders.ts
888
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
889
- // ../kit/src/secrets.ts
890
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
891
- // ../kit/src/sessions.ts
892
- var {Glob } = globalThis.Bun;
893
- var SESSION_FILES = new Glob("*.json");
894
- var ACCOUNT_DIRS = new Glob("*/sessions");
895
- // ../kit/src/picker/line.ts
896
- var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
897
- var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
898
- var FORWARD_KILLS = new Set(["killnext", "killend"]);
899
- function isEditKey(key) {
900
- return EDIT_KEYS.has(key);
901
- }
902
- function endsKills(key) {
903
- return typeof key !== "object" && !isEditKey(key);
904
- }
905
- var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
906
- var SPACE = /\s/;
907
- function isWord(char) {
908
- return char !== undefined && WORD_CHARACTER.test(char);
909
- }
910
- function wordStart(chars, from) {
911
- let at = from;
912
- while (at > 0 && !isWord(chars[at - 1]))
913
- at--;
914
- while (at > 0 && isWord(chars[at - 1]))
915
- at--;
916
- return at;
917
- }
918
- function wordEnd(chars, from) {
919
- let at = from;
920
- while (at < chars.length && !isWord(chars[at]))
921
- at++;
922
- while (at < chars.length && isWord(chars[at]))
923
- at++;
924
- return at;
925
- }
926
- function spacedStart(chars, from) {
927
- let at = from;
928
- while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
929
- at--;
930
- while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
931
- at--;
932
- return at;
933
- }
934
- function cut(chars, from, to) {
935
- return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
936
- }
937
- function insert(chars, at, text) {
938
- const typed = [...text];
939
- return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
940
- }
941
- function editLine(line, key) {
942
- const { killed = "", chained = false } = line;
943
- const chars = [...line.text];
944
- const at = Math.min(Math.max(line.caret, 0), chars.length);
945
- const edited = edit(chars, at, key, killed);
946
- if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
947
- return line.killed === undefined ? edited : { ...edited, killed };
948
- const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
949
- if (taken === "")
950
- return { ...edited, killed, chained };
951
- if (!chained)
952
- return { ...edited, killed: taken, chained: true };
953
- return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
954
- }
955
- function edit(chars, at, key, killed) {
956
- const text = chars.join("");
957
- if (typeof key === "object")
958
- return insert(chars, at, key.text);
959
- switch (key) {
960
- case "left":
961
- return { text, caret: Math.max(at - 1, 0) };
962
- case "right":
963
- return { text, caret: Math.min(at + 1, chars.length) };
964
- case "wordleft":
965
- return { text, caret: wordStart(chars, at) };
966
- case "wordright":
967
- return { text, caret: wordEnd(chars, at) };
968
- case "linestart":
969
- return { text, caret: 0 };
970
- case "lineend":
971
- return { text, caret: chars.length };
972
- case "erase":
973
- return cut(chars, Math.max(at - 1, 0), at);
974
- case "delete":
975
- return cut(chars, at, Math.min(at + 1, chars.length));
976
- case "word":
977
- return cut(chars, spacedStart(chars, at), at);
978
- case "killword":
979
- return cut(chars, wordStart(chars, at), at);
980
- case "killnext":
981
- return cut(chars, at, wordEnd(chars, at));
982
- case "clear":
983
- return cut(chars, 0, at);
984
- case "killend":
985
- return cut(chars, at, chars.length);
986
- case "yank":
987
- return insert(chars, at, killed);
988
- }
989
- }
990
- function visible({ text, caret }, room) {
991
- const chars = [...text];
992
- const at = Math.min(Math.max(caret, 0), chars.length);
993
- const cells = at === chars.length ? [...chars, " "] : chars;
994
- const widths = cells.map((char) => Bun.stringWidth(char));
995
- const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
996
- const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
997
- let start = at;
998
- let end = at + 1;
999
- while (start > 0 && fits(start - 1, end))
1000
- start--;
1001
- while (end < cells.length && fits(start, end + 1))
1002
- end++;
1003
- const left = start > 0 ? "\u2026" : "";
1004
- const right = end < cells.length ? "\u2026" : "";
1005
- 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) };
1006
- }
1007
-
1008
- // ../kit/src/picker/score.ts
1009
- var MATCH = 16;
1010
- var CONSECUTIVE = 12;
1011
- var BOUNDARY = 10;
1012
- var PREFIX = 8;
1013
- var GAP = 1;
1014
- var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1015
- var UPPER = /\p{Lu}/u;
1016
- var LOWER = /\p{Ll}/u;
1017
- var NONE = Number.NEGATIVE_INFINITY;
1018
- function startsWord(text, index) {
1019
- if (index === 0)
1020
- return true;
1021
- const before = text[index - 1];
1022
- return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
852
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
853
+ var init_line = __esm(() => {
854
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
855
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
856
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
857
+ WORD_CHARACTER = /[\p{L}\p{N}_]/u;
858
+ SPACE = /\s/;
859
+ });
860
+
861
+ // ../kit/src/picker/score.ts
862
+ function startsWord(text, index) {
863
+ if (index === 0)
864
+ return true;
865
+ const before = text[index - 1];
866
+ return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
1023
867
  }
1024
868
  function fuzzy(query, text) {
1025
869
  if (query === "")
@@ -1087,229 +931,678 @@ function rank(query, lines) {
1087
931
  }
1088
932
  return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
1089
933
  }
934
+ var MATCH = 16, CONSECUTIVE = 12, BOUNDARY = 10, PREFIX = 8, GAP = 1, BOUNDARY_AFTER, UPPER, LOWER, NONE;
935
+ var init_score = __esm(() => {
936
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
937
+ UPPER = /\p{Lu}/u;
938
+ LOWER = /\p{Ll}/u;
939
+ NONE = Number.NEGATIVE_INFINITY;
940
+ });
1090
941
 
1091
942
  // ../kit/src/picker/state.ts
1092
- var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1093
- var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1094
- var SGR = /^\x1B\[[0-9;]*m$/;
1095
- var RESET = /^\x1B\[0?m$/;
1096
- var COLUMN_GAP = 2;
1097
- var PASTE_START = "\x1B[200~";
1098
- var PASTE_END = "\x1B[201~";
1099
- var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1100
- var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1101
- var WHEEL_LINES = 3;
1102
- var KEYS = {
1103
- "\x1B[A": "up",
1104
- "\x1BOA": "up",
1105
- "\x10": "up",
1106
- "\x1B[B": "down",
1107
- "\x1BOB": "down",
1108
- "\x0E": "down",
1109
- "\x1B[5~": "pageup",
1110
- "\x1B[6~": "pagedown",
1111
- "\x1B[H": "home",
1112
- "\x1B[1~": "home",
1113
- "\x1BOH": "home",
1114
- "\x1B[F": "end",
1115
- "\x1B[4~": "end",
1116
- "\x1BOF": "end",
1117
- "\r": "enter",
1118
- "\n": "enter",
1119
- "\x03": "cancel",
1120
- "\x1B": "cancel",
1121
- "\x1B[D": "left",
1122
- "\x1BOD": "left",
1123
- "\x1B[C": "right",
1124
- "\x1BOC": "right",
1125
- "\x1B[1;5D": "wordleft",
1126
- "\x1B[1;3D": "wordleft",
1127
- "\x1Bb": "wordleft",
1128
- "\x1B[1;5C": "wordright",
1129
- "\x1B[1;3C": "wordright",
1130
- "\x1Bf": "wordright",
1131
- "\x01": "linestart",
1132
- "\x05": "lineend",
1133
- "\x7F": "erase",
1134
- "\x1B[3~": "delete",
1135
- "\b": "killword",
1136
- "\x1B\x7F": "killword",
1137
- "\x1B[3;5~": "killnext",
1138
- "\x1Bd": "killnext",
1139
- "\x15": "clear",
1140
- "\v": "killend",
1141
- "\x17": "word",
1142
- "\x19": "yank",
1143
- "\x1A": "suspend",
1144
- "\t": "tab",
1145
- "\x1F": "help",
1146
- "\x1BOP": "help",
1147
- "\x1B[11~": "help"
1148
- };
1149
943
  function repeat(value, count) {
1150
944
  return Array.from({ length: count }).fill(value);
1151
945
  }
1152
- function styled(line) {
1153
- let text = "";
1154
- const styles = [];
1155
- let active = "";
1156
- let colored = false;
1157
- let last = 0;
1158
- function add(chunk) {
1159
- const flat = chunk.replace(CONTROL2, " ");
1160
- text += flat;
1161
- colored ||= active !== "" && flat !== "";
1162
- styles.push(...repeat(active, flat.length));
1163
- }
1164
- for (const found of line.matchAll(ANSI)) {
1165
- add(line.slice(last, found.index));
1166
- last = found.index + found[0].length;
1167
- if (SGR.test(found[0]))
1168
- active = RESET.test(found[0]) ? "" : active + found[0];
946
+ function styled(line) {
947
+ let text = "";
948
+ const styles = [];
949
+ let active = "";
950
+ let colored = false;
951
+ let last = 0;
952
+ function add(chunk) {
953
+ const flat = chunk.replace(CONTROL2, " ");
954
+ text += flat;
955
+ colored ||= active !== "" && flat !== "";
956
+ styles.push(...repeat(active, flat.length));
957
+ }
958
+ for (const found of line.matchAll(ANSI)) {
959
+ add(line.slice(last, found.index));
960
+ last = found.index + found[0].length;
961
+ if (SGR.test(found[0]))
962
+ active = RESET.test(found[0]) ? "" : active + found[0];
963
+ }
964
+ add(line.slice(last));
965
+ return { text, styles: colored ? styles : undefined };
966
+ }
967
+ function lay(rows, searched) {
968
+ const parsed = rows.map((row) => row.cells.map(styled));
969
+ const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
970
+ return parsed.map((cells, at) => {
971
+ let text = "";
972
+ const styles = [];
973
+ let colored = false;
974
+ let searchEnd = 0;
975
+ for (const [column, cell] of cells.entries()) {
976
+ const last = column === cells.length - 1;
977
+ const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
978
+ text += shown;
979
+ colored ||= cell.styles !== undefined;
980
+ styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
981
+ if (column < searched)
982
+ searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
983
+ if (!last) {
984
+ const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
985
+ text += " ".repeat(pad);
986
+ styles.push(...repeat("", pad));
987
+ }
988
+ }
989
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
990
+ });
991
+ }
992
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
993
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
994
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
995
+ const wheel = MOUSE.exec(sequence)?.[1];
996
+ if (wheel !== undefined)
997
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
998
+ const named = codes.get(sequence);
999
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1000
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1001
+ paste.active = sequence === PASTE_START;
1002
+ return [];
1003
+ }
1004
+ if (paste.active && (sequence === "\r" || sequence === `
1005
+ `))
1006
+ return [];
1007
+ if (key !== undefined)
1008
+ return [key];
1009
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1010
+ });
1011
+ }
1012
+ function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1013
+ 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 };
1014
+ return withRows(state, rows);
1015
+ }
1016
+ function withRows(state, rows, header = state.header) {
1017
+ const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1018
+ const laid = lay(cells, state.searched);
1019
+ const searchable = laid.map((row) => row.searchable);
1020
+ const matches = rank(state.query, searchable);
1021
+ 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 };
1022
+ }
1023
+ function withQuery(state, key) {
1024
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1025
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1026
+ }
1027
+ function move(state, by) {
1028
+ return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1029
+ }
1030
+ function highlighted(state) {
1031
+ return state.matches[state.cursor]?.index;
1032
+ }
1033
+ function press(state, key) {
1034
+ if (state.done !== undefined)
1035
+ return state;
1036
+ if (state.chained && endsKills(key))
1037
+ state = { ...state, chained: false };
1038
+ if (state.help)
1039
+ return { ...state, help: false };
1040
+ if (typeof key === "object") {
1041
+ if ("text" in key)
1042
+ return withQuery(state, key);
1043
+ return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1044
+ }
1045
+ if (isEditKey(key))
1046
+ return withQuery(state, key);
1047
+ switch (key) {
1048
+ case "up":
1049
+ return move(state, -1);
1050
+ case "down":
1051
+ return move(state, 1);
1052
+ case "pageup":
1053
+ return move(state, -state.page);
1054
+ case "pagedown":
1055
+ return move(state, state.page);
1056
+ case "home":
1057
+ return move(state, -state.matches.length);
1058
+ case "end":
1059
+ return move(state, state.matches.length);
1060
+ case "cancel":
1061
+ return { ...state, done: "cancel" };
1062
+ case "help":
1063
+ return { ...state, help: true };
1064
+ case "suspend":
1065
+ return state;
1066
+ case "enter":
1067
+ return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1068
+ case "tab": {
1069
+ const at = highlighted(state);
1070
+ if (!state.multi || at === undefined)
1071
+ return state;
1072
+ const marked = new Set(state.marked);
1073
+ if (!marked.delete(at))
1074
+ marked.add(at);
1075
+ return move({ ...state, marked }, 1);
1076
+ }
1077
+ }
1078
+ }
1079
+ function chosen(state) {
1080
+ if (state.marked.size > 0)
1081
+ return state.rows.filter((_, index) => state.marked.has(index));
1082
+ const at = highlighted(state);
1083
+ return at === undefined ? [] : [state.rows[at]];
1084
+ }
1085
+ var CONTROL2, IS_CONTROL, SGR, RESET, COLUMN_GAP = 2, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
1086
+ var init_state = __esm(() => {
1087
+ init_text();
1088
+ init_line();
1089
+ init_score();
1090
+ CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1091
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1092
+ SGR = /^\x1B\[[0-9;]*m$/;
1093
+ RESET = /^\x1B\[0?m$/;
1094
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1095
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1096
+ KEYS = {
1097
+ "\x1B[A": "up",
1098
+ "\x1BOA": "up",
1099
+ "\x10": "up",
1100
+ "\x1B[B": "down",
1101
+ "\x1BOB": "down",
1102
+ "\x0E": "down",
1103
+ "\x1B[5~": "pageup",
1104
+ "\x1B[6~": "pagedown",
1105
+ "\x1B[H": "home",
1106
+ "\x1B[1~": "home",
1107
+ "\x1BOH": "home",
1108
+ "\x1B[F": "end",
1109
+ "\x1B[4~": "end",
1110
+ "\x1BOF": "end",
1111
+ "\r": "enter",
1112
+ "\n": "enter",
1113
+ "\x03": "cancel",
1114
+ "\x1B": "cancel",
1115
+ "\x1B[D": "left",
1116
+ "\x1BOD": "left",
1117
+ "\x1B[C": "right",
1118
+ "\x1BOC": "right",
1119
+ "\x1B[1;5D": "wordleft",
1120
+ "\x1B[1;3D": "wordleft",
1121
+ "\x1Bb": "wordleft",
1122
+ "\x1B[1;5C": "wordright",
1123
+ "\x1B[1;3C": "wordright",
1124
+ "\x1Bf": "wordright",
1125
+ "\x01": "linestart",
1126
+ "\x05": "lineend",
1127
+ "\x7F": "erase",
1128
+ "\x1B[3~": "delete",
1129
+ "\b": "killword",
1130
+ "\x1B\x7F": "killword",
1131
+ "\x1B[3;5~": "killnext",
1132
+ "\x1Bd": "killnext",
1133
+ "\x15": "clear",
1134
+ "\v": "killend",
1135
+ "\x17": "word",
1136
+ "\x19": "yank",
1137
+ "\x1A": "suspend",
1138
+ "\t": "tab",
1139
+ "\x1F": "help",
1140
+ "\x1BOP": "help",
1141
+ "\x1B[11~": "help"
1142
+ };
1143
+ });
1144
+
1145
+ // ../kit/src/job.ts
1146
+ import process16 from "process";
1147
+ function stopJob() {
1148
+ process16.kill(0, "SIGTSTP");
1149
+ }
1150
+ var init_job = () => {};
1151
+
1152
+ // ../kit/src/redraw.ts
1153
+ function overwrite(lines, columns) {
1154
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1155
+ `);
1156
+ }
1157
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
1158
+ var init_redraw = __esm(() => {
1159
+ init_format();
1160
+ });
1161
+
1162
+ // src/pick.ts
1163
+ import process19 from "process";
1164
+
1165
+ // ../kit/src/index.ts
1166
+ init_args();
1167
+
1168
+ // ../kit/src/argv.ts
1169
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
1170
+ import { resolve as resolve3 } from "path";
1171
+ import process10 from "process";
1172
+ function commandLine() {
1173
+ try {
1174
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
1175
+ } catch {
1176
+ return;
1177
+ }
1178
+ }
1179
+ function realPath(word) {
1180
+ try {
1181
+ return realpathSync(resolve3(word));
1182
+ } catch {
1183
+ return;
1184
+ }
1185
+ }
1186
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
1187
+ const target = script === undefined ? undefined : realPath(script) ?? script;
1188
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
1189
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
1190
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
1191
+ }
1192
+ // ../kit/src/chart.ts
1193
+ init_format();
1194
+ init_mode();
1195
+ init_style();
1196
+ init_theme();
1197
+ // ../kit/src/ci.ts
1198
+ init_args();
1199
+ init_format();
1200
+
1201
+ // ../kit/src/progress.ts
1202
+ init_format();
1203
+
1204
+ // ../kit/src/process.ts
1205
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
1206
+
1207
+ // ../kit/src/progress.ts
1208
+ init_style();
1209
+ init_theme();
1210
+ var ESC = String.fromCharCode(27);
1211
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1212
+ var RESET_STYLE = `${ESC}[0m`;
1213
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1214
+
1215
+ // ../kit/src/ci.ts
1216
+ init_style();
1217
+
1218
+ // ../kit/src/tool.ts
1219
+ init_format();
1220
+ // ../kit/src/cli.ts
1221
+ init_args();
1222
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
1223
+ import { dirname as dirname3, join as join5 } from "path";
1224
+ import process14 from "process";
1225
+
1226
+ // ../kit/src/askpass.ts
1227
+ import process11 from "process";
1228
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1229
+ async function askpassClient(argv) {
1230
+ const socketPath = process11.env[SOCKET_VARIABLE];
1231
+ if (socketPath === undefined)
1232
+ return;
1233
+ const request = { prompt: argv[0] ?? "", ...process11.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1234
+ const { promise, resolve } = Promise.withResolvers();
1235
+ let received = "";
1236
+ try {
1237
+ await Bun.connect({
1238
+ unix: socketPath,
1239
+ socket: {
1240
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1241
+ `),
1242
+ data: (_, chunk) => {
1243
+ received += chunk.toString();
1244
+ },
1245
+ close: () => resolve(received),
1246
+ error: () => resolve("")
1247
+ }
1248
+ });
1249
+ } catch {
1250
+ return 1;
1251
+ }
1252
+ const reply = await promise;
1253
+ if (reply === "")
1254
+ return 1;
1255
+ const { answer } = JSON.parse(reply);
1256
+ if (request.notice === true)
1257
+ return 0;
1258
+ if (answer === undefined)
1259
+ return 1;
1260
+ process11.stdout.write(`${answer}
1261
+ `);
1262
+ return 0;
1263
+ }
1264
+
1265
+ // ../kit/src/completions.ts
1266
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1267
+ 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'
1268
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1269
+ set -l current (commandline -ct)
1270
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1271
+ if test "$line" = __files__
1272
+ __fish_complete_path $current
1273
+ else
1274
+ echo $line
1275
+ end
1276
+ end
1277
+ end`;
1278
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1279
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1280
+ local -a lines
1281
+ COMPREPLY=()
1282
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1283
+ for line in "\${lines[@]}"; do
1284
+ if [[ $line == __files__ ]]; then
1285
+ COMPREPLY+=($(compgen -f -- "$cur"))
1286
+ else
1287
+ words+="\${line%%$'\\t'*}"$'\\n'
1288
+ fi
1289
+ done
1290
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1291
+ }`;
1292
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1293
+ local line
1294
+ local -a described plain
1295
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1296
+ if [[ $line == __files__ ]]; then
1297
+ _files
1298
+ elif [[ $line == *$'\\t'* ]]; then
1299
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1300
+ else
1301
+ plain+=("$line")
1302
+ fi
1303
+ done
1304
+ (( \${#described} )) && _describe -V value described
1305
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1306
+ return 0
1307
+ }`;
1308
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1309
+ if (shell === "fish")
1310
+ return `${header}
1311
+ ${FISH_FUNCTION}
1312
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1313
+ `).join("")}`;
1314
+ if (shell === "bash")
1315
+ return `${header}
1316
+ ${BASH_FUNCTION}
1317
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1318
+ `;
1319
+ return `${header}
1320
+ ${ZSH_FUNCTION}
1321
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1322
+ `;
1323
+ }
1324
+
1325
+ // ../kit/src/notify.ts
1326
+ init_format();
1327
+ init_mode();
1328
+ import process12 from "process";
1329
+ var NOTIFY_AFTER_MS = 1e4;
1330
+ var CANCELLED = 130;
1331
+ function base64(text) {
1332
+ return Buffer.from(text).toString("base64");
1333
+ }
1334
+ function notification(title, body, env = process12.env) {
1335
+ const id = `kit${process12.pid}`;
1336
+ 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\\`];
1337
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1338
+ }
1339
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
1340
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1341
+ return;
1342
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1343
+ }
1344
+
1345
+ // ../kit/src/cli.ts
1346
+ init_style();
1347
+ init_text();
1348
+
1349
+ // ../kit/src/usage.ts
1350
+ import { appendFileSync, mkdirSync } from "fs";
1351
+ import { homedir as homedir3 } from "os";
1352
+ import { dirname as dirname2, join as join4 } from "path";
1353
+ import process13 from "process";
1354
+
1355
+ // ../kit/src/logs.ts
1356
+ init_user_config();
1357
+ var DAY_MS = 24 * 60 * 60 * 1000;
1358
+ var CLI_FOLDER = "kaynooo-cli";
1359
+
1360
+ // ../kit/src/usage.ts
1361
+ init_user_config();
1362
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1363
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1364
+ var LONGEST_NAME = 40;
1365
+ var usageError;
1366
+ function noteUsageError(message) {
1367
+ usageError = message;
1368
+ }
1369
+ function stateHome(env = process13.env) {
1370
+ return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
1371
+ }
1372
+ function usagePath(env = process13.env) {
1373
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1374
+ }
1375
+ function usageRecorded(env = process13.env) {
1376
+ const off = env.KAYNOOO_CLI_NO_USAGE;
1377
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1378
+ }
1379
+ function flagNames(argv) {
1380
+ const end = argv.indexOf("--");
1381
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1382
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1383
+ }
1384
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1385
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1386
+ usageError = undefined;
1387
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1388
+ }
1389
+ function recordUsage(entry, env = process13.env) {
1390
+ if (!usageRecorded(env))
1391
+ return;
1392
+ try {
1393
+ const path = usagePath(env);
1394
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1395
+ appendFileSync(path, `${JSON.stringify(entry)}
1396
+ `, { mode: 384 });
1397
+ } catch {}
1398
+ }
1399
+
1400
+ // ../kit/src/cli.ts
1401
+ var LEVEL_OPTIONS = {
1402
+ ...OUTPUT_OPTIONS,
1403
+ help: { type: "boolean", short: "h", description: "show this help" }
1404
+ };
1405
+ var TOP_OPTIONS = {
1406
+ ...LEVEL_OPTIONS,
1407
+ version: { type: "boolean", short: "v", description: "print the version" },
1408
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1409
+ };
1410
+ function printError(prefix, message, hint, cause) {
1411
+ const colors = paint(process14.stderr);
1412
+ const styled = takesControlCodes(process14.stderr);
1413
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1414
+ const under = (label, text, tint) => text === undefined ? "" : `
1415
+ ${styled ? tint(label) : `${label}:`} ${text}`;
1416
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1417
+ }
1418
+ function printJsonError(message, hint, cause) {
1419
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1420
+ }
1421
+ function wantsJson(argv) {
1422
+ const end = argv.indexOf("--");
1423
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1424
+ }
1425
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
1426
+ if (error instanceof HelpShown)
1427
+ return 0;
1428
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1429
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1430
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1431
+ if (error instanceof Exit && error.code === 2)
1432
+ noteUsageError(error.message);
1433
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1434
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1435
+ return error instanceof Exit ? error.code : 1;
1436
+ }
1437
+ var COMPLETE = "__complete";
1438
+ var FILES = "__files__";
1439
+ async function completingOf(run) {
1440
+ completion.active = true;
1441
+ try {
1442
+ await run([]);
1443
+ } catch (error) {
1444
+ if (error instanceof Completing)
1445
+ return error;
1446
+ } finally {
1447
+ completion.active = false;
1169
1448
  }
1170
- add(line.slice(last));
1171
- return { text, styles: colored ? styles : undefined };
1449
+ return new Completing({});
1172
1450
  }
1173
- function lay(rows, searched) {
1174
- const parsed = rows.map((row) => row.cells.map(styled));
1175
- const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1176
- return parsed.map((cells, at) => {
1177
- let text = "";
1178
- const styles = [];
1179
- let colored = false;
1180
- let searchEnd = 0;
1181
- for (const [column, cell] of cells.entries()) {
1182
- const last = column === cells.length - 1;
1183
- const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1184
- text += shown;
1185
- colored ||= cell.styles !== undefined;
1186
- styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1187
- if (column < searched)
1188
- searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1189
- if (!last) {
1190
- const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1191
- text += " ".repeat(pad);
1192
- styles.push(...repeat("", pad));
1193
- }
1194
- }
1195
- return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1196
- });
1451
+ function candidateLine(candidate) {
1452
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1197
1453
  }
1198
- function parseKeys(input, paste = { active: false }, ctrls = []) {
1199
- const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1200
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1201
- const wheel = MOUSE.exec(sequence)?.[1];
1202
- if (wheel !== undefined)
1203
- return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1204
- const named = codes.get(sequence);
1205
- const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1206
- if (sequence === PASTE_START || sequence === PASTE_END) {
1207
- paste.active = sequence === PASTE_START;
1208
- return [];
1454
+ function positionalBeingTyped(before, { options, positionals }) {
1455
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1456
+ const typed = [];
1457
+ let at = 0;
1458
+ while (at < before.length) {
1459
+ const word = before[at];
1460
+ if (word === "--") {
1461
+ typed.push(...before.slice(at + 1));
1462
+ break;
1209
1463
  }
1210
- if (paste.active && (sequence === "\r" || sequence === `
1211
- `))
1212
- return [];
1213
- if (key !== undefined)
1214
- return [key];
1215
- return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1216
- });
1464
+ if (!word.startsWith("-"))
1465
+ typed.push(word);
1466
+ else if (takesValue(word))
1467
+ at++;
1468
+ at++;
1469
+ }
1470
+ const last = positionals.at(-1);
1471
+ if (typed.length < positionals.length)
1472
+ return { name: positionals[typed.length], typed };
1473
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1217
1474
  }
1218
- function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1219
- 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 };
1220
- return withRows(state, rows);
1475
+ async function leafCandidates(run, words) {
1476
+ const completing = await completingOf(run);
1477
+ if ((words.at(-1) ?? "").startsWith("-"))
1478
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1479
+ const flag = words.at(-2);
1480
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1481
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1482
+ if (option?.type === "string") {
1483
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1484
+ return values === undefined ? [FILES] : values.map(candidateLine);
1485
+ }
1486
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1487
+ return values === undefined ? [FILES] : values.map(candidateLine);
1221
1488
  }
1222
- function withRows(state, rows, header = state.header) {
1223
- const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1224
- const laid = lay(cells, state.searched);
1225
- const searchable = laid.map((row) => row.searchable);
1226
- const matches = rank(state.query, searchable);
1227
- 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 };
1489
+ var COMPLETIONS = "--completions";
1490
+ function flagValue([flag = "", ...rest]) {
1491
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1228
1492
  }
1229
- function withQuery(state, key) {
1230
- const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1231
- return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1493
+ function printCompletionScript(name, args) {
1494
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1495
+ if (shell === undefined || args.length !== 1) {
1496
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1497
+ return 2;
1498
+ }
1499
+ console.log(completionScript(shell, [name]).trimEnd());
1500
+ return 0;
1232
1501
  }
1233
- function move(state, by) {
1234
- return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1502
+ async function printCandidates(found) {
1503
+ for (const line of await found)
1504
+ console.log(line);
1505
+ return 0;
1235
1506
  }
1236
- function highlighted(state) {
1237
- return state.matches[state.cursor]?.index;
1507
+ function packageVersion(entry = Bun.main) {
1508
+ let resolved = entry;
1509
+ try {
1510
+ resolved = realpathSync2(entry);
1511
+ } catch {}
1512
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1513
+ try {
1514
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1515
+ if (typeof version === "string")
1516
+ return version;
1517
+ } catch {}
1518
+ if (dirname3(dir) === dir)
1519
+ return "0.0.0";
1520
+ }
1238
1521
  }
1239
- function press(state, key) {
1240
- if (state.done !== undefined)
1241
- return state;
1242
- if (state.chained && endsKills(key))
1243
- state = { ...state, chained: false };
1244
- if (state.help)
1245
- return { ...state, help: false };
1246
- if (typeof key === "object") {
1247
- if ("text" in key)
1248
- return withQuery(state, key);
1249
- return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1522
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1523
+ const answered = await askpassClient(argv);
1524
+ if (answered !== undefined)
1525
+ return answered;
1526
+ if (argv[0] === COMPLETE)
1527
+ return printCandidates(leafCandidates(run, argv.slice(1)));
1528
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1529
+ return printCompletionScript(name, flagValue(argv));
1530
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1531
+ console.log(version ?? packageVersion());
1532
+ return 0;
1250
1533
  }
1251
- if (isEditKey(key))
1252
- return withQuery(state, key);
1253
- switch (key) {
1254
- case "up":
1255
- return move(state, -1);
1256
- case "down":
1257
- return move(state, 1);
1258
- case "pageup":
1259
- return move(state, -state.page);
1260
- case "pagedown":
1261
- return move(state, state.page);
1262
- case "home":
1263
- return move(state, -state.matches.length);
1264
- case "end":
1265
- return move(state, state.matches.length);
1266
- case "cancel":
1267
- return { ...state, done: "cancel" };
1268
- case "help":
1269
- return { ...state, help: true };
1270
- case "suspend":
1271
- return state;
1272
- case "enter":
1273
- return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1274
- case "tab": {
1275
- const at = highlighted(state);
1276
- if (!state.multi || at === undefined)
1277
- return state;
1278
- const marked = new Set(state.marked);
1279
- if (!marked.delete(at))
1280
- marked.add(at);
1281
- return move({ ...state, marked }, 1);
1282
- }
1534
+ let code;
1535
+ const started = performance.now();
1536
+ try {
1537
+ code = await run(argv);
1538
+ } catch (error) {
1539
+ code = reportThrown(name, error, redact, wantsJson(argv));
1283
1540
  }
1541
+ notifyEnd(name, code, performance.now() - started);
1542
+ if (usage !== false) {
1543
+ try {
1544
+ recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
1545
+ } catch {}
1546
+ }
1547
+ return code;
1284
1548
  }
1285
- function chosen(state) {
1286
- if (state.marked.size > 0)
1287
- return state.rows.filter((_, index) => state.marked.has(index));
1288
- const at = highlighted(state);
1289
- return at === undefined ? [] : [state.rows[at]];
1290
- }
1549
+
1550
+ // ../kit/src/index.ts
1551
+ init_config();
1552
+
1553
+ // ../kit/src/excerpt.ts
1554
+ init_text();
1555
+
1556
+ // ../kit/src/index.ts
1557
+ init_folders();
1558
+ init_format();
1559
+
1560
+ // ../kit/src/git.ts
1561
+ init_args();
1562
+ // ../kit/src/limit.ts
1563
+ init_args();
1564
+
1565
+ // ../kit/src/index.ts
1566
+ init_mode();
1567
+
1568
+ // ../kit/src/report.ts
1569
+ init_style();
1570
+ init_text();
1571
+ // ../kit/src/secrets.ts
1572
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1573
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1574
+ // ../kit/src/sessions.ts
1575
+ var {Glob } = globalThis.Bun;
1576
+ var SESSION_FILES = new Glob("*.json");
1577
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1578
+
1579
+ // ../kit/src/index.ts
1580
+ init_style();
1581
+ init_text();
1582
+ init_theme();
1583
+ init_user_config();
1584
+
1585
+ // ../kit/src/watch.ts
1586
+ init_args();
1587
+ init_input();
1588
+ init_style();
1589
+ // ../kit/src/workspace-root.ts
1590
+ init_user_config();
1591
+ // ../kit/src/picker.ts
1592
+ init_folders();
1593
+ init_state();
1291
1594
 
1292
1595
  // ../kit/src/picker/terminal.ts
1596
+ init_args();
1597
+ init_job();
1598
+ init_redraw();
1599
+ init_style();
1293
1600
  import { openSync } from "fs";
1294
- import process17 from "process";
1601
+ import process18 from "process";
1295
1602
  import tty from "tty";
1296
1603
 
1297
- // ../kit/src/job.ts
1298
- import process15 from "process";
1299
- function stopJob() {
1300
- process15.kill(0, "SIGTSTP");
1301
- }
1302
-
1303
- // ../kit/src/redraw.ts
1304
- var SYNC_START = "\x1B[?2026h";
1305
- var SYNC_END = "\x1B[?2026l";
1306
- function overwrite(lines, columns) {
1307
- return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1308
- `);
1309
- }
1310
-
1311
1604
  // ../kit/src/picker/preview.ts
1312
- import process16 from "process";
1605
+ import process17 from "process";
1313
1606
 
1314
1607
  // ../kit/src/shell.ts
1315
1608
  var SEPARATORS = new Set([`
@@ -1320,6 +1613,7 @@ var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
1320
1613
  var SAFE_WORD = /^[\w@%+=:,./-]+$/;
1321
1614
  var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
1322
1615
  var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
1616
+ var FISH_COMBINERS = new Set(["and", "or", "not"]);
1323
1617
  var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
1324
1618
  var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
1325
1619
  var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
@@ -1331,6 +1625,7 @@ var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
1331
1625
  function wrapper(short = "", long = [], operands = 0, runsString = false) {
1332
1626
  return { short, long, operands, runsString };
1333
1627
  }
1628
+ var RUNNER = { ...wrapper(), afterDashes: true };
1334
1629
  var WRAPPERS = new Map([
1335
1630
  ["command", wrapper()],
1336
1631
  ["builtin", wrapper()],
@@ -1352,7 +1647,23 @@ var WRAPPERS = new Map([
1352
1647
  ["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
1353
1648
  ["unbuffer", wrapper()],
1354
1649
  ["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
1355
- ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
1650
+ ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])],
1651
+ ["strace", wrapper("abeEIoOpPsSuUX", ["--trace", "--output", "--attach", "--string-limit", "--user", "--env", "--columns", "--trace-path", "--signal", "--status", "--summary-sort-by", "--summary-columns", "--const-print-style", "--interruptible", "--detach-on"])],
1652
+ ["ltrace", wrapper("aeFlnopsuxX", ["--output", "--user", "--library", "--config", "--align", "--indent"])],
1653
+ ["taskset", wrapper("", [], 1)],
1654
+ ["fakeroot", wrapper("lsib", ["--lib", "--faked"])],
1655
+ ["sshpass", wrapper("pfdP")],
1656
+ ["coproc", wrapper()],
1657
+ ["proxychains", wrapper("f")],
1658
+ ["proxychains4", wrapper("f")],
1659
+ ["torsocks", wrapper("upaP", ["--user", "--pass", "--address", "--port"])],
1660
+ ["chrt", wrapper("TPD", ["--sched-runtime", "--sched-period", "--sched-deadline"], 1)],
1661
+ ["unshare", wrapper("SGRw", ["--setuid", "--setgid", "--root", "--wd", "--map-user", "--map-group", "--map-users", "--map-groups", "--propagation", "--setgroups"])],
1662
+ ["nsenter", wrapper("tSG", ["--target", "--setuid", "--setgid"])],
1663
+ ["out", RUNNER],
1664
+ ["slot", RUNNER],
1665
+ ["waitfor", RUNNER],
1666
+ ["base", RUNNER]
1356
1667
  ]);
1357
1668
  function shellQuote(word) {
1358
1669
  return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
@@ -1378,7 +1689,7 @@ async function runPreview(template, line, signal, hidden = []) {
1378
1689
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1379
1690
  const stop = () => {
1380
1691
  try {
1381
- process16.kill(-proc.pid, "SIGKILL");
1692
+ process17.kill(-proc.pid, "SIGKILL");
1382
1693
  } catch {
1383
1694
  proc.kill();
1384
1695
  }
@@ -1403,7 +1714,12 @@ ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe",
1403
1714
  return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
1404
1715
  }
1405
1716
 
1717
+ // ../kit/src/picker/terminal.ts
1718
+ init_state();
1719
+
1406
1720
  // ../kit/src/picker/view.ts
1721
+ init_line();
1722
+ init_state();
1407
1723
  var MIN_HEIGHT = 4;
1408
1724
  var PREVIEW_MIN_COLUMNS = 80;
1409
1725
  var PREVIEW_MIN_ROWS = 10;
@@ -1537,7 +1853,7 @@ function openTerminal() {
1537
1853
  return fail("no terminal to read keys from (/dev/tty)");
1538
1854
  }
1539
1855
  const keys = Bun.file("/dev/tty").stream().getReader();
1540
- const out = process17.stderr;
1856
+ const out = process18.stderr;
1541
1857
  let resize;
1542
1858
  async function read(onChunk) {
1543
1859
  const decoder = new TextDecoder;
@@ -1726,9 +2042,9 @@ async function select(rows, settings, terminal = openTerminal()) {
1726
2042
  const ended = new Promise((resolve) => {
1727
2043
  finish = resolve;
1728
2044
  });
1729
- process17.once("exit", restore);
2045
+ process18.once("exit", restore);
1730
2046
  for (const signal of SIGNALS)
1731
- process17.once(signal, stop);
2047
+ process18.once(signal, stop);
1732
2048
  try {
1733
2049
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1734
2050
  terminal.listen(onChunk, () => draw(true));
@@ -1741,8 +2057,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1741
2057
  await ended;
1742
2058
  } finally {
1743
2059
  for (const signal of SIGNALS)
1744
- process17.off(signal, stop);
1745
- process17.off("exit", restore);
2060
+ process18.off(signal, stop);
2061
+ process18.off("exit", restore);
1746
2062
  restore();
1747
2063
  }
1748
2064
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1754,6 +2070,10 @@ async function previewOf(preview, hidden, signal) {
1754
2070
  return [error instanceof Error ? error.message : String(error)];
1755
2071
  }
1756
2072
  }
2073
+
2074
+ // ../kit/src/picker.ts
2075
+ init_score();
2076
+
1757
2077
  // src/fields.ts
1758
2078
  var INDEX = /^-?\d+$/;
1759
2079
  function splitFields(line, delimiter) {
@@ -1795,14 +2115,10 @@ function pickFields(line, select, delimiter) {
1795
2115
  // src/pick.ts
1796
2116
  var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
1797
2117
 
1798
- 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.
1799
- 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).
1800
- --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.
1801
-
1802
- --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.
1803
- --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.
1804
-
1805
- 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.`;
2118
+ 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.
2119
+ 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.
2120
+ --delimiter, --nth and --with-nth split lines into fields in fzf's syntax, and the printed line is always the whole input line.
2121
+ Without a terminal on stderr it prints the best match, or every match with --multi.`;
1806
2122
  var EXITS = [[0, "it printed a choice"], [1, "nothing matches or there are no lines"], [2, "a usage error"], [130, "cancelled"]];
1807
2123
  var OPTIONS = {
1808
2124
  multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
@@ -1821,11 +2137,21 @@ var OPTIONS = {
1821
2137
  height: { type: "string", description: "lines or a percentage of the terminal to draw in (100%)" },
1822
2138
  json: jsonOption("{picked: [lines]}, the choice or the marked lines in input order")
1823
2139
  };
1824
- function print(chosen, json, end) {
2140
+ function print(chosen, lines, raw, json, end) {
1825
2141
  if (json)
1826
- printJson({ picked: chosen });
2142
+ printJson({ picked: chosen.map((index) => lines[index]) });
1827
2143
  else
1828
- process18.stdout.write(chosen.map((line) => line + end).join(""));
2144
+ process19.stdout.write(Buffer.concat(chosen.flatMap((index) => [raw[index], Buffer.from(end)])));
2145
+ }
2146
+ function splitBytes(bytes, separator) {
2147
+ const parts = [];
2148
+ let start = 0;
2149
+ for (let at = bytes.indexOf(separator);at !== -1; at = bytes.indexOf(separator, start)) {
2150
+ parts.push(bytes.subarray(start, at));
2151
+ start = at + 1;
2152
+ }
2153
+ parts.push(bytes.subarray(start));
2154
+ return parts.filter((part) => part.length > 0);
1829
2155
  }
1830
2156
  async function main(args) {
1831
2157
  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"] });
@@ -1834,7 +2160,7 @@ async function main(args) {
1834
2160
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1835
2161
  if (height === undefined)
1836
2162
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1837
- if (process18.stdin.isTTY)
2163
+ if (process19.stdin.isTTY)
1838
2164
  badUsage("pipe the lines to pick on stdin");
1839
2165
  const fieldsOf = (name) => {
1840
2166
  const text = values[name];
@@ -1850,8 +2176,9 @@ async function main(args) {
1850
2176
  } catch {
1851
2177
  badUsage(`--delimiter is a regex, not ${values.delimiter}`);
1852
2178
  }
1853
- const lines = (await Bun.stdin.text()).split(values.read0 === true ? "\x00" : `
1854
- `).filter((line) => line !== "");
2179
+ const raw = splitBytes(await Bun.stdin.bytes(), values.read0 === true ? 0 : 10);
2180
+ const decoder = new TextDecoder;
2181
+ const lines = raw.map((bytes) => decoder.decode(bytes));
1855
2182
  if (lines.length === 0)
1856
2183
  fail("nothing to pick from", 1);
1857
2184
  const query = values.filter ?? values.query ?? "";
@@ -1859,22 +2186,22 @@ async function main(args) {
1859
2186
  `;
1860
2187
  const json = values.json === true;
1861
2188
  const searched = lines.map((line) => nth === undefined ? line : pickFields(line, nth, delimiter));
1862
- const matching = rank(query, searched).map(({ index }) => lines[index]);
1863
- if (matching.length === 0 && (values["exit-0"] === true || values.filter !== undefined || !process18.stderr.isTTY))
2189
+ const matching = rank(query, searched).map(({ index }) => index);
2190
+ if (matching.length === 0 && (values["exit-0"] === true || values.filter !== undefined || !process19.stderr.isTTY))
1864
2191
  return 1;
1865
- if (values.filter !== undefined || !process18.stderr.isTTY) {
1866
- print(values.multi === true || values.filter !== undefined ? matching : matching.slice(0, 1), json, end);
2192
+ if (values.filter !== undefined || !process19.stderr.isTTY) {
2193
+ print(values.multi === true || values.filter !== undefined ? matching : matching.slice(0, 1), lines, raw, json, end);
1867
2194
  return 0;
1868
2195
  }
1869
2196
  if (values["select-1"] === true && matching.length === 1) {
1870
- print(matching, json, end);
2197
+ print(matching, lines, raw, json, end);
1871
2198
  return 0;
1872
2199
  }
1873
2200
  const rows = lines.map((line, index) => ({ hidden: [line], cells: [withNth === undefined ? line : pickFields(line, withNth, delimiter).trimEnd()], ...nth === undefined ? {} : { search: searched[index] } }));
1874
2201
  const picked = await select(rows, { multi: values.multi === true, prompt: values.prompt ?? "> ", query, height, preview: values.preview, header: values.header });
1875
2202
  if (picked === undefined)
1876
2203
  return 130;
1877
- print(picked.rows.map((row) => row.hidden[0]), json, end);
2204
+ print(picked.rows.map((row) => rows.indexOf(row)), lines, raw, json, end);
1878
2205
  return 0;
1879
2206
  }
1880
- process18.exitCode = await runMain({ name: "pick", run: main });
2207
+ process19.exitCode = await runMain({ name: "pick", run: main });