@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/redact.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/redact.ts
5
- import process16 from "process";
5
+ import process18 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"]);
@@ -1152,11 +1293,11 @@ var {Glob } = globalThis.Bun;
1152
1293
  var SESSION_FILES = new Glob("*.json");
1153
1294
  var ACCOUNT_DIRS = new Glob("*/sessions");
1154
1295
  // src/commands/redact.ts
1155
- import process15 from "process";
1296
+ import process17 from "process";
1156
1297
 
1157
1298
  // src/files.ts
1158
1299
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
1159
- import { basename, dirname as dirname4, join as join6 } from "path";
1300
+ import { basename, dirname as dirname4, join as join7 } from "path";
1160
1301
 
1161
1302
  // src/dotenv.ts
1162
1303
  var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
@@ -1214,7 +1355,8 @@ function parseDotenv(text) {
1214
1355
  let body = start.slice(1);
1215
1356
  let raw = line;
1216
1357
  let end = closingQuote(body, quote);
1217
- while (end === -1 && index + 1 < physical.length) {
1358
+ const first = index;
1359
+ while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
1218
1360
  index++;
1219
1361
  body += `
1220
1362
  ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
@@ -1222,6 +1364,11 @@ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1222
1364
  ${physical[index] ?? ""}`;
1223
1365
  end = closingQuote(body, quote);
1224
1366
  }
1367
+ if (end === -1 && index + 1 < physical.length) {
1368
+ index = first;
1369
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()), unterminated: true });
1370
+ continue;
1371
+ }
1225
1372
  const inner = end === -1 ? body : body.slice(0, end);
1226
1373
  lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1227
1374
  }
@@ -1287,9 +1434,30 @@ var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
1287
1434
  function isPlaceholder(value) {
1288
1435
  return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
1289
1436
  }
