@kaynooo/cli-code 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,17 @@
1
1
  #!/usr/bin/env -S bun --no-env-file
2
2
  // @bun
3
3
 
4
- // src/peek.ts
5
- import { realpathSync as realpathSync2 } from "fs";
6
- import { isAbsolute as isAbsolute2, join as join4, relative as relative2, resolve, sep } from "path";
7
- import process10 from "process";
4
+ // src/peek-cli.ts
5
+ import process14 from "process";
8
6
  // ../kit/src/args.ts
9
- import process5 from "process";
7
+ import process8 from "process";
10
8
  import { parseArgs } from "util";
11
9
 
12
10
  // ../kit/src/format.ts
13
- import process3 from "process";
11
+ import process6 from "process";
14
12
 
15
13
  // ../kit/src/style.ts
16
- import process2 from "process";
14
+ import process5 from "process";
17
15
 
18
16
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
19
17
  function x(s) {
@@ -276,36 +274,222 @@ function le(i = {}) {
276
274
  }
277
275
  var t = le();
278
276
 
279
- // ../kit/src/style.ts
280
- var MARKS = {
281
- ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
282
- warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
283
- problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
284
- note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
277
+ // ../kit/src/theme.ts
278
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
279
+ import { homedir as homedir2 } from "os";
280
+ import { join as join3, resolve as resolve2 } from "path";
281
+ import process4 from "process";
282
+
283
+ // ../kit/src/config.ts
284
+ import { existsSync } from "fs";
285
+ import { dirname, join, resolve } from "path";
286
+ import process2 from "process";
287
+ function findUp(names, from = process2.cwd(), stop = () => false) {
288
+ const wanted = typeof names === "string" ? [names] : names;
289
+ for (let dir = resolve(from);; dir = dirname(dir)) {
290
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
291
+ if (found !== undefined)
292
+ return found;
293
+ if (stop(dir) || dirname(dir) === dir)
294
+ return;
295
+ }
296
+ }
297
+
298
+ // ../kit/src/user-config.ts
299
+ import { homedir } from "os";
300
+ import { join as join2 } from "path";
301
+ import process3 from "process";
302
+ function configBase(where = {}) {
303
+ const xdg = where.xdg ?? (where.home === undefined ? process3.env.XDG_CONFIG_HOME : undefined);
304
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
305
+ }
306
+ function userConfigPath(bin, where = {}) {
307
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
308
+ }
309
+
310
+ // ../kit/src/theme.ts
311
+ var DEFAULT = {
312
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
313
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
314
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
315
+ bins: {}
285
316
  };
286
- function takesControlCodes(stream, env = process2.env) {
317
+ var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
318
+ var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
319
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
320
+ var PRESETS = {
321
+ default: {},
322
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
323
+ mono: { colors: MONO, accents: ["bold"] },
324
+ ascii: { glyphs: ASCII }
325
+ };
326
+ 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"]);
327
+ var HEX = /^#[0-9a-f]{6}$/i;
328
+ var CONTROL = /\p{Cc}/u;
329
+ var MAX_FILE_BYTES = 64 * 1024;
330
+ var SPACES = /\s+/;
331
+ function isColorSpec(spec) {
332
+ if (typeof spec === "number")
333
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
334
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
335
+ }
336
+ function tinted(colors, spec) {
337
+ if (typeof spec === "number")
338
+ return colors.ansi256(spec);
339
+ return spec.trim().split(SPACES).reduce((chain, token) => HEX.test(token) ? chain.hex(token) : chain[token] ?? chain, colors);
340
+ }
341
+ function isRecord(value) {
342
+ return typeof value === "object" && value !== null && !Array.isArray(value);
343
+ }
344
+ function readThemeFile(path, warn) {
345
+ try {
346
+ const stat = statSync(path, { throwIfNoEntry: false });
347
+ if (stat === undefined)
348
+ return;
349
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
350
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
351
+ return;
352
+ }
353
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
354
+ if (isRecord(parsed))
355
+ return parsed;
356
+ warn(`${path} is not a JSON object, theme ignored`);
357
+ } catch (error) {
358
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
359
+ }
360
+ return;
361
+ }
362
+ function applyPreset(theme, name, warn, where) {
363
+ if (name === undefined)
364
+ return;
365
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
366
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
367
+ return;
368
+ }
369
+ const preset = PRESETS[name];
370
+ Object.assign(theme.colors, preset.colors);
371
+ Object.assign(theme.glyphs, preset.glyphs);
372
+ if (preset.accents !== undefined)
373
+ theme.accents = [...preset.accents];
374
+ return name;
375
+ }
376
+ function applyFile(theme, file, where, warn) {
377
+ if (isRecord(file.colors)) {
378
+ for (const [key, value] of Object.entries(file.colors)) {
379
+ if (!Object.hasOwn(DEFAULT.colors, key))
380
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
381
+ else if (!isColorSpec(value))
382
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
383
+ else
384
+ theme.colors[key] = value;
385
+ }
386
+ }
387
+ if (isRecord(file.glyphs)) {
388
+ for (const [key, value] of Object.entries(file.glyphs)) {
389
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
390
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
391
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
392
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
393
+ else
394
+ theme.glyphs[key] = value;
395
+ }
396
+ }
397
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
398
+ theme.accents = [...file.accents];
399
+ else if (file.accents !== undefined)
400
+ warn(`${where}: accents must be a non-empty list of colours`);
401
+ if (isRecord(file.bins)) {
402
+ for (const [bin, value] of Object.entries(file.bins)) {
403
+ if (isColorSpec(value))
404
+ theme.bins[bin] = value;
405
+ else
406
+ warn(`${where}: bin ${bin} has no valid colour`);
407
+ }
408
+ }
409
+ }
410
+ function endsWalk(home) {
411
+ return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
412
+ }
413
+ var warned = new Set;
414
+ function warnOnce(message) {
415
+ if (warned.has(message))
416
+ return;
417
+ warned.add(message);
418
+ console.error(`warning: theme ${message}`);
419
+ }
420
+ function isPath(chosen) {
421
+ return chosen.includes("/") || chosen.endsWith(".json");
422
+ }
423
+ function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(), warn = warnOnce } = {}) {
424
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
425
+ const sources = [];
426
+ const chosen = env.KIT_THEME ?? "";
427
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
428
+ if (isPath(chosen))
429
+ wanted.push(resolve2(from, chosen));
430
+ const files = [];
431
+ for (const path of wanted) {
432
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
433
+ if (path !== undefined && file !== undefined)
434
+ files.push({ path, file });
435
+ }
436
+ let preset = "default";
437
+ if (chosen !== "" && !isPath(chosen)) {
438
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
439
+ } else {
440
+ const named = files.findLast(({ file }) => file.preset !== undefined);
441
+ if (named !== undefined)
442
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
443
+ }
444
+ for (const { path, file } of files) {
445
+ applyFile(theme, file, path, warn);
446
+ sources.push(path);
447
+ }
448
+ return { theme, sources, preset };
449
+ }
450
+ var current;
451
+ var currentKey = "";
452
+ function activeTheme() {
453
+ const key = `${process4.cwd()}\x00${process4.env.KIT_THEME ?? ""}\x00${process4.env.XDG_CONFIG_HOME ?? ""}`;
454
+ if (current === undefined || key !== currentKey) {
455
+ current = loadTheme();
456
+ currentKey = key;
457
+ }
458
+ return current;
459
+ }
460
+
461
+ // ../kit/src/style.ts
462
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:" };
463
+ function takesControlCodes(stream, env = process5.env) {
287
464
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
288
465
  }
