@kaynooo/cli-base 0.4.0 → 0.4.1

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/dist/cli.js +277 -108
  2. package/dist/proof.js +277 -108
  3. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -2,16 +2,16 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process7 from "process";
5
+ import process9 from "process";
6
6
 
7
7
  // ../kit/src/args.ts
8
- import process2 from "process";
8
+ import process3 from "process";
9
9
  import { parseArgs } from "util";
10
10
 
11
11
  // ../kit/src/style.ts
12
12
  import process from "process";
13
13
 
14
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
14
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
15
  function x(s) {
16
16
  let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
17
17
  if (!/^[a-f0-9]+$/.test(r))
@@ -231,7 +231,7 @@ class e {
231
231
  }
232
232
  }
233
233
 
234
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
234
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
235
235
  var r = 39;
236
236
  var o = 49;
237
237
  var f2 = "\x1B[";
@@ -298,6 +298,55 @@ function printJson(value) {
298
298
  console.log(JSON.stringify(value, undefined, 2));
299
299
  }
300
300
 
301
+ // ../kit/src/help.ts
302
+ import process2 from "process";
303
+ var OPTIONAL = /\[[^\]]+\]/g;
304
+ var USAGE_PREFIX = /^usage:\s*/i;
305
+ var FULL_STOP = /\.$/;
306
+ function usageLine(usage, colors = paint(process2.stdout)) {
307
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
308
+ }
309
+ function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
310
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
311
+ `);
312
+ }
313
+ function replacesRows(replaces, colors = paint(process2.stdout)) {
314
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
315
+ }
316
+ function wantsHelpJson(env = process2.env) {
317
+ return env.KIT_HELP === "json";
318
+ }
319
+ function description(usage, { examples = [], replaces } = {}) {
320
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
321
+ `);
322
+ const first = lines[0];
323
+ const colon = first.indexOf(": ");
324
+ const prose = lines[lines.indexOf("") + 1] ?? "";
325
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
326
+ return {
327
+ synopsis: colon === -1 ? first : first.slice(0, colon),
328
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
329
+ ...replaces === undefined ? {} : { replaces },
330
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
331
+ };
332
+ }
333
+ function exampleRows(examples, colors = paint(process2.stdout)) {
334
+ if (examples.length === 0)
335
+ return [];
336
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
337
+ }
338
+ function optionRows(options, colors = paint(process2.stdout)) {
339
+ const rows = Object.entries(options).map(([name, option]) => {
340
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
341
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
342
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
343
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
344
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
345
+ });
346
+ const width = Math.max(0, ...rows.map((row) => row.width));
347
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
348
+ }
349
+
301
350
  // ../kit/src/text.ts
