@kaynooo/cli-env 0.8.0 → 0.9.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.
package/dist/ev.js CHANGED
@@ -2,10 +2,9 @@
2
2
  // @bun
3
3
 
4
4
  // src/ev.ts
5
- import process8 from "process";
6
-
5
+ import process11 from "process";
7
6
  // ../kit/src/args.ts
8
- import process4 from "process";
7
+ import process6 from "process";
9
8
  import { parseArgs } from "util";
10
9
 
11
10
  // ../kit/src/format.ts
@@ -14,7 +13,7 @@ import process3 from "process";
14
13
  // ../kit/src/style.ts
15
14
  import process2 from "process";
16
15
 
17
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
16
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
17
  function x(s) {
19
18
  let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
19
  if (!/^[a-f0-9]+$/.test(r))
@@ -234,7 +233,7 @@ class e {
234
233
  }
235
234
  }
236
235
 
237
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
236
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
237
  var r = 39;
239
238
  var o = 49;
240
239
  var f2 = "\x1B[";
@@ -358,6 +357,63 @@ function printJson(value) {
358
357
  console.log(JSON.stringify(value, undefined, 2));
359
358
  }
360
359
 
360
+ // ../kit/src/help.ts
361
+ import process4 from "process";
362
+ var OPTIONAL = /\[[^\]]+\]/g;
363
+ var USAGE_PREFIX = /^usage:\s*/i;
364
+ var FULL_STOP = /\.$/;
365
+ function usageLine(usage, colors = paint(process4.stdout)) {
366
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
367
+ }
368
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
369
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
370
+ `);
371
+ }
372
+ function exitRows(exits, colors = paint(process4.stdout)) {
373
+ if (exits.length === 0)
374
+ return [];
375
+ const width = Math.max(...exits.map(([code]) => String(code).length));
376
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
377
+ }
378
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
379
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
380
+ }
381
+ function wantsHelpJson(env = process4.env) {
382
+ return env.KIT_HELP === "json";
383
+ }
384
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
385
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
386
+ `);
387
+ const first = lines[0];
388
+ const colon = first.indexOf(": ");
389
+ const prose = lines[lines.indexOf("") + 1] ?? "";
390
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
391
+ return {
392
+ synopsis: colon === -1 ? first : first.slice(0, colon),
393
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
394
+ ...replaces === undefined ? {} : { replaces },
395
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
396
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
397
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
398
+ };
399
+ }
400
+ function exampleRows(examples, colors = paint(process4.stdout)) {
401
+ if (examples.length === 0)
402
+ return [];
403
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
404
+ }
405
+ function optionRows(options, colors = paint(process4.stdout)) {
406
+ const rows = Object.entries(options).map(([name, option]) => {
407
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
408
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
409
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
410
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
411
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
412
+ });
413
+ const width = Math.max(0, ...rows.map((row) => row.width));
414
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
415
+ }
416
+
361
417
  // ../kit/src/text.ts
362
418
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
363
419
  function distance(a, b) {
@@ -377,8 +433,22 @@ function closest(name, names) {
377
433
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
378
434
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
379
435
  }
436
+ // ../kit/src/input.ts
437
+ import process5 from "process";
438
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
439
+ if (path === "-") {
440
+ if (process5.stdin.isTTY)
441
+ fail(noStdin);
442
+ return Bun.stdin.text();
443
+ }
444
+ const file = Bun.file(path);
445
+ if (!await file.exists())
446
+ fail(`no file ${path}`);
447
+ return file.text();
448
+ }
380
449
 
381
450
  // ../kit/src/args.ts
451
+ var DASHES = /^-+/;
382
452
  function jsonOption(holds) {
383
453
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
384
454
  }
