@kaynooo/cli-env 0.13.1 → 0.14.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,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/ev.ts
5
- import process17 from "process";
5
+ import process22 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process10 from "process";
8
8
  import { parseArgs } from "util";
@@ -45,6 +45,9 @@ function outputMode(stream = process2.stdout, env = process2.env) {
45
45
  return "terminal";
46
46
  return isSet(env.CI) ? "ci" : "pipe";
47
47
  }
48
+ function isInteractive(streams = process2) {
49
+ return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
50
+ }
48
51
 
49
52
  // ../kit/src/style.ts
50
53
  import process6 from "process";
@@ -374,6 +377,23 @@ var STATUS_WORDS = {
374
377
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
375
378
 
376
379
  // ../kit/src/format.ts
380
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
381
+ function formatSeconds(total) {
382
+ let rest = Math.max(0, Math.round(total));
383
+ const amounts = UNITS.map(([unit, size]) => {
384
+ const amount = Math.floor(rest / size);
385
+ rest -= amount * size;
386
+ return `${amount}${unit}`;
387
+ });
388
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
389
+ if (first === -1)
390
+ return "0s";
391
+ const next = amounts[first + 1];
392
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
393
+ }
394
+ function formatDuration(ms) {
395
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
396
+ }
377
397
  function upTo(text, separator) {
378
398
  const end = text.indexOf(separator);
379
399
  return end === -1 ? text : text.slice(0, end);
@@ -434,24 +454,20 @@ function printJson(value) {
434
454
 
435
455
  // ../kit/src/help.ts
436
456
  import process8 from "process";
437
- var OPTIONAL = /\[[^\]]+\]/g;
457
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
438
458
  var USAGE_PREFIX = /^usage:\s*/i;
439
459
  var FULL_STOP = /\.$/;
440
460
  function usageLine(usage, colors = paint(process8.stdout)) {
441
461
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
442
462
  }
443
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
444
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
463
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
464
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
445
465
  `);
446
466
  }
447
467
  function exitRows(exits, colors = paint(process8.stdout)) {
448
468
  if (exits.length === 0)
449
469
  return [];
450
- const width = Math.max(...exits.map(([code]) => String(code).length));
451
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
452
- }
453
- function replacesRows(replaces, colors = paint(process8.stdout)) {
454
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
470
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
455
471
  }
456
472
  function wantsHelpJson(env = process8.env) {
457
473
  return env.KIT_HELP === "json";
@@ -477,29 +493,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
477
493
  return [];
478
494
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
479
495
  }
496
+ var MAX_INLINE_CHOICES = 24;
480
497
  function optionRows(options, colors = paint(process8.stdout)) {
481
498
  const rows = Object.entries(options).map(([name, option]) => {
482
499
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
483
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
500
+ const choices = option.choices?.join("|");
501
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
502
+ const named = inline ? `<${choices}>` : "<value>";
484
503
  const placeholder = option.optional === undefined ? named : `[${named}]`;
485
504
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
486
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
505
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
506
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
487
507
  });
488
508
  const width = Math.max(0, ...rows.map((row) => row.width));
489
509
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
490
510
  }
491
511
 
492
512
  // ../kit/src/text.ts
493
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
494
513
  function distance(a, b) {
495
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
496
- for (const [i, left] of [...a].entries()) {
514
+ const left = [...a];
515
+ const right = [...b];
516
+ let before = [];
517
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
518
+ for (const [i, x] of left.entries()) {
497
519
  const current = [i + 1];
498
- for (const [j, right] of [...b].entries())
499
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
520
+ for (const [j, y] of right.entries()) {
521
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
522
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
523
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
524
+ current.push(cost);
525
+ }
526
+ before = previous;
500
527
  previous = current;
501
528
  }
502
- return previous[b.length] ?? 0;
529
+ return previous[right.length] ?? 0;
503
530
  }
504
531
  function closest(name, names) {
505
532
  const started = names.find((known) => known.startsWith(name));
@@ -739,21 +766,63 @@ function nearestOption(message, options, allowNegative) {
739
766
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
740
767
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
741
768
  }
769
+ // ../kit/src/argv.ts
770
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
771
+ import { resolve as resolve3 } from "path";
772
+ import process11 from "process";
773
+ function commandLine() {
774
+ try {
775
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
776
+ } catch {
777
+ return;
778
+ }
779
+ }
780
+ function realPath(word) {
781
+ try {
782
+ return realpathSync(resolve3(word));
783
+ } catch {
784
+ return;
785
+ }
786
+ }
787
+ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
788
+ const target = script === undefined ? undefined : realPath(script) ?? script;
789
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
790
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
791
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
792
+ }
742
793
  // ../kit/src/progress.ts
743
794
  var ESC = String.fromCharCode(27);
744
795
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
745
796
  var RESET_STYLE = `${ESC}[0m`;
746
797
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
747
798
  // ../kit/src/cli.ts
748
- import { readFileSync as readFileSync3, realpathSync } from "fs";
799
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
749
800
  import { dirname as dirname3, join as join5 } from "path";
801
+ import process14 from "process";
802
+
803
+ // ../kit/src/notify.ts
750
804
  import process12 from "process";
805
+ var NOTIFY_AFTER_MS = 1e4;
806
+ var CANCELLED = 130;
807
+ function base64(text) {
808
+ return Buffer.from(text).toString("base64");
809
+ }
810
+ function notification(title, body, env = process12.env) {
811
+ const id = `kit${process12.pid}`;
812
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
813
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
814
+ }
815
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
816
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
817
+ return;
818
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
819
+ }
751
820
 
752
821
  // ../kit/src/usage.ts
753
822
  import { appendFileSync, mkdirSync } from "fs";
754
823
  import { homedir as homedir3 } from "os";
755
824
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
756
- import process11 from "process";
825
+ import process13 from "process";
757
826
 
758
827
  // ../kit/src/logs.ts
759
828
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -767,14 +836,14 @@ var usageError;
767
836
  function noteUsageError(message) {
768
837
  usageError = message;
769
838
  }
770
- function stateHome(env = process11.env) {
839
+ function stateHome(env = process13.env) {
771
840
  const dir = env.XDG_STATE_HOME;
772
841
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
773
842
  }
774
- function usagePath(env = process11.env) {
843
+ function usagePath(env = process13.env) {
775
844
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
776
845
  }
777
- function usageRecorded(env = process11.env) {
846
+ function usageRecorded(env = process13.env) {
778
847
  const off = env.KAYNOOO_CLI_NO_USAGE;
779
848
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
780
849
  }
@@ -788,7 +857,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
788
857
  usageError = undefined;
789
858
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
790
859
  }
791
- function recordUsage(entry, env = process11.env) {
860
+ function recordUsage(entry, env = process13.env) {
792
861
  if (!usageRecorded(env))
793
862
  return;
794
863
  try {
@@ -865,7 +934,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
865
934
  header(colors, summary),
866
935
  "",
867
936
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
868
- ...replacesRows(replaces, colors),
869
937
  "",
870
938
  ...await commandRows(commands, colors),
871
939
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -879,8 +947,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
879
947
  `);
880
948
  }
881
949
  function printError(prefix, message, hint, cause) {
882
- const colors = paint(process12.stderr);
883
- const styled = takesControlCodes(process12.stderr);
950
+ const colors = paint(process14.stderr);
951
+ const styled = takesControlCodes(process14.stderr);
884
952
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
885
953
  const under = (label, text, tint) => text === undefined ? "" : `
886
954
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -923,11 +991,11 @@ async function dispatch(level, typed, { version, redact }) {
923
991
  }
924
992
  }
925
993
  if (name === undefined && level.path.length > 1) {
926
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
994
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
927
995
  return 2;
928
996
  }
929
997
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
930
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
998
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
931
999
  return 0;
932
1000
  }
933
1001
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -983,24 +1051,24 @@ function candidateLine(candidate) {
983
1051
  }
984
1052
  function positionalBeingTyped(before, { options, positionals }) {
985
1053
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
986
- let index = 0;
1054
+ const typed = [];
987
1055
  let at = 0;
988
1056
  while (at < before.length) {
989
1057
  const word = before[at];
990
1058
  if (word === "--") {
991
- index += before.length - at - 1;
1059
+ typed.push(...before.slice(at + 1));
992
1060
  break;
993
1061
  }
994
1062
  if (!word.startsWith("-"))
995
- index++;
1063
+ typed.push(word);
996
1064
  else if (takesValue(word))
997
1065
  at++;
998
1066
  at++;
999
1067
  }
1000
1068
  const last = positionals.at(-1);
1001
- if (index < positionals.length)
1002
- return positionals[index];
1003
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1069
+ if (typed.length < positionals.length)
1070
+ return { name: positionals[typed.length], typed };
1071
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1004
1072
  }
1005
1073
  async function leafCandidates(run, words) {
1006
1074
  const completing = await completingOf(run);
@@ -1008,12 +1076,12 @@ async function leafCandidates(run, words) {
1008
1076
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1009
1077
  const flag = words.at(-2);
1010
1078
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1079
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1011
1080
  if (option?.type === "string") {
1012
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1081
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1013
1082
  return values === undefined ? [FILES] : values.map(candidateLine);
1014
1083
  }
1015
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1016
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1084
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1017
1085
  return values === undefined ? [FILES] : values.map(candidateLine);
1018
1086
  }
1019
1087
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1044,9 +1112,13 @@ async function printCandidates(found) {
1044
1112
  return 0;
1045
1113
  }
1046
1114
  function packageVersion(entry = Bun.main) {
1047
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1115
+ let resolved = entry;
1116
+ try {
1117
+ resolved = realpathSync2(entry);
1118
+ } catch {}
1119
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1048
1120
  try {
1049
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1121
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1050
1122
  if (typeof version === "string")
1051
1123
  return version;
1052
1124
  } catch {}
@@ -1054,14 +1126,17 @@ function packageVersion(entry = Bun.main) {
1054
1126
  return "0.0.0";
1055
1127
  }
1056
1128
  }
1057
- async function runCli(cli, argv = process12.argv.slice(2)) {
1129
+ async function runCli(cli, argv = scriptArgs()) {
1058
1130
  const version = cli.version ?? packageVersion();
1059
1131
  if (argv[0] === COMPLETE)
1060
1132
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1133
+ const started = performance.now();
1061
1134
  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 });
1135
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1136
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1062
1137
  if (cli.usage !== false) {
1063
1138
  try {
1064
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1139
+ recordUsage(usageEntry(cli.name, command, argv, code));
1065
1140
  } catch {}
1066
1141
  }
1067
1142
  return code;
@@ -1081,7 +1156,7 @@ function commandPath(scope, argv) {
1081
1156
  }
1082
1157
  return path.length === 0 ? undefined : path.join(" ");
1083
1158
  }
1084
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1159
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1085
1160
  if (argv[0] === COMPLETE)
1086
1161
  return printCandidates(leafCandidates(run, argv.slice(1)));
1087
1162
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1089,11 +1164,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process12.a
1089
1164
  return 0;
1090
1165
  }
1091
1166
  let code;
1167
+ const started = performance.now();
1092
1168
  try {
1093
1169
  code = await run(argv);
1094
1170
  } catch (error) {
1095
1171
  code = reportThrown(name, error, redact, wantsJson(argv));
1096
1172
  }
1173
+ notifyEnd(name, code, performance.now() - started);
1097
1174
  if (usage !== false) {
1098
1175
  try {
1099
1176
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1111,12 +1188,18 @@ async function compose(args, { flags = [], ...options } = {}) {
1111
1188
  return captureOutput(["docker", "compose", ...flags, ...args], options);
1112
1189
  }
1113
1190
  // ../kit/src/folders.ts
1191
+ import { homedir as homedir4 } from "os";
1192
+ import { join as join6 } from "path";
1193
+ import process15 from "process";
1114
1194
  var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1115
1195
  function ignoredFolders(extra = [], where = {}) {
1116
1196
  const configured = readUserConfig("config", where).ignore;
1117
1197
  const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1118
1198
  return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1119
1199
  }
1200
+ function cacheFolder({ home = homedir4(), env = process15.env } = {}) {
1201
+ return env.XDG_CACHE_HOME ?? join6(home, ".cache");
1202
+ }
1120
1203
  // ../kit/src/secrets.ts
1121
1204
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
1122
1205
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -1130,8 +1213,8 @@ var SESSION_FILES = new Glob("*.json");
1130
1213
  var ACCOUNT_DIRS = new Glob("*/sessions");
1131
1214
  // src/commands/audit.ts
1132
1215
  import { stat as stat4 } from "fs/promises";
1133
- import { relative, resolve as resolve3 } from "path";
1134
- import process14 from "process";
1216
+ import { relative, resolve as resolve4 } from "path";
1217
+ import process17 from "process";
1135
1218
 
1136
1219
  // ../kit/src/shell.ts
1137
1220
  var SEPARATORS = new Set([`
@@ -1182,12 +1265,12 @@ function shellQuote(word) {
1182
1265
 
1183
1266
  // src/audit.ts
1184
1267
  import { readdir as readdir2, stat as stat2 } from "fs/promises";
1185
- import { dirname as dirname5, join as join7 } from "path";
1268
+ import { dirname as dirname5, join as join8 } from "path";
1186
1269
  var {$ } = globalThis.Bun;
1187
1270
 
1188
1271
  // src/files.ts
1189
1272
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
1190
- import { basename, dirname as dirname4, join as join6 } from "path";
1273
+ import { basename, dirname as dirname4, join as join7 } from "path";
1191
1274
 
1192
1275
  // src/dotenv.ts
1193
1276
  var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
@@ -1245,7 +1328,8 @@ function parseDotenv(text) {
1245
1328
  let body = start.slice(1);
1246
1329
  let raw = line;
1247
1330
  let end = closingQuote(body, quote);
1248
- while (end === -1 && index + 1 < physical.length) {
1331
+ const first = index;
1332
+ while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
1249
1333
  index++;
1250
1334
  body += `
1251
1335
  ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
@@ -1253,6 +1337,11 @@ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1253
1337
  ${physical[index] ?? ""}`;
1254
1338
  end = closingQuote(body, quote);
1255
1339
  }
1340
+ if (end === -1 && index + 1 < physical.length) {
1341
+ index = first;
1342
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()), unterminated: true });
1343
+ continue;
1344
+ }
1256
1345
  const inner = end === -1 ? body : body.slice(0, end);
1257
1346
  lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1258
1347
  }
