@kaynooo/cli-env 0.13.2 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ev.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/ev.ts
5
- import process18 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,7 +454,7 @@ 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)) {
@@ -473,29 +493,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
473
493
  return [];
474
494
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
475
495
  }
496
+ var MAX_INLINE_CHOICES = 24;
476
497
  function optionRows(options, colors = paint(process8.stdout)) {
477
498
  const rows = Object.entries(options).map(([name, option]) => {
478
499
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
479
- 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>";
480
503
  const placeholder = option.optional === undefined ? named : `[${named}]`;
481
504
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
482
- 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 };
483
507
  });
484
508
  const width = Math.max(0, ...rows.map((row) => row.width));
485
509
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
486
510
  }
487
511
 
488
512
  // ../kit/src/text.ts
489
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
490
513
  function distance(a, b) {
491
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
492
- 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()) {
493
519
  const current = [i + 1];
494
- for (const [j, right] of [...b].entries())
495
- 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;
496
527
  previous = current;
497
528
  }
498
- return previous[b.length] ?? 0;
529
+ return previous[right.length] ?? 0;
499
530
  }
500
531
  function closest(name, names) {
501
532
  const started = names.find((known) => known.startsWith(name));
@@ -563,7 +594,7 @@ class Completing {
563
594
  }
564
595
  var completion = { active: false };
565
596
  var OUTPUT_OPTIONS = {
566
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
597
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
567
598
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
568
599
  };
569
600
  function applyOutput(color, plain, env = process10.env) {
@@ -767,13 +798,91 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
767
798
  // ../kit/src/cli.ts
768
799
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
769
800
  import { dirname as dirname3, join as join5 } from "path";
770
- import process13 from "process";
801
+ import process14 from "process";
802
+
803
+ // ../kit/src/completions.ts
804
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
805
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
806
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
807
+ set -l current (commandline -ct)
808
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
809
+ if test "$line" = __files__
810
+ __fish_complete_path $current
811
+ else
812
+ echo $line
813
+ end
814
+ end
815
+ end`;
816
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
817
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
818
+ local -a lines
819
+ COMPREPLY=()
820
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
821
+ for line in "\${lines[@]}"; do
822
+ if [[ $line == __files__ ]]; then
823
+ COMPREPLY+=($(compgen -f -- "$cur"))
824
+ else
825
+ words+="\${line%%$'\\t'*}"$'\\n'
826
+ fi
827
+ done
828
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
829
+ }`;
830
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
831
+ local line
832
+ local -a described plain
833
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
834
+ if [[ $line == __files__ ]]; then
835
+ _files
836
+ elif [[ $line == *$'\\t'* ]]; then
837
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
838
+ else
839
+ plain+=("$line")
840
+ fi
841
+ done
842
+ (( \${#described} )) && _describe -V value described
843
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
844
+ return 0
845
+ }`;
846
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
847
+ if (shell === "fish")
848
+ return `${header}
849
+ ${FISH_FUNCTION}
850
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
851
+ `).join("")}`;
852
+ if (shell === "bash")
853
+ return `${header}
854
+ ${BASH_FUNCTION}
855
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
856
+ `;
857
+ return `${header}
858
+ ${ZSH_FUNCTION}
859
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
860
+ `;
861
+ }
862
+
863
+ // ../kit/src/notify.ts
864
+ import process12 from "process";
865
+ var NOTIFY_AFTER_MS = 1e4;
866
+ var CANCELLED = 130;
867
+ function base64(text) {
868
+ return Buffer.from(text).toString("base64");
869
+ }
870
+ function notification(title, body, env = process12.env) {
871
+ const id = `kit${process12.pid}`;
872
+ 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\\`];
873
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
874
+ }
875
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
876
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
877
+ return;
878
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
879
+ }
771
880
 
772
881
  // ../kit/src/usage.ts
773
882
  import { appendFileSync, mkdirSync } from "fs";
774
883
  import { homedir as homedir3 } from "os";
775
884
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
776
- import process12 from "process";
885
+ import process13 from "process";
777
886
 
778
887
  // ../kit/src/logs.ts
779
888
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -787,14 +896,14 @@ var usageError;
787
896
  function noteUsageError(message) {
788
897
  usageError = message;
789
898
  }
790
- function stateHome(env = process12.env) {
899
+ function stateHome(env = process13.env) {
791
900
  const dir = env.XDG_STATE_HOME;
792
901
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
793
902
  }
794
- function usagePath(env = process12.env) {
903
+ function usagePath(env = process13.env) {
795
904
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
796
905
  }
797
- function usageRecorded(env = process12.env) {
906
+ function usageRecorded(env = process13.env) {
798
907
  const off = env.KAYNOOO_CLI_NO_USAGE;
799
908
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
800
909
  }
@@ -808,7 +917,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
808
917
  usageError = undefined;
809
918
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
810
919
  }
811
- function recordUsage(entry, env = process12.env) {
920
+ function recordUsage(entry, env = process13.env) {
812
921
  if (!usageRecorded(env))
813
922
  return;
814
923
  try {
@@ -824,7 +933,11 @@ var LEVEL_OPTIONS = {
824
933
  ...OUTPUT_OPTIONS,
825
934
  help: { type: "boolean", short: "h", description: "show this help" }
826
935
  };
827
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
936
+ var TOP_OPTIONS = {
937
+ ...LEVEL_OPTIONS,
938
+ version: { type: "boolean", short: "v", description: "print the version" },
939
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
940
+ };
828
941
  async function commandRows(all, colors) {
829
942
  const commands = shown(all);
830
943
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -898,8 +1011,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
898
1011
  `);
899
1012
  }
900
1013
  function printError(prefix, message, hint, cause) {
901
- const colors = paint(process13.stderr);
902
- const styled = takesControlCodes(process13.stderr);
1014
+ const colors = paint(process14.stderr);
1015
+ const styled = takesControlCodes(process14.stderr);
903
1016
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
904
1017
  const under = (label, text, tint) => text === undefined ? "" : `
905
1018
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -942,11 +1055,11 @@ async function dispatch(level, typed, { version, redact }) {
942
1055
  }
943
1056
  }
944
1057
  if (name === undefined && level.path.length > 1) {
945
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1058
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
946
1059
  return 2;
947
1060
  }
948
1061
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
949
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1062
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
950
1063
  return 0;
951
1064
  }
952
1065
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1057,6 +1170,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1057
1170
  }
1058
1171
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1059
1172
  }
1173
+ var COMPLETIONS = "--completions";
1174
+ function flagValue([flag = "", ...rest]) {
1175
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1176
+ }
1177
+ function printCompletionScript(name, args) {
1178
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1179
+ if (shell === undefined || args.length !== 1) {
1180
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1181
+ return 2;
1182
+ }
1183
+ console.log(completionScript(shell, [name]).trimEnd());
1184
+ return 0;
1185
+ }
1060
1186
  async function printCandidates(found) {
1061
1187
  for (const line of await found)
1062
1188
  console.log(line);
@@ -1081,10 +1207,15 @@ async function runCli(cli, argv = scriptArgs()) {
1081
1207
  const version = cli.version ?? packageVersion();
1082
1208
  if (argv[0] === COMPLETE)
1083
1209
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1210
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1211
+ return printCompletionScript(cli.name, flagValue(argv));
1212
+ const started = performance.now();
1084
1213
  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 });
1214
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1215
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1085
1216
  if (cli.usage !== false) {
1086
1217
  try {
1087
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1218
+ recordUsage(usageEntry(cli.name, command, argv, code));
1088
1219
  } catch {}
1089
1220
  }
1090
1221
  return code;
@@ -1107,16 +1238,20 @@ function commandPath(scope, argv) {
1107
1238
  async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1108
1239
  if (argv[0] === COMPLETE)
1109
1240
  return printCandidates(leafCandidates(run, argv.slice(1)));
1241
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1242
+ return printCompletionScript(name, flagValue(argv));
1110
1243
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1111
1244
  console.log(version ?? packageVersion());
1112
1245
  return 0;
1113
1246
  }
1114
1247
  let code;
1248
+ const started = performance.now();
1115
1249
  try {
1116
1250
  code = await run(argv);
1117
1251
  } catch (error) {
1118
1252
  code = reportThrown(name, error, redact, wantsJson(argv));
1119
1253
  }
1254
+ notifyEnd(name, code, performance.now() - started);
1120
1255
  if (usage !== false) {
1121
1256
  try {
1122
1257
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1134,12 +1269,18 @@ async function compose(args, { flags = [], ...options } = {}) {
1134
1269
  return captureOutput(["docker", "compose", ...flags, ...args], options);
1135
1270
  }
1136
1271
  // ../kit/src/folders.ts
1272
+ import { homedir as homedir4 } from "os";
1273
+ import { join as join6 } from "path";
1274
+ import process15 from "process";
1137
1275
  var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1138
1276
  function ignoredFolders(extra = [], where = {}) {
1139
1277
  const configured = readUserConfig("config", where).ignore;
1140
1278
  const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1141
1279
  return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1142
1280
  }
1281
+ function cacheFolder({ home = homedir4(), env = process15.env } = {}) {
1282
+ return env.XDG_CACHE_HOME ?? join6(home, ".cache");
1283
+ }
1143
1284
  // ../kit/src/secrets.ts
1144
1285
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
1145
1286
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -1154,7 +1295,7 @@ var ACCOUNT_DIRS = new Glob("*/sessions");
1154
1295
  // src/commands/audit.ts
1155
1296
  import { stat as stat4 } from "fs/promises";
1156
1297
  import { relative, resolve as resolve4 } from "path";
1157
- import process15 from "process";
1298
+ import process17 from "process";
1158
1299
 
1159
1300
  // ../kit/src/shell.ts
1160
1301
  var SEPARATORS = new Set([`
@@ -1205,12 +1346,12 @@ function shellQuote(word) {
1205
1346
 
1206
1347
  // src/audit.ts
1207
1348
  import { readdir as readdir2, stat as stat2 } from "fs/promises";
1208
- import { dirname as dirname5, join as join7 } from "path";
1349
+ import { dirname as dirname5, join as join8 } from "path";
1209
1350
  var {$ } = globalThis.Bun;
1210
1351
 
1211
1352
  // src/files.ts
1212
1353
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
1213
- import { basename, dirname as dirname4, join as join6 } from "path";
1354
+ import { basename, dirname as dirname4, join as join7 } from "path";
1214
1355
 
1215
1356
  // src/dotenv.ts
1216
1357
  var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
@@ -1268,7 +1409,8 @@ function parseDotenv(text) {
1268
1409
  let body = start.slice(1);
1269
1410
  let raw = line;
1270
1411
  let end = closingQuote(body, quote);
1271
- while (end === -1 && index + 1 < physical.length) {
1412
+ const first = index;
1413
+ while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
1272
1414
  index++;
1273
1415
  body += `
1274
1416
  ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
@@ -1276,6 +1418,11 @@ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1276
1418
  ${physical[index] ?? ""}`;
1277
1419
  end = closingQuote(body, quote);
1278
1420
  }
1421
+ if (end === -1 && index + 1 < physical.length) {
1422
+ index = first;
1423
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()), unterminated: true });
1424
+ continue;
1425
+ }
1279
1426
  const inner = end === -1 ? body : body.slice(0, end);
1280
1427
  lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1281
1428
  }
@@ -1341,9 +1488,30 @@ var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
1341
1488
  function isPlaceholder(value) {
1342
1489
  return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
1343
1490
  }
1491
+ var STRONG_NAME = "password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key";
1492
+ var WEAK_NAME = "token|credentials?|auth";
1493
+ var PLAIN_WORD = /^[a-z]+$/i;
1494
+ var AFTER_COLON = /:\s*$/;
1495
+ var DIGIT = /\d/;
1496
+ var KEY_VALUE_GAP = "\\s*[:=]\\s*";
1497
+ function isProse(value, before) {
1498
+ return isPlaceholder(value) || AFTER_COLON.test(before) && PLAIN_WORD.test(value);
1499
+ }
1500
+ function isWeak(value, before) {
1501
+ return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
1502
+ }
1503
+ function keyed(names, value) {
1504
+ return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
1505
+ }
1344
1506
  var TOKEN_FORMATS = [
1345
1507
  { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
1346
- { kind: "GitLab token", pattern: /\bglpat-[\w-]{20,}/dg },
1508
+ { kind: "GitLab token", pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
1509
+ { kind: "Hugging Face token", pattern: /\bhf_[A-Za-z]{30,}/dg },
1510
+ { kind: "webhook secret", pattern: /\bwhsec_\w{20,}/dg },
1511
+ { kind: "DigitalOcean token", pattern: /\bdop_v1_\w{20,}/dg },
1512
+ { kind: "Shopify token", pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
1513
+ { kind: "password", pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
1514
+ { kind: "password", pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
1347
1515
  { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
1348
1516
  { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
1349
1517
  { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
@@ -1354,8 +1522,10 @@ var TOKEN_FORMATS = [
1354
1522
  { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
1355
1523
  { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
1356
1524
  { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
1357
- { kind: "password", pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
1358
- { kind: "password", pattern: /(?<![\w-])["']?(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?["']?\s*[:=]\s*(["'])((?:\\.|(?!\1)[^\\\n]){4,})\1/dgi, skip: isPlaceholder }
1525
+ { kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
1526
+ { kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
1527
+ { kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isPlaceholder },
1528
+ { kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isWeak }
1359
1529
  ];
1360
1530
  var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1361
1531
  var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
@@ -1460,7 +1630,7 @@ function findSecrets(line, known) {
1460
1630
  if (start === undefined || end === undefined)
1461
1631
  continue;
1462
1632
  const value = line.slice(start, end);
1463
- if (!skip?.(value))
1633
+ if (!skip?.(value, line.slice(0, start)))
1464
1634
  found.push({ start, end, kind, mask: hint(value) });
1465
1635
  }
1466
1636
  }
@@ -1522,7 +1692,7 @@ async function envFiles(folder = process.cwd()) {
1522
1692
  const found = await readdir(folder, { withFileTypes: true });
1523
1693
  const names = [];
1524
1694
  for (const entry of found) {
1525
- if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join6(folder, entry.name)))
1695
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join7(folder, entry.name)))
1526
1696
  names.push(entry.name);
1527
1697
  }
1528
1698
  return names.sort();
@@ -1546,7 +1716,7 @@ async function writeAtomic(path, text) {
1546
1716
  if (error.code !== "ENOENT")
1547
1717
  throw error;
1548
1718
  }
1549
- const temp = join6(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1719
+ const temp = join7(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1550
1720
  try {
1551
1721
  await writeFile(temp, text, { mode: 384, flag: "wx" });
1552
1722
  if (owner !== undefined)
@@ -1602,7 +1772,7 @@ async function acquire(path) {
1602
1772
  try {
1603
1773
  real = await realpath(path);
1604
1774
  } catch {}
1605
- const lock = join6(dirname4(real), `.${basename(real)}.lock`);
1775
+ const lock = join7(dirname4(real), `.${basename(real)}.lock`);
1606
1776
  const deadline = Date.now() + LOCK_WAIT_MS;
1607
1777
  while (true) {
1608
1778
  try {
@@ -1637,7 +1807,7 @@ async function envFilesBelow(folder, depth = 0) {
1637
1807
  return found;
1638
1808
  }
1639
1809
  for (const entry of children) {
1640
- const path = join6(folder, entry.name);
1810
+ const path = join7(folder, entry.name);
1641
1811
  if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1642
1812
  found.push(...await envFilesBelow(path, depth + 1));
1643
1813
  else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
@@ -1728,7 +1898,7 @@ async function* candidates2(root, unread, depth = 0) {
1728
1898
  return;
1729
1899
  }
1730
1900
  for (const entry of found) {
1731
- const path = join7(root, entry.name);
1901
+ const path = join8(root, entry.name);
1732
1902
  if (entry.isDirectory() && depth < MAX_DEPTH && !SKIPPED.has(entry.name))
1733
1903
  yield* candidates2(path, unread, depth + 1);
1734
1904
  else if (!TEMPLATE.test(entry.name) && (ENV_FILE.test(entry.name) || COMPOSE_FILE.test(entry.name)) && await isFileEntry(entry, path))
@@ -1760,7 +1930,7 @@ async function audit(roots) {
1760
1930
 
1761
1931
  // src/fix.ts
1762
1932
  import { chmod as chmod2, chown as chown2, lstat, rm as rm2, stat as stat3 } from "fs/promises";
1763
- import { dirname as dirname6, join as join8 } from "path";
1933
+ import { dirname as dirname6, join as join9 } from "path";
1764
1934
  var MAP_ENTRY = /^(\s*)(["']?)([A-Z0-9_]+)\2(\s*:)(.*)$/;
1765
1935
  var LIST_ENTRY = /^(\s*-[ \t]*)(["']?)([A-Z0-9_]+)=(.*)$/;
1766
1936
  var TRAILING = /^\s*(?:#.*)?$/;
@@ -1853,7 +2023,7 @@ async function shutOthersOut(path, group = false) {
1853
2023
  }
1854
2024
  }
1855
2025
  async function fixCompose(path, group = false) {
1856
- const env = join8(dirname6(path), ".env");
2026
+ const env = join9(dirname6(path), ".env");
1857
2027
  const compose = await Bun.file(path).text();
1858
2028
  const envBefore = await Bun.file(env).exists() ? await Bun.file(env).text() : undefined;
1859
2029
  const dotenv = parseDotenv(envBefore ?? "");
@@ -1971,12 +2141,12 @@ async function isFolder(path) {
1971
2141
  }
1972
2142
  }
1973
2143
  function shown2(path) {
1974
- return path.startsWith(`${process15.cwd()}/`) ? relative(process15.cwd(), path) : path;
2144
+ return path.startsWith(`${process17.cwd()}/`) ? relative(process17.cwd(), path) : path;
1975
2145
  }
1976
2146
  async function fixAll(exposed, json) {
1977
2147
  const fixed = [];
1978
2148
  let left = false;
1979
- const tint = role("path", process15.stdout);
2149
+ const tint = role("path", process17.stdout);
1980
2150
  for (const { path, readable, group, tracked, secrets } of exposed) {
1981
2151
  const fix = secrets === undefined ? undefined : await fixCompose(path, group === true);
1982
2152
  const open = fix?.open ?? (readable && !await shutOthersOut(path, group === true) ? [path] : []);
@@ -2028,8 +2198,8 @@ async function audit2(args) {
2028
2198
  console.log("no exposed .env file nor compose file writing a secret out");
2029
2199
  return 0;
2030
2200
  }
2031
- const uid = process15.getuid?.();
2032
- const tint = role("path", process15.stdout);
2201
+ const uid = process17.getuid?.();
2202
+ const tint = role("path", process17.stdout);
2033
2203
  for (const { path, readable, group, tracked, secrets } of exposed) {
2034
2204
  const sudo = uid !== undefined && uid !== 0 && (await stat4(path)).uid !== uid ? "sudo " : "";
2035
2205
  const problems = [
@@ -2045,7 +2215,7 @@ async function audit2(args) {
2045
2215
  }
2046
2216
 
2047
2217
  // src/commands/compare.ts
2048
- import process16 from "process";
2218
+ import process18 from "process";
2049
2219
  var diffUsage = `ev diff <a> <b>
2050
2220
 
2051
2221
  Names the keys set in one file and not the other, never their values.
@@ -2077,8 +2247,8 @@ ${diffUsage}`);
2077
2247
  printJson({ a, b, onlyA, onlyB });
2078
2248
  return onlyA.length + onlyB.length === 0 ? 0 : 1;
2079
2249
  }
2080
- const path = role("path", process16.stdout);
2081
- const value = role("value", process16.stdout);
2250
+ const path = role("path", process18.stdout);
2251
+ const value = role("value", process18.stdout);
2082
2252
  const lines = [...onlyA.map((key) => `only in ${path(a)}: ${value(key)}`), ...onlyB.map((key) => `only in ${path(b)}: ${value(key)}`)];
2083
2253
  if (lines.length === 0)
2084
2254
  return 0;
@@ -2099,13 +2269,417 @@ async function missing(args) {
2099
2269
  }
2100
2270
  if (absent.length === 0)
2101
2271
  return 0;
2102
- const path = role("path", process16.stdout);
2103
- const value = role("value", process16.stdout);
2272
+ const path = role("path", process18.stdout);
2273
+ const value = role("value", process18.stdout);
2104
2274
  console.log(absent.map((key) => `${value(key)} (set in ${path(against)}, not in ${path(file)})`).join(`
2105
2275
  `));
2106
2276
  return 1;
2107
2277
  }
2108
2278
 
2279
+ // ../kit/src/prompt.ts
2280
+ import process20 from "process";
2281
+
2282
+ // ../kit/src/answers.ts
2283
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync } from "fs";
2284
+ import { dirname as dirname7, join as join10 } from "path";
2285
+ var KEPT = 50;
2286
+ function answersFile() {
2287
+ return join10(cacheFolder(), "kaynooo-cli", "answers.json");
2288
+ }
2289
+ function stored() {
2290
+ try {
2291
+ const parsed = JSON.parse(readFileSync5(answersFile(), "utf-8"));
2292
+ if (typeof parsed !== "object" || parsed === null)
2293
+ return {};
2294
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
2295
+ } catch {
2296
+ return {};
2297
+ }
2298
+ }
2299
+ function earlierAnswers(key) {
2300
+ return stored()[key] ?? [];
2301
+ }
2302
+ function rememberAnswer(key, answer) {
2303
+ const all = stored();
2304
+ const file = answersFile();
2305
+ all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
2306
+ try {
2307
+ mkdirSync2(dirname7(file), { recursive: true });
2308
+ writeFileSync(file, JSON.stringify(all));
2309
+ } catch {}
2310
+ }
2311
+
2312
+ // ../kit/src/job.ts
2313
+ import process19 from "process";
2314
+ function stopJob() {
2315
+ process19.kill(0, "SIGTSTP");
2316
+ }
2317
+
2318
+ // ../kit/src/picker/line.ts
2319
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
2320
+ var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
2321
+ var FORWARD_KILLS = new Set(["killnext", "killend"]);
2322
+ function isEditKey(key) {
2323
+ return EDIT_KEYS.has(key);
2324
+ }
2325
+ function endsKills(key) {
2326
+ return typeof key !== "object" && !isEditKey(key);
2327
+ }
2328
+ var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
2329
+ var SPACE = /\s/;
2330
+ function isWord(char) {
2331
+ return char !== undefined && WORD_CHARACTER.test(char);
2332
+ }
2333
+ function wordStart(chars, from) {
2334
+ let at = from;
2335
+ while (at > 0 && !isWord(chars[at - 1]))
2336
+ at--;
2337
+ while (at > 0 && isWord(chars[at - 1]))
2338
+ at--;
2339
+ return at;
2340
+ }
2341
+ function wordEnd(chars, from) {
2342
+ let at = from;
2343
+ while (at < chars.length && !isWord(chars[at]))
2344
+ at++;
2345
+ while (at < chars.length && isWord(chars[at]))
2346
+ at++;
2347
+ return at;
2348
+ }
2349
+ function spacedStart(chars, from) {
2350
+ let at = from;
2351
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
2352
+ at--;
2353
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
2354
+ at--;
2355
+ return at;
2356
+ }
2357
+ function cut(chars, from, to) {
2358
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
2359
+ }
2360
+ function insert(chars, at, text) {
2361
+ const typed = [...text];
2362
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
2363
+ }
2364
+ function editLine(line, key) {
2365
+ const { killed = "", chained = false } = line;
2366
+ const chars = [...line.text];
2367
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
2368
+ const edited = edit(chars, at, key, killed);
2369
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
2370
+ return line.killed === undefined ? edited : { ...edited, killed };
2371
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
2372
+ if (taken === "")
2373
+ return { ...edited, killed, chained };
2374
+ if (!chained)
2375
+ return { ...edited, killed: taken, chained: true };
2376
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
2377
+ }
2378
+ function edit(chars, at, key, killed) {
2379
+ const text = chars.join("");
2380
+ if (typeof key === "object")
2381
+ return insert(chars, at, key.text);
2382
+ switch (key) {
2383
+ case "left":
2384
+ return { text, caret: Math.max(at - 1, 0) };
2385
+ case "right":
2386
+ return { text, caret: Math.min(at + 1, chars.length) };
2387
+ case "wordleft":
2388
+ return { text, caret: wordStart(chars, at) };
2389
+ case "wordright":
2390
+ return { text, caret: wordEnd(chars, at) };
2391
+ case "linestart":
2392
+ return { text, caret: 0 };
2393
+ case "lineend":
2394
+ return { text, caret: chars.length };
2395
+ case "erase":
2396
+ return cut(chars, Math.max(at - 1, 0), at);
2397
+ case "delete":
2398
+ return cut(chars, at, Math.min(at + 1, chars.length));
2399
+ case "word":
2400
+ return cut(chars, spacedStart(chars, at), at);
2401
+ case "killword":
2402
+ return cut(chars, wordStart(chars, at), at);
2403
+ case "killnext":
2404
+ return cut(chars, at, wordEnd(chars, at));
2405
+ case "clear":
2406
+ return cut(chars, 0, at);
2407
+ case "killend":
2408
+ return cut(chars, at, chars.length);
2409
+ case "yank":
2410
+ return insert(chars, at, killed);
2411
+ }
2412
+ }
2413
+ function visible({ text, caret }, room) {
2414
+ const chars = [...text];
2415
+ const at = Math.min(Math.max(caret, 0), chars.length);
2416
+ const cells = at === chars.length ? [...chars, " "] : chars;
2417
+ const widths = cells.map((char) => Bun.stringWidth(char));
2418
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
2419
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
2420
+ let start = at;
2421
+ let end = at + 1;
2422
+ while (start > 0 && fits(start - 1, end))
2423
+ start--;
2424
+ while (end < cells.length && fits(start, end + 1))
2425
+ end++;
2426
+ const left = start > 0 ? "\u2026" : "";
2427
+ const right = end < cells.length ? "\u2026" : "";
2428
+ 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) };
2429
+ }
2430
+
2431
+ // ../kit/src/picker/score.ts
2432
+ var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
2433
+ var NONE = Number.NEGATIVE_INFINITY;
2434
+
2435
+ // ../kit/src/picker/state.ts
2436
+ var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
2437
+ var PASTE_START = "\x1B[200~";
2438
+ var PASTE_END = "\x1B[201~";
2439
+ var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
2440
+ var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
2441
+ var WHEEL_LINES = 3;
2442
+ var KEYS = {
2443
+ "\x1B[A": "up",
2444
+ "\x1BOA": "up",
2445
+ "\x10": "up",
2446
+ "\x1B[B": "down",
2447
+ "\x1BOB": "down",
2448
+ "\x0E": "down",
2449
+ "\x1B[5~": "pageup",
2450
+ "\x1B[6~": "pagedown",
2451
+ "\x1B[H": "home",
2452
+ "\x1B[1~": "home",
2453
+ "\x1BOH": "home",
2454
+ "\x1B[F": "end",
2455
+ "\x1B[4~": "end",
2456
+ "\x1BOF": "end",
2457
+ "\r": "enter",
2458
+ "\n": "enter",
2459
+ "\x03": "cancel",
2460
+ "\x1B": "cancel",
2461
+ "\x1B[D": "left",
2462
+ "\x1BOD": "left",
2463
+ "\x1B[C": "right",
2464
+ "\x1BOC": "right",
2465
+ "\x1B[1;5D": "wordleft",
2466
+ "\x1B[1;3D": "wordleft",
2467
+ "\x1Bb": "wordleft",
2468
+ "\x1B[1;5C": "wordright",
2469
+ "\x1B[1;3C": "wordright",
2470
+ "\x1Bf": "wordright",
2471
+ "\x01": "linestart",
2472
+ "\x05": "lineend",
2473
+ "\x7F": "erase",
2474
+ "\x1B[3~": "delete",
2475
+ "\b": "killword",
2476
+ "\x1B\x7F": "killword",
2477
+ "\x1B[3;5~": "killnext",
2478
+ "\x1Bd": "killnext",
2479
+ "\x15": "clear",
2480
+ "\v": "killend",
2481
+ "\x17": "word",
2482
+ "\x19": "yank",
2483
+ "\x1A": "suspend",
2484
+ "\t": "tab",
2485
+ "\x1F": "help",
2486
+ "\x1BOP": "help",
2487
+ "\x1B[11~": "help"
2488
+ };
2489
+ function repeat(value, count) {
2490
+ return Array.from({ length: count }).fill(value);
2491
+ }
2492
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
2493
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
2494
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
2495
+ const wheel = MOUSE.exec(sequence)?.[1];
2496
+ if (wheel !== undefined)
2497
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
2498
+ const named = codes.get(sequence);
2499
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
2500
+ if (sequence === PASTE_START || sequence === PASTE_END) {
2501
+ paste.active = sequence === PASTE_START;
2502
+ return [];
2503
+ }
2504
+ if (paste.active && (sequence === "\r" || sequence === `
2505
+ `))
2506
+ return [];
2507
+ if (key !== undefined)
2508
+ return [key];
2509
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
2510
+ });
2511
+ }
2512
+
2513
+ // ../kit/src/redraw.ts
2514
+ var SYNC_START = "\x1B[?2026h";
2515
+ var SYNC_END = "\x1B[?2026l";
2516
+ function overwrite(lines, columns) {
2517
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
2518
+ `);
2519
+ }
2520
+ function rowsTaken(lines, columns) {
2521
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
2522
+ }
2523
+
2524
+ // ../kit/src/prompt.ts
2525
+ var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
2526
+ var MAX_LISTED = 12;
2527
+ function readKeys(input, paste = { active: false }) {
2528
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
2529
+ }
2530
+ function roomAfter(question, columns) {
2531
+ return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
2532
+ }
2533
+ function withCaret(colors, line, room, dim = false) {
2534
+ const { before, at, after } = visible(line, room);
2535
+ const tone = dim ? colors.dim : (text) => text;
2536
+ return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
2537
+ }
2538
+ function sharedStart(texts) {
2539
+ const [first = [], ...rest] = texts.map((text) => [...text]);
2540
+ let length = first.length;
2541
+ for (const chars of rest) {
2542
+ const differs = chars.findIndex((char, index) => char !== first[index]);
2543
+ length = Math.min(length, differs === -1 ? chars.length : differs);
2544
+ }
2545
+ return first.slice(0, length).join("");
2546
+ }
2547
+ function listed2(colors, found, columns) {
2548
+ const shared = sharedStart(found);
2549
+ const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
2550
+ const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
2551
+ const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
2552
+ return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
2553
+ }
2554
+ async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
2555
+ let line = { text: "", caret: 0 };
2556
+ let invalid;
2557
+ let completions = [];
2558
+ const remembered = history === undefined || mask ? undefined : history;
2559
+ const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
2560
+ let recalled = -1;
2561
+ let draft = line;
2562
+ const taken = () => line.text === "" ? fallback ?? "" : line.text;
2563
+ const shown = () => mask ? "*".repeat([...taken()].length) : taken();
2564
+ const accepted = await ask(question, settings, (colors, state, { columns }) => {
2565
+ if (state !== "asking")
2566
+ return [answer(colors, question, state, shown())];
2567
+ const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
2568
+ return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
2569
+ }, (key) => {
2570
+ if (key === "cancel")
2571
+ return "cancel";
2572
+ invalid = undefined;
2573
+ completions = [];
2574
+ if (line.chained === true && endsKills(key))
2575
+ line = { ...line, chained: false };
2576
+ if (key === "tab") {
2577
+ const chars = [...line.text];
2578
+ const before = chars.slice(0, line.caret).join("");
2579
+ const found = complete?.(before) ?? [];
2580
+ const filled = sharedStart(found);
2581
+ if ([...filled].length > [...before].length)
2582
+ line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
2583
+ else
2584
+ completions = found;
2585
+ return;
2586
+ }
2587
+ if (key === "enter") {
2588
+ invalid = validate?.(taken());
2589
+ return invalid === undefined ? "enter" : undefined;
2590
+ }
2591
+ if (key === "up" || key === "down") {
2592
+ const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
2593
+ if (recalled === -1)
2594
+ draft = line;
2595
+ recalled = to;
2596
+ const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
2597
+ line = { ...shown, killed: line.killed ?? "" };
2598
+ return;
2599
+ }
2600
+ const edit = { home: "linestart", end: "lineend" }[key] ?? key;
2601
+ if (typeof edit === "object" || isEditKey(edit))
2602
+ line = editLine(line, edit);
2603
+ return;
2604
+ });
2605
+ if (!accepted)
2606
+ return;
2607
+ if (remembered !== undefined && taken() !== "")
2608
+ rememberAnswer(remembered, taken());
2609
+ return taken();
2610
+ }
2611
+ function answer(colors, question, state, picked) {
2612
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
2613
+ }
2614
+ async function ask(question, { hint, terminal = process20 }, render, press) {
2615
+ const { stdin, stderr } = terminal;
2616
+ if (!isInteractive(terminal))
2617
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
2618
+ const colors = paint(stderr);
2619
+ let current = "asking";
2620
+ let outcome;
2621
+ const columns = () => stderr.columns || 80;
2622
+ const draw = (state, last = false) => {
2623
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
2624
+ const rows = rowsTaken(frame, columns());
2625
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
2626
+ current = state;
2627
+ };
2628
+ const redraw = () => draw(current);
2629
+ const paste = { active: false };
2630
+ const stop = terminal.stop ?? (terminal === process20 ? stopJob : undefined);
2631
+ const suspend = () => {
2632
+ if (stop === undefined)
2633
+ return;
2634
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
2635
+ stdin.setRawMode(false);
2636
+ stop();
2637
+ stdin.setRawMode(true);
2638
+ stderr.write("\x1B[?25l\x1B[?2004h");
2639
+ };
2640
+ try {
2641
+ stderr.on?.("resize", redraw);
2642
+ stdin.setRawMode(true);
2643
+ stdin.resume();
2644
+ stderr.write("\x1B[?25l\x1B[?2004h");
2645
+ draw("asking");
2646
+ return await new Promise((resolve) => {
2647
+ function onData(data) {
2648
+ for (const key of readKeys(data.toString(), paste)) {
2649
+ if (key === "suspend") {
2650
+ suspend();
2651
+ continue;
2652
+ }
2653
+ const pressed = press(key);
2654
+ if (pressed !== undefined) {
2655
+ settle(pressed);
2656
+ return;
2657
+ }
2658
+ }
2659
+ draw("asking");
2660
+ }
2661
+ function onEnd() {
2662
+ settle("cancel");
2663
+ }
2664
+ function settle(settled) {
2665
+ outcome = settled;
2666
+ stdin.off("data", onData);
2667
+ stdin.off("end", onEnd);
2668
+ resolve(settled === "enter");
2669
+ }
2670
+ stdin.on("data", onData);
2671
+ stdin.on("end", onEnd);
2672
+ });
2673
+ } finally {
2674
+ stderr.off?.("resize", redraw);
2675
+ draw(outcome ?? "cancel", true);
2676
+ stderr.write(`
2677
+ \x1B[?25h\x1B[?2004l`);
2678
+ stdin.setRawMode(false);
2679
+ stdin.pause();
2680
+ }
2681
+ }
2682
+
2109
2683
  // src/commands/edit.ts
2110
2684
  var DEFAULT_FILE = ".env";
2111
2685
  var TRAILING_NEWLINE = /\r?\n$/;
@@ -2113,8 +2687,8 @@ var KEY_NAME = /^[A-Z_][\w.-]*$/i;
2113
2687
  var QUIET = { quiet: { type: "boolean", short: "q", description: "print nothing on success" } };
2114
2688
  var setUsage = `ev set KEY [file] [--quiet]
2115
2689
 
2116
- 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.`;
2117
- var SET_EXITS = [[0, "it wrote the key"], [1, "it could not"], [2, "a usage error"]];
2690
+ 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.`;
2691
+ var SET_EXITS = [[0, "it wrote the key"], [1, "it could not"], [2, "a usage error"], [130, "the prompt was cancelled"]];
2118
2692
  var unsetUsage = `ev unset KEY [file] [--quiet]
2119
2693
 
2120
2694
  Removes every line setting KEY from the file (.env by default), leaving comments and other lines as they are.`;
@@ -2127,11 +2701,11 @@ var cpUsage = `ev cp KEY --from <file> --to <file> [--as NEWKEY] [--quiet]
2127
2701
 
2128
2702
  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.`;
2129
2703
  var CP_EXITS = [[0, "it copied the key"], [1, "the source lacks it"], [2, "a usage error"]];
2130
- async function readValue(from) {
2131
- const input = await readInput(from ?? "-", { noStdin: "pipe the value on stdin or give -F <file>, it is never taken from the command line" });
2132
- if (input === "")
2704
+ async function readValue(key, from) {
2705
+ 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" });
2706
+ if (value === "")
2133
2707
  fail("the value is empty, nothing was written: --empty sets an empty value");
2134
- return input.replace(TRAILING_NEWLINE, "");
2708
+ return value.replace(TRAILING_NEWLINE, "");
2135
2709
  }
2136
2710
  function checkKey(key) {
2137
2711
  if (!KEY_NAME.test(key))
@@ -2154,7 +2728,7 @@ ${setUsage}`);
2154
2728
  if (parsed.values.empty === true && parsed.values.file !== undefined)
2155
2729
  fail("--empty and -F exclude each other");
2156
2730
  checkKey(key);
2157
- const value = parsed.values.empty === true ? "" : await readValue(parsed.values.file);
2731
+ const value = parsed.values.empty === true ? "" : await readValue(key, parsed.values.file);
2158
2732
  const file = await withLocks([target], async () => {
2159
2733
  const current = await readOrEmpty(target);
2160
2734
  setLine(current, key, value);
@@ -2246,11 +2820,11 @@ ${cpUsage}`);
2246
2820
 
2247
2821
  // src/commands/pins.ts
2248
2822
  import { readdir as readdir4, stat as stat5 } from "fs/promises";
2249
- import { join as join10, resolve as resolve5 } from "path";
2823
+ import { join as join12, resolve as resolve5 } from "path";
2250
2824
 
2251
2825
  // src/pins.ts
2252
2826
  import { readdir as readdir3, readFile } from "fs/promises";
2253
- import { join as join9, relative as relative2 } from "path";
2827
+ import { join as join11, relative as relative2 } from "path";
2254
2828
  var OPTIONAL2 = /^\s*([A-Z][A-Z0-9_]*)\s*:\s*s\.Optional\(/gm;
2255
2829
  var REACHING = /(?:URL|URI|TOKEN|KEY|SECRET|PASSWORD|DSN|_HOST)(?:_FILE)?$/;
2256
2830
  var SELF = /(?:^|_)(?:PUBLIC|SITE|BASE|APP)_URL$/;
@@ -2279,7 +2853,7 @@ async function walk(folder, keep) {
2279
2853
  for (const entry of entries) {
2280
2854
  if (SKIPPED.has(entry.name))
2281
2855
  continue;
2282
- const path = join9(folder, entry.name);
2856
+ const path = join11(folder, entry.name);
2283
2857
  if (entry.isDirectory())
2284
2858
  found.push(...await walk(path, keep));
2285
2859
  else if (entry.isFile() && keep(entry.name))
@@ -2290,7 +2864,7 @@ async function walk(folder, keep) {
2290
2864
  async function testFiles(folder) {
2291
2865
  const found = [];
2292
2866
  for (const root of TEST_ROOTS) {
2293
- found.push(...await walk(join9(folder, root), (name) => TEST_FILE.test(name)));
2867
+ found.push(...await walk(join11(folder, root), (name) => TEST_FILE.test(name)));
2294
2868
  }
2295
2869
  return found;
2296
2870
  }
@@ -2358,7 +2932,7 @@ function reachesOutside(name) {
2358
2932
  }
2359
2933
  async function schemaFile(folder) {
2360
2934
  for (const candidate of SCHEMA_CANDIDATES) {
2361
- const path = join9(folder, candidate);
2935
+ const path = join11(folder, candidate);
2362
2936
  if (await exists(path) && (await readFile(path, "utf8")).includes("defineEnv("))
2363
2937
  return path;
2364
2938
  }
@@ -2369,7 +2943,7 @@ async function testEnvKeys(folder) {
2369
2943
  for (const entry of await readdir3(folder, { withFileTypes: true })) {
2370
2944
  if (!entry.isFile() || !ENV_TEST.test(entry.name))
2371
2945
  continue;
2372
- for (const line of parseDotenv(await readFile(join9(folder, entry.name), "utf8")).lines) {
2946
+ for (const line of parseDotenv(await readFile(join11(folder, entry.name), "utf8")).lines) {
2373
2947
  if (line.key !== undefined)
2374
2948
  keys.add(line.key);
2375
2949
  }
@@ -2377,7 +2951,7 @@ async function testEnvKeys(folder) {
2377
2951
  return keys;
2378
2952
  }
2379
2953
  async function pinningPreload(folder) {
2380
- const path = join9(folder, "bunfig.toml");
2954
+ const path = join11(folder, "bunfig.toml");
2381
2955
  if (!await exists(path))
2382
2956
  return;
2383
2957
  let config;
@@ -2388,7 +2962,7 @@ async function pinningPreload(folder) {
2388
2962
  }
2389
2963
  const preloads = [config.test?.preload, config.preload].flat().filter((entry) => typeof entry === "string" && entry.startsWith("."));
2390
2964
  for (const preload of preloads) {
2391
- const file = join9(folder, preload);
2965
+ const file = join11(folder, preload);
2392
2966
  if (!await exists(file))
2393
2967
  continue;
2394
2968
  const source = await readFile(file, "utf8");
@@ -2450,7 +3024,7 @@ async function apps(dir, except) {
2450
3024
  for (const entry of (await readdir4(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
2451
3025
  if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules")
2452
3026
  continue;
2453
- const app = await checkApp(join10(dir, entry.name), except);
3027
+ const app = await checkApp(join12(dir, entry.name), except);
2454
3028
  if (app !== undefined)
2455
3029
  found.push(app);
2456
3030
  }
@@ -2638,7 +3212,7 @@ ${showUsage}`);
2638
3212
  }
2639
3213
 
2640
3214
  // src/commands/redact.ts
2641
- import process17 from "process";
3215
+ import process21 from "process";
2642
3216
 
2643
3217
  // src/redactor.ts
2644
3218
  var DIFF_START = /^(?:diff --git |@@ )/;
@@ -2777,13 +3351,13 @@ async function redact(args) {
2777
3351
  const redactor = new Redactor(known);
2778
3352
  const decoder = new TextDecoder;
2779
3353
  for await (const chunk of Bun.stdin.stream())
2780
- process17.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
2781
- process17.stdout.write(redactor.push(decoder.decode()) + redactor.end());
3354
+ process21.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
3355
+ process21.stdout.write(redactor.push(decoder.decode()) + redactor.end());
2782
3356
  return 0;
2783
3357
  }
2784
3358
 
2785
3359
  // src/ev.ts
2786
- process18.exitCode = await runCli({
3360
+ process22.exitCode = await runCli({
2787
3361
  name: "ev",
2788
3362
  about: ".env files listed and edited with secrets masked",
2789
3363
  replaces: "cat .env, grep on env files and editing them by hand",