@@ -413,61 +483,20 @@ class HelpShown extends Exit {
413
483
 
414
484
  class Completing {
415
485
  options;
416
- constructor(options) {
486
+ positionals;
487
+ candidates;
488
+ constructor(options, positionals = [], candidates = {}) {
417
489
  this.options = options;
490
+ this.positionals = positionals;
491
+ this.candidates = candidates;
418
492
  }
419
493
  }
420
494
  var completion = { active: false };
421
- var OPTIONAL = /\[[^\]]+\]/g;
422
- var USAGE_PREFIX = /^usage:\s*/i;
423
- var FULL_STOP = /\.$/;
424
- var DASHES = /^-+/;
425
- function usageLine(usage, colors = paint(process4.stdout)) {
426
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
427
- }
428
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces } = {}) {
429
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
430
- `);
431
- }
432
- function replacesRows(replaces, colors = paint(process4.stdout)) {
433
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
434
- }
435
- function wantsHelpJson(env = process4.env) {
436
- return env.KIT_HELP === "json";
437
- }
438
- function description(usage, { examples = [], replaces } = {}) {
439
- const lines = usage.replace(USAGE_PREFIX, "").split(`
440
- `);
441
- const first = lines[0];
442
- const colon = first.indexOf(": ");
443
- const prose = lines[lines.indexOf("") + 1] ?? "";
444
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
445
- return {
446
- synopsis: colon === -1 ? first : first.slice(0, colon),
447
- summary: colon === -1 ? fallback : first.slice(colon + 2),
448
- ...replaces === undefined ? {} : { replaces },
449
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
450
- };
451
- }
452
- function exampleRows(examples, colors = paint(process4.stdout)) {
453
- if (examples.length === 0)
454
- return [];
455
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
456
- }
457
- function optionRows(options, colors = paint(process4.stdout)) {
458
- const rows = Object.entries(options).map(([name, option]) => {
459
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
460
- const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
461
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
462
- });
463
- const width = Math.max(0, ...rows.map((row) => row.width));
464
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
465
- }
466
495
  var OUTPUT_OPTIONS = {
467
496
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
468
497
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
469
498
  };
470
- function applyOutput(color, plain, env = process4.env) {
499
+ function applyOutput(color, plain, env = process6.env) {
471
500
  const when = plain === true ? "never" : color ?? "auto";
472
501
  if (when === "auto")
473
502
  return;
@@ -484,14 +513,13 @@ function applyOutput(color, plain, env = process4.env) {
484
513
  function parse(args, usage, options, settings = {}) {
485
514
  const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
486
515
  const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
516
+ const listing = listed(all, settings.allowNegative === true);
487
517
  if (completion.active)
488
- throw new Completing(all);
489
- const separator = settings.rest === true ? args.indexOf("--") : -1;
490
- const own = separator === -1 ? args : args.slice(0, separator);
491
- const rest = separator === -1 ? undefined : args.slice(separator + 1);
518
+ throw new Completing(listing, settings.positionals, settings.candidates);
519
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
492
520
  let parsed;
493
521
  try {
494
- parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
522
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
495
523
  } catch (error) {
496
524
  const message = parseError(error);
497
525
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -499,12 +527,96 @@ function parse(args, usage, options, settings = {}) {
499
527
  const values = parsed.values;
500
528
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
501
529
  if (values.help === true) {
502
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
530
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
503
531
  throw new HelpShown;
504
532
  }
533
+ checkChoices(parsed.values, all);
534
+ checkConflicts(parsed.values, all);
505
535
  if (settings.positionals !== undefined)
506
536
  checkPositionals(parsed.positionals, settings.positionals);
507
- return { ...parsed, positionals: parsed.positionals, rest };
537
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
538
+ }
539
+ function splitRest(args, passes) {
540
+ const separator = passes ? args.indexOf("--") : -1;
541
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
542
+ }
543
+ function splitTrailing(args, options, count) {
544
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
545
+ let seen = 0;
546
+ if (count === 0)
547
+ return { own: args, rest: undefined };
548
+ for (let at = 0;at < args.length; at++) {
549
+ const word = args[at];
550
+ if (word === "--")
551
+ break;
552
+ if (word.startsWith("-")) {
553
+ if (takesValue(word))
554
+ at++;
555
+ continue;
556
+ }
557
+ seen++;
558
+ if (seen === count)
559
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
560
+ }
561
+ return { own: args, rest: undefined };
562
+ }
563
+ function listed(options, allowNegative) {
564
+ if (!allowNegative)
565
+ return options;
566
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
567
+ if (option.type !== "boolean" || option.negative === undefined)
568
+ return [[name, option]];
569
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
570
+ }));
571
+ }
572
+ function withAliases(args, options) {
573
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
574
+ if (named.size === 0)
575
+ return args;
576
+ const separator = args.indexOf("--");
577
+ const own = separator === -1 ? args : args.slice(0, separator);
578
+ return [...own.map((arg) => {
579
+ const at = arg.indexOf("=");
580
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
581
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
582
+ }), ...separator === -1 ? [] : args.slice(separator)];
583
+ }
584
+ function withBare(args, options) {
585
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
586
+ if (bare.size === 0)
587
+ return args;
588
+ const separator = args.indexOf("--");
589
+ const own = separator === -1 ? args : args.slice(0, separator);
590
+ return [...own.flatMap((arg, index) => {
591
+ const optional = bare.get(arg);
592
+ const next = own[index + 1];
593
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
594
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
595
+ }), ...separator === -1 ? [] : args.slice(separator)];
596
+ }
597
+ function checkConflicts(values, options) {
598
+ const given = (name) => values[name] !== undefined && values[name] !== false;
599
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
600
+ const other = given(name) ? conflicts.find(given) : undefined;
601
+ if (other !== undefined)
602
+ badUsage(`--${name} cannot be used with --${other}`);
603
+ }
604
+ }
605
+ function checkChoices(values, options) {
606
+ for (const [name, option] of Object.entries(options)) {
607
+ if (option.choices === undefined)
608
+ continue;
609
+ const given = values[name];
610
+ for (const value of Array.isArray(given) ? given : [given]) {
611
+ if (typeof value === "string")
612
+ oneOf(value, name, option.choices);
613
+ }
614
+ }
615
+ }
616
+ function oneOf(value, name, choices) {
617
+ if (!choices.includes(value))
618
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
619
+ return value;
508
620
  }
509
621
  function checkPositionals(given, names) {
510
622
  const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
@@ -553,31 +665,75 @@ function nearestOption(message, options, allowNegative) {
553
665
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
554
666
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
555
667
  }
556
- async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
557
- if (path === "-") {
558
- if (process4.stdin.isTTY)
559
- fail(noStdin);
560
- return Bun.stdin.text();
561
- }
562
- const file = Bun.file(path);
563
- if (!await file.exists())
564
- fail(`no file ${path}`);
565
- return file.text();
566
- }
567
668
  // ../kit/src/progress.ts
568
669
  var ESC = String.fromCharCode(27);
569
670
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
570
671
  var RESET_STYLE = `${ESC}[0m`;
571
672
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
572
673
  // ../kit/src/cli.ts
573
- import process5 from "process";
674
+ import { readFileSync, realpathSync } from "fs";
675
+ import { dirname as dirname2, join as join2 } from "path";
676
+ import process8 from "process";
677
+
678
+ // ../kit/src/usage.ts
679
+ import { appendFileSync, mkdirSync } from "fs";
680
+ import { homedir } from "os";
681
+ import { dirname, isAbsolute, join } from "path";
682
+ import process7 from "process";
683
+
684
+ // ../kit/src/logs.ts
685
+ var DAY_MS = 24 * 60 * 60 * 1000;
686
+ var CLI_FOLDER = "kaynooo-cli";
687
+
688
+ // ../kit/src/usage.ts
689
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
690
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
691
+ var LONGEST_NAME = 40;
692
+ var usageError;
693
+ function noteUsageError(message) {
694
+ usageError = message;
695
+ }
696
+ function stateHome(env = process7.env) {
697
+ const dir = env.XDG_STATE_HOME;
698
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
699
+ }
700
+ function usagePath(env = process7.env) {
701
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
702
+ }
703
+ function usageRecorded(env = process7.env) {
704
+ const off = env.KAYNOOO_CLI_NO_USAGE;
705
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
706
+ }
707
+ function flagNames(argv) {
708
+ const end = argv.indexOf("--");
709
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
710
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
711
+ }
712
+ function usageEntry(bin, command, argv, code, now = new Date) {
713
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
714
+ usageError = undefined;
715
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
716
+ }
717
+ function recordUsage(entry, env = process7.env) {
718
+ if (!usageRecorded(env))
719
+ return;
720
+ try {
721
+ const path = usagePath(env);
722
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
723
+ appendFileSync(path, `${JSON.stringify(entry)}
724
+ `, { mode: 384 });
725
+ } catch {}
726
+ }
727
+
728
+ // ../kit/src/cli.ts
574
729
  var LEVEL_OPTIONS = {
575
730
  ...OUTPUT_OPTIONS,
576
731
  help: { type: "boolean", short: "h", description: "show this help" }
577
732
  };
578
733
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
579
- async function commandRows(commands, colors) {
580
- const width = Math.max(...Object.keys(commands).map((name) => name.length));
734
+ async function commandRows(all, colors) {
735
+ const commands = shown(all);
736
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
581
737
  const groups = new Map([["Commands:", []]]);
582
738
  const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
583
739
  for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
@@ -588,6 +744,9 @@ async function commandRows(commands, colors) {
588
744
  }
589
745
  return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
590
746
  }
747
+ function shown(commands) {
748
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
749
+ }
591
750
  function takeOutputFlags(argv) {
592
751
  let index = 0;
593
752
  for (;index < argv.length; index++) {
@@ -619,7 +778,7 @@ async function expand(scope, words) {
619
778
  }
620
779
  return { ...scope, commands, lazy: [] };
621
780
  }
622
- async function help({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
781
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
623
782
  const colors = paint(stream);
624
783
  const prefix = path.join(" ");
625
784
  const summary = await resolveSummary(lazySummary);
@@ -646,8 +805,8 @@ async function help({ path, header, summary: lazySummary, commands, defaultComma
646
805
  `);
647
806
  }