289
- function paint(stream, env = process2.env) {
466
+ function paint(stream, env = process5.env) {
290
467
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
291
468
  }
292
- function marked(mark, text, stream, detail, env = process2.env) {
469
+ function marked(mark, text, stream, detail, env = process5.env) {
293
470
  const colors = paint(stream, env);
294
- const { symbol, word, paint: tint } = MARKS[mark];
295
- const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
471
+ let head = MARK_WORDS[mark];
472
+ if (takesControlCodes(stream, env)) {
473
+ const { theme } = activeTheme();
474
+ head = tinted(colors.bold, theme.colors[mark])(theme.glyphs[mark]);
475
+ }
296
476
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
297
477
  }
298
478
  function warn(text, detail) {
299
- console.error(marked("warn", text, process2.stderr, detail));
300
- }
301
- var STATUSES = {
302
- passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
303
- failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
304
- running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
305
- queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
306
- skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
479
+ console.error(marked("warn", text, process5.stderr, detail));
480
+ }
481
+ function role(name, stream, env = process5.env) {
482
+ const colors = paint(stream, env);
483
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name]) : colors;
484
+ }
485
+ var STATUS_WORDS = {
486
+ passed: ["passed", "success", "succeeded", "ok"],
487
+ failed: ["failed", "failure", "error", "errored"],
488
+ running: ["running", "in_progress", "started"],
489
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
490
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
307
491
  };
308
- var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
492
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
309
493
 
310
494
  // ../kit/src/format.ts
311
495
  function upTo(text, separator) {
@@ -320,7 +504,7 @@ var ESCAPE = String.fromCharCode(27);
320
504
  function textWidth(text) {
321
505
  return Bun.stringWidth(text);
322
506
  }
323
- function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
507
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process6.stdout } = {}) {
324
508
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
325
509
  const widths = [];
326
510
  for (const row of cells) {
@@ -328,7 +512,7 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
328
512
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
329
513
  }
330
514
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
331
- const colors = paint(process3.stdout);
515
+ const colors = paint(stream);
332
516
  const lines = shown.map((row) => row.map((cell, index) => {
333
517
  const width = widths[index] ?? 0;
334
518
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -336,7 +520,8 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
336
520
  return `${gap}${cell}`;
337
521
  return index === row.length - 1 ? cell : `${cell}${gap}`;
338
522
  }).join(" ").trimEnd());
339
- return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
523
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
524
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
340
525
  `);
341
526
  }
342
527
  function narrow(rows, widths, limit) {
@@ -360,27 +545,27 @@ function printJson(value) {
360
545
  }
361
546
 
362
547
  // ../kit/src/help.ts
363
- import process4 from "process";
548
+ import process7 from "process";
364
549
  var OPTIONAL = /\[[^\]]+\]/g;
365
550
  var USAGE_PREFIX = /^usage:\s*/i;
366
551
  var FULL_STOP = /\.$/;
367
- function usageLine(usage, colors = paint(process4.stdout)) {
552
+ function usageLine(usage, colors = paint(process7.stdout)) {
368
553
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
369
554
  }
370
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
555
+ function helpText(usage, options, colors = paint(process7.stdout), { examples = [], replaces, exits = [] } = {}) {
371
556
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
372
557
  `);
373
558
  }
374
- function exitRows(exits, colors = paint(process4.stdout)) {
559
+ function exitRows(exits, colors = paint(process7.stdout)) {
375
560
  if (exits.length === 0)
376
561
  return [];
377
562
  const width = Math.max(...exits.map(([code]) => String(code).length));
378
563
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
379
564
  }
380
- function replacesRows(replaces, colors = paint(process4.stdout)) {
565
+ function replacesRows(replaces, colors = paint(process7.stdout)) {
381
566
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
382
567
  }
383
- function wantsHelpJson(env = process4.env) {
568
+ function wantsHelpJson(env = process7.env) {
384
569
  return env.KIT_HELP === "json";
385
570
  }
386
571
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -399,12 +584,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
399
584
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
400
585
  };
401
586
  }
402
- function exampleRows(examples, colors = paint(process4.stdout)) {
587
+ function exampleRows(examples, colors = paint(process7.stdout)) {
403
588
  if (examples.length === 0)
404
589
  return [];
405
590
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
406
591
  }
407
- function optionRows(options, colors = paint(process4.stdout)) {
592
+ function optionRows(options, colors = paint(process7.stdout)) {
408
593
  const rows = Object.entries(options).map(([name, option]) => {
409
594
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
410
595
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -511,7 +696,7 @@ var OUTPUT_OPTIONS = {
511
696
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
512
697
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
513
698
  };
514
- function applyOutput(color, plain, env = process5.env) {
699
+ function applyOutput(color, plain, env = process8.env) {
515
700
  const when = plain === true ? "never" : color ?? "auto";
516
701
  if (when === "auto")
517
702
  return;
@@ -682,7 +867,7 @@ function nearestOption(message, options, allowNegative) {
682
867
  }
683
868
  // ../kit/src/process.ts
684
869
  import { constants } from "os";
685
- import process6 from "process";
870
+ import process9 from "process";
686
871
  var KILL_GRACE_MS = 2000;
687
872
  function exitCodeOf(code, signal) {
688
873
  if (code !== null)
@@ -702,7 +887,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
702
887
  return;
703
888
  try {
704
889
  if (grouped)
705
- process6.kill(-proc.pid, killing);
890
+ process9.kill(-proc.pid, killing);
706
891
  else
707
892
  proc.kill(killing);
708
893
  } catch {}
@@ -776,15 +961,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
776
961
  var RESET_STYLE = `${ESC}[0m`;
777
962
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
778
963
  // ../kit/src/cli.ts
779
- import { readFileSync, realpathSync } from "fs";
780
- import { dirname as dirname2, join as join2 } from "path";
781
- import process8 from "process";
964
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
965
+ import { dirname as dirname3, join as join5 } from "path";
966
+ import process11 from "process";
782
967
 
783
968
  // ../kit/src/usage.ts
784
969
  import { appendFileSync, mkdirSync } from "fs";
785
- import { homedir } from "os";
786
- import { dirname, isAbsolute, join } from "path";
787
- import process7 from "process";
970
+ import { homedir as homedir3 } from "os";
971
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
972
+ import process10 from "process";
788
973
 
789
974
  // ../kit/src/logs.ts
790
975
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -798,14 +983,14 @@ var usageError;
798
983
  function noteUsageError(message) {
799
984
  usageError = message;
800
985
  }
801
- function stateHome(env = process7.env) {
986
+ function stateHome(env = process10.env) {
802
987
  const dir = env.XDG_STATE_HOME;
803
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
988
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
804
989
  }
805
- function usagePath(env = process7.env) {
806
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
990
+ function usagePath(env = process10.env) {
991
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
807
992
  }
808
- function usageRecorded(env = process7.env) {
993
+ function usageRecorded(env = process10.env) {
809
994
  const off = env.KAYNOOO_CLI_NO_USAGE;
810
995
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
811
996
  }
@@ -819,12 +1004,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
819
1004
  usageError = undefined;
820
1005
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
821
1006
  }
822
- function recordUsage(entry, env = process7.env) {
1007
+ function recordUsage(entry, env = process10.env) {
823
1008
  if (!usageRecorded(env))
824
1009
  return;
825
1010
  try {
826
1011
  const path = usagePath(env);
827
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
1012
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
828
1013
  appendFileSync(path, `${JSON.stringify(entry)}
829
1014
  `, { mode: 384 });
830
1015
  } catch {}
@@ -836,9 +1021,82 @@ var LEVEL_OPTIONS = {
836
1021
  help: { type: "boolean", short: "h", description: "show this help" }
837
1022
  };
838
1023
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1024
+ async function commandRows(all, colors) {
1025
+ const commands = shown(all);
1026
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
1027
+ const groups = new Map([["Commands:", []]]);
1028
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
1029
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
1030
+ const heading = group === undefined ? "Commands:" : `${group}:`;
1031
+ const rows = groups.get(heading) ?? [];
1032
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
1033
+ groups.set(heading, rows);
1034
+ }
1035
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
1036
+ }
1037
+ function shown(commands) {
1038
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
1039
+ }
1040
+ function takeOutputFlags(argv) {
1041
+ let index = 0;
1042
+ for (;index < argv.length; index++) {
1043
+ const word = argv[index];
1044
+ if (word === "--plain")
1045
+ applyOutput(undefined, true);
1046
+ else if (word.startsWith("--color="))
1047
+ applyOutput(word.slice("--color=".length), undefined);
1048
+ else if (word === "--color" && argv[index + 1] !== undefined)
1049
+ applyOutput(argv[++index], undefined);
1050
+ else
1051
+ break;
1052
+ }
1053
+ return argv.slice(index);
1054
+ }
1055
+ async function resolveSummary(summary) {
1056
+ return typeof summary === "string" ? summary : summary();
1057
+ }
1058
+ function scopeOf(commands, extra, aliases) {
1059
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1060
+ }
1061
+ async function expand(scope, words) {
1062
+ if (scope.lazy.length === 0)
1063
+ return scope;
1064
+ const commands = { ...scope.commands };
1065
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
1066
+ for (const [name, command] of Object.entries(added))
1067
+ commands[name] ??= command;
1068
+ }
1069
+ return { ...scope, commands, lazy: [] };
1070
+ }
1071
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
1072
+ const colors = paint(stream);
1073
+ const prefix = path.join(" ");
1074
+ const summary = await resolveSummary(lazySummary);
1075
+ if (wantsHelpJson())
1076
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
1077
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1078
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
1079
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
1080
+ return [
1081
+ header(colors, summary),
1082
+ "",
1083
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
1084
+ ...replacesRows(replaces, colors),
1085
+ "",
1086
+ ...await commandRows(commands, colors),
1087
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
1088
+ "",
1089
+ colors.bold("Options:"),
1090
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
1091
+ ...exampleRows(examples ?? [], colors),
1092
+ "",
1093
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
1094
+ ].join(`
1095
+ `);
1096
+ }
839
1097
  function printError(prefix, message, hint, cause) {
840
- const colors = paint(process8.stderr);
841
- const styled = takesControlCodes(process8.stderr);
1098
+ const colors = paint(process11.stderr);
1099
+ const styled = takesControlCodes(process11.stderr);
842
1100
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
843
1101
  const under = (label, text, tint) => text === undefined ? "" : `
844
1102
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -857,12 +1115,68 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
857
1115
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
858
1116
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
859
1117
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
860
- if (error instanceof UsageError)
1118
+ if (error instanceof Exit && error.code === 2)
861
1119
  noteUsageError(error.message);
862
1120
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
863
1121
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
864
1122
  return error instanceof Exit ? error.code : 1;
865
1123
  }
1124
+ async function dispatch(level, typed, { version, redact }) {
1125
+ const prefix = level.path.join(" ");
1126
+ let argv;
1127
+ try {
1128
+ argv = takeOutputFlags(typed);
1129
+ } catch (error) {
1130
+ return reportThrown(prefix, error);
1131
+ }
1132
+ const [name, ...args] = argv;
1133
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
1134
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
1135
+ try {
1136
+ return await fallback.run([]);
1137
+ } catch (error) {
1138
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
1139
+ }
1140
+ }
1141
+ if (name === undefined && level.path.length > 1) {
1142
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stderr));
1143
+ return 2;
1144
+ }
1145
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1146
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stdout));
1147
+ return 0;
1148
+ }
1149
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1150
+ console.log(version);
1151
+ return 0;
1152
+ }
1153
+ let command = level.commands[level.aliases?.[name] ?? name];
1154
+ let rest = args;
1155
+ let ran = name;
1156
+ if (command === undefined && level.lazy.length > 0) {
1157
+ level = await expand(level, [...level.path.slice(1), ...argv]);
1158
+ command = level.commands[level.aliases?.[name] ?? name];
1159
+ }
1160
+ if (command === undefined && level.defaultCommand !== undefined) {
1161
+ command = level.commands[level.defaultCommand];
1162
+ rest = argv;
1163
+ ran = level.defaultCommand;
1164
+ }
1165
+ if (command === undefined) {
1166
+ const meant = closest(name, Object.keys(shown(level.commands)));
1167
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
1168
+ return 2;
1169
+ }
1170
+ if ("commands" in command) {
1171
+ const { summary } = command;
1172
+ return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
1173
+ }
1174
+ try {
1175
+ return await command.run(rest);
1176
+ } catch (error) {
1177
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
1178
+ }
1179
+ }
866
1180
  var COMPLETE = "__complete";
867
1181
  var FILES = "__files__";
868
1182
  async function completingOf(run) {
@@ -877,6 +1191,9 @@ async function completingOf(run) {
877
1191
  }
878
1192
  return new Completing({});
879
1193
  }
1194
+ async function optionsOf(run) {
1195
+ return (await completingOf(run)).options;
1196
+ }
880
1197
  function candidateLine(candidate) {
881
1198
  return typeof candidate === "string" ? candidate : candidate.join("\t");
882
1199
  }
@@ -915,23 +1232,72 @@ async function leafCandidates(run, words) {
915
1232
  const values = name === undefined ? undefined : await completing.candidates[name]?.();
916
1233
  return values === undefined ? [FILES] : values.map(candidateLine);
917
1234
  }
1235
+ async function candidates(scope, defaultCommand, words, before = []) {
1236
+ const [word = "", ...rest] = words;
1237
+ const listing = rest.length === 0 && !word.startsWith("-");
1238
+ let { commands, aliases } = scope;
1239
+ let command = commands[aliases?.[word] ?? word];
1240
+ if (listing || command === undefined) {
1241
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
1242
+ command = commands[aliases?.[word] ?? word];
1243
+ }
1244
+ if (listing) {
1245
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1246
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1247
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1248
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1249
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1250
+ }
1251
+ if (command === undefined) {
1252
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1253
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
1254
+ }
1255
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1256
+ }
918
1257
  async function printCandidates(found) {
919
1258
  for (const line of await found)
920
1259
  console.log(line);
921
1260
  return 0;
922
1261
  }
923
1262
  function packageVersion(entry = Bun.main) {
924
- for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1263
+ for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
925
1264
  try {
926
- const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1265
+ const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
927
1266
  if (typeof version === "string")
928
1267
  return version;
929
1268
  } catch {}
930
- if (dirname2(dir) === dir)
1269
+ if (dirname3(dir) === dir)
931
1270
  return "0.0.0";
932
1271
  }
933
1272
  }
934
- async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
1273
+ async function runCli(cli, argv = process11.argv.slice(2)) {
1274
+ const version = cli.version ?? packageVersion();
1275
+ if (argv[0] === COMPLETE)
1276
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1277
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1278
+ if (cli.usage !== false) {
1279
+ try {
1280
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1281
+ } catch {}
1282
+ }
1283
+ return code;
1284
+ }
1285
+ function commandPath(scope, argv) {
1286
+ const path = [];
1287
+ let level = scope;
1288
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
1289
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1290
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1291
+ if (command === undefined)
1292
+ break;
1293
+ path.push(word);
1294
+ if (!("commands" in command))
1295
+ break;
1296
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1297
+ }
1298
+ return path.length === 0 ? undefined : path.join(" ");
1299
+ }
1300
+ async function runMain({ name, version, run, redact, usage }, argv = process11.argv.slice(2)) {
935
1301
  if (argv[0] === COMPLETE)
936
1302
  return printCandidates(leafCandidates(run, argv.slice(1)));
937
1303
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -978,9 +1344,14 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
978
1344
  var {Glob } = globalThis.Bun;
979
1345
  var SESSION_FILES = new Glob("*.json");
980
1346
  var ACCOUNT_DIRS = new Glob("*/sessions");
1347
+ // src/peek.ts
1348
+ import { realpathSync as realpathSync2 } from "fs";
1349
+ import { isAbsolute as isAbsolute2, join as join7, relative as relative2, resolve as resolve3, sep } from "path";
1350
+ import process13 from "process";
1351
+
981
1352
  // src/files.ts
982
- import { existsSync, readdirSync, statSync } from "fs";
983
- import { join as join3, relative } from "path";
1353
+ import { existsSync as existsSync3, readdirSync, statSync as statSync2 } from "fs";
1354
+ import { join as join6, relative } from "path";
984
1355
  var MAX_BYTES = 2000000;
985
1356
  var SNIFF_BYTES = 8000;
986
1357
  var SKIPPED = new Set(["node_modules", "dist", "build", "vendor", "target", "coverage"]);
@@ -995,18 +1366,18 @@ function walk(dir, found) {
995
1366
  if (entry.name.startsWith(".") || SKIPPED.has(entry.name))
996
1367
  continue;
997
1368
  if (entry.isDirectory())
998
- walk(join3(dir, entry.name), found);
1369
+ walk(join6(dir, entry.name), found);
999
1370
  else if (entry.isFile())
1000
- found.push(join3(dir, entry.name));
1371
+ found.push(join6(dir, entry.name));
1001
1372
  }
1002
1373
  return found;
1003
1374
  }
1004
1375
  async function listFiles(paths, cwd) {
1005
1376
  const listed = await runCommand(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], { cwd });
1006
1377
  if (listed.code === 0)
1007
- return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join3(cwd, path))).sort();
1008
- const roots = paths.length === 0 ? [cwd] : paths.map((path) => join3(cwd, path));
1009
- return roots.flatMap((root) => statSync(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [])).map((path) => relative(cwd, path)).sort();
1378
+ return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync3(join6(cwd, path))).sort();
1379
+ const roots = paths.length === 0 ? [cwd] : paths.map((path) => join6(cwd, path));
1380
+ return roots.flatMap((root) => statSync2(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [])).map((path) => relative(cwd, path)).sort();
1010
1381
  }
1011
1382
  async function readText(path) {
1012
1383
  const file = Bun.file(path);
@@ -1225,13 +1596,13 @@ function cut(text) {
1225
1596
  return text.length > LONGEST_LINE ? `${text.slice(0, LONGEST_LINE - 1)}\u2026` : text;
1226
1597
  }
1227
1598
  async function readableRoot() {
1228
- const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process10.cwd() });
1229
- return realpathSync2(ran.code === 0 ? ran.text.trim() : process10.cwd());
1599
+ const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process13.cwd() });
1600
+ return realpathSync2(ran.code === 0 ? ran.text.trim() : process13.cwd());
1230
1601
  }
1231
1602
  async function isOutside(path) {
1232
1603
  let real;
1233
1604
  try {
1234
- real = realpathSync2(resolve(process10.cwd(), path));
1605
+ real = realpathSync2(resolve3(process13.cwd(), path));
1235
1606
  } catch {
1236
1607
  return false;
1237
1608
  }
@@ -1245,7 +1616,7 @@ async function checkInside(path) {
1245
1616
  async function pipedSpans(text, context) {
1246
1617
  const spans = [];
1247
1618
  for (const [path, numbers] of locations(text)) {
1248
- const source = await isOutside(path) ? undefined : await readText(resolve(process10.cwd(), path));
1619
+ const source = await isOutside(path) ? undefined : await readText(resolve3(process13.cwd(), path));
1249
1620
  if (source !== undefined)
1250
1621
  spans.push(...spansAround(path, source.replace(TRAILING_NEWLINE2, "").split(`
1251
1622
  `).length, numbers, context));
@@ -1254,7 +1625,7 @@ async function pipedSpans(text, context) {
1254
1625
  }
1255
1626
  async function textOf(path) {
1256
1627
  await checkInside(path);
1257
- const text = await readText(resolve(process10.cwd(), path));
1628
+ const text = await readText(resolve3(process13.cwd(), path));
1258
1629
  if (text === undefined)
1259
1630
  fail(`cannot read ${path} (missing, binary or too large)`, 1);
1260
1631
  return text;
@@ -1312,8 +1683,8 @@ async function spanOf(target) {
1312
1683
  async function* sources(paths) {
1313
1684
  for (const path of paths)
1314
1685
  await checkInside(path);
1315
- for (const path of await listFiles(paths, process10.cwd())) {
1316
- const text = await readText(join4(process10.cwd(), path));
1686
+ for (const path of await listFiles(paths, process13.cwd())) {
1687
+ const text = await readText(join7(process13.cwd(), path));
1317
1688
  if (text !== undefined)
1318
1689
  yield { path, text };
1319
1690
  }
@@ -1336,7 +1707,7 @@ async function definitionsOf(symbols, paths) {
1336
1707
  fail(`no declaration of ${missing.join(", ")} found`, 1);
1337
1708
  return [...found.values()].flat();
1338
1709
  }
1339
- async function main(args) {
1710
+ async function peek(args) {
1340
1711
  const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[target...]"], replaces: "sed -n N,Mp, grep -n chains and whole-file reads", examples: [["peek src/a.ts:120-140 src/b.ts:1-40", "two spans in one call"], ["peek --def parseArgs src", "a whole declaration"]] });
1341
1712
  const modes = [values.def?.length === 0 ? undefined : values.def, values.refs, values.outline, values.around].filter((mode) => mode !== undefined && mode !== false);
1342
1713
  const json = values.json === true;
@@ -1411,4 +1782,6 @@ async function main(args) {
1411
1782
  await printSpans(await Promise.all(positionals.map(spanOf)), json);
1412
1783
  return 0;
1413
1784
  }
1414
- process10.exitCode = await runMain({ name: "peek", run: main });
1785
+
1786
+ // src/peek-cli.ts
1787
+ process14.exitCode = await runMain({ name: "peek", run: peek });