@@ -1318,9 +1407,30 @@ var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
1318
1407
  function isPlaceholder(value) {
1319
1408
  return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
1320
1409
  }
1410
+ var STRONG_NAME = "password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key";
1411
+ var WEAK_NAME = "token|credentials?|auth";
1412
+ var PLAIN_WORD = /^[a-z]+$/i;
1413
+ var AFTER_COLON = /:\s*$/;
1414
+ var DIGIT = /\d/;
1415
+ var KEY_VALUE_GAP = "\\s*[:=]\\s*";
1416
+ function isProse(value, before) {
1417
+ return isPlaceholder(value) || AFTER_COLON.test(before) && PLAIN_WORD.test(value);
1418
+ }
1419
+ function isWeak(value, before) {
1420
+ return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
1421
+ }
1422
+ function keyed(names, value) {
1423
+ return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
1424
+ }
1321
1425
  var TOKEN_FORMATS = [
1322
1426
  { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
1323
- { kind: "GitLab token", pattern: /\bglpat-[\w-]{20,}/dg },
1427
+ { kind: "GitLab token", pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
1428
+ { kind: "Hugging Face token", pattern: /\bhf_[A-Za-z]{30,}/dg },
1429
+ { kind: "webhook secret", pattern: /\bwhsec_\w{20,}/dg },
1430
+ { kind: "DigitalOcean token", pattern: /\bdop_v1_\w{20,}/dg },
1431
+ { kind: "Shopify token", pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
1432
+ { kind: "password", pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
1433
+ { kind: "password", pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
1324
1434
  { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
1325
1435
  { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
1326
1436
  { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
@@ -1331,8 +1441,10 @@ var TOKEN_FORMATS = [
1331
1441
  { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
1332
1442
  { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
1333
1443
  { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
1334
- { kind: "password", pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
1335
- { kind: "password", pattern: /(?<![\w-])["']?(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?["']?\s*[:=]\s*(["'])((?:\\.|(?!\1)[^\\\n]){4,})\1/dgi, skip: isPlaceholder }
1444
+ { kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
1445
+ { kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
1446
+ { kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isPlaceholder },
1447
+ { kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isWeak }
1336
1448
  ];
1337
1449
  var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1338
1450
  var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
@@ -1437,7 +1549,7 @@ function findSecrets(line, known) {
1437
1549
  if (start === undefined || end === undefined)
1438
1550
  continue;
1439
1551
  const value = line.slice(start, end);
1440
- if (!skip?.(value))
1552
+ if (!skip?.(value, line.slice(0, start)))
1441
1553
  found.push({ start, end, kind, mask: hint(value) });
1442
1554
  }
1443
1555
  }
@@ -1499,7 +1611,7 @@ async function envFiles(folder = process.cwd()) {
1499
1611
  const found = await readdir(folder, { withFileTypes: true });
1500
1612
  const names = [];
1501
1613
  for (const entry of found) {
1502
- if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join6(folder, entry.name)))
1614
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join7(folder, entry.name)))
1503
1615
  names.push(entry.name);
1504
1616
  }
1505
1617
  return names.sort();
@@ -1523,7 +1635,7 @@ async function writeAtomic(path, text) {
1523
1635
  if (error.code !== "ENOENT")
1524
1636
  throw error;
1525
1637
  }
1526
- const temp = join6(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1638
+ const temp = join7(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1527
1639
  try {
1528
1640
  await writeFile(temp, text, { mode: 384, flag: "wx" });
1529
1641
  if (owner !== undefined)
@@ -1579,7 +1691,7 @@ async function acquire(path) {
1579
1691
  try {
1580
1692
  real = await realpath(path);
1581
1693
  } catch {}
1582
- const lock = join6(dirname4(real), `.${basename(real)}.lock`);
1694
+ const lock = join7(dirname4(real), `.${basename(real)}.lock`);
1583
1695
  const deadline = Date.now() + LOCK_WAIT_MS;
1584
1696
  while (true) {
1585
1697
  try {
@@ -1614,7 +1726,7 @@ async function envFilesBelow(folder, depth = 0) {
1614
1726
  return found;
1615
1727
  }
1616
1728
  for (const entry of children) {
1617
- const path = join6(folder, entry.name);
1729
+ const path = join7(folder, entry.name);
1618
1730
  if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1619
1731
  found.push(...await envFilesBelow(path, depth + 1));
1620
1732
  else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
@@ -1705,7 +1817,7 @@ async function* candidates2(root, unread, depth = 0) {
1705
1817
  return;
1706
1818
  }
1707
1819
  for (const entry of found) {
1708
- const path = join7(root, entry.name);
1820
+ const path = join8(root, entry.name);
1709
1821
  if (entry.isDirectory() && depth < MAX_DEPTH && !SKIPPED.has(entry.name))
1710
1822
  yield* candidates2(path, unread, depth + 1);
1711
1823
  else if (!TEMPLATE.test(entry.name) && (ENV_FILE.test(entry.name) || COMPOSE_FILE.test(entry.name)) && await isFileEntry(entry, path))
@@ -1737,7 +1849,7 @@ async function audit(roots) {
1737
1849
 
1738
1850
  // src/fix.ts
1739
1851
  import { chmod as chmod2, chown as chown2, lstat, rm as rm2, stat as stat3 } from "fs/promises";
1740
- import { dirname as dirname6, join as join8 } from "path";
1852
+ import { dirname as dirname6, join as join9 } from "path";
1741
1853
  var MAP_ENTRY = /^(\s*)(["']?)([A-Z0-9_]+)\2(\s*:)(.*)$/;
1742
1854
  var LIST_ENTRY = /^(\s*-[ \t]*)(["']?)([A-Z0-9_]+)=(.*)$/;
1743
1855
  var TRAILING = /^\s*(?:#.*)?$/;
@@ -1830,7 +1942,7 @@ async function shutOthersOut(path, group = false) {
1830
1942
  }
1831
1943
  }
1832
1944
  async function fixCompose(path, group = false) {
1833
- const env = join8(dirname6(path), ".env");
1945
+ const env = join9(dirname6(path), ".env");
1834
1946
  const compose = await Bun.file(path).text();
1835
1947
  const envBefore = await Bun.file(env).exists() ? await Bun.file(env).text() : undefined;
1836
1948
  const dotenv = parseDotenv(envBefore ?? "");
@@ -1927,8 +2039,8 @@ var usage2 = `ev audit [dir...] [--fix]
1927
2039
 
1928
2040
  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.
1929
2041
  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.
1930
- With --fix, moves each secret a listed compose file writes out into the .env beside it as \${KEY}, puts it back when \`docker compose config\` resolves differently after, and shuts other accounts out of both files and of every listed .env; a key the .env already sets to another value stays put.
1931
- Exits 0 when it finds none (with --fix, when none is left), 1 when it finds one, 2 on a usage error.`;
2042
+ With --fix, moves each secret a listed compose file writes out into the .env beside it as \${KEY}, puts it back when \`docker compose config\` resolves differently after, and shuts other accounts out of both files and of every listed .env; a key the .env already sets to another value stays put.`;
2043
+ var EXITS = [[0, "it finds none (with --fix, when none is left)"], [1, "it finds one"], [2, "a usage error"]];
1932
2044
  var options = {
1933
2045
  json: jsonOption("the findings and the folders it could not read"),
1934
2046
  fix: { type: "boolean", description: "move inline compose secrets into a .env and shut other accounts out" }
@@ -1948,12 +2060,12 @@ async function isFolder(path) {
1948
2060
  }
1949
2061
  }
1950
2062
  function shown2(path) {
1951
- return path.startsWith(`${process14.cwd()}/`) ? relative(process14.cwd(), path) : path;
2063
+ return path.startsWith(`${process17.cwd()}/`) ? relative(process17.cwd(), path) : path;
1952
2064
  }
1953
2065
  async function fixAll(exposed, json) {
1954
2066
  const fixed = [];
1955
2067
  let left = false;
1956
- const tint = role("path", process14.stdout);
2068
+ const tint = role("path", process17.stdout);
1957
2069
  for (const { path, readable, group, tracked, secrets } of exposed) {
1958
2070
  const fix = secrets === undefined ? undefined : await fixCompose(path, group === true);
1959
2071
  const open = fix?.open ?? (readable && !await shutOthersOut(path, group === true) ? [path] : []);
@@ -1977,8 +2089,8 @@ async function fixAll(exposed, json) {
1977
2089
  return { fixed, left };
1978
2090
  }
1979
2091
  async function audit2(args) {
1980
- const parsed = parse(args, usage2, options);
1981
- const roots = (parsed.positionals.length > 0 ? parsed.positionals : ["."]).map((dir) => resolve3(dir));
2092
+ const parsed = parse(args, usage2, options, { exits: EXITS });
2093
+ const roots = (parsed.positionals.length > 0 ? parsed.positionals : ["."]).map((dir) => resolve4(dir));
1982
2094
  for (const dir of roots) {
1983
2095
  if (!await isFolder(dir))
1984
2096
  fail(`${dir} is not a folder`);
@@ -2005,8 +2117,8 @@ async function audit2(args) {
2005
2117
  console.log("no exposed .env file nor compose file writing a secret out");
2006
2118
  return 0;
2007
2119
  }
2008
- const uid = process14.getuid?.();
2009
- const tint = role("path", process14.stdout);
2120
+ const uid = process17.getuid?.();
2121
+ const tint = role("path", process17.stdout);
2010
2122
  for (const { path, readable, group, tracked, secrets } of exposed) {
2011
2123
  const sudo = uid !== undefined && uid !== 0 && (await stat4(path)).uid !== uid ? "sudo " : "";
2012
2124
  const problems = [
@@ -2022,27 +2134,25 @@ async function audit2(args) {
2022
2134
  }
2023
2135
 
2024
2136
  // src/commands/compare.ts
2025
- import process15 from "process";
2137
+ import process18 from "process";
2026
2138
  var diffUsage = `ev diff <a> <b>
2027
2139
 
2028
2140
  Names the keys set in one file and not the other, never their values.
2029
2141
 
2030
- --json prints {a, b, onlyA, onlyB}.
2031
-
2032
- Exits 0 when both set the same keys, 1 when they differ, 2 on a usage error.`;
2142
+ --json prints {a, b, onlyA, onlyB}.`;
2143
+ var DIFF_EXITS = [[0, "both set the same keys"], [1, "they differ"], [2, "a usage error"]];
2033
2144
  var missingUsage = `ev missing [file]
2034
2145
 
2035
2146
  Names the keys the reference file sets that the file (.env by default) does not.
2036
2147
 
2037
- --json prints {a, b, onlyA, onlyB} with the reference as a, so onlyA is what is missing.
2038
-
2039
- Exits 0 when none is missing, 1 when some are, 2 on a usage error.`;
2148
+ --json prints {a, b, onlyA, onlyB} with the reference as a, so onlyA is what is missing.`;
2149
+ var MISSING_EXITS = [[0, "none is missing"], [1, "some are"], [2, "a usage error"]];
2040
2150
  var jsonFlag = { json: jsonOption() };
2041
2151
  async function keys(path) {
2042
2152
  return new Set(entries(await readEnv(path)).keys());
2043
2153
  }
2044
2154
  async function diff(args) {
2045
- const parsed = parse(args, diffUsage, jsonFlag);
2155
+ const parsed = parse(args, diffUsage, jsonFlag, { exits: DIFF_EXITS });
2046
2156
  const [a, b] = parsed.positionals;
2047
2157
  if (a === undefined || b === undefined)
2048
2158
  fail(`needs two files
@@ -2056,8 +2166,8 @@ ${diffUsage}`);
2056
2166
  printJson({ a, b, onlyA, onlyB });
2057
2167
  return onlyA.length + onlyB.length === 0 ? 0 : 1;
2058
2168
  }
2059
- const path = role("path", process15.stdout);
2060
- const value = role("value", process15.stdout);
2169
+ const path = role("path", process18.stdout);
2170
+ const value = role("value", process18.stdout);
2061
2171
  const lines = [...onlyA.map((key) => `only in ${path(a)}: ${value(key)}`), ...onlyB.map((key) => `only in ${path(b)}: ${value(key)}`)];
2062
2172
  if (lines.length === 0)
2063
2173
  return 0;
@@ -2066,7 +2176,7 @@ ${diffUsage}`);
2066
2176
  return 1;
2067
2177
  }
2068
2178
  async function missing(args) {
2069
- const parsed = parse(args, missingUsage, { against: { type: "string", description: "the reference file (.env.example by default)" }, ...jsonFlag });
2179
+ const parsed = parse(args, missingUsage, { against: { type: "string", description: "the reference file (.env.example by default)" }, ...jsonFlag }, { exits: MISSING_EXITS });
2070
2180
  const [file = ".env"] = parsed.positionals;
2071
2181
  const against = parsed.values.against ?? ".env.example";
2072
2182
  const have = await keys(file);
@@ -2078,13 +2188,417 @@ async function missing(args) {
2078
2188
  }
2079
2189
  if (absent.length === 0)
2080
2190
  return 0;
2081
- const path = role("path", process15.stdout);
2082
- const value = role("value", process15.stdout);
2191
+ const path = role("path", process18.stdout);
2192
+ const value = role("value", process18.stdout);
2083
2193
  console.log(absent.map((key) => `${value(key)} (set in ${path(against)}, not in ${path(file)})`).join(`
2084
2194
  `));
2085
2195
  return 1;
2086
2196
  }
2087
2197
 
2198
+ // ../kit/src/prompt.ts
2199
+ import process20 from "process";
2200
+
2201
+ // ../kit/src/answers.ts
2202
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync } from "fs";
2203
+ import { dirname as dirname7, join as join10 } from "path";
2204
+ var KEPT = 50;
2205
+ function answersFile() {
2206
+ return join10(cacheFolder(), "kaynooo-cli", "answers.json");
2207
+ }
2208
+ function stored() {
2209
+ try {
2210
+ const parsed = JSON.parse(readFileSync5(answersFile(), "utf-8"));
2211
+ if (typeof parsed !== "object" || parsed === null)
2212
+ return {};
2213
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
2214
+ } catch {
2215
+ return {};
2216
+ }
2217
+ }
2218
+ function earlierAnswers(key) {
2219
+ return stored()[key] ?? [];
2220
+ }
2221
+ function rememberAnswer(key, answer) {
2222
+ const all = stored();
2223
+ const file = answersFile();
2224
+ all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
2225
+ try {
2226
+ mkdirSync2(dirname7(file), { recursive: true });
2227
+ writeFileSync(file, JSON.stringify(all));
2228
+ } catch {}
2229
+ }
2230
+
2231
+ // ../kit/src/job.ts
2232
+ import process19 from "process";
2233
+ function stopJob() {
2234
+ process19.kill(0, "SIGTSTP");
2235
+ }
2236
+
2237
+ // ../kit/src/picker/line.ts
2238
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
2239
+ var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
2240
+ var FORWARD_KILLS = new Set(["killnext", "killend"]);
2241
+ function isEditKey(key) {
2242
+ return EDIT_KEYS.has(key);
2243
+ }
2244
+ function endsKills(key) {
2245
+ return typeof key !== "object" && !isEditKey(key);
2246
+ }
2247
+ var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
2248
+ var SPACE = /\s/;
2249
+ function isWord(char) {
2250
+ return char !== undefined && WORD_CHARACTER.test(char);
2251
+ }
2252
+ function wordStart(chars, from) {
2253
+ let at = from;
2254
+ while (at > 0 && !isWord(chars[at - 1]))
2255
+ at--;
2256
+ while (at > 0 && isWord(chars[at - 1]))
2257
+ at--;
2258
+ return at;
2259
+ }
2260
+ function wordEnd(chars, from) {
2261
+ let at = from;
2262
+ while (at < chars.length && !isWord(chars[at]))
2263
+ at++;
2264
+ while (at < chars.length && isWord(chars[at]))
2265
+ at++;
2266
+ return at;
2267
+ }
2268
+ function spacedStart(chars, from) {
2269
+ let at = from;
2270
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
2271
+ at--;
2272
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
2273
+ at--;
2274
+ return at;
2275
+ }
2276
+ function cut(chars, from, to) {
2277
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
2278
+ }
2279
+ function insert(chars, at, text) {
2280
+ const typed = [...text];
2281
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
2282
+ }
2283
+ function editLine(line, key) {
2284
+ const { killed = "", chained = false } = line;
2285
+ const chars = [...line.text];
2286
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
2287
+ const edited = edit(chars, at, key, killed);
2288
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
2289
+ return line.killed === undefined ? edited : { ...edited, killed };
2290
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
2291
+ if (taken === "")
2292
+ return { ...edited, killed, chained };
2293
+ if (!chained)
2294
+ return { ...edited, killed: taken, chained: true };
2295
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
2296
+ }
2297
+ function edit(chars, at, key, killed) {
2298
+ const text = chars.join("");
2299
+ if (typeof key === "object")
2300
+ return insert(chars, at, key.text);
2301
+ switch (key) {
2302
+ case "left":
2303
+ return { text, caret: Math.max(at - 1, 0) };
2304
+ case "right":
2305
+ return { text, caret: Math.min(at + 1, chars.length) };
2306
+ case "wordleft":
2307
+ return { text, caret: wordStart(chars, at) };
2308
+ case "wordright":
2309
+ return { text, caret: wordEnd(chars, at) };
2310
+ case "linestart":
2311
+ return { text, caret: 0 };
2312
+ case "lineend":
2313
+ return { text, caret: chars.length };
2314
+ case "erase":
2315
+ return cut(chars, Math.max(at - 1, 0), at);
2316
+ case "delete":
2317
+ return cut(chars, at, Math.min(at + 1, chars.length));
2318
+ case "word":
2319
+ return cut(chars, spacedStart(chars, at), at);
2320
+ case "killword":
2321
+ return cut(chars, wordStart(chars, at), at);
2322
+ case "killnext":
2323
+ return cut(chars, at, wordEnd(chars, at));
2324
+ case "clear":
2325
+ return cut(chars, 0, at);
2326
+ case "killend":
2327
+ return cut(chars, at, chars.length);
2328
+ case "yank":
2329
+ return insert(chars, at, killed);
2330
+ }
2331
+ }
2332
+ function visible({ text, caret }, room) {
2333
+ const chars = [...text];
2334
+ const at = Math.min(Math.max(caret, 0), chars.length);
2335
+ const cells = at === chars.length ? [...chars, " "] : chars;
2336
+ const widths = cells.map((char) => Bun.stringWidth(char));
2337
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
2338
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
2339
+ let start = at;
2340
+ let end = at + 1;
2341
+ while (start > 0 && fits(start - 1, end))
2342
+ start--;
2343
+ while (end < cells.length && fits(start, end + 1))
2344
+ end++;
2345
+ const left = start > 0 ? "\u2026" : "";
2346
+ const right = end < cells.length ? "\u2026" : "";
2347
+ return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
2348
+ }
2349
+
2350
+ // ../kit/src/picker/score.ts
2351
+ var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
2352
+ var NONE = Number.NEGATIVE_INFINITY;
2353
+
2354
+ // ../kit/src/picker/state.ts
2355
+ var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
2356
+ var PASTE_START = "\x1B[200~";
2357
+ var PASTE_END = "\x1B[201~";
2358
+ var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
2359
+ var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
2360
+ var WHEEL_LINES = 3;
2361
+ var KEYS = {
2362
+ "\x1B[A": "up",
2363
+ "\x1BOA": "up",
2364
+ "\x10": "up",
2365
+ "\x1B[B": "down",
2366
+ "\x1BOB": "down",
2367
+ "\x0E": "down",
2368
+ "\x1B[5~": "pageup",
2369
+ "\x1B[6~": "pagedown",
2370
+ "\x1B[H": "home",
2371
+ "\x1B[1~": "home",
2372
+ "\x1BOH": "home",
2373
+ "\x1B[F": "end",
2374
+ "\x1B[4~": "end",
2375
+ "\x1BOF": "end",
2376
+ "\r": "enter",
2377
+ "\n": "enter",
2378
+ "\x03": "cancel",
2379
+ "\x1B": "cancel",
2380
+ "\x1B[D": "left",
2381
+ "\x1BOD": "left",
2382
+ "\x1B[C": "right",
2383
+ "\x1BOC": "right",
2384
+ "\x1B[1;5D": "wordleft",
2385
+ "\x1B[1;3D": "wordleft",
2386
+ "\x1Bb": "wordleft",
2387
+ "\x1B[1;5C": "wordright",
2388
+ "\x1B[1;3C": "wordright",
2389
+ "\x1Bf": "wordright",
2390
+ "\x01": "linestart",
2391
+ "\x05": "lineend",
2392
+ "\x7F": "erase",
2393
+ "\x1B[3~": "delete",
2394
+ "\b": "killword",
2395
+ "\x1B\x7F": "killword",
2396
+ "\x1B[3;5~": "killnext",
2397
+ "\x1Bd": "killnext",
2398
+ "\x15": "clear",
2399
+ "\v": "killend",
2400
+ "\x17": "word",
2401
+ "\x19": "yank",
2402
+ "\x1A": "suspend",
2403
+ "\t": "tab",
2404
+ "\x1F": "help",
2405
+ "\x1BOP": "help",
2406
+ "\x1B[11~": "help"
2407
+ };
2408
+ function repeat(value, count) {
2409
+ return Array.from({ length: count }).fill(value);
2410
+ }
2411
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
2412
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
2413
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
2414
+ const wheel = MOUSE.exec(sequence)?.[1];
2415
+ if (wheel !== undefined)
2416
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
2417
+ const named = codes.get(sequence);
2418
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
2419
+ if (sequence === PASTE_START || sequence === PASTE_END) {
2420
+ paste.active = sequence === PASTE_START;
2421
+ return [];
2422
+ }
2423
+ if (paste.active && (sequence === "\r" || sequence === `
2424
+ `))
2425
+ return [];
2426
+ if (key !== undefined)
2427
+ return [key];
2428
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
2429
+ });
2430
+ }
2431
+
2432
+ // ../kit/src/redraw.ts
2433
+ var SYNC_START = "\x1B[?2026h";
2434
+ var SYNC_END = "\x1B[?2026l";
2435
+ function overwrite(lines, columns) {
2436
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
2437
+ `);
2438
+ }
2439
+ function rowsTaken(lines, columns) {
2440
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
2441
+ }
2442
+
2443
+ // ../kit/src/prompt.ts
2444
+ var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
2445
+ var MAX_LISTED = 12;
2446
+ function readKeys(input, paste = { active: false }) {
2447
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
2448
+ }
2449
+ function roomAfter(question, columns) {
2450
+ return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
2451
+ }
2452
+ function withCaret(colors, line, room, dim = false) {
2453
+ const { before, at, after } = visible(line, room);
2454
+ const tone = dim ? colors.dim : (text) => text;
2455
+ return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
2456
+ }
2457
+ function sharedStart(texts) {
2458
+ const [first = [], ...rest] = texts.map((text) => [...text]);
2459
+ let length = first.length;
2460
+ for (const chars of rest) {
2461
+ const differs = chars.findIndex((char, index) => char !== first[index]);
2462
+ length = Math.min(length, differs === -1 ? chars.length : differs);
2463
+ }
2464
+ return first.slice(0, length).join("");
2465
+ }
2466
+ function listed2(colors, found, columns) {
2467
+ const shared = sharedStart(found);
2468
+ const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
2469
+ const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
2470
+ const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
2471
+ return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
2472
+ }
2473
+ async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
2474
+ let line = { text: "", caret: 0 };
2475
+ let invalid;
2476
+ let completions = [];
2477
+ const remembered = history === undefined || mask ? undefined : history;
2478
+ const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
2479
+ let recalled = -1;
2480
+ let draft = line;
2481
+ const taken = () => line.text === "" ? fallback ?? "" : line.text;
2482
+ const shown = () => mask ? "*".repeat([...taken()].length) : taken();
2483
+ const accepted = await ask(question, settings, (colors, state, { columns }) => {
2484
+ if (state !== "asking")
2485
+ return [answer(colors, question, state, shown())];
2486
+ const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
2487
+ return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
2488
+ }, (key) => {
2489
+ if (key === "cancel")
2490
+ return "cancel";
2491
+ invalid = undefined;
2492
+ completions = [];
2493
+ if (line.chained === true && endsKills(key))
2494
+ line = { ...line, chained: false };
2495
+ if (key === "tab") {
2496
+ const chars = [...line.text];
2497
+ const before = chars.slice(0, line.caret).join("");
2498
+ const found = complete?.(before) ?? [];
2499
+ const filled = sharedStart(found);
2500
+ if ([...filled].length > [...before].length)
2501
+ line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
2502
+ else
2503
+ completions = found;
2504
+ return;
2505
+ }
2506
+ if (key === "enter") {
2507
+ invalid = validate?.(taken());
2508
+ return invalid === undefined ? "enter" : undefined;
2509
+ }
2510
+ if (key === "up" || key === "down") {
2511
+ const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
2512
+ if (recalled === -1)
2513
+ draft = line;
2514
+ recalled = to;
2515
+ const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
2516
+ line = { ...shown, killed: line.killed ?? "" };
2517
+ return;
2518
+ }
2519
+ const edit = { home: "linestart", end: "lineend" }[key] ?? key;
2520
+ if (typeof edit === "object" || isEditKey(edit))
2521
+ line = editLine(line, edit);
2522
+ return;
2523
+ });
2524
+ if (!accepted)
2525
+ return;
2526
+ if (remembered !== undefined && taken() !== "")
2527
+ rememberAnswer(remembered, taken());
2528
+ return taken();
2529
+ }
2530
+ function answer(colors, question, state, picked) {
2531
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
2532
+ }
2533
+ async function ask(question, { hint, terminal = process20 }, render, press) {
2534
+ const { stdin, stderr } = terminal;
2535
+ if (!isInteractive(terminal))
2536
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
2537
+ const colors = paint(stderr);
2538
+ let current = "asking";
2539
+ let outcome;
2540
+ const columns = () => stderr.columns || 80;
2541
+ const draw = (state, last = false) => {
2542
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
2543
+ const rows = rowsTaken(frame, columns());
2544
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
2545
+ current = state;
2546
+ };
2547
+ const redraw = () => draw(current);
2548
+ const paste = { active: false };
2549
+ const stop = terminal.stop ?? (terminal === process20 ? stopJob : undefined);
2550
+ const suspend = () => {
2551
+ if (stop === undefined)
2552
+ return;
2553
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
2554
+ stdin.setRawMode(false);
2555
+ stop();
2556
+ stdin.setRawMode(true);
2557
+ stderr.write("\x1B[?25l\x1B[?2004h");
2558
+ };
2559
+ try {
2560
+ stderr.on?.("resize", redraw);
2561
+ stdin.setRawMode(true);
2562
+ stdin.resume();
2563
+ stderr.write("\x1B[?25l\x1B[?2004h");
2564
+ draw("asking");
2565
+ return await new Promise((resolve) => {
2566
+ function onData(data) {
2567
+ for (const key of readKeys(data.toString(), paste)) {
2568
+ if (key === "suspend") {
2569
+ suspend();
2570
+ continue;
2571
+ }
2572
+ const pressed = press(key);
2573
+ if (pressed !== undefined) {
2574
+ settle(pressed);
2575
+ return;
2576
+ }
2577
+ }
2578
+ draw("asking");
2579
+ }
2580
+ function onEnd() {
2581
+ settle("cancel");
2582
+ }
2583
+ function settle(settled) {
2584
+ outcome = settled;
2585
+ stdin.off("data", onData);
2586
+ stdin.off("end", onEnd);
2587
+ resolve(settled === "enter");
2588
+ }
2589
+ stdin.on("data", onData);
2590
+ stdin.on("end", onEnd);
2591
+ });
2592
+ } finally {
2593
+ stderr.off?.("resize", redraw);
2594
+ draw(outcome ?? "cancel", true);
2595
+ stderr.write(`
2596
+ \x1B[?25h\x1B[?2004l`);
2597
+ stdin.setRawMode(false);
2598
+ stdin.pause();
2599
+ }
2600
+ }
2601
+
2088
2602
  // src/commands/edit.ts
2089
2603
  var DEFAULT_FILE = ".env";
2090
2604
  var TRAILING_NEWLINE = /\r?\n$/;
@@ -2092,29 +2606,25 @@ var KEY_NAME = /^[A-Z_][\w.-]*$/i;
2092
2606
  var QUIET = { quiet: { type: "boolean", short: "q", description: "print nothing on success" } };
2093
2607
  var setUsage = `ev set KEY [file] [--quiet]
2094
2608
 
2095
- Sets KEY in the file (.env by default, created when missing), replacing its line in place or appending one. The value is read from stdin, or from -F <file>, so it never appears in a command line; --empty sets it to an empty value.
2096
-
2097
- Exits 0 when it wrote the key, 1 when it could not, 2 on a usage error.`;
2609
+ Sets KEY in the file (.env by default, created when missing), replacing its line in place or appending one. The value is read from stdin, or from -F <file>, so it never appears in a command line; on a terminal with nothing piped it is asked for, masked as it is typed. --empty sets it to an empty value.`;
2610
+ var SET_EXITS = [[0, "it wrote the key"], [1, "it could not"], [2, "a usage error"], [130, "the prompt was cancelled"]];
2098
2611
  var unsetUsage = `ev unset KEY [file] [--quiet]
2099
2612
 
2100
- Removes every line setting KEY from the file (.env by default), leaving comments and other lines as they are.
2101
-
2102
- Exits 0 when it removed the key, 1 when the file does not set it, 2 on a usage error.`;
2613
+ Removes every line setting KEY from the file (.env by default), leaving comments and other lines as they are.`;
2614
+ var UNSET_EXITS = [[0, "it removed the key"], [1, "the file does not set it"], [2, "a usage error"]];
2103
2615
  var mvUsage = `ev mv KEY --from <file> --to <file> [--quiet]
2104
2616
 
2105
- Moves KEY's line from one file to another, as written. Refuses to replace a key the target already sets unless --force.
2106
-
2107
- Exits 0 when it moved the key, 1 when the source lacks it or the target already sets it, 2 on a usage error.`;
2617
+ Moves KEY's line from one file to another, as written. Refuses to replace a key the target already sets unless --force.`;
2618
+ var MV_EXITS = [[0, "it moved the key"], [1, "the source lacks it or the target already sets it"], [2, "a usage error"]];
2108
2619
  var cpUsage = `ev cp KEY --from <file> --to <file> [--as NEWKEY] [--quiet]
2109
2620
 
2110
- Copies KEY's value from one file to another without printing it, replacing the key's line in the target in place or appending one, and prints the masked result as ev set does. --as stores the copy under another key.
2111
-
2112
- Exits 0 when it copied the key, 1 when the source lacks it, 2 on a usage error.`;
2113
- async function readValue(from) {
2114
- const input = await readInput(from ?? "-", { noStdin: "pipe the value on stdin or give -F <file>, it is never taken from the command line" });
2115
- if (input === "")
2621
+ Copies KEY's value from one file to another without printing it, replacing the key's line in the target in place or appending one, and prints the masked result as ev set does. --as stores the copy under another key.`;
2622
+ var CP_EXITS = [[0, "it copied the key"], [1, "the source lacks it"], [2, "a usage error"]];
2623
+ async function readValue(key, from) {
2624
+ const value = from === undefined && isInteractive() ? await input2(`value of ${key}`, { mask: true }) ?? fail("cancelled, nothing was written", 130) : await readInput(from ?? "-", { noStdin: "pipe the value on stdin or give -F <file>, it is never taken from the command line" });
2625
+ if (value === "")
2116
2626
  fail("the value is empty, nothing was written: --empty sets an empty value");
2117
- return input.replace(TRAILING_NEWLINE, "");
2627
+ return value.replace(TRAILING_NEWLINE, "");
2118
2628
  }
2119
2629
  function checkKey(key) {
2120
2630
  if (!KEY_NAME.test(key))
@@ -2128,7 +2638,7 @@ async function set(args) {
2128
2638
  file: { type: "string", short: "F", description: "read the value from this file instead of stdin" },
2129
2639
  empty: { type: "boolean", description: "set an empty value, reading nothing" },
2130
2640
  ...QUIET
2131
- });
2641
+ }, { exits: SET_EXITS });
2132
2642
  const [key, target = DEFAULT_FILE] = parsed.positionals;
2133
2643
  if (key === undefined)
2134
2644
  fail(`missing KEY
@@ -2137,7 +2647,7 @@ ${setUsage}`);
2137
2647
  if (parsed.values.empty === true && parsed.values.file !== undefined)
2138
2648
  fail("--empty and -F exclude each other");
2139
2649
  checkKey(key);
2140
- const value = parsed.values.empty === true ? "" : await readValue(parsed.values.file);
2650
+ const value = parsed.values.empty === true ? "" : await readValue(key, parsed.values.file);
2141
2651
  const file = await withLocks([target], async () => {
2142
2652
  const current = await readOrEmpty(target);
2143
2653
  setLine(current, key, value);
@@ -2150,7 +2660,7 @@ ${setUsage}`);
2150
2660
  return 0;
2151
2661
  }
2152
2662
  async function unset(args) {
2153
- const parsed = parse(args, unsetUsage, QUIET);
2663
+ const parsed = parse(args, unsetUsage, QUIET, { exits: UNSET_EXITS });
2154
2664
  const [key, target = DEFAULT_FILE] = parsed.positionals;
2155
2665
  if (key === undefined)
2156
2666
  fail(`missing KEY
@@ -2191,7 +2701,7 @@ async function mv(args) {
2191
2701
  to: { type: "string", description: "the file to put KEY in, created when missing" },
2192
2702
  force: { type: "boolean", description: "replace KEY when the target already sets it" },
2193
2703
  ...QUIET
2194
- });
2704
+ }, { exits: MV_EXITS });
2195
2705
  const [key] = parsed.positionals;
2196
2706
  const { from, to, force } = parsed.values;
2197
2707
  if (key === undefined || from === undefined || to === undefined)
@@ -2213,7 +2723,7 @@ async function cp(args) {
2213
2723
  to: { type: "string", description: "the file to put the copy in, created when missing" },
2214
2724
  as: { type: "string", description: "store the copy under this key instead" },
2215
2725
  ...QUIET
2216
- });
2726
+ }, { exits: CP_EXITS });
2217
2727
  const [key] = parsed.positionals;
2218
2728
  const { from, to, as } = parsed.values;
2219
2729
  if (key === undefined || from === undefined || to === undefined)
@@ -2229,11 +2739,11 @@ ${cpUsage}`);
2229
2739
 
2230
2740
  // src/commands/pins.ts
2231
2741
  import { readdir as readdir4, stat as stat5 } from "fs/promises";
2232
- import { join as join10, resolve as resolve4 } from "path";
2742
+ import { join as join12, resolve as resolve5 } from "path";
2233
2743
 
2234
2744
  // src/pins.ts
2235
2745
  import { readdir as readdir3, readFile } from "fs/promises";
2236
- import { join as join9, relative as relative2 } from "path";
2746
+ import { join as join11, relative as relative2 } from "path";
2237
2747
  var OPTIONAL2 = /^\s*([A-Z][A-Z0-9_]*)\s*:\s*s\.Optional\(/gm;
2238
2748
  var REACHING = /(?:URL|URI|TOKEN|KEY|SECRET|PASSWORD|DSN|_HOST)(?:_FILE)?$/;
2239
2749
  var SELF = /(?:^|_)(?:PUBLIC|SITE|BASE|APP)_URL$/;
@@ -2262,7 +2772,7 @@ async function walk(folder, keep) {
2262
2772
  for (const entry of entries) {
2263
2773
  if (SKIPPED.has(entry.name))
2264
2774
  continue;
2265
- const path = join9(folder, entry.name);
2775
+ const path = join11(folder, entry.name);
2266
2776
  if (entry.isDirectory())
2267
2777
  found.push(...await walk(path, keep));
2268
2778
  else if (entry.isFile() && keep(entry.name))
@@ -2273,7 +2783,7 @@ async function walk(folder, keep) {
2273
2783
  async function testFiles(folder) {
2274
2784
  const found = [];
2275
2785
  for (const root of TEST_ROOTS) {
2276
- found.push(...await walk(join9(folder, root), (name) => TEST_FILE.test(name)));
2786
+ found.push(...await walk(join11(folder, root), (name) => TEST_FILE.test(name)));
2277
2787
  }
2278
2788
  return found;
2279
2789
  }
@@ -2341,7 +2851,7 @@ function reachesOutside(name) {
2341
2851
  }
2342
2852
  async function schemaFile(folder) {
2343
2853
  for (const candidate of SCHEMA_CANDIDATES) {
2344
- const path = join9(folder, candidate);
2854
+ const path = join11(folder, candidate);
2345
2855
  if (await exists(path) && (await readFile(path, "utf8")).includes("defineEnv("))
2346
2856
  return path;
2347
2857
  }
@@ -2352,7 +2862,7 @@ async function testEnvKeys(folder) {
2352
2862
  for (const entry of await readdir3(folder, { withFileTypes: true })) {
2353
2863
  if (!entry.isFile() || !ENV_TEST.test(entry.name))
2354
2864
  continue;
2355
- for (const line of parseDotenv(await readFile(join9(folder, entry.name), "utf8")).lines) {
2865
+ for (const line of parseDotenv(await readFile(join11(folder, entry.name), "utf8")).lines) {
2356
2866
  if (line.key !== undefined)
2357
2867
  keys.add(line.key);
2358
2868
  }
@@ -2360,7 +2870,7 @@ async function testEnvKeys(folder) {
2360
2870
  return keys;
2361
2871
  }
2362
2872
  async function pinningPreload(folder) {
2363
- const path = join9(folder, "bunfig.toml");
2873
+ const path = join11(folder, "bunfig.toml");
2364
2874
  if (!await exists(path))
2365
2875
  return;
2366
2876
  let config;
@@ -2371,7 +2881,7 @@ async function pinningPreload(folder) {
2371
2881
  }
2372
2882
  const preloads = [config.test?.preload, config.preload].flat().filter((entry) => typeof entry === "string" && entry.startsWith("."));
2373
2883
  for (const preload of preloads) {
2374
- const file = join9(folder, preload);
2884
+ const file = join11(folder, preload);
2375
2885
  if (!await exists(file))
2376
2886
  continue;
2377
2887
  const source = await readFile(file, "utf8");
@@ -2412,8 +2922,8 @@ Checks that an app's tests pin the env that reaches outside.
2412
2922
  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.
2413
2923
  A file whose pages reach none of them says so with a \`// ev pins: none reached, <why>\` comment.
2414
2924
  The dir is an app, or a monorepo holding apps one level down (the current folder by default).
2415
- Reads variable names only, never a value.
2416
- Exits 0 when everything is pinned, 1 when something is not, 2 on a usage error.`;
2925
+ Reads variable names only, never a value.`;
2926
+ var EXITS2 = [[0, "everything is pinned"], [1, "something is not"], [2, "a usage error"]];
2417
2927
  var options2 = {
2418
2928
  json: jsonOption("each app with its reaching, unpinned variables and flagged test files"),
2419
2929
  except: { type: "string", description: "comma-separated variables to leave out, as ones that only link back to the app" }
@@ -2433,7 +2943,7 @@ async function apps(dir, except) {
2433
2943
  for (const entry of (await readdir4(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
2434
2944
  if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules")
2435
2945
  continue;
2436
- const app = await checkApp(join10(dir, entry.name), except);
2946
+ const app = await checkApp(join12(dir, entry.name), except);
2437
2947
  if (app !== undefined)
2438
2948
  found.push(app);
2439
2949
  }
@@ -2446,9 +2956,9 @@ function name(app, root) {
2446
2956
  return app.app === root ? app.app.split("/").at(-1) ?? app.app : app.app.slice(root.length + 1);
2447
2957
  }
2448
2958
  async function pins(args) {
2449
- const parsed = parse(args, usage3, options2, { positionals: ["[dir]"] });
2959
+ const parsed = parse(args, usage3, options2, { positionals: ["[dir]"], exits: EXITS2 });
2450
2960
  const json = parsed.values.json === true;
2451
- const root = resolve4(parsed.positionals[0] ?? ".");
2961
+ const root = resolve5(parsed.positionals[0] ?? ".");
2452
2962
  const except = new Set((parsed.values.except ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry !== ""));
2453
2963
  if (!await isFolder2(root))
2454
2964
  fail(`${root} is not a folder`);
@@ -2480,16 +2990,14 @@ var listUsage = `ev list [file]
2480
2990
 
2481
2991
  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.
2482
2992
 
2483
- --json prints [{file, key, value, secret}], value masked and secret true when a value was.
2484
-
2485
- Exits 0 when it printed them, 1 when there is no .env* file, 2 on a usage error.`;
2993
+ --json prints [{file, key, value, secret}], value masked and secret true when a value was.`;
2994
+ var LIST_EXITS = [[0, "it printed them"], [1, "there is no .env* file"], [2, "a usage error"]];
2486
2995
  var getUsage = `ev get KEY [file]
2487
2996
 
2488
2997
  Prints the masked value of one key, from every .env* file that sets it or from one file.
2489
2998
 
2490
- --json prints [{file, key, value, secret}] for each file that sets it.
2491
-
2492
- Exits 0 when the key is set, 1 when it is not set anywhere, 2 on a usage error.`;
2999
+ --json prints [{file, key, value, secret}] for each file that sets it.`;
3000
+ var GET_EXITS = [[0, "the key is set"], [1, "it is not set anywhere"], [2, "a usage error"]];
2493
3001
  function display(key, value, known) {
2494
3002
  return maskValue(key, value, known).replaceAll(`
2495
3003
  `, "\\n").replaceAll("\r", "\\r");
@@ -2522,7 +3030,7 @@ async function readAll(names) {
2522
3030
  return { files, known: await loadKnown(process.cwd(), files.map(([, file]) => file)) };
2523
3031
  }
2524
3032
  async function list(args) {
2525
- const parsed = parse(args, listUsage, jsonFlag2);
3033
+ const parsed = parse(args, listUsage, jsonFlag2, { exits: LIST_EXITS });
2526
3034
  const [file] = parsed.positionals;
2527
3035
  const names = file === undefined ? await envFiles() : [file];
2528
3036
  if (names.length === 0)
@@ -2540,7 +3048,7 @@ async function list(args) {
2540
3048
  return 0;
2541
3049
  }
2542
3050
  async function get(args) {
2543
- const parsed = parse(args, getUsage, jsonFlag2);
3051
+ const parsed = parse(args, getUsage, jsonFlag2, { exits: GET_EXITS });
2544
3052
  const [key, file] = parsed.positionals;
2545
3053
  if (key === undefined)
2546
3054
  fail(`missing KEY
@@ -2563,19 +3071,17 @@ var grepUsage = `ev grep [-i] <regex> [file...]
2563
3071
 
2564
3072
  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\`.
2565
3073
 
2566
- --json prints [{file, key, value, secret}].
2567
-
2568
- Exits 0 when a key matches, 1 when none does, 2 on a usage error.`;
3074
+ --json prints [{file, key, value, secret}].`;
3075
+ var GREP_EXITS = [[0, "a key matches"], [1, "none does"], [2, "a usage error"]];
2569
3076
  var showUsage = `ev show <rev>:<file>
2570
3077
 
2571
3078
  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\`.
2572
3079
 
2573
- --json prints [{file, key, value, secret}].
2574
-
2575
- Exits 0 when it printed them, 1 when git cannot show the file, 2 on a usage error.`;
3080
+ --json prints [{file, key, value, secret}].`;
3081
+ var SHOW_EXITS = [[0, "it printed them"], [1, "git cannot show the file"], [2, "a usage error"]];
2576
3082
  var REVISION = /^([^:]+):(.+)$/;
2577
3083
  async function grep(args) {
2578
- const parsed = parse(args, grepUsage, { "ignore-case": { type: "boolean", short: "i", description: "match the key whatever its case" }, ...jsonFlag2 });
3084
+ const parsed = parse(args, grepUsage, { "ignore-case": { type: "boolean", short: "i", description: "match the key whatever its case" }, ...jsonFlag2 }, { exits: GREP_EXITS });
2579
3085
  const [source, ...given] = parsed.positionals;
2580
3086
  if (source === undefined)
2581
3087
  fail(`missing the regex
@@ -2602,7 +3108,7 @@ ${grepUsage}`);
2602
3108
  return 0;
2603
3109
  }
2604
3110
  async function show(args) {
2605
- const parsed = parse(args, showUsage, jsonFlag2);
3111
+ const parsed = parse(args, showUsage, jsonFlag2, { exits: SHOW_EXITS });
2606
3112
  const [target] = parsed.positionals;
2607
3113
  const [, revision, path] = REVISION.exec(target ?? "") ?? [];
2608
3114
  if (revision === undefined || path === undefined)
@@ -2625,7 +3131,7 @@ ${showUsage}`);
2625
3131
  }
2626
3132
 
2627
3133
  // src/commands/redact.ts
2628
- import process16 from "process";
3134
+ import process21 from "process";
2629
3135
 
2630
3136
  // src/redactor.ts
2631
3137
  var DIFF_START = /^(?:diff --git |@@ )/;
@@ -2746,15 +3252,14 @@ function check(text, known) {
2746
3252
  var usage4 = `redact [--check]
2747
3253
 
2748
3254
  Copies stdin to stdout line by line with secrets masked: known token formats (GitHub, GitLab, Slack, AWS, npm, Stripe, Google and SendGrid keys, sk-, JWTs, Authorization headers, password= and secret= pairs), private key blocks, the password and the tokens of any URL and the values of secret-looking keys in this folder's .env* files.
2749
- --check prints nothing of the input and lists the file and line of each secret found, exiting 1 when there is any: \`git diff --cached | redact --check\`.
2750
-
2751
- Exits 0 when it copied the input or found no secret, 1 when --check finds one, 2 on a usage error.`;
3255
+ --check prints nothing of the input and lists the file and line of each secret found, exiting 1 when there is any: \`git diff --cached | redact --check\`.`;
3256
+ var EXITS3 = [[0, "it copied the input or found no secret"], [1, "--check finds one"], [2, "a usage error"]];
2752
3257
  var options3 = {
2753
3258
  check: { type: "boolean", description: "list where secrets are instead of masking them, exit 1 when found" },
2754
3259
  "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
2755
3260
  };
2756
3261
  async function redact(args) {
2757
- const parsed = parse(args, usage4, options3, { replaces: "printing a command's secrets into a log or a transcript", examples: [["docker compose config | redact", "the resolved compose file, secrets masked"], ["git diff --cached | redact --check", "refuse a commit carrying a secret"]] });
3262
+ const parsed = parse(args, usage4, options3, { exits: EXITS3, replaces: "printing a command's secrets into a log or a transcript", examples: [["docker compose config | redact", "the resolved compose file, secrets masked"], ["git diff --cached | redact --check", "refuse a commit carrying a secret"]] });
2758
3263
  const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
2759
3264
  if (parsed.values.check === true) {
2760
3265
  const findings = check(await readInput("-"), known);
@@ -2765,13 +3270,13 @@ async function redact(args) {
2765
3270
  const redactor = new Redactor(known);
2766
3271
  const decoder = new TextDecoder;
2767
3272
  for await (const chunk of Bun.stdin.stream())
2768
- process16.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
2769
- process16.stdout.write(redactor.push(decoder.decode()) + redactor.end());
3273
+ process21.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
3274
+ process21.stdout.write(redactor.push(decoder.decode()) + redactor.end());
2770
3275
  return 0;
2771
3276
  }
2772
3277
 
2773
3278
  // src/ev.ts
2774
- process17.exitCode = await runCli({
3279
+ process22.exitCode = await runCli({
2775
3280
  name: "ev",
2776
3281
  about: ".env files listed and edited with secrets masked",
2777
3282
  replaces: "cat .env, grep on env files and editing them by hand",