648
807
  function printError(prefix, message, hint, cause) {
649
- const colors = paint(process5.stderr);
650
- const styled = takesControlCodes(process5.stderr);
808
+ const colors = paint(process8.stderr);
809
+ const styled = takesControlCodes(process8.stderr);
651
810
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
652
811
  const under = (label, text, tint) => text === undefined ? "" : `
653
812
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -666,6 +825,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
666
825
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
667
826
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
668
827
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
828
+ if (error instanceof UsageError)
829
+ noteUsageError(error.message);
669
830
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
670
831
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
671
832
  return error instanceof Exit ? error.code : 1;
@@ -679,12 +840,20 @@ async function dispatch(level, typed, { version, redact }) {
679
840
  return reportThrown(prefix, error);
680
841
  }
681
842
  const [name, ...args] = argv;
843
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
844
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
845
+ try {
846
+ return await fallback.run([]);
847
+ } catch (error) {
848
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
849
+ }
850
+ }
682
851
  if (name === undefined && level.path.length > 1) {
683
- console.error(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
852
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
684
853
  return 2;
685
854
  }
686
855
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
687
- console.log(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
856
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
688
857
  return 0;
689
858
  }
690
859
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -693,6 +862,7 @@ async function dispatch(level, typed, { version, redact }) {
693
862
  }
694
863
  let command = level.commands[level.aliases?.[name] ?? name];
695
864
  let rest = args;
865
+ let ran = name;
696
866
  if (command === undefined && level.lazy.length > 0) {
697
867
  level = await expand(level, [...level.path.slice(1), ...argv]);
698
868
  command = level.commands[level.aliases?.[name] ?? name];
@@ -700,40 +870,77 @@ async function dispatch(level, typed, { version, redact }) {
700
870
  if (command === undefined && level.defaultCommand !== undefined) {
701
871
  command = level.commands[level.defaultCommand];
702
872
  rest = argv;
873
+ ran = level.defaultCommand;
703
874
  }
704
875
  if (command === undefined) {
705
- const meant = closest(name, Object.keys(level.commands));
876
+ const meant = closest(name, Object.keys(shown(level.commands)));
706
877
  printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
707
878
  return 2;
708
879
  }
709
880
  if ("commands" in command) {
710
881
  const { summary } = command;
711
- return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, examples: command.examples, replaces: undefined }, rest, { version, redact });
882
+ 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 });
712
883
  }
713
884
  try {
714
885
  return await command.run(rest);
715
886
  } catch (error) {
716
- return reportThrown(`${prefix} ${name}`, error, redact, wantsJson(rest));
887
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
717
888
  }
718
889
  }
719
890
  var COMPLETE = "__complete";
720
891
  var FILES = "__files__";
721
- async function optionsOf(run) {
892
+ async function completingOf(run) {
722
893
  completion.active = true;
723
894
  try {
724
895
  await run([]);
725
896
  } catch (error) {
726
897
  if (error instanceof Completing)
727
- return error.options;
898
+ return error;
728
899
  } finally {
729
900
  completion.active = false;
730
901
  }
731
- return {};
902
+ return new Completing({});
903
+ }
904
+ async function optionsOf(run) {
905
+ return (await completingOf(run)).options;
906
+ }
907
+ function candidateLine(candidate) {
908
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
909
+ }
910
+ function positionalBeingTyped(before, { options, positionals }) {
911
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
912
+ let index = 0;
913
+ let at = 0;
914
+ while (at < before.length) {
915
+ const word = before[at];
916
+ if (word === "--") {
917
+ index += before.length - at - 1;
918
+ break;
919
+ }
920
+ if (!word.startsWith("-"))
921
+ index++;
922
+ else if (takesValue(word))
923
+ at++;
924
+ at++;
925
+ }
926
+ const last = positionals.at(-1);
927
+ if (index < positionals.length)
928
+ return positionals[index];
929
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
732
930
  }
733
931
  async function leafCandidates(run, words) {
734
- if (!(words.at(-1) ?? "").startsWith("-"))
735
- return [FILES];
736
- return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
932
+ const completing = await completingOf(run);
933
+ if ((words.at(-1) ?? "").startsWith("-"))
934
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
935
+ const flag = words.at(-2);
936
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
937
+ if (option?.type === "string") {
938
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
939
+ return values === undefined ? [FILES] : values.map(candidateLine);
940
+ }
941
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
942
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
943
+ return values === undefined ? [FILES] : values.map(candidateLine);
737
944
  }
738
945
  async function candidates(scope, defaultCommand, words, before = []) {
739
946
  const [word = "", ...rest] = words;
@@ -744,8 +951,13 @@ async function candidates(scope, defaultCommand, words, before = []) {
744
951
  ({ commands, aliases } = await expand(scope, [...before, ...words]));
745
952
  command = commands[aliases?.[word] ?? word];
746
953
  }
747
- if (listing)
748
- return Promise.all(Object.entries(commands).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
954
+ if (listing) {
955
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
956
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
957
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
958
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
959
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
960
+ }
749
961
  if (command === undefined) {
750
962
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
751
963
  return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
@@ -757,26 +969,73 @@ async function printCandidates(found) {
757
969
  console.log(line);
758
970
  return 0;
759
971
  }
760
- async function runCli(cli, argv = process5.argv.slice(2)) {
972
+ function packageVersion(entry = Bun.main) {
973
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
974
+ try {
975
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
976
+ if (typeof version === "string")
977
+ return version;
978
+ } catch {}
979
+ if (dirname2(dir) === dir)
980
+ return "0.0.0";
981
+ }
982
+ }
983
+ async function runCli(cli, argv = process8.argv.slice(2)) {
984
+ const version = cli.version ?? packageVersion();
761
985
  if (argv[0] === COMPLETE)
762
986
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
763
- return dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
987
+ 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 });
988
+ if (cli.usage !== false) {
989
+ try {
990
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
991
+ } catch {}
992
+ }
993
+ return code;
764
994
  }
765
- async function runMain({ name, version, run, redact }, argv = process5.argv.slice(2)) {
995
+ function commandPath(scope, argv) {
996
+ const path = [];
997
+ let level = scope;
998
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
999
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1000
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1001
+ if (command === undefined)
1002
+ break;
1003
+ path.push(word);
1004
+ if (!("commands" in command))
1005
+ break;
1006
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1007
+ }
1008
+ return path.length === 0 ? undefined : path.join(" ");
1009
+ }
1010
+ async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
766
1011
  if (argv[0] === COMPLETE)
767
1012
  return printCandidates(leafCandidates(run, argv.slice(1)));
768
1013
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
769
- console.log(version);
1014
+ console.log(version ?? packageVersion());
770
1015
  return 0;
771
1016
  }
1017
+ let code;
772
1018
  try {
773
- return await run(argv);
1019
+ code = await run(argv);
774
1020
  } catch (error) {
775
- return reportThrown(name, error, redact, wantsJson(argv));
1021
+ code = reportThrown(name, error, redact, wantsJson(argv));
776
1022
  }
1023
+ if (usage !== false) {
1024
+ try {
1025
+ recordUsage(usageEntry(name, undefined, argv, code));
1026
+ } catch {}
1027
+ }
1028
+ return code;
1029
+ }
1030
+ // ../kit/src/compose.ts
1031
+ async function captureOutput(argv, { cwd, env } = {}) {
1032
+ const run = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, env: { ...process.env, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
1033
+ const [stdout, stderr, code] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
1034
+ return { code, stdout, stderr };
1035
+ }
1036
+ async function compose(args, { flags = [], ...options } = {}) {
1037
+ return captureOutput(["docker", "compose", ...flags, ...args], options);
777
1038
  }
778
- // ../kit/src/logs.ts
779
- var DAY_MS = 24 * 60 * 60 * 1000;
780
1039
  // ../kit/src/secrets.ts
781
1040
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
782
1041
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -788,13 +1047,10 @@ function isSecretName(name) {
788
1047
  var {Glob } = globalThis.Bun;
789
1048
  var SESSION_FILES = new Glob("*.json");
790
1049
  var ACCOUNT_DIRS = new Glob("*/sessions");
791
- // package.json
792
- var version = "0.8.0";
793
-
794
1050
  // src/commands/audit.ts
795
1051
  import { stat as stat4 } from "fs/promises";
796
1052
  import { relative, resolve } from "path";
797
- import process7 from "process";
1053
+ import process10 from "process";
798
1054
 
799
1055
  // ../kit/src/shell.ts
800
1056
  var SEPARATORS = new Set([`
@@ -805,13 +1061,16 @@ var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
805
1061
  var SAFE_WORD = /^[\w@%+=:,./-]+$/;
806
1062
  var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
807
1063
  var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
808
- var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh"]);
809
- var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, "su", "runuser"]);
1064
+ var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
1065
+ var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
1066
+ var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
1067
+ var POWERSHELL = new Set(["pwsh", "powershell"]);
810
1068
  var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
1069
+ var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
811
1070
  var PRINTERS = new Set(["echo", "printf"]);
812
1071
  var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
813
- function wrapper(short = "", long = [], operands = 0) {
814
- return { short, long, operands };
1072
+ function wrapper(short = "", long = [], operands = 0, runsString = false) {
1073
+ return { short, long, operands, runsString };
815
1074
  }
816
1075
  var WRAPPERS = new Map([
817
1076
  ["command", wrapper()],
@@ -829,6 +1088,11 @@ var WRAPPERS = new Map([
829
1088
  ["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
830
1089
  ["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
831
1090
  ["chroot", wrapper("", ["--userspec", "--groups"], 1)],
1091
+ ["watch", wrapper("n", ["--interval"], 0, true)],
1092
+ ["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
1093
+ ["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
1094
+ ["unbuffer", wrapper()],
1095
+ ["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
832
1096
  ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
833
1097
  ]);
834
1098
  function shellQuote(word) {
@@ -837,12 +1101,12 @@ function shellQuote(word) {
837
1101
 
838
1102
  // src/audit.ts
839
1103
  import { readdir as readdir2, stat as stat2 } from "fs/promises";
840
- import { dirname as dirname2, join as join2 } from "path";
1104
+ import { dirname as dirname4, join as join4 } from "path";
841
1105
  var {$ } = globalThis.Bun;
842
1106
 
843
1107
  // src/files.ts
844
1108
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
845
- import { basename, dirname, join } from "path";
1109
+ import { basename, dirname as dirname3, join as join3 } from "path";
846
1110
 
847
1111
  // src/dotenv.ts
848
1112
  var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
@@ -925,14 +1189,16 @@ function entries(file) {
925
1189
  }
926
1190
  return map;
927
1191
  }
1192
+ function escapeDouble(value) {
1193
+ return value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("\r", "\\r").replaceAll(`
1194
+ `, "\\n").replaceAll("$", "\\$");
1195
+ }
928
1196
  function formatAssignment(key, value) {
929
1197
  if (value === "" || !NEEDS_QUOTES.test(value))
930
1198
  return `${key}=${value}`;
931
1199
  if (RAW_ONLY.test(value) && !value.includes("'") && !LINE_BREAK.test(value))
932
1200
  return `${key}='${value.replaceAll("$", "\\$")}'`;
933
- const escaped = value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("\r", "\\r").replaceAll(`
934
- `, "\\n").replaceAll("$", "\\$");
935
- return `${key}="${escaped}"`;
1201
+ return `${key}="${escapeDouble(value)}"`;
936
1202
  }
937
1203
  function setLine(file, key, value, raw) {
938
1204
  const index = file.lines.findLastIndex((line) => line.key === key);
@@ -1001,6 +1267,9 @@ var WEBHOOK_FORMATS = [
1001
1267
  ["healthchecks.io ping URL", /^hc-ping\.com\/([\w-]+)/di]
1002
1268
  ];
1003
1269
  var OPAQUE_SEGMENT = /^(?:(?=[\w-]{20,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w-]+|(?=[A-Za-z\d]{32,}$)(?=.*[A-Za-z])(?=.*\d).+)$/;
1270
+ function isSecretKey(key) {
1271
+ return isSecretName(key);
1272
+ }
1004
1273
  function hint(value) {
1005
1274
  const shown = Math.min(3, Math.floor(value.length / 4));
1006
1275
  return `${value.slice(0, shown)}***(${value.length})`;
@@ -1133,6 +1402,7 @@ var KNOWN_DEPTH = 3;
1133
1402
  var SKIPPED = new Set(["node_modules", ".git", "vendor"]);
1134
1403
  var LOCK_WAIT_MS = 5000;
1135
1404
  var LOCK_STALE_MS = 30000;
1405
+ var REAP_STALE_MS = 5000;
1136
1406
  async function isFileEntry(entry, path) {
1137
1407
  if (entry.isFile())
1138
1408
  return true;
@@ -1148,7 +1418,7 @@ async function envFiles(folder = process.cwd()) {
1148
1418
  const found = await readdir(folder, { withFileTypes: true });
1149
1419
  const names = [];
1150
1420
  for (const entry of found) {
1151
- if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join(folder, entry.name)))
1421
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join3(folder, entry.name)))
1152
1422
  names.push(entry.name);
1153
1423
  }
1154
1424
  return names.sort();
@@ -1172,7 +1442,7 @@ async function writeAtomic(path, text) {
1172
1442
  if (error.code !== "ENOENT")
1173
1443
  throw error;
1174
1444
  }
1175
- const temp = join(dirname(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1445
+ const temp = join3(dirname3(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1176
1446
  try {
1177
1447
  await writeFile(temp, text, { mode: 384, flag: "wx" });
1178
1448
  if (owner !== undefined)
@@ -1205,12 +1475,30 @@ async function withLocks(paths, fn) {
1205
1475
  await rm(lock, { force: true });
1206
1476
  }
1207
1477
  }
1478
+ async function reap(lock) {
1479
+ const guard = `${lock}.reap`;
1480
+ try {
1481
+ await writeFile(guard, String(process.pid), { flag: "wx", mode: 384 });
1482
+ } catch {
1483
+ try {
1484
+ if (Date.now() - (await stat(guard)).mtimeMs > REAP_STALE_MS)
1485
+ await rm(guard, { force: true });
1486
+ } catch {}
1487
+ return;
1488
+ }
1489
+ try {
1490
+ if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS)
1491
+ await rm(lock, { force: true });
1492
+ } catch {} finally {
1493
+ await rm(guard, { force: true });
1494
+ }
1495
+ }
1208
1496
  async function acquire(path) {
1209
1497
  let real = path;
1210
1498
  try {
1211
1499
  real = await realpath(path);
1212
1500
  } catch {}
1213
- const lock = join(dirname(real), `.${basename(real)}.lock`);
1501
+ const lock = join3(dirname3(real), `.${basename(real)}.lock`);
1214
1502
  const deadline = Date.now() + LOCK_WAIT_MS;
1215
1503
  while (true) {
1216
1504
  try {
@@ -1220,10 +1508,7 @@ async function acquire(path) {
1220
1508
  if (error.code !== "EEXIST")
1221
1509
  throw error;
1222
1510
  }
1223
- try {
1224
- if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS)
1225
- await rm(lock, { force: true });
1226
- } catch {}
1511
+ await reap(lock);
1227
1512
  if (Date.now() > deadline)
1228
1513
  fail(`${path} is locked by another ev run (${lock})`, 1);
1229
1514
  await Bun.sleep(25);
@@ -1248,7 +1533,7 @@ async function envFilesBelow(folder, depth = 0) {
1248
1533
  return found;
1249
1534
  }
1250
1535
  for (const entry of children) {
1251
- const path = join(folder, entry.name);
1536
+ const path = join3(folder, entry.name);
1252
1537
  if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1253
1538
  found.push(...await envFilesBelow(path, depth + 1));
1254
1539
  else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
@@ -1290,18 +1575,28 @@ function inlineSecrets(compose) {
1290
1575
  async function openToOthers(path) {
1291
1576
  if (((await stat2(path)).mode & 4) === 0)
1292
1577
  return false;
1293
- for (let dir = dirname2(path);dir !== "/"; dir = dirname2(dir)) {
1578
+ for (let dir = dirname4(path);dir !== "/"; dir = dirname4(dir)) {
1294
1579
  if (((await stat2(dir)).mode & 1) === 0)
1295
1580
  return false;
1296
1581
  }
1297
1582
  return true;
1298
1583
  }
1584
+ function groupReads(mode, gid, ownerGroup) {
1585
+ return (mode & 32) !== 0 && gid !== ownerGroup && gid !== process.getgid?.();
1586
+ }
1587
+ function primaryGroup(uid) {
1588
+ if (uid === process.getuid?.())
1589
+ return process.getgid?.() ?? uid;
1590
+ const run = Bun.spawnSync(["id", "-g", String(uid)], { stdout: "pipe", stderr: "ignore" });
1591
+ const gid = Number(run.stdout.toString().trim());
1592
+ return run.exitCode === 0 && Number.isInteger(gid) ? gid : uid;
1593
+ }
1299
1594
  async function sharedWith(path) {
1300
1595
  const info = await stat2(path);
1301
- const shared = (info.mode & 32) !== 0 && info.gid !== info.uid && info.gid !== process.getgid?.();
1596
+ const shared = groupReads(info.mode, info.gid, primaryGroup(info.uid));
1302
1597
  if (!shared && (Bun.which("getfacl") === null || !await hasAclReader(path)))
1303
1598
  return false;
1304
- for (let dir = dirname2(path);dir !== "/"; dir = dirname2(dir)) {
1599
+ for (let dir = dirname4(path);dir !== "/"; dir = dirname4(dir)) {
1305
1600
  if (((await stat2(dir)).mode & 9) === 0)
1306
1601
  return false;
1307
1602
  }
@@ -1313,7 +1608,7 @@ async function hasAclReader(path) {
1313
1608
  `).some((line) => ACL_READER.test(line));
1314
1609
  }
1315
1610
  async function tracked(path) {
1316
- const run = await $`git ls-files --error-unmatch -- ${path}`.cwd(dirname2(path)).quiet().nothrow();
1611
+ const run = await $`git ls-files --error-unmatch -- ${path}`.cwd(dirname4(path)).quiet().nothrow();
1317
1612
  const error = run.stderr.toString();
1318
1613
  if (run.exitCode === 0)
1319
1614
  return true;
@@ -1330,7 +1625,7 @@ async function* candidates2(root, unread, depth = 0) {
1330
1625
  return;
1331
1626
  }
1332
1627
  for (const entry of found) {
1333
- const path = join2(root, entry.name);
1628
+ const path = join4(root, entry.name);
1334
1629
  if (entry.isDirectory() && depth < MAX_DEPTH && !SKIPPED2.has(entry.name))
1335
1630
  yield* candidates2(path, unread, depth + 1);
1336
1631
  else if (!TEMPLATE.test(entry.name) && (ENV_FILE.test(entry.name) || COMPOSE_FILE.test(entry.name)) && await isFileEntry(entry, path))
@@ -1362,7 +1657,7 @@ async function audit(roots) {
1362
1657
 
1363
1658
  // src/fix.ts
1364
1659
  import { chmod as chmod2, chown as chown2, lstat, rm as rm2, stat as stat3 } from "fs/promises";
1365
- import { dirname as dirname3, join as join3 } from "path";
1660
+ import { dirname as dirname5, join as join5 } from "path";
1366
1661
  var MAP_ENTRY = /^(\s*)(["']?)([A-Z0-9_]+)\2(\s*:)(.*)$/;
1367
1662
  var LIST_ENTRY = /^(\s*-[ \t]*)(["']?)([A-Z0-9_]+)=(.*)$/;
1368
1663
  var TRAILING = /^\s*(?:#.*)?$/;
@@ -1420,8 +1715,11 @@ function composeEntry(line) {
1420
1715
  function envLine(key, value) {
1421
1716
  if (ENV_PLAIN.test(value))
1422
1717
  return `${key}=${value}`;
1423
- return value.includes("'") || value.includes(`
1424
- `) ? undefined : `${key}='${value}'`;
1718
+ if (LINE_BREAK.test(value))
1719
+ return;
1720
+ if (value.includes("$"))
1721
+ return `${key}="${escapeDouble(value)}"`;
1722
+ return value.includes("'") ? undefined : `${key}='${value}'`;
1425
1723
  }
1426
1724
  async function isLink(path) {
1427
1725
  try {
@@ -1433,9 +1731,8 @@ async function isLink(path) {
1433
1731
  }
1434
1732
  }
1435
1733
  async function resolved(path) {
1436
- const run = Bun.spawn(["docker", "compose", "-f", path, "config", "--format", "json"], { cwd: dirname3(path), stdout: "pipe", stderr: "ignore", stdin: "ignore" });
1437
- const [out, code] = await Promise.all([new Response(run.stdout).text(), run.exited]);
1438
- return code === 0 ? out : undefined;
1734
+ const { code, stdout } = await compose(["config", "--format", "json"], { flags: ["-f", path], cwd: dirname5(path) });
1735
+ return code === 0 ? stdout : undefined;
1439
1736
  }
1440
1737
  function gainedBy(before, after, key) {
1441
1738
  const services = (config) => Object.entries(JSON.parse(config).services ?? {});
@@ -1453,7 +1750,7 @@ async function shutOthersOut(path, group = false) {
1453
1750
  }
1454
1751
  }
1455
1752
  async function fixCompose(path, group = false) {
1456
- const env = join3(dirname3(path), ".env");
1753
+ const env = join5(dirname5(path), ".env");
1457
1754
  const compose = await Bun.file(path).text();
1458
1755
  const envBefore = await Bun.file(env).exists() ? await Bun.file(env).text() : undefined;
1459
1756
  const dotenv = parseDotenv(envBefore ?? "");
@@ -1546,7 +1843,7 @@ async function move(fix, compose, composeAfter, envBefore, envAfter) {
1546
1843
  }
1547
1844
 
1548
1845
  // src/commands/audit.ts
1549
- var usage = `ev audit [dir...] [--fix]
1846
+ var usage2 = `ev audit [dir...] [--fix]
1550
1847
 
1551
1848
  Lists the .env files any account on the machine can read or git tracks, and the compose files any account can read that write a secret out (a secret-named value or a URL password) instead of reading it from a .env, never printing a value.
1552
1849
  Looks under each folder (the current one by default) down to 5 levels, skipping node_modules, vendor and .git, and leaves .example, .sample, .template and .dist files out. A folder it cannot read is named on stderr.
@@ -1570,8 +1867,8 @@ async function isFolder(path) {
1570
1867
  return false;
1571
1868
  }
1572
1869
  }
1573
- function shown(path) {
1574
- return path.startsWith(`${process7.cwd()}/`) ? relative(process7.cwd(), path) : path;
1870
+ function shown2(path) {
1871
+ return path.startsWith(`${process10.cwd()}/`) ? relative(process10.cwd(), path) : path;
1575
1872
  }
1576
1873
  async function fixAll(exposed, json) {
1577
1874
  const fixed = [];
@@ -1585,21 +1882,21 @@ async function fixAll(exposed, json) {
1585
1882
  if (json)
1586
1883
  continue;
1587
1884
  const lines = [
1588
- ...fix === undefined || fix.moved.length === 0 ? [] : [`moved ${fix.moved.join(", ")} into ${shown(fix.env)}`],
1885
+ ...fix === undefined || fix.moved.length === 0 ? [] : [`moved ${fix.moved.join(", ")} into ${shown2(fix.env)}`],
1589
1886
  ...fix?.left.map(({ key, why }) => `left ${key} in place: ${why}`) ?? [],
1590
1887
  ...fix?.check === undefined ? [] : [CHECKS[fix.check]],
1591
- ...open.map((file) => `another account owns ${file === path ? "it" : shown(file)}, so it stays readable: sudo chmod go-rwx ${shellQuote(shown(file))}`),
1888
+ ...open.map((file) => `another account owns ${file === path ? "it" : shown2(file)}, so it stays readable: sudo chmod go-rwx ${shellQuote(shown2(file))}`),
1592
1889
  ...readable && !open.includes(path) ? ["now unreadable by other accounts"] : [],
1593
- ...tracked ? [`tracked by git: git rm --cached ${shellQuote(shown(path))}, then ignore it`] : []
1890
+ ...tracked ? [`tracked by git: git rm --cached ${shellQuote(shown2(path))}, then ignore it`] : []
1594
1891
  ];
1595
- console.log(`${shown(path)}
1892
+ console.log(`${shown2(path)}
1596
1893
  ${lines.join(`
1597
1894
  `)}`);
1598
1895
  }
1599
1896
  return { fixed, left };
1600
1897
  }
1601
1898
  async function audit2(args) {
1602
- const parsed = parse(args, usage, options);
1899
+ const parsed = parse(args, usage2, options);
1603
1900
  const roots = (parsed.positionals.length > 0 ? parsed.positionals : ["."]).map((dir) => resolve(dir));
1604
1901
  for (const dir of roots) {
1605
1902
  if (!await isFolder(dir))
@@ -1627,15 +1924,15 @@ async function audit2(args) {
1627
1924
  console.log("no exposed .env file nor compose file writing a secret out");
1628
1925
  return 0;
1629
1926
  }
1630
- const uid = process7.getuid?.();
1927
+ const uid = process10.getuid?.();
1631
1928
  for (const { path, readable, group, tracked, secrets } of exposed) {
1632
1929
  const sudo = uid !== undefined && uid !== 0 && (await stat4(path)).uid !== uid ? "sudo " : "";
1633
1930
  const problems = [
1634
1931
  ...secrets === undefined ? [] : [`writes out ${secrets.join(", ")}: ev audit --fix moves the values into a .env beside it`],
1635
- ...readable ? [group === true ? `readable by its group or an ACL: ${sudo}chmod go-rwx ${shellQuote(shown(path))}` : `readable by any account: ${sudo}chmod o-rwx ${shellQuote(shown(path))}`] : [],
1636
- ...tracked ? [`tracked by git: git rm --cached ${shellQuote(shown(path))}, then ignore it`] : []
1932
+ ...readable ? [group === true ? `readable by its group or an ACL: ${sudo}chmod go-rwx ${shellQuote(shown2(path))}` : `readable by any account: ${sudo}chmod o-rwx ${shellQuote(shown2(path))}`] : [],
1933
+ ...tracked ? [`tracked by git: git rm --cached ${shellQuote(shown2(path))}, then ignore it`] : []
1637
1934
  ];
1638
- console.log(`${shown(path)}
1935
+ console.log(`${shown2(path)}
1639
1936
  ${problems.join(`
1640
1937
  `)}`);
1641
1938
  }
@@ -1647,17 +1944,22 @@ var diffUsage = `ev diff <a> <b>
1647
1944
 
1648
1945
  Names the keys set in one file and not the other, never their values.
1649
1946
 
1947
+ --json prints {a, b, onlyA, onlyB}.
1948
+
1650
1949
  Exits 0 when both set the same keys, 1 when they differ, 2 on a usage error.`;
1651
1950
  var missingUsage = `ev missing [file]
1652
1951
 
1653
1952
  Names the keys the reference file sets that the file (.env by default) does not.
1654
1953
 
1954
+ --json prints {a, b, onlyA, onlyB} with the reference as a, so onlyA is what is missing.
1955
+
1655
1956
  Exits 0 when none is missing, 1 when some are, 2 on a usage error.`;
1957
+ var jsonFlag = { json: jsonOption() };
1656
1958
  async function keys(path) {
1657
1959
  return new Set(entries(await readEnv(path)).keys());
1658
1960
  }
1659
1961
  async function diff(args) {
1660
- const parsed = parse(args, diffUsage, {});
1962
+ const parsed = parse(args, diffUsage, jsonFlag);
1661
1963
  const [a, b] = parsed.positionals;
1662
1964
  if (a === undefined || b === undefined)
1663
1965
  fail(`needs two files
@@ -1665,10 +1967,13 @@ async function diff(args) {
1665
1967
  ${diffUsage}`);
1666
1968
  const left = await keys(a);
1667
1969
  const right = await keys(b);
1668
- const lines = [
1669
- ...[...left].filter((key) => !right.has(key)).map((key) => `only in ${a}: ${key}`),
1670
- ...[...right].filter((key) => !left.has(key)).map((key) => `only in ${b}: ${key}`)
1671
- ];
1970
+ const onlyA = [...left].filter((key) => !right.has(key));
1971
+ const onlyB = [...right].filter((key) => !left.has(key));
1972
+ if (parsed.values.json === true) {
1973
+ printJson({ a, b, onlyA, onlyB });
1974
+ return onlyA.length + onlyB.length === 0 ? 0 : 1;
1975
+ }
1976
+ const lines = [...onlyA.map((key) => `only in ${a}: ${key}`), ...onlyB.map((key) => `only in ${b}: ${key}`)];
1672
1977
  if (lines.length === 0)
1673
1978
  return 0;
1674
1979
  console.log(lines.join(`
@@ -1676,11 +1981,16 @@ ${diffUsage}`);
1676
1981
  return 1;
1677
1982
  }
1678
1983
  async function missing(args) {
1679
- const parsed = parse(args, missingUsage, { against: { type: "string", description: "the reference file (.env.example by default)" } });
1984
+ const parsed = parse(args, missingUsage, { against: { type: "string", description: "the reference file (.env.example by default)" }, ...jsonFlag });
1680
1985
  const [file = ".env"] = parsed.positionals;
1681
1986
  const against = parsed.values.against ?? ".env.example";
1682
1987
  const have = await keys(file);
1683
- const absent = [...await keys(against)].filter((key) => !have.has(key));
1988
+ const reference = await keys(against);
1989
+ const absent = [...reference].filter((key) => !have.has(key));
1990
+ if (parsed.values.json === true) {
1991
+ printJson({ a: against, b: file, onlyA: absent, onlyB: [...have].filter((key) => !reference.has(key)) });
1992
+ return absent.length === 0 ? 0 : 1;
1993
+ }
1684
1994
  if (absent.length === 0)
1685
1995
  return 0;
1686
1996
  console.log(absent.map((key) => `${key} (set in ${against}, not in ${file})`).join(`
@@ -1825,11 +2135,11 @@ ${cpUsage}`);
1825
2135
 
1826
2136
  // src/commands/pins.ts
1827
2137
  import { readdir as readdir4, stat as stat5 } from "fs/promises";
1828
- import { join as join5, resolve as resolve2 } from "path";
2138
+ import { join as join7, resolve as resolve2 } from "path";
1829
2139
 
1830
2140
  // src/pins.ts
1831
2141
  import { readdir as readdir3, readFile } from "fs/promises";
1832
- import { join as join4, relative as relative2 } from "path";
2142
+ import { join as join6, relative as relative2 } from "path";
1833
2143
  var OPTIONAL2 = /^\s*([A-Z][A-Z0-9_]*)\s*:\s*s\.Optional\(/gm;
1834
2144
  var REACHING = /(?:URL|URI|TOKEN|KEY|SECRET|PASSWORD|DSN|_HOST)(?:_FILE)?$/;
1835
2145
  var SELF = /(?:^|_)(?:PUBLIC|SITE|BASE|APP)_URL$/;
@@ -1859,7 +2169,7 @@ async function walk(folder, keep) {
1859
2169
  for (const entry of entries) {
1860
2170
  if (SKIPPED3.has(entry.name))
1861
2171
  continue;
1862
- const path = join4(folder, entry.name);
2172
+ const path = join6(folder, entry.name);
1863
2173
  if (entry.isDirectory())
1864
2174
  found.push(...await walk(path, keep));
1865
2175
  else if (entry.isFile() && keep(entry.name))
@@ -1870,7 +2180,7 @@ async function walk(folder, keep) {
1870
2180
  async function testFiles(folder) {
1871
2181
  const found = [];
1872
2182
  for (const root of TEST_ROOTS) {
1873
- found.push(...await walk(join4(folder, root), (name) => TEST_FILE.test(name)));
2183
+ found.push(...await walk(join6(folder, root), (name) => TEST_FILE.test(name)));
1874
2184
  }
1875
2185
  return found;
1876
2186
  }
@@ -1938,7 +2248,7 @@ function reachesOutside(name) {
1938
2248
  }
1939
2249
  async function schemaFile(folder) {
1940
2250
  for (const candidate of SCHEMA_CANDIDATES) {
1941
- const path = join4(folder, candidate);
2251
+ const path = join6(folder, candidate);
1942
2252
  if (await exists(path) && (await readFile(path, "utf8")).includes("defineEnv("))
1943
2253
  return path;
1944
2254
  }
@@ -1949,7 +2259,7 @@ async function testEnvKeys(folder) {
1949
2259
  for (const entry of await readdir3(folder, { withFileTypes: true })) {
1950
2260
  if (!entry.isFile() || !ENV_TEST.test(entry.name))
1951
2261
  continue;
1952
- for (const line of parseDotenv(await readFile(join4(folder, entry.name), "utf8")).lines) {
2262
+ for (const line of parseDotenv(await readFile(join6(folder, entry.name), "utf8")).lines) {
1953
2263
  if (line.key !== undefined)
1954
2264
  keys.add(line.key);
1955
2265
  }
@@ -1957,13 +2267,18 @@ async function testEnvKeys(folder) {
1957
2267
  return keys;
1958
2268
  }
1959
2269
  async function pinningPreload(folder) {
1960
- const path = join4(folder, "bunfig.toml");
2270
+ const path = join6(folder, "bunfig.toml");
1961
2271
  if (!await exists(path))
1962
2272
  return;
1963
- const config = Bun.TOML.parse(await readFile(path, "utf8"));
2273
+ let config;
2274
+ try {
2275
+ config = Bun.TOML.parse(await readFile(path, "utf8"));
2276
+ } catch {
2277
+ fail(`${path} is not valid TOML`);
2278
+ }
1964
2279
  const preloads = [config.test?.preload, config.preload].flat().filter((entry) => typeof entry === "string" && entry.startsWith("."));
1965
2280
  for (const preload of preloads) {
1966
- const file = join4(folder, preload);
2281
+ const file = join6(folder, preload);
1967
2282
  if (!await exists(file))
1968
2283
  continue;
1969
2284
  const source = await readFile(file, "utf8");
@@ -1998,7 +2313,7 @@ async function checkApp(folder, except = new Set) {
1998
2313
  }
1999
2314
 
2000
2315
  // src/commands/pins.ts
2001
- var usage2 = `ev pins [dir] [--except NAME,...]
2316
+ var usage3 = `ev pins [dir] [--except NAME,...]
2002
2317
 
2003
2318
  Checks that an app's tests pin the env that reaches outside.
2004
2319
  Reads the app's env schema (the file calling defineEnv, src/env.ts) and lists its optional URL, key, token, secret, password and host variables, then the ones no \`.env.test\` entry, test-level overrideEnv or local bunfig preload dropping what .env sets pins, and each test file that calls testSite or proxyKeyTests without pinning them all.
@@ -2025,7 +2340,7 @@ async function apps(dir, except) {
2025
2340
  for (const entry of (await readdir4(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
2026
2341
  if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules")
2027
2342
  continue;
2028
- const app = await checkApp(join5(dir, entry.name), except);
2343
+ const app = await checkApp(join7(dir, entry.name), except);
2029
2344
  if (app !== undefined)
2030
2345
  found.push(app);
2031
2346
  }
@@ -2038,7 +2353,7 @@ function name(app, root) {
2038
2353
  return app.app === root ? app.app.split("/").at(-1) ?? app.app : app.app.slice(root.length + 1);
2039
2354
  }
2040
2355
  async function pins(args) {
2041
- const parsed = parse(args, usage2, options2, { positionals: ["[dir]"] });
2356
+ const parsed = parse(args, usage3, options2, { positionals: ["[dir]"] });
2042
2357
  const json = parsed.values.json === true;
2043
2358
  const root = resolve2(parsed.positionals[0] ?? ".");
2044
2359
  const except = new Set((parsed.values.except ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry !== ""));
@@ -2072,16 +2387,32 @@ var listUsage = `ev list [file]
2072
2387
 
2073
2388
  Prints every key of the folder's .env* files, or of one file, with secret values masked: a few leading characters and the length under a key named like TOKEN, SECRET, PASSWORD, PASS, PWD, KEY, PRIVATE, DSN, AUTH, SALT or COOKIE, any value equal to a secret of the folder's .env* files, and the password and tokens of any URL.
2074
2389
 
2390
+ --json prints [{file, key, value, secret}], value masked and secret true when a value was.
2391
+
2075
2392
  Exits 0 when it printed them, 1 when there is no .env* file, 2 on a usage error.`;
2076
2393
  var getUsage = `ev get KEY [file]
2077
2394
 
2078
2395
  Prints the masked value of one key, from every .env* file that sets it or from one file.
2079
2396
 
2397
+ --json prints [{file, key, value, secret}] for each file that sets it.
2398
+
2080
2399
  Exits 0 when the key is set, 1 when it is not set anywhere, 2 on a usage error.`;
2081
2400
  function display(key, value, known) {
2082
2401
  return maskValue(key, value, known).replaceAll(`
2083
2402
  `, "\\n").replaceAll("\r", "\\r");
2084
2403
  }
2404
+ var jsonFlag2 = { json: jsonOption() };
2405
+ function row(file, key, value, known) {
2406
+ const shown = display(key, value, known);
2407
+ return { file, key, value: shown, secret: shown !== value.replaceAll(`
2408
+ `, "\\n").replaceAll("\r", "\\r") || isSecretKey(key) };
2409
+ }
2410
+ function printRows(rows, json, plain) {
2411
+ if (json)
2412
+ printJson(rows);
2413
+ else
2414
+ plain();
2415
+ }
2085
2416
  async function readAll(names) {
2086
2417
  const files = [];
2087
2418
  for (const name of names)
@@ -2089,7 +2420,7 @@ async function readAll(names) {
2089
2420
  return { files, known: await loadKnown(process.cwd(), files.map(([, file]) => file)) };
2090
2421
  }
2091
2422
  async function list(args) {
2092
- const parsed = parse(args, listUsage, {});
2423
+ const parsed = parse(args, listUsage, jsonFlag2);
2093
2424
  const [file] = parsed.positionals;
2094
2425
  const names = file === undefined ? await envFiles() : [file];
2095
2426
  if (names.length === 0)
@@ -2098,14 +2429,16 @@ async function list(args) {
2098
2429
  const { files, known } = await readAll(names);
2099
2430
  for (const [name, file] of files) {
2100
2431
  for (const [key, value] of entries(file))
2101
- rows.push([name, key, display(key, value, known)]);
2432
+ rows.push(row(name, key, value, known));
2102
2433
  }
2103
- if (rows.length > 0)
2104
- console.log(table(rows));
2434
+ printRows(rows, parsed.values.json === true, () => {
2435
+ if (rows.length > 0)
2436
+ console.log(table(rows.map((each) => [each.file, each.key, each.value])));
2437
+ });
2105
2438
  return 0;
2106
2439
  }
2107
2440
  async function get(args) {
2108
- const parsed = parse(args, getUsage, {});
2441
+ const parsed = parse(args, getUsage, jsonFlag2);
2109
2442
  const [key, file] = parsed.positionals;
2110
2443
  if (key === undefined)
2111
2444
  fail(`missing KEY
@@ -2117,26 +2450,30 @@ ${getUsage}`);
2117
2450
  for (const [name, file] of files) {
2118
2451
  const value = entries(file).get(key);
2119
2452
  if (value !== undefined)
2120
- rows.push([name, display(key, value, known)]);
2453
+ rows.push(row(name, key, value, known));
2121
2454
  }
2122
2455
  if (rows.length === 0)
2123
2456
  fail(`${key} is not set in ${file ?? "any .env* file"}`, 1);
2124
- console.log(file === undefined ? table(rows) : rows[0]?.[1]);
2457
+ printRows(rows, parsed.values.json === true, () => console.log(file === undefined ? table(rows.map((each) => [each.file, each.value])) : rows[0]?.value));
2125
2458
  return 0;
2126
2459
  }
2127
2460
  var grepUsage = `ev grep [-i] <regex> [file...]
2128
2461
 
2129
2462
  Prints the keys matching the regular expression, from the folder's .env* files or the files given, with their values masked as ev list does. The regex is matched against the key only, never the value: \`ev grep '^DATABASE_'\` instead of \`grep ^DATABASE_ .env\`.
2130
2463
 
2464
+ --json prints [{file, key, value, secret}].
2465
+
2131
2466
  Exits 0 when a key matches, 1 when none does, 2 on a usage error.`;
2132
2467
  var showUsage = `ev show <rev>:<file>
2133
2468
 
2134
2469
  Prints every key of an env file as a git revision holds it, values masked as ev list does: \`ev show HEAD~1:api/.env\` instead of \`git show HEAD~1:api/.env\`.
2135
2470
 
2471
+ --json prints [{file, key, value, secret}].
2472
+
2136
2473
  Exits 0 when it printed them, 1 when git cannot show the file, 2 on a usage error.`;
2137
2474
  var REVISION = /^([^:]+):(.+)$/;
2138
2475
  async function grep(args) {
2139
- const parsed = parse(args, grepUsage, { "ignore-case": { type: "boolean", short: "i", description: "match the key whatever its case" } });
2476
+ const parsed = parse(args, grepUsage, { "ignore-case": { type: "boolean", short: "i", description: "match the key whatever its case" }, ...jsonFlag2 });
2140
2477
  const [source, ...given] = parsed.positionals;
2141
2478
  if (source === undefined)
2142
2479
  fail(`missing the regex
@@ -2154,16 +2491,16 @@ ${grepUsage}`);
2154
2491
  for (const [name, file] of files) {
2155
2492
  for (const [key, value] of entries(file)) {
2156
2493
  if (pattern.test(key))
2157
- rows.push([name, key, display(key, value, known)]);
2494
+ rows.push(row(name, key, value, known));
2158
2495
  }
2159
2496
  }
2160
2497
  if (rows.length === 0)
2161
2498
  fail(`no key matches ${source} in ${names.join(", ") || "any .env* file"}`, 1);
2162
- console.log(table(rows));
2499
+ printRows(rows, parsed.values.json === true, () => console.log(table(rows.map((each) => [each.file, each.key, each.value]))));
2163
2500
  return 0;
2164
2501
  }
2165
2502
  async function show(args) {
2166
- const parsed = parse(args, showUsage, {});
2503
+ const parsed = parse(args, showUsage, jsonFlag2);
2167
2504
  const [target] = parsed.positionals;
2168
2505
  const [, revision, path] = REVISION.exec(target ?? "") ?? [];
2169
2506
  if (revision === undefined || path === undefined)
@@ -2177,16 +2514,17 @@ ${showUsage}`);
2177
2514
  fail(`git show ${revision}:${path} failed: ${shown.stderr.toString().trim()}`, 1);
2178
2515
  const file = parseDotenv(shown.stdout.toString());
2179
2516
  const known = await loadKnown(process.cwd(), [file]);
2180
- const rows = [...entries(file)].map(([key, value]) => [key, display(key, value, known)]);
2181
- if (rows.length > 0)
2182
- console.log(table(rows));
2517
+ const rows = [...entries(file)].map(([key, value]) => row(target ?? "", key, value, known));
2518
+ printRows(rows, parsed.values.json === true, () => {
2519
+ if (rows.length > 0)
2520
+ console.log(table(rows.map((each) => [each.key, each.value])));
2521
+ });
2183
2522
  return 0;
2184
2523
  }
2185
2524
 
2186
2525
  // src/ev.ts
2187
- process8.exitCode = await runCli({
2526
+ process11.exitCode = await runCli({
2188
2527
  name: "ev",
2189
- version,
2190
2528
  about: ".env files listed and edited with secrets masked",
2191
2529
  replaces: "cat .env, grep on env files and editing them by hand",
2192
2530
  examples: ["ev list", ["ev get DATABASE_URL", "one key, its value masked"]],