1437
+ var STRONG_NAME = "password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key";
1438
+ var WEAK_NAME = "token|credentials?|auth";
1439
+ var PLAIN_WORD = /^[a-z]+$/i;
1440
+ var AFTER_COLON = /:\s*$/;
1441
+ var DIGIT = /\d/;
1442
+ var KEY_VALUE_GAP = "\\s*[:=]\\s*";
1443
+ function isProse(value, before) {
1444
+ return isPlaceholder(value) || AFTER_COLON.test(before) && PLAIN_WORD.test(value);
1445
+ }
1446
+ function isWeak(value, before) {
1447
+ return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
1448
+ }
1449
+ function keyed(names, value) {
1450
+ return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
1451
+ }
1290
1452
  var TOKEN_FORMATS = [
1291
1453
  { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
1292
- { kind: "GitLab token", pattern: /\bglpat-[\w-]{20,}/dg },
1454
+ { kind: "GitLab token", pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
1455
+ { kind: "Hugging Face token", pattern: /\bhf_[A-Za-z]{30,}/dg },
1456
+ { kind: "webhook secret", pattern: /\bwhsec_\w{20,}/dg },
1457
+ { kind: "DigitalOcean token", pattern: /\bdop_v1_\w{20,}/dg },
1458
+ { kind: "Shopify token", pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
1459
+ { kind: "password", pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
1460
+ { kind: "password", pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
1293
1461
  { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
1294
1462
  { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
1295
1463
  { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
@@ -1300,8 +1468,10 @@ var TOKEN_FORMATS = [
1300
1468
  { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
1301
1469
  { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
1302
1470
  { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
1303
- { kind: "password", pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
1304
- { kind: "password", pattern: /(?<![\w-])["']?(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?["']?\s*[:=]\s*(["'])((?:\\.|(?!\1)[^\\\n]){4,})\1/dgi, skip: isPlaceholder }
1471
+ { kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
1472
+ { kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
1473
+ { kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isPlaceholder },
1474
+ { kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isWeak }
1305
1475
  ];
1306
1476
  var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1307
1477
  var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
@@ -1406,7 +1576,7 @@ function findSecrets(line, known) {
1406
1576
  if (start === undefined || end === undefined)
1407
1577
  continue;
1408
1578
  const value = line.slice(start, end);
1409
- if (!skip?.(value))
1579
+ if (!skip?.(value, line.slice(0, start)))
1410
1580
  found.push({ start, end, kind, mask: hint(value) });
1411
1581
  }
1412
1582
  }
@@ -1468,7 +1638,7 @@ async function envFiles(folder = process.cwd()) {
1468
1638
  const found = await readdir(folder, { withFileTypes: true });
1469
1639
  const names = [];
1470
1640
  for (const entry of found) {
1471
- if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join6(folder, entry.name)))
1641
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join7(folder, entry.name)))
1472
1642
  names.push(entry.name);
1473
1643
  }
1474
1644
  return names.sort();
@@ -1492,7 +1662,7 @@ async function writeAtomic(path, text) {
1492
1662
  if (error.code !== "ENOENT")
1493
1663
  throw error;
1494
1664
  }
1495
- const temp = join6(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1665
+ const temp = join7(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1496
1666
  try {
1497
1667
  await writeFile(temp, text, { mode: 384, flag: "wx" });
1498
1668
  if (owner !== undefined)
@@ -1548,7 +1718,7 @@ async function acquire(path) {
1548
1718
  try {
1549
1719
  real = await realpath(path);
1550
1720
  } catch {}
1551
- const lock = join6(dirname4(real), `.${basename(real)}.lock`);
1721
+ const lock = join7(dirname4(real), `.${basename(real)}.lock`);
1552
1722
  const deadline = Date.now() + LOCK_WAIT_MS;
1553
1723
  while (true) {
1554
1724
  try {
@@ -1583,7 +1753,7 @@ async function envFilesBelow(folder, depth = 0) {
1583
1753
  return found;
1584
1754
  }
1585
1755
  for (const entry of children) {
1586
- const path = join6(folder, entry.name);
1756
+ const path = join7(folder, entry.name);
1587
1757
  if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1588
1758
  found.push(...await envFilesBelow(path, depth + 1));
1589
1759
  else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
@@ -1738,10 +1908,10 @@ async function redact(args) {
1738
1908
  const redactor = new Redactor(known);
1739
1909
  const decoder = new TextDecoder;
1740
1910
  for await (const chunk of Bun.stdin.stream())
1741
- process15.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1742
- process15.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1911
+ process17.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1912
+ process17.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1743
1913
  return 0;
1744
1914
  }
1745
1915
 
1746
1916
  // src/redact.ts
1747
- process16.exitCode = await runMain({ name: "redact", run: redact });
1917
+ process18.exitCode = await runMain({ name: "redact", run: redact });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-env",
3
3
  "type": "module",
4
- "version": "0.13.2",
4
+ "version": "0.14.1",
5
5
  "description": "ev lists and edits .env files with secrets masked, redact masks secrets in any piped output.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -36,7 +36,7 @@
36
36
  "ev": "$npm_execpath src/ev.ts",
37
37
  "redact": "$npm_execpath src/redact.ts"
38
38
  },
39
- "devDependencies": {
40
- "@kaynooo/cli-kit": "0.38.2"
39
+ "dependencies": {
40
+ "@kaynooo/cli-kit": "0.41.0"
41
41
  }
42
42
  }
@@ -1,5 +1,6 @@
1
1
  import type { ExitRow } from '@kaynooo/cli-kit'
2
- import { badUsage, fail, parse, readInput } from '@kaynooo/cli-kit'
2
+ import { badUsage, fail, isInteractive, parse, readInput } from '@kaynooo/cli-kit'
3
+ import { input } from '@kaynooo/cli-kit/prompt'
3
4
  import { entries, lastLine, removeKey, setLine } from '../dotenv'
4
5
  import { loadKnown, readEnv, withLocks, writeEnv } from '../files'
5
6
  import { maskValue } from '../mask'
@@ -12,9 +13,9 @@ const QUIET = { quiet: { type: 'boolean', short: 'q', description: 'print nothin
12
13
 
13
14
  const setUsage = `ev set KEY [file] [--quiet]
14
15
 
15
- 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.`
16
+ 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.`
16
17
 
17
- const SET_EXITS: ExitRow[] = [[0, 'it wrote the key'], [1, 'it could not'], [2, 'a usage error']]
18
+ const SET_EXITS: ExitRow[] = [[0, 'it wrote the key'], [1, 'it could not'], [2, 'a usage error'], [130, 'the prompt was cancelled']]
18
19
 
19
20
  const unsetUsage = `ev unset KEY [file] [--quiet]
20
21
 
@@ -34,13 +35,15 @@ Copies KEY's value from one file to another without printing it, replacing the k
34
35
 
35
36
  const CP_EXITS: ExitRow[] = [[0, 'it copied the key'], [1, 'the source lacks it'], [2, 'a usage error']]
36
37
 
37
- async function readValue(from: string | undefined): Promise<string> {
38
- const input = await readInput(from ?? '-', { noStdin: 'pipe the value on stdin or give -F <file>, it is never taken from the command line' })
38
+ async function readValue(key: string, from: string | undefined): Promise<string> {
39
+ const value = from === undefined && isInteractive()
40
+ ? await input(`value of ${key}`, { mask: true }) ?? fail('cancelled, nothing was written', 130)
41
+ : await readInput(from ?? '-', { noStdin: 'pipe the value on stdin or give -F <file>, it is never taken from the command line' })
39
42
 
40
- if (input === '')
43
+ if (value === '')
41
44
  fail('the value is empty, nothing was written: --empty sets an empty value')
42
45
 
43
- return input.replace(TRAILING_NEWLINE, '')
46
+ return value.replace(TRAILING_NEWLINE, '')
44
47
  }
45
48
 
46
49
  // A key that is not a plain name could carry a line break or an `=` and write more than one line.
@@ -70,7 +73,7 @@ export async function set(args: string[]): Promise<number> {
70
73
 
71
74
  checkKey(key)
72
75
 
73
- const value = parsed.values.empty === true ? '' : await readValue(parsed.values.file)
76
+ const value = parsed.values.empty === true ? '' : await readValue(key, parsed.values.file)
74
77
 
75
78
  const file = await withLocks([target], async () => {
76
79
  const current = await readOrEmpty(target)
package/src/dotenv.ts CHANGED
@@ -3,6 +3,8 @@ export interface DotenvLine {
3
3
  raw: string
4
4
  key?: string
5
5
  value?: string
6
+ // The value opens a quote that no line closes before the next assignment: it is read as the rest of its own line, as Bun does.
7
+ unterminated?: boolean
6
8
  }
7
9
 
8
10
  export interface Dotenv {
@@ -83,13 +85,22 @@ export function parseDotenv(text: string): Dotenv {
83
85
  let raw = line
84
86
  let end = closingQuote(body, quote)
85
87
 
86
- while (end === -1 && index + 1 < physical.length) {
88
+ const first = index
89
+
90
+ while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? '')) {
87
91
  index++
88
92
  body += `\n${(physical[index] ?? '').replace(CARRIAGE_RETURN, '')}`
89
93
  raw += `\n${physical[index] ?? ''}`
90
94
  end = closingQuote(body, quote)
91
95
  }
92
96
 
97
+ if (end === -1 && index + 1 < physical.length) {
98
+ index = first
99
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, '').trim()), unterminated: true })
100
+
101
+ continue
102
+ }
103
+
93
104
  const inner = end === -1 ? body : body.slice(0, end)
94
105
 
95
106
  lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) })
package/src/mask.ts CHANGED
@@ -28,8 +28,8 @@ const ESCAPE = /[.*+?^${}()|[\]\\]/g
28
28
  interface TokenFormat {
29
29
  kind: string
30
30
  pattern: RegExp
31
- // Skips a candidate that is a placeholder or a plain word.
32
- skip?: (value: string) => boolean
31
+ // Skips a candidate that is a placeholder or a plain word. `before` is the line text ahead of it.
32
+ skip?: (value: string, before: string) => boolean
33
33
  }
34
34
 
35
35
  // A secret value starting like this is a reference or a placeholder, not the secret.
@@ -37,10 +37,39 @@ function isPlaceholder(value: string): boolean {
37
37
  return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value)
38
38
  }
39
39
 
40
+ // Names that are secrets whatever they are followed by, and names that also open prose (`token: expired`, `auth: failed`).
41
+ const STRONG_NAME = 'password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key'
42
+ const WEAK_NAME = 'token|credentials?|auth'
43
+ const PLAIN_WORD = /^[a-z]+$/i
44
+ const AFTER_COLON = /:\s*$/
45
+ const DIGIT = /\d/
46
+ const KEY_VALUE_GAP = '\\s*[:=]\\s*'
47
+
48
+ // A strong name before a colon, so likely prose, holding only a word is left alone.
49
+ function isProse(value: string, before: string): boolean {
50
+ return isPlaceholder(value) || (AFTER_COLON.test(before) && PLAIN_WORD.test(value))
51
+ }
52
+
53
+ // A value under a weak name is a secret only when it holds a digit or is long, which a word of prose never does.
54
+ function isWeak(value: string, before: string): boolean {
55
+ return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16)
56
+ }
57
+
58
+ // A key name holding one of the words: `AWS_SECRET_ACCESS_KEY`, `X-Api-Key`, `access_token`.
59
+ function keyed(names: string, value: string): RegExp {
60
+ return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, 'dgi')
61
+ }
62
+
40
63
  // A pattern with a group masks that group only, else the whole match.
41
64
  const TOKEN_FORMATS: TokenFormat[] = [
42
65
  { kind: 'GitHub token', pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
43
- { kind: 'GitLab token', pattern: /\bglpat-[\w-]{20,}/dg },
66
+ { kind: 'GitLab token', pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
67
+ { kind: 'Hugging Face token', pattern: /\bhf_[A-Za-z]{30,}/dg },
68
+ { kind: 'webhook secret', pattern: /\bwhsec_\w{20,}/dg },
69
+ { kind: 'DigitalOcean token', pattern: /\bdop_v1_\w{20,}/dg },
70
+ { kind: 'Shopify token', pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
71
+ { kind: 'password', pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
72
+ { kind: 'password', pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
44
73
  { kind: 'API key', pattern: /\bsk-[\w-]{20,}/dg },
45
74
  { kind: 'Slack token', pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
46
75
  { kind: 'JWT', pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
@@ -51,8 +80,10 @@ const TOKEN_FORMATS: TokenFormat[] = [
51
80
  { kind: 'SendGrid key', pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
52
81
  { kind: 'Authorization header', pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
53
82
  { kind: 'Bearer token', pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
54
- { kind: 'password', pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
55
- { kind: 'password', pattern: /(?<![\w-])["']?(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?["']?\s*[:=]\s*(["'])((?:\\.|(?!\1)[^\\\n]){4,})\1/dgi, skip: isPlaceholder },
83
+ { kind: 'password', pattern: keyed(STRONG_NAME, '([^\\s"\'&;,]{4,})'), skip: isProse },
84
+ { kind: 'password', pattern: keyed(WEAK_NAME, '([^\\s"\'&;,]{4,})'), skip: isWeak },
85
+ { kind: 'password', pattern: keyed(STRONG_NAME, '(["\'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1'), skip: isPlaceholder },
86
+ { kind: 'password', pattern: keyed(WEAK_NAME, '(["\'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1'), skip: isWeak },
56
87
  ]
57
88
 
58
89
  // A private key block (PEM, PGP). Its body is masked from just after the BEGIN marker to the END marker or the end of the line, so one line may hold the whole key escaped as JSON.
@@ -207,7 +238,7 @@ export function findSecrets(line: string, known?: KnownSecrets): Match[] {
207
238
 
208
239
  const value = line.slice(start, end)
209
240
 
210
- if (!skip?.(value))
241
+ if (!skip?.(value, line.slice(0, start)))
211
242
  found.push({ start, end, kind, mask: hint(value) })
212
243
  }
213
244
  }