302
351
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
303
352
  function distance(a, b) {
@@ -319,6 +368,7 @@ function closest(name, names) {
319
368
  }
320
369
 
321
370
  // ../kit/src/args.ts
371
+ var DASHES = /^-+/;
322
372
  function jsonOption(holds) {
323
373
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
324
374
  }
@@ -353,61 +403,20 @@ class HelpShown extends Exit {
353
403
 
354
404
  class Completing {
355
405
  options;
356
- constructor(options) {
406
+ positionals;
407
+ candidates;
408
+ constructor(options, positionals = [], candidates = {}) {
357
409
  this.options = options;
410
+ this.positionals = positionals;
411
+ this.candidates = candidates;
358
412
  }
359
413
  }
360
414
  var completion = { active: false };
361
- var OPTIONAL = /\[[^\]]+\]/g;
362
- var USAGE_PREFIX = /^usage:\s*/i;
363
- var FULL_STOP = /\.$/;
364
- var DASHES = /^-+/;
365
- function usageLine(usage, colors = paint(process2.stdout)) {
366
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
367
- }
368
- function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
369
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
370
- `);
371
- }
372
- function replacesRows(replaces, colors = paint(process2.stdout)) {
373
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
374
- }
375
- function wantsHelpJson(env = process2.env) {
376
- return env.KIT_HELP === "json";
377
- }
378
- function description(usage, { examples = [], replaces } = {}) {
379
- const lines = usage.replace(USAGE_PREFIX, "").split(`
380
- `);
381
- const first = lines[0];
382
- const colon = first.indexOf(": ");
383
- const prose = lines[lines.indexOf("") + 1] ?? "";
384
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
385
- return {
386
- synopsis: colon === -1 ? first : first.slice(0, colon),
387
- summary: colon === -1 ? fallback : first.slice(colon + 2),
388
- ...replaces === undefined ? {} : { replaces },
389
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
390
- };
391
- }
392
- function exampleRows(examples, colors = paint(process2.stdout)) {
393
- if (examples.length === 0)
394
- return [];
395
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
396
- }
397
- function optionRows(options, colors = paint(process2.stdout)) {
398
- const rows = Object.entries(options).map(([name, option]) => {
399
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
400
- const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
401
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
402
- });
403
- const width = Math.max(0, ...rows.map((row) => row.width));
404
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
405
- }
406
415
  var OUTPUT_OPTIONS = {
407
416
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
408
417
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
409
418
  };
410
- function applyOutput(color, plain, env = process2.env) {
419
+ function applyOutput(color, plain, env = process3.env) {
411
420
  const when = plain === true ? "never" : color ?? "auto";
412
421
  if (when === "auto")
413
422
  return;
@@ -424,14 +433,13 @@ function applyOutput(color, plain, env = process2.env) {
424
433
  function parse(args, usage, options, settings = {}) {
425
434
  const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
426
435
  const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
436
+ const listing = listed(all, settings.allowNegative === true);
427
437
  if (completion.active)
428
- throw new Completing(all);
429
- const separator = settings.rest === true ? args.indexOf("--") : -1;
430
- const own = separator === -1 ? args : args.slice(0, separator);
431
- const rest = separator === -1 ? undefined : args.slice(separator + 1);
438
+ throw new Completing(listing, settings.positionals, settings.candidates);
439
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
432
440
  let parsed;
433
441
  try {
434
- parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
442
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
435
443
  } catch (error) {
436
444
  const message = parseError(error);
437
445
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -439,12 +447,84 @@ function parse(args, usage, options, settings = {}) {
439
447
  const values = parsed.values;
440
448
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
441
449
  if (values.help === true) {
442
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
450
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
443
451
  throw new HelpShown;
444
452
  }
453
+ checkChoices(parsed.values, all);
454
+ checkConflicts(parsed.values, all);
445
455
  if (settings.positionals !== undefined)
446
456
  checkPositionals(parsed.positionals, settings.positionals);
447
- return { ...parsed, positionals: parsed.positionals, rest };
457
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
458
+ }
459
+ function splitRest(args, passes) {
460
+ const separator = passes ? args.indexOf("--") : -1;
461
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
462
+ }
463
+ function splitTrailing(args, options, count) {
464
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
465
+ let seen = 0;
466
+ if (count === 0)
467
+ return { own: args, rest: undefined };
468
+ for (let at = 0;at < args.length; at++) {
469
+ const word = args[at];
470
+ if (word === "--")
471
+ break;
472
+ if (word.startsWith("-")) {
473
+ if (takesValue(word))
474
+ at++;
475
+ continue;
476
+ }
477
+ seen++;
478
+ if (seen === count)
479
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
480
+ }
481
+ return { own: args, rest: undefined };
482
+ }
483
+ function listed(options, allowNegative) {
484
+ if (!allowNegative)
485
+ return options;
486
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
487
+ if (option.type !== "boolean" || option.negative === undefined)
488
+ return [[name, option]];
489
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
490
+ }));
491
+ }
492
+ function withBare(args, options) {
493
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
494
+ if (bare.size === 0)
495
+ return args;
496
+ const separator = args.indexOf("--");
497
+ const own = separator === -1 ? args : args.slice(0, separator);
498
+ return [...own.flatMap((arg, index) => {
499
+ const optional = bare.get(arg);
500
+ const next = own[index + 1];
501
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
502
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
503
+ }), ...separator === -1 ? [] : args.slice(separator)];
504
+ }
505
+ function checkConflicts(values, options) {
506
+ const given = (name) => values[name] !== undefined && values[name] !== false;
507
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
508
+ const other = given(name) ? conflicts.find(given) : undefined;
509
+ if (other !== undefined)
510
+ badUsage(`--${name} cannot be used with --${other}`);
511
+ }
512
+ }
513
+ function checkChoices(values, options) {
514
+ for (const [name, option] of Object.entries(options)) {
515
+ if (option.choices === undefined)
516
+ continue;
517
+ const given = values[name];
518
+ for (const value of Array.isArray(given) ? given : [given]) {
519
+ if (typeof value === "string")
520
+ oneOf(value, name, option.choices);
521
+ }
522
+ }
523
+ }
524
+ function oneOf(value, name, choices) {
525
+ if (!choices.includes(value))
526
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
527
+ return value;
448
528
  }
449
529
  function checkPositionals(given, names) {
450
530
  const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
@@ -495,7 +575,7 @@ function nearestOption(message, options, allowNegative) {
495
575
  }
496
576
  // ../kit/src/process.ts
497
577
  import { constants } from "os";
498
- import process3 from "process";
578
+ import process4 from "process";
499
579
  var KILL_GRACE_MS = 2000;
500
580
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
501
581
  function exitCodeOf(code, signal) {
@@ -517,7 +597,7 @@ function holdSignals(cleanup) {
517
597
  },
518
598
  release: () => {
519
599
  for (const signal of SIGNALS)
520
- process3.off(signal, onSignal);
600
+ process4.off(signal, onSignal);
521
601
  }
522
602
  };
523
603
  function onSignal(signal) {
@@ -530,10 +610,10 @@ function holdSignals(cleanup) {
530
610
  return;
531
611
  held.release();
532
612
  cleanup(signal);
533
- process3.kill(process3.pid, signal);
613
+ process4.kill(process4.pid, signal);
534
614
  }
535
615
  for (const signal of SIGNALS)
536
- process3.on(signal, onSignal);
616
+ process4.on(signal, onSignal);
537
617
  return held;
538
618
  }
539
619
  async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
@@ -547,7 +627,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
547
627
  return;
548
628
  try {
549
629
  if (grouped)
550
- process3.kill(-proc.pid, killing);
630
+ process4.kill(-proc.pid, killing);
551
631
  else
552
632
  proc.kill(killing);
553
633
  } catch {}
@@ -621,15 +701,67 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
621
701
  var RESET_STYLE = `${ESC}[0m`;
622
702
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
623
703
  // ../kit/src/cli.ts
624
- import process4 from "process";
704
+ import process6 from "process";
705
+
706
+ // ../kit/src/usage.ts
707
+ import { appendFileSync, mkdirSync } from "fs";
708
+ import { homedir } from "os";
709
+ import { dirname, isAbsolute, join } from "path";
710
+ import process5 from "process";
711
+
712
+ // ../kit/src/logs.ts
713
+ var DAY_MS = 24 * 60 * 60 * 1000;
714
+ var CLI_FOLDER = "kaynooo-cli";
715
+
716
+ // ../kit/src/usage.ts
717
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
718
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
719
+ var LONGEST_NAME = 40;
720
+ var usageError;
721
+ function noteUsageError(message) {
722
+ usageError = message;
723
+ }
724
+ function stateHome(env = process5.env) {
725
+ const dir = env.XDG_STATE_HOME;
726
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
727
+ }
728
+ function usagePath(env = process5.env) {
729
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
730
+ }
731
+ function usageRecorded(env = process5.env) {
732
+ const off = env.KAYNOOO_CLI_NO_USAGE;
733
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
734
+ }
735
+ function flagNames(argv) {
736
+ const end = argv.indexOf("--");
737
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
738
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
739
+ }
740
+ function usageEntry(bin, command, argv, code, now = new Date) {
741
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
742
+ usageError = undefined;
743
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
744
+ }
745
+ function recordUsage(entry, env = process5.env) {
746
+ if (!usageRecorded(env))
747
+ return;
748
+ try {
749
+ const path = usagePath(env);
750
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
751
+ appendFileSync(path, `${JSON.stringify(entry)}
752
+ `, { mode: 384 });
753
+ } catch {}
754
+ }
755
+
756
+ // ../kit/src/cli.ts
625
757
  var LEVEL_OPTIONS = {
626
758
  ...OUTPUT_OPTIONS,
627
759
  help: { type: "boolean", short: "h", description: "show this help" }
628
760
  };
629
761
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
630
762
  function printError(prefix, message, hint, cause) {
631
- const colors = paint(process4.stderr);
632
- const styled = takesControlCodes(process4.stderr);
763
+ const colors = paint(process6.stderr);
764
+ const styled = takesControlCodes(process6.stderr);
633
765
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
634
766
  const under = (label, text, tint) => text === undefined ? "" : `
635
767
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -648,49 +780,86 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
648
780
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
649
781
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
650
782
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
783
+ if (error instanceof UsageError)
784
+ noteUsageError(error.message);
651
785
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
652
786
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
653
787
  return error instanceof Exit ? error.code : 1;
654
788
  }
655
789
  var COMPLETE = "__complete";
656
790
  var FILES = "__files__";
657
- async function optionsOf(run) {
791
+ async function completingOf(run) {
658
792
  completion.active = true;
659
793
  try {
660
794
  await run([]);
661
795
  } catch (error) {
662
796
  if (error instanceof Completing)
663
- return error.options;
797
+ return error;
664
798
  } finally {
665
799
  completion.active = false;
666
800
  }
667
- return {};
801
+ return new Completing({});
802
+ }
803
+ function candidateLine(candidate) {
804
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
805
+ }
806
+ function positionalBeingTyped(before, { options, positionals }) {
807
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
808
+ let index = 0;
809
+ let at = 0;
810
+ while (at < before.length) {
811
+ const word = before[at];
812
+ if (word === "--") {
813
+ index += before.length - at - 1;
814
+ break;
815
+ }
816
+ if (!word.startsWith("-"))
817
+ index++;
818
+ else if (takesValue(word))
819
+ at++;
820
+ at++;
821
+ }
822
+ const last = positionals.at(-1);
823
+ if (index < positionals.length)
824
+ return positionals[index];
825
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
668
826
  }
669
827
  async function leafCandidates(run, words) {
670
- if (!(words.at(-1) ?? "").startsWith("-"))
671
- return [FILES];
672
- return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
828
+ const completing = await completingOf(run);
829
+ if ((words.at(-1) ?? "").startsWith("-"))
830
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
831
+ const flag = words.at(-2);
832
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
833
+ if (option?.type === "string") {
834
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
835
+ return values === undefined ? [FILES] : values.map(candidateLine);
836
+ }
837
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
838
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
839
+ return values === undefined ? [FILES] : values.map(candidateLine);
673
840
  }
674
841
  async function printCandidates(found) {
675
842
  for (const line of await found)
676
843
  console.log(line);
677
844
  return 0;
678
845
  }
679
- async function runMain({ name, version, run, redact }, argv = process4.argv.slice(2)) {
846
+ async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
680
847
  if (argv[0] === COMPLETE)
681
848
  return printCandidates(leafCandidates(run, argv.slice(1)));
682
849
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
683
850
  console.log(version);
684
851
  return 0;
685
852
  }
853
+ let code;
686
854
  try {
687
- return await run(argv);
855
+ code = await run(argv);
688
856
  } catch (error) {
689
- return reportThrown(name, error, redact, wantsJson(argv));
857
+ code = reportThrown(name, error, redact, wantsJson(argv));
690
858
  }
859
+ if (usage !== false)
860
+ recordUsage(usageEntry(name, undefined, argv, code));
861
+ return code;
691
862
  }
692
- // ../kit/src/logs.ts
693
- var DAY_MS = 24 * 60 * 60 * 1000;
694
863
  // ../kit/src/secrets.ts
695
864
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
696
865
  // ../kit/src/sessions.ts
@@ -698,13 +867,13 @@ var {Glob } = globalThis.Bun;
698
867
  var SESSION_FILES = new Glob("*.json");
699
868
  var ACCOUNT_DIRS = new Glob("*/sessions");
700
869
  // package.json
701
- var version = "0.4.0";
870
+ var version = "0.4.1";
702
871
 
703
872
  // src/worktree.ts
704
- import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "fs";
873
+ import { cpSync, existsSync, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "fs";
705
874
  import { tmpdir } from "os";
706
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "path";
707
- import process6 from "process";
875
+ import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join2, relative, resolve, sep } from "path";
876
+ import process8 from "process";
708
877
  var WHITESPACE = /\s/;
709
878
  var ENV_FILE = /^\.env(?:\..+)?$/;
710
879
  var DEPENDENCIES = new Set(["node_modules", "vendor", ".venv"]);
@@ -739,8 +908,8 @@ function keptPaths(root, cwd, paths) {
739
908
  const realRoot = realpathSync(root);
740
909
  return paths.map((path) => {
741
910
  const absolute = resolve(cwd, path);
742
- const inRepo = relative(realRoot, join(realpathSync(dirname(absolute)), basename(absolute)));
743
- if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute(inRepo))
911
+ const inRepo = relative(realRoot, join2(realpathSync(dirname2(absolute)), basename(absolute)));
912
+ if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute2(inRepo))
744
913
  fail(`--keep ${path} is outside the repository`);
745
914
  if (!existsSync(absolute))
746
915
  fail(`--keep ${path}: no such file`);
@@ -749,8 +918,8 @@ function keptPaths(root, cwd, paths) {
749
918
  }
750
919
  function checkNoSymlink(dir, path) {
751
920
  let current = dir;
752
- for (const part of dirname(path).split(sep)) {
753
- current = join(current, part);
921
+ for (const part of dirname2(path).split(sep)) {
922
+ current = join2(current, part);
754
923
  if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink() === true)
755
924
  fail(`--keep ${path} goes through the symlink ${relative(dir, current)} of the ref, which would write outside the worktree`);
756
925
  }
@@ -766,10 +935,10 @@ async function linkedEntries(root) {
766
935
  }).map((entry) => entry.replace(TRAILING_SLASH, ""));
767
936
  }
768
937
  async function addWorktree(root, sha) {
769
- const dir = join(mkdtempSync(join(tmpdir(), "base-")), basename(root));
938
+ const dir = join2(mkdtempSync(join2(tmpdir(), "base-")), basename(root));
770
939
  const ran = await git2(["worktree", "add", "--detach", dir, sha], root);
771
940
  if (ran.code !== 0) {
772
- rmSync(dirname(dir), { recursive: true, force: true });
941
+ rmSync(dirname2(dir), { recursive: true, force: true });
773
942
  fail(`git worktree add failed:
774
943
  ${ran.text.trim()}`);
775
944
  }
@@ -778,41 +947,41 @@ ${ran.text.trim()}`);
778
947
  function copyKept(root, dir, paths) {
779
948
  for (const path of paths) {
780
949
  checkNoSymlink(dir, path);
781
- const target = join(dir, path);
950
+ const target = join2(dir, path);
782
951
  rmSync(target, { recursive: true, force: true });
783
- mkdirSync(dirname(target), { recursive: true });
784
- cpSync(join(root, path), target, { recursive: true });
952
+ mkdirSync2(dirname2(target), { recursive: true });
953
+ cpSync(join2(root, path), target, { recursive: true });
785
954
  }
786
955
  }
787
956
  function linkEntries(root, dir, entries) {
788
957
  const links = [];
789
958
  for (const entry of entries) {
790
- const link = join(dir, entry);
959
+ const link = join2(dir, entry);
791
960
  if (existsSync(link))
792
961
  continue;
793
- mkdirSync(dirname(link), { recursive: true });
962
+ mkdirSync2(dirname2(link), { recursive: true });
794
963
  if (basename(entry) === "node_modules" && hasWorkspaceLinks(root, entry)) {
795
964
  links.push(...linkModules(root, dir, entry));
796
965
  continue;
797
966
  }
798
- symlinkSync(join(root, entry), link);
967
+ symlinkSync(join2(root, entry), link);
799
968
  links.push(link);
800
969
  }
801
970
  return links;
802
971
  }
803
972
  function moduleLinks(root, folder) {
804
973
  const found = [];
805
- for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
974
+ for (const entry of readdirSync(join2(root, folder), { withFileTypes: true })) {
806
975
  if (entry.isSymbolicLink())
807
- found.push({ path: join(folder, entry.name), name: entry.name });
976
+ found.push({ path: join2(folder, entry.name), name: entry.name });
808
977
  else if (entry.isDirectory() && entry.name.startsWith("@"))
809
- found.push(...moduleLinks(root, join(folder, entry.name)));
978
+ found.push(...moduleLinks(root, join2(folder, entry.name)));
810
979
  }
811
980
  return found;
812
981
  }
813
982
  function workspaceTarget(root, path) {
814
983
  try {
815
- const inRepo = relative(realpathSync(root), realpathSync(join(root, path)));
984
+ const inRepo = relative(realpathSync(root), realpathSync(join2(root, path)));
816
985
  return inRepo === "" || inRepo.startsWith(PARENT) || inRepo.split(sep).includes("node_modules") ? undefined : inRepo;
817
986
  } catch {
818
987
  return;
@@ -823,16 +992,16 @@ function hasWorkspaceLinks(root, folder) {
823
992
  }
824
993
  function linkModules(root, dir, folder) {
825
994
  const links = [];
826
- mkdirSync(join(dir, folder), { recursive: true });
827
- for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
828
- const path = join(folder, entry.name);
829
- const link = join(dir, path);
995
+ mkdirSync2(join2(dir, folder), { recursive: true });
996
+ for (const entry of readdirSync(join2(root, folder), { withFileTypes: true })) {
997
+ const path = join2(folder, entry.name);
998
+ const link = join2(dir, path);
830
999
  if (entry.isDirectory() && entry.name.startsWith("@")) {
831
1000
  links.push(...linkModules(root, dir, path));
832
1001
  continue;
833
1002
  }
834
1003
  const workspace = entry.isSymbolicLink() ? workspaceTarget(root, path) : undefined;
835
- symlinkSync(workspace === undefined ? join(root, path) : join(dir, workspace), link);
1004
+ symlinkSync(workspace === undefined ? join2(root, path) : join2(dir, workspace), link);
836
1005
  links.push(link);
837
1006
  }
838
1007
  return links;
@@ -842,9 +1011,9 @@ async function sweepStale(root) {
842
1011
  for (const name of readdirSync(tmpdir())) {
843
1012
  if (!BASE_DIR.test(name))
844
1013
  continue;
845
- const path = join(tmpdir(), name);
1014
+ const path = join2(tmpdir(), name);
846
1015
  const stat = lstatSync(path, { throwIfNoEntry: false });
847
- if (stat?.isDirectory() === true && stat.uid === process6.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1016
+ if (stat?.isDirectory() === true && stat.uid === process8.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
848
1017
  rmSync(path, { recursive: true, force: true });
849
1018
  }
850
1019
  await git2(["worktree", "prune"], root);
@@ -855,7 +1024,7 @@ async function removeWorktree(root, dir, links) {
855
1024
  unlinkSync(link);
856
1025
  }
857
1026
  await git2(["worktree", "remove", "--force", dir], root);
858
- rmSync(dirname(dir), { recursive: true, force: true });
1027
+ rmSync(dirname2(dir), { recursive: true, force: true });
859
1028
  await git2(["worktree", "prune"], root);
860
1029
  }
861
1030
  function shellCommand(given) {
@@ -903,7 +1072,7 @@ async function inWorktree(options, body) {
903
1072
  try {
904
1073
  copyKept(root, dir, kept);
905
1074
  links = link ? linkEntries(root, dir, await linkedEntries(root)) : [];
906
- const runDir = join(dir, prefix);
1075
+ const runDir = join2(dir, prefix);
907
1076
  if (!existsSync(runDir))
908
1077
  fail(`${prefix} does not exist at ${ref}`);
909
1078
  return await body(runDir, signals);
@@ -934,7 +1103,7 @@ ${USAGE}`);
934
1103
  if (runsInContainer(given))
935
1104
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
936
1105
  const command = shellCommand(given);
937
- const cwd = process7.cwd();
1106
+ const cwd = process9.cwd();
938
1107
  const { root, prefix } = await checkout(cwd);
939
1108
  const ref = parsed.values.ref ?? "HEAD";
940
1109
  const sha = await resolveRef(root, ref);
@@ -945,4 +1114,4 @@ ${USAGE}`);
945
1114
  console.error(`base: ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
946
1115
  return ran.code;
947
1116
  }
948
- process7.exitCode = await runMain({ name: "base", version, run: main });
1117
+ process9.exitCode = await runMain({ name: "base", version, run: main });
package/dist/proof.js CHANGED
@@ -2,16 +2,16 @@
2
2
  // @bun
3
3
 
4
4
  // src/proof.ts
5
- import process7 from "process";
5
+ import process9 from "process";
6
6
 
7
7
  // ../kit/src/args.ts
8
- import process2 from "process";
8
+ import process3 from "process";
9
9
  import { parseArgs } from "util";
10
10
 
11
11
  // ../kit/src/style.ts
12
12
  import process from "process";
13
13
 
14
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
14
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
15
  function x(s) {
16
16
  let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
17
17
  if (!/^[a-f0-9]+$/.test(r))
@@ -231,7 +231,7 @@ class e {
231
231
  }
232
232
  }
233
233
 
234
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
234
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
235
235
  var r = 39;
236
236
  var o = 49;
237
237
  var f2 = "\x1B[";
@@ -298,6 +298,55 @@ function printJson(value) {
298
298
  console.log(JSON.stringify(value, undefined, 2));
299
299
  }
300
300
 
301
+ // ../kit/src/help.ts
302
+ import process2 from "process";
303
+ var OPTIONAL = /\[[^\]]+\]/g;
304
+ var USAGE_PREFIX = /^usage:\s*/i;
305
+ var FULL_STOP = /\.$/;
306
+ function usageLine(usage, colors = paint(process2.stdout)) {
307
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
308
+ }
309
+ function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
310
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
311
+ `);
312
+ }
313
+ function replacesRows(replaces, colors = paint(process2.stdout)) {
314
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
315
+ }
316
+ function wantsHelpJson(env = process2.env) {
317
+ return env.KIT_HELP === "json";
318
+ }
319
+ function description(usage, { examples = [], replaces } = {}) {
320
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
321
+ `);
322
+ const first = lines[0];
323
+ const colon = first.indexOf(": ");
324
+ const prose = lines[lines.indexOf("") + 1] ?? "";
325
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
326
+ return {
327
+ synopsis: colon === -1 ? first : first.slice(0, colon),
328
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
329
+ ...replaces === undefined ? {} : { replaces },
330
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
331
+ };
332
+ }
333
+ function exampleRows(examples, colors = paint(process2.stdout)) {
334
+ if (examples.length === 0)
335
+ return [];
336
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
337
+ }
338
+ function optionRows(options, colors = paint(process2.stdout)) {
339
+ const rows = Object.entries(options).map(([name, option]) => {
340
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
341
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
342
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
343
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
344
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
345
+ });
346
+ const width = Math.max(0, ...rows.map((row) => row.width));
347
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
348
+ }
349
+
301
350
  // ../kit/src/text.ts
302
351
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
303
352
  function distance(a, b) {
@@ -319,6 +368,7 @@ function closest(name, names) {
319
368
  }
320
369
 
321
370
  // ../kit/src/args.ts
371
+ var DASHES = /^-+/;
322
372
  function jsonOption(holds) {
323
373
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
324
374
  }
@@ -353,61 +403,20 @@ class HelpShown extends Exit {
353
403
 
354
404
  class Completing {
355
405
  options;
356
- constructor(options) {
406
+ positionals;
407
+ candidates;
408
+ constructor(options, positionals = [], candidates = {}) {
357
409
  this.options = options;
410
+ this.positionals = positionals;
411
+ this.candidates = candidates;
358
412
  }
359
413
  }
360
414
  var completion = { active: false };
361
- var OPTIONAL = /\[[^\]]+\]/g;
362
- var USAGE_PREFIX = /^usage:\s*/i;
363
- var FULL_STOP = /\.$/;
364
- var DASHES = /^-+/;
365
- function usageLine(usage, colors = paint(process2.stdout)) {
366
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
367
- }
368
- function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
369
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
370
- `);
371
- }
372
- function replacesRows(replaces, colors = paint(process2.stdout)) {
373
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
374
- }
375
- function wantsHelpJson(env = process2.env) {
376
- return env.KIT_HELP === "json";
377
- }
378
- function description(usage, { examples = [], replaces } = {}) {
379
- const lines = usage.replace(USAGE_PREFIX, "").split(`
380
- `);
381
- const first = lines[0];
382
- const colon = first.indexOf(": ");
383
- const prose = lines[lines.indexOf("") + 1] ?? "";
384
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
385
- return {
386
- synopsis: colon === -1 ? first : first.slice(0, colon),
387
- summary: colon === -1 ? fallback : first.slice(colon + 2),
388
- ...replaces === undefined ? {} : { replaces },
389
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
390
- };
391
- }
392
- function exampleRows(examples, colors = paint(process2.stdout)) {
393
- if (examples.length === 0)
394
- return [];
395
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
396
- }
397
- function optionRows(options, colors = paint(process2.stdout)) {
398
- const rows = Object.entries(options).map(([name, option]) => {
399
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
400
- const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
401
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
402
- });
403
- const width = Math.max(0, ...rows.map((row) => row.width));
404
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
405
- }
406
415
  var OUTPUT_OPTIONS = {
407
416
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
408
417
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
409
418
  };
410
- function applyOutput(color, plain, env = process2.env) {
419
+ function applyOutput(color, plain, env = process3.env) {
411
420
  const when = plain === true ? "never" : color ?? "auto";
412
421
  if (when === "auto")
413
422
  return;
@@ -424,14 +433,13 @@ function applyOutput(color, plain, env = process2.env) {
424
433
  function parse(args, usage, options, settings = {}) {
425
434
  const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
426
435
  const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
436
+ const listing = listed(all, settings.allowNegative === true);
427
437
  if (completion.active)
428
- throw new Completing(all);
429
- const separator = settings.rest === true ? args.indexOf("--") : -1;
430
- const own = separator === -1 ? args : args.slice(0, separator);
431
- const rest = separator === -1 ? undefined : args.slice(separator + 1);
438
+ throw new Completing(listing, settings.positionals, settings.candidates);
439
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
432
440
  let parsed;
433
441
  try {
434
- parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
442
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
435
443
  } catch (error) {
436
444
  const message = parseError(error);
437
445
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -439,12 +447,84 @@ function parse(args, usage, options, settings = {}) {
439
447
  const values = parsed.values;
440
448
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
441
449
  if (values.help === true) {
442
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
450
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
443
451
  throw new HelpShown;
444
452
  }
453
+ checkChoices(parsed.values, all);
454
+ checkConflicts(parsed.values, all);
445
455
  if (settings.positionals !== undefined)
446
456
  checkPositionals(parsed.positionals, settings.positionals);
447
- return { ...parsed, positionals: parsed.positionals, rest };
457
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
458
+ }
459
+ function splitRest(args, passes) {
460
+ const separator = passes ? args.indexOf("--") : -1;
461
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
462
+ }
463
+ function splitTrailing(args, options, count) {
464
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
465
+ let seen = 0;
466
+ if (count === 0)
467
+ return { own: args, rest: undefined };
468
+ for (let at = 0;at < args.length; at++) {
469
+ const word = args[at];
470
+ if (word === "--")
471
+ break;
472
+ if (word.startsWith("-")) {
473
+ if (takesValue(word))
474
+ at++;
475
+ continue;
476
+ }
477
+ seen++;
478
+ if (seen === count)
479
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
480
+ }
481
+ return { own: args, rest: undefined };
482
+ }
483
+ function listed(options, allowNegative) {
484
+ if (!allowNegative)
485
+ return options;
486
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
487
+ if (option.type !== "boolean" || option.negative === undefined)
488
+ return [[name, option]];
489
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
490
+ }));
491
+ }
492
+ function withBare(args, options) {
493
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
494
+ if (bare.size === 0)
495
+ return args;
496
+ const separator = args.indexOf("--");
497
+ const own = separator === -1 ? args : args.slice(0, separator);
498
+ return [...own.flatMap((arg, index) => {
499
+ const optional = bare.get(arg);
500
+ const next = own[index + 1];
501
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
502
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
503
+ }), ...separator === -1 ? [] : args.slice(separator)];
504
+ }
505
+ function checkConflicts(values, options) {
506
+ const given = (name) => values[name] !== undefined && values[name] !== false;
507
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
508
+ const other = given(name) ? conflicts.find(given) : undefined;
509
+ if (other !== undefined)
510
+ badUsage(`--${name} cannot be used with --${other}`);
511
+ }
512
+ }
513
+ function checkChoices(values, options) {
514
+ for (const [name, option] of Object.entries(options)) {
515
+ if (option.choices === undefined)
516
+ continue;
517
+ const given = values[name];
518
+ for (const value of Array.isArray(given) ? given : [given]) {
519
+ if (typeof value === "string")
520
+ oneOf(value, name, option.choices);
521
+ }
522
+ }
523
+ }
524
+ function oneOf(value, name, choices) {
525
+ if (!choices.includes(value))
526
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
527
+ return value;
448
528
  }
449
529
  function checkPositionals(given, names) {
450
530
  const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
@@ -495,7 +575,7 @@ function nearestOption(message, options, allowNegative) {
495
575
  }
496
576
  // ../kit/src/process.ts
497
577
  import { constants } from "os";
498
- import process3 from "process";
578
+ import process4 from "process";
499
579
  var KILL_GRACE_MS = 2000;
500
580
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
501
581
  function exitCodeOf(code, signal) {
@@ -517,7 +597,7 @@ function holdSignals(cleanup) {
517
597
  },
518
598
  release: () => {
519
599
  for (const signal of SIGNALS)
520
- process3.off(signal, onSignal);
600
+ process4.off(signal, onSignal);
521
601
  }
522
602
  };
523
603
  function onSignal(signal) {
@@ -530,10 +610,10 @@ function holdSignals(cleanup) {
530
610
  return;
531
611
  held.release();
532
612
  cleanup(signal);
533
- process3.kill(process3.pid, signal);
613
+ process4.kill(process4.pid, signal);
534
614
  }
535
615
  for (const signal of SIGNALS)
536
- process3.on(signal, onSignal);
616
+ process4.on(signal, onSignal);
537
617
  return held;
538
618
  }
539
619
  async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
@@ -547,7 +627,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
547
627
  return;
548
628
  try {
549
629
  if (grouped)
550
- process3.kill(-proc.pid, killing);
630
+ process4.kill(-proc.pid, killing);
551
631
  else
552
632
  proc.kill(killing);
553
633
  } catch {}
@@ -621,15 +701,67 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
621
701
  var RESET_STYLE = `${ESC}[0m`;
622
702
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
623
703
  // ../kit/src/cli.ts
624
- import process4 from "process";
704
+ import process6 from "process";
705
+
706
+ // ../kit/src/usage.ts
707
+ import { appendFileSync, mkdirSync } from "fs";
708
+ import { homedir } from "os";
709
+ import { dirname, isAbsolute, join } from "path";
710
+ import process5 from "process";
711
+
712
+ // ../kit/src/logs.ts
713
+ var DAY_MS = 24 * 60 * 60 * 1000;
714
+ var CLI_FOLDER = "kaynooo-cli";
715
+
716
+ // ../kit/src/usage.ts
717
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
718
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
719
+ var LONGEST_NAME = 40;
720
+ var usageError;
721
+ function noteUsageError(message) {
722
+ usageError = message;
723
+ }
724
+ function stateHome(env = process5.env) {
725
+ const dir = env.XDG_STATE_HOME;
726
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
727
+ }
728
+ function usagePath(env = process5.env) {
729
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
730
+ }
731
+ function usageRecorded(env = process5.env) {
732
+ const off = env.KAYNOOO_CLI_NO_USAGE;
733
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
734
+ }
735
+ function flagNames(argv) {
736
+ const end = argv.indexOf("--");
737
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
738
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
739
+ }
740
+ function usageEntry(bin, command, argv, code, now = new Date) {
741
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
742
+ usageError = undefined;
743
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
744
+ }
745
+ function recordUsage(entry, env = process5.env) {
746
+ if (!usageRecorded(env))
747
+ return;
748
+ try {
749
+ const path = usagePath(env);
750
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
751
+ appendFileSync(path, `${JSON.stringify(entry)}
752
+ `, { mode: 384 });
753
+ } catch {}
754
+ }
755
+
756
+ // ../kit/src/cli.ts
625
757
  var LEVEL_OPTIONS = {
626
758
  ...OUTPUT_OPTIONS,
627
759
  help: { type: "boolean", short: "h", description: "show this help" }
628
760
  };
629
761
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
630
762
  function printError(prefix, message, hint, cause) {
631
- const colors = paint(process4.stderr);
632
- const styled = takesControlCodes(process4.stderr);
763
+ const colors = paint(process6.stderr);
764
+ const styled = takesControlCodes(process6.stderr);
633
765
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
634
766
  const under = (label, text, tint) => text === undefined ? "" : `
635
767
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -648,49 +780,86 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
648
780
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
649
781
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
650
782
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
783
+ if (error instanceof UsageError)
784
+ noteUsageError(error.message);
651
785
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
652
786
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
653
787
  return error instanceof Exit ? error.code : 1;
654
788
  }
655
789
  var COMPLETE = "__complete";
656
790
  var FILES = "__files__";
657
- async function optionsOf(run) {
791
+ async function completingOf(run) {
658
792
  completion.active = true;
659
793
  try {
660
794
  await run([]);
661
795
  } catch (error) {
662
796
  if (error instanceof Completing)
663
- return error.options;
797
+ return error;
664
798
  } finally {
665
799
  completion.active = false;
666
800
  }
667
- return {};
801
+ return new Completing({});
802
+ }
803
+ function candidateLine(candidate) {
804
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
805
+ }
806
+ function positionalBeingTyped(before, { options, positionals }) {
807
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
808
+ let index = 0;
809
+ let at = 0;
810
+ while (at < before.length) {
811
+ const word = before[at];
812
+ if (word === "--") {
813
+ index += before.length - at - 1;
814
+ break;
815
+ }
816
+ if (!word.startsWith("-"))
817
+ index++;
818
+ else if (takesValue(word))
819
+ at++;
820
+ at++;
821
+ }
822
+ const last = positionals.at(-1);
823
+ if (index < positionals.length)
824
+ return positionals[index];
825
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
668
826
  }
669
827
  async function leafCandidates(run, words) {
670
- if (!(words.at(-1) ?? "").startsWith("-"))
671
- return [FILES];
672
- return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
828
+ const completing = await completingOf(run);
829
+ if ((words.at(-1) ?? "").startsWith("-"))
830
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
831
+ const flag = words.at(-2);
832
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
833
+ if (option?.type === "string") {
834
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
835
+ return values === undefined ? [FILES] : values.map(candidateLine);
836
+ }
837
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
838
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
839
+ return values === undefined ? [FILES] : values.map(candidateLine);
673
840
  }
674
841
  async function printCandidates(found) {
675
842
  for (const line of await found)
676
843
  console.log(line);
677
844
  return 0;
678
845
  }
679
- async function runMain({ name, version, run, redact }, argv = process4.argv.slice(2)) {
846
+ async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
680
847
  if (argv[0] === COMPLETE)
681
848
  return printCandidates(leafCandidates(run, argv.slice(1)));
682
849
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
683
850
  console.log(version);
684
851
  return 0;
685
852
  }
853
+ let code;
686
854
  try {
687
- return await run(argv);
855
+ code = await run(argv);
688
856
  } catch (error) {
689
- return reportThrown(name, error, redact, wantsJson(argv));
857
+ code = reportThrown(name, error, redact, wantsJson(argv));
690
858
  }
859
+ if (usage !== false)
860
+ recordUsage(usageEntry(name, undefined, argv, code));
861
+ return code;
691
862
  }
692
- // ../kit/src/logs.ts
693
- var DAY_MS = 24 * 60 * 60 * 1000;
694
863
  // ../kit/src/secrets.ts
695
864
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
696
865
  // ../kit/src/sessions.ts
@@ -698,13 +867,13 @@ var {Glob } = globalThis.Bun;
698
867
  var SESSION_FILES = new Glob("*.json");
699
868
  var ACCOUNT_DIRS = new Glob("*/sessions");
700
869
  // package.json
701
- var version = "0.4.0";
870
+ var version = "0.4.1";
702
871
 
703
872
  // src/worktree.ts
704
- import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "fs";
873
+ import { cpSync, existsSync, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "fs";
705
874
  import { tmpdir } from "os";
706
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "path";
707
- import process6 from "process";
875
+ import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join2, relative, resolve, sep } from "path";
876
+ import process8 from "process";
708
877
  var WHITESPACE = /\s/;
709
878
  var ENV_FILE = /^\.env(?:\..+)?$/;
710
879
  var DEPENDENCIES = new Set(["node_modules", "vendor", ".venv"]);
@@ -739,8 +908,8 @@ function keptPaths(root, cwd, paths) {
739
908
  const realRoot = realpathSync(root);
740
909
  return paths.map((path) => {
741
910
  const absolute = resolve(cwd, path);
742
- const inRepo = relative(realRoot, join(realpathSync(dirname(absolute)), basename(absolute)));
743
- if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute(inRepo))
911
+ const inRepo = relative(realRoot, join2(realpathSync(dirname2(absolute)), basename(absolute)));
912
+ if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute2(inRepo))
744
913
  fail(`--keep ${path} is outside the repository`);
745
914
  if (!existsSync(absolute))
746
915
  fail(`--keep ${path}: no such file`);
@@ -749,8 +918,8 @@ function keptPaths(root, cwd, paths) {
749
918
  }
750
919
  function checkNoSymlink(dir, path) {
751
920
  let current = dir;
752
- for (const part of dirname(path).split(sep)) {
753
- current = join(current, part);
921
+ for (const part of dirname2(path).split(sep)) {
922
+ current = join2(current, part);
754
923
  if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink() === true)
755
924
  fail(`--keep ${path} goes through the symlink ${relative(dir, current)} of the ref, which would write outside the worktree`);
756
925
  }
@@ -766,10 +935,10 @@ async function linkedEntries(root) {
766
935
  }).map((entry) => entry.replace(TRAILING_SLASH, ""));
767
936
  }
768
937
  async function addWorktree(root, sha) {
769
- const dir = join(mkdtempSync(join(tmpdir(), "base-")), basename(root));
938
+ const dir = join2(mkdtempSync(join2(tmpdir(), "base-")), basename(root));
770
939
  const ran = await git2(["worktree", "add", "--detach", dir, sha], root);
771
940
  if (ran.code !== 0) {
772
- rmSync(dirname(dir), { recursive: true, force: true });
941
+ rmSync(dirname2(dir), { recursive: true, force: true });
773
942
  fail(`git worktree add failed:
774
943
  ${ran.text.trim()}`);
775
944
  }
@@ -778,41 +947,41 @@ ${ran.text.trim()}`);
778
947
  function copyKept(root, dir, paths) {
779
948
  for (const path of paths) {
780
949
  checkNoSymlink(dir, path);
781
- const target = join(dir, path);
950
+ const target = join2(dir, path);
782
951
  rmSync(target, { recursive: true, force: true });
783
- mkdirSync(dirname(target), { recursive: true });
784
- cpSync(join(root, path), target, { recursive: true });
952
+ mkdirSync2(dirname2(target), { recursive: true });
953
+ cpSync(join2(root, path), target, { recursive: true });
785
954
  }
786
955
  }
787
956
  function linkEntries(root, dir, entries) {
788
957
  const links = [];
789
958
  for (const entry of entries) {
790
- const link = join(dir, entry);
959
+ const link = join2(dir, entry);
791
960
  if (existsSync(link))
792
961
  continue;
793
- mkdirSync(dirname(link), { recursive: true });
962
+ mkdirSync2(dirname2(link), { recursive: true });
794
963
  if (basename(entry) === "node_modules" && hasWorkspaceLinks(root, entry)) {
795
964
  links.push(...linkModules(root, dir, entry));
796
965
  continue;
797
966
  }
798
- symlinkSync(join(root, entry), link);
967
+ symlinkSync(join2(root, entry), link);
799
968
  links.push(link);
800
969
  }
801
970
  return links;
802
971
  }
803
972
  function moduleLinks(root, folder) {
804
973
  const found = [];
805
- for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
974
+ for (const entry of readdirSync(join2(root, folder), { withFileTypes: true })) {
806
975
  if (entry.isSymbolicLink())
807
- found.push({ path: join(folder, entry.name), name: entry.name });
976
+ found.push({ path: join2(folder, entry.name), name: entry.name });
808
977
  else if (entry.isDirectory() && entry.name.startsWith("@"))
809
- found.push(...moduleLinks(root, join(folder, entry.name)));
978
+ found.push(...moduleLinks(root, join2(folder, entry.name)));
810
979
  }
811
980
  return found;
812
981
  }
813
982
  function workspaceTarget(root, path) {
814
983
  try {
815
- const inRepo = relative(realpathSync(root), realpathSync(join(root, path)));
984
+ const inRepo = relative(realpathSync(root), realpathSync(join2(root, path)));
816
985
  return inRepo === "" || inRepo.startsWith(PARENT) || inRepo.split(sep).includes("node_modules") ? undefined : inRepo;
817
986
  } catch {
818
987
  return;
@@ -823,16 +992,16 @@ function hasWorkspaceLinks(root, folder) {
823
992
  }
824
993
  function linkModules(root, dir, folder) {
825
994
  const links = [];
826
- mkdirSync(join(dir, folder), { recursive: true });
827
- for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
828
- const path = join(folder, entry.name);
829
- const link = join(dir, path);
995
+ mkdirSync2(join2(dir, folder), { recursive: true });
996
+ for (const entry of readdirSync(join2(root, folder), { withFileTypes: true })) {
997
+ const path = join2(folder, entry.name);
998
+ const link = join2(dir, path);
830
999
  if (entry.isDirectory() && entry.name.startsWith("@")) {
831
1000
  links.push(...linkModules(root, dir, path));
832
1001
  continue;
833
1002
  }
834
1003
  const workspace = entry.isSymbolicLink() ? workspaceTarget(root, path) : undefined;
835
- symlinkSync(workspace === undefined ? join(root, path) : join(dir, workspace), link);
1004
+ symlinkSync(workspace === undefined ? join2(root, path) : join2(dir, workspace), link);
836
1005
  links.push(link);
837
1006
  }
838
1007
  return links;
@@ -842,9 +1011,9 @@ async function sweepStale(root) {
842
1011
  for (const name of readdirSync(tmpdir())) {
843
1012
  if (!BASE_DIR.test(name))
844
1013
  continue;
845
- const path = join(tmpdir(), name);
1014
+ const path = join2(tmpdir(), name);
846
1015
  const stat = lstatSync(path, { throwIfNoEntry: false });
847
- if (stat?.isDirectory() === true && stat.uid === process6.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1016
+ if (stat?.isDirectory() === true && stat.uid === process8.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
848
1017
  rmSync(path, { recursive: true, force: true });
849
1018
  }
850
1019
  await git2(["worktree", "prune"], root);
@@ -855,7 +1024,7 @@ async function removeWorktree(root, dir, links) {
855
1024
  unlinkSync(link);
856
1025
  }
857
1026
  await git2(["worktree", "remove", "--force", dir], root);
858
- rmSync(dirname(dir), { recursive: true, force: true });
1027
+ rmSync(dirname2(dir), { recursive: true, force: true });
859
1028
  await git2(["worktree", "prune"], root);
860
1029
  }
861
1030
  function shellCommand(given) {
@@ -903,7 +1072,7 @@ async function inWorktree(options, body) {
903
1072
  try {
904
1073
  copyKept(root, dir, kept);
905
1074
  links = link ? linkEntries(root, dir, await linkedEntries(root)) : [];
906
- const runDir = join(dir, prefix);
1075
+ const runDir = join2(dir, prefix);
907
1076
  if (!existsSync(runDir))
908
1077
  fail(`${prefix} does not exist at ${ref}`);
909
1078
  return await body(runDir, signals);
@@ -957,7 +1126,7 @@ ${USAGE}`);
957
1126
  if (runsInContainer(given))
958
1127
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
959
1128
  const command = shellCommand(given);
960
- const cwd = process7.cwd();
1129
+ const cwd = process9.cwd();
961
1130
  const { root, prefix } = await checkout(cwd);
962
1131
  const ref = parsed.values.ref ?? "HEAD";
963
1132
  const sha = await resolveRef(root, ref);
@@ -996,4 +1165,4 @@ ${folded(run.output)}`}`);
996
1165
  ${folded(shown.output)}`);
997
1166
  return proved ? 0 : 1;
998
1167
  }
999
- process7.exitCode = await runMain({ name: "proof", version, run: main });
1168
+ process9.exitCode = await runMain({ name: "proof", version, run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-base",
3
3
  "type": "module",
4
- "version": "0.4.0",
4
+ "version": "0.4.1",
5
5
  "description": "base: a command run at HEAD or another ref in a temporary worktree, the working tree left untouched.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -38,6 +38,6 @@
38
38
  "proof": "$npm_execpath src/proof.ts"
39
39
  },
40
40
  "devDependencies": {
41
- "@kaynooo/cli-kit": "0.15.0"
41
+ "@kaynooo/cli-kit": "0.20.0"
42
42
  }
43
43
  }