@kaynooo/cli-env 0.8.1 → 0.9.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
@@ -1,9 +1,8 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file
2
2
  // @bun
3
3
 
4
4
  // src/ev.ts
5
5
  import process11 from "process";
6
-
7
6
  // ../kit/src/args.ts
8
7
  import process6 from "process";
9
8
  import { parseArgs } from "util";
@@ -366,17 +365,23 @@ var FULL_STOP = /\.$/;
366
365
  function usageLine(usage, colors = paint(process4.stdout)) {
367
366
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
368
367
  }
369
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces } = {}) {
370
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
368
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
369
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
371
370
  `);
372
371
  }
372
+ function exitRows(exits, colors = paint(process4.stdout)) {
373
+ if (exits.length === 0)
374
+ return [];
375
+ const width = Math.max(...exits.map(([code]) => String(code).length));
376
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
377
+ }
373
378
  function replacesRows(replaces, colors = paint(process4.stdout)) {
374
379
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
375
380
  }
376
381
  function wantsHelpJson(env = process4.env) {
377
382
  return env.KIT_HELP === "json";
378
383
  }
379
- function description(usage, { examples = [], replaces } = {}) {
384
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
380
385
  const lines = usage.replace(USAGE_PREFIX, "").split(`
381
386
  `);
382
387
  const first = lines[0];
@@ -387,7 +392,9 @@ function description(usage, { examples = [], replaces } = {}) {
387
392
  synopsis: colon === -1 ? first : first.slice(0, colon),
388
393
  summary: colon === -1 ? fallback : first.slice(colon + 2),
389
394
  ...replaces === undefined ? {} : { replaces },
390
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
395
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
396
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
397
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
391
398
  };
392
399
  }
393
400
  function exampleRows(examples, colors = paint(process4.stdout)) {
@@ -512,7 +519,7 @@ function parse(args, usage, options, settings = {}) {
512
519
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
513
520
  let parsed;
514
521
  try {
515
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
522
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
516
523
  } catch (error) {
517
524
  const message = parseError(error);
518
525
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -520,7 +527,7 @@ function parse(args, usage, options, settings = {}) {
520
527
  const values = parsed.values;
521
528
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
522
529
  if (values.help === true) {
523
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
530
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
524
531
  throw new HelpShown;
525
532
  }
526
533
  checkChoices(parsed.values, all);
@@ -562,6 +569,18 @@ function listed(options, allowNegative) {
562
569
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
563
570
  }));
564
571
  }
572
+ function withAliases(args, options) {
573
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
574
+ if (named.size === 0)
575
+ return args;
576
+ const separator = args.indexOf("--");
577
+ const own = separator === -1 ? args : args.slice(0, separator);
578
+ return [...own.map((arg) => {
579
+ const at = arg.indexOf("=");
580
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
581
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
582
+ }), ...separator === -1 ? [] : args.slice(separator)];
583
+ }
565
584
  function withBare(args, options) {
566
585
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
567
586
  if (bare.size === 0)
@@ -652,6 +671,8 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
652
671
  var RESET_STYLE = `${ESC}[0m`;
653
672
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
654
673
  // ../kit/src/cli.ts
674
+ import { readFileSync, realpathSync } from "fs";
675
+ import { dirname as dirname2, join as join2 } from "path";
655
676
  import process8 from "process";
656
677
 
657
678
  // ../kit/src/usage.ts
@@ -948,10 +969,22 @@ async function printCandidates(found) {
948
969
  console.log(line);
949
970
  return 0;
950
971
  }
972
+ function packageVersion(entry = Bun.main) {
973
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
974
+ try {
975
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
976
+ if (typeof version === "string")
977
+ return version;
978
+ } catch {}
979
+ if (dirname2(dir) === dir)
980
+ return "0.0.0";
981
+ }
982
+ }
951
983
  async function runCli(cli, argv = process8.argv.slice(2)) {
984
+ const version = cli.version ?? packageVersion();
952
985
  if (argv[0] === COMPLETE)
953
986
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
954
- const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
987
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
955
988
  if (cli.usage !== false) {
956
989
  try {
957
990
  recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
@@ -978,7 +1011,7 @@ async function runMain({ name, version, run, redact, usage }, argv = process8.ar
978
1011
  if (argv[0] === COMPLETE)
979
1012
  return printCandidates(leafCandidates(run, argv.slice(1)));
980
1013
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
981
- console.log(version);
1014
+ console.log(version ?? packageVersion());
982
1015
  return 0;
983
1016
  }
984
1017
  let code;
@@ -987,10 +1020,22 @@ async function runMain({ name, version, run, redact, usage }, argv = process8.ar
987
1020
  } catch (error) {
988
1021
  code = reportThrown(name, error, redact, wantsJson(argv));
989
1022
  }
990
- if (usage !== false)
991
- recordUsage(usageEntry(name, undefined, argv, code));
1023
+ if (usage !== false) {
1024
+ try {
1025
+ recordUsage(usageEntry(name, undefined, argv, code));
1026
+ } catch {}
1027
+ }
992
1028
  return code;
993
1029
  }
1030
+ // ../kit/src/compose.ts
1031
+ async function captureOutput(argv, { cwd, env } = {}) {
1032
+ const run = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, env: { ...process.env, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
1033
+ const [stdout, stderr, code] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
1034
+ return { code, stdout, stderr };
1035
+ }
1036
+ async function compose(args, { flags = [], ...options } = {}) {
1037
+ return captureOutput(["docker", "compose", ...flags, ...args], options);
1038
+ }
994
1039
  // ../kit/src/secrets.ts
995
1040
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
996
1041
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -1002,9 +1047,6 @@ function isSecretName(name) {
1002
1047
  var {Glob } = globalThis.Bun;
1003
1048
  var SESSION_FILES = new Glob("*.json");
1004
1049
  var ACCOUNT_DIRS = new Glob("*/sessions");
1005
- // package.json
1006
- var version = "0.8.1";
1007
-
1008
1050
  // src/commands/audit.ts
1009
1051
  import { stat as stat4 } from "fs/promises";
1010
1052
  import { relative, resolve } from "path";
@@ -1019,13 +1061,16 @@ var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
1019
1061
  var SAFE_WORD = /^[\w@%+=:,./-]+$/;
1020
1062
  var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
1021
1063
  var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
1022
- var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh"]);
1023
- var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, "su", "runuser"]);
1064
+ var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
1065
+ var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
1066
+ var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
1067
+ var POWERSHELL = new Set(["pwsh", "powershell"]);
1024
1068
  var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
1069
+ var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
1025
1070
  var PRINTERS = new Set(["echo", "printf"]);
1026
1071
  var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
1027
- function wrapper(short = "", long = [], operands = 0) {
1028
- return { short, long, operands };
1072
+ function wrapper(short = "", long = [], operands = 0, runsString = false) {
1073
+ return { short, long, operands, runsString };
1029
1074
  }
1030
1075
  var WRAPPERS = new Map([
1031
1076
  ["command", wrapper()],
@@ -1043,6 +1088,11 @@ var WRAPPERS = new Map([
1043
1088
  ["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
1044
1089
  ["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
1045
1090
  ["chroot", wrapper("", ["--userspec", "--groups"], 1)],
1091
+ ["watch", wrapper("n", ["--interval"], 0, true)],
1092
+ ["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
1093
+ ["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
1094
+ ["unbuffer", wrapper()],
1095
+ ["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
1046
1096
  ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
1047
1097
  ]);
1048
1098
  function shellQuote(word) {
@@ -1051,12 +1101,12 @@ function shellQuote(word) {
1051
1101
 
1052
1102
  // src/audit.ts
1053
1103
  import { readdir as readdir2, stat as stat2 } from "fs/promises";
1054
- import { dirname as dirname3, join as join3 } from "path";
1104
+ import { dirname as dirname4, join as join4 } from "path";
1055
1105
  var {$ } = globalThis.Bun;
1056
1106
 
1057
1107
  // src/files.ts
1058
1108
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
1059
- import { basename, dirname as dirname2, join as join2 } from "path";
1109
+ import { basename, dirname as dirname3, join as join3 } from "path";
1060
1110
 
1061
1111
  // src/dotenv.ts
1062
1112
  var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
@@ -1139,14 +1189,16 @@ function entries(file) {
1139
1189
  }
1140
1190
  return map;
1141
1191
  }
1192
+ function escapeDouble(value) {
1193
+ return value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("\r", "\\r").replaceAll(`
1194
+ `, "\\n").replaceAll("$", "\\$");
1195
+ }
1142
1196
  function formatAssignment(key, value) {
1143
1197
  if (value === "" || !NEEDS_QUOTES.test(value))
1144
1198
  return `${key}=${value}`;
1145
1199
  if (RAW_ONLY.test(value) && !value.includes("'") && !LINE_BREAK.test(value))
1146
1200
  return `${key}='${value.replaceAll("$", "\\$")}'`;
1147
- const escaped = value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("\r", "\\r").replaceAll(`
1148
- `, "\\n").replaceAll("$", "\\$");
1149
- return `${key}="${escaped}"`;
1201
+ return `${key}="${escapeDouble(value)}"`;
1150
1202
  }
1151
1203
  function setLine(file, key, value, raw) {
1152
1204
  const index = file.lines.findLastIndex((line) => line.key === key);
@@ -1215,6 +1267,9 @@ var WEBHOOK_FORMATS = [
1215
1267
  ["healthchecks.io ping URL", /^hc-ping\.com\/([\w-]+)/di]
1216
1268
  ];
1217
1269
  var OPAQUE_SEGMENT = /^(?:(?=[\w-]{20,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w-]+|(?=[A-Za-z\d]{32,}$)(?=.*[A-Za-z])(?=.*\d).+)$/;
1270
+ function isSecretKey(key) {
1271
+ return isSecretName(key);
1272
+ }
1218
1273
  function hint(value) {
1219
1274
  const shown = Math.min(3, Math.floor(value.length / 4));
1220
1275
  return `${value.slice(0, shown)}***(${value.length})`;
@@ -1347,6 +1402,7 @@ var KNOWN_DEPTH = 3;
1347
1402
  var SKIPPED = new Set(["node_modules", ".git", "vendor"]);
1348
1403
  var LOCK_WAIT_MS = 5000;
1349
1404
  var LOCK_STALE_MS = 30000;
1405
+ var REAP_STALE_MS = 5000;
1350
1406
  async function isFileEntry(entry, path) {
1351
1407
  if (entry.isFile())
1352
1408
  return true;
@@ -1362,7 +1418,7 @@ async function envFiles(folder = process.cwd()) {
1362
1418
  const found = await readdir(folder, { withFileTypes: true });
1363
1419
  const names = [];
1364
1420
  for (const entry of found) {
1365
- if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join2(folder, entry.name)))
1421
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join3(folder, entry.name)))
1366
1422
  names.push(entry.name);
1367
1423
  }
1368
1424
  return names.sort();
@@ -1386,7 +1442,7 @@ async function writeAtomic(path, text) {
1386
1442
  if (error.code !== "ENOENT")
1387
1443
  throw error;
1388
1444
  }
1389
- const temp = join2(dirname2(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1445
+ const temp = join3(dirname3(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1390
1446
  try {
1391
1447
  await writeFile(temp, text, { mode: 384, flag: "wx" });
1392
1448
  if (owner !== undefined)
@@ -1419,12 +1475,30 @@ async function withLocks(paths, fn) {
1419
1475
  await rm(lock, { force: true });
1420
1476
  }
1421
1477
  }
1478
+ async function reap(lock) {
1479
+ const guard = `${lock}.reap`;
1480
+ try {
1481
+ await writeFile(guard, String(process.pid), { flag: "wx", mode: 384 });
1482
+ } catch {
1483
+ try {
1484
+ if (Date.now() - (await stat(guard)).mtimeMs > REAP_STALE_MS)
1485
+ await rm(guard, { force: true });
1486
+ } catch {}
1487
+ return;
1488
+ }
1489
+ try {
1490
+ if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS)
1491
+ await rm(lock, { force: true });
1492
+ } catch {} finally {
1493
+ await rm(guard, { force: true });
1494
+ }
1495
+ }
1422
1496
  async function acquire(path) {
1423
1497
  let real = path;
1424
1498
  try {
1425
1499
  real = await realpath(path);
1426
1500
  } catch {}
1427
- const lock = join2(dirname2(real), `.${basename(real)}.lock`);
1501
+ const lock = join3(dirname3(real), `.${basename(real)}.lock`);
1428
1502
  const deadline = Date.now() + LOCK_WAIT_MS;
1429
1503
  while (true) {
1430
1504
  try {
@@ -1434,10 +1508,7 @@ async function acquire(path) {
1434
1508
  if (error.code !== "EEXIST")
1435
1509
  throw error;
1436
1510
  }
1437
- try {
1438
- if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS)
1439
- await rm(lock, { force: true });
1440
- } catch {}
1511
+ await reap(lock);
1441
1512
  if (Date.now() > deadline)
1442
1513
  fail(`${path} is locked by another ev run (${lock})`, 1);
1443
1514
  await Bun.sleep(25);
@@ -1462,7 +1533,7 @@ async function envFilesBelow(folder, depth = 0) {
1462
1533
  return found;
1463
1534
  }
1464
1535
  for (const entry of children) {
1465
- const path = join2(folder, entry.name);
1536
+ const path = join3(folder, entry.name);
1466
1537
  if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1467
1538
  found.push(...await envFilesBelow(path, depth + 1));
1468
1539
  else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
@@ -1504,18 +1575,28 @@ function inlineSecrets(compose) {
1504
1575
  async function openToOthers(path) {
1505
1576
  if (((await stat2(path)).mode & 4) === 0)
1506
1577
  return false;
1507
- for (let dir = dirname3(path);dir !== "/"; dir = dirname3(dir)) {
1578
+ for (let dir = dirname4(path);dir !== "/"; dir = dirname4(dir)) {
1508
1579
  if (((await stat2(dir)).mode & 1) === 0)
1509
1580
  return false;
1510
1581
  }
1511
1582
  return true;
1512
1583
  }
1584
+ function groupReads(mode, gid, ownerGroup) {
1585
+ return (mode & 32) !== 0 && gid !== ownerGroup && gid !== process.getgid?.();
1586
+ }
1587
+ function primaryGroup(uid) {
1588
+ if (uid === process.getuid?.())
1589
+ return process.getgid?.() ?? uid;
1590
+ const run = Bun.spawnSync(["id", "-g", String(uid)], { stdout: "pipe", stderr: "ignore" });
1591
+ const gid = Number(run.stdout.toString().trim());
1592
+ return run.exitCode === 0 && Number.isInteger(gid) ? gid : uid;
1593
+ }
1513
1594
  async function sharedWith(path) {
1514
1595
  const info = await stat2(path);
1515
- const shared = (info.mode & 32) !== 0 && info.gid !== info.uid && info.gid !== process.getgid?.();
1596
+ const shared = groupReads(info.mode, info.gid, primaryGroup(info.uid));
1516
1597
  if (!shared && (Bun.which("getfacl") === null || !await hasAclReader(path)))
1517
1598
  return false;
1518
- for (let dir = dirname3(path);dir !== "/"; dir = dirname3(dir)) {
1599
+ for (let dir = dirname4(path);dir !== "/"; dir = dirname4(dir)) {
1519
1600
  if (((await stat2(dir)).mode & 9) === 0)
1520
1601
  return false;
1521
1602
  }
@@ -1527,7 +1608,7 @@ async function hasAclReader(path) {
1527
1608
  `).some((line) => ACL_READER.test(line));
1528
1609
  }
1529
1610
  async function tracked(path) {
1530
- const run = await $`git ls-files --error-unmatch -- ${path}`.cwd(dirname3(path)).quiet().nothrow();
1611
+ const run = await $`git ls-files --error-unmatch -- ${path}`.cwd(dirname4(path)).quiet().nothrow();
1531
1612
  const error = run.stderr.toString();
1532
1613
  if (run.exitCode === 0)
1533
1614
  return true;
@@ -1544,7 +1625,7 @@ async function* candidates2(root, unread, depth = 0) {
1544
1625
  return;
1545
1626
  }
1546
1627
  for (const entry of found) {
1547
- const path = join3(root, entry.name);
1628
+ const path = join4(root, entry.name);
1548
1629
  if (entry.isDirectory() && depth < MAX_DEPTH && !SKIPPED2.has(entry.name))
1549
1630
  yield* candidates2(path, unread, depth + 1);
1550
1631
  else if (!TEMPLATE.test(entry.name) && (ENV_FILE.test(entry.name) || COMPOSE_FILE.test(entry.name)) && await isFileEntry(entry, path))
@@ -1576,7 +1657,7 @@ async function audit(roots) {
1576
1657
 
1577
1658
  // src/fix.ts
1578
1659
  import { chmod as chmod2, chown as chown2, lstat, rm as rm2, stat as stat3 } from "fs/promises";
1579
- import { dirname as dirname4, join as join4 } from "path";
1660
+ import { dirname as dirname5, join as join5 } from "path";
1580
1661
  var MAP_ENTRY = /^(\s*)(["']?)([A-Z0-9_]+)\2(\s*:)(.*)$/;
1581
1662
  var LIST_ENTRY = /^(\s*-[ \t]*)(["']?)([A-Z0-9_]+)=(.*)$/;
1582
1663
  var TRAILING = /^\s*(?:#.*)?$/;
@@ -1634,8 +1715,11 @@ function composeEntry(line) {
1634
1715
  function envLine(key, value) {
1635
1716
  if (ENV_PLAIN.test(value))
1636
1717
  return `${key}=${value}`;
1637
- return value.includes("'") || value.includes(`
1638
- `) ? undefined : `${key}='${value}'`;
1718
+ if (LINE_BREAK.test(value))
1719
+ return;
1720
+ if (value.includes("$"))
1721
+ return `${key}="${escapeDouble(value)}"`;
1722
+ return value.includes("'") ? undefined : `${key}='${value}'`;
1639
1723
  }
1640
1724
  async function isLink(path) {
1641
1725
  try {
@@ -1647,9 +1731,8 @@ async function isLink(path) {
1647
1731
  }
1648
1732
  }
1649
1733
  async function resolved(path) {
1650
- const run = Bun.spawn(["docker", "compose", "-f", path, "config", "--format", "json"], { cwd: dirname4(path), stdout: "pipe", stderr: "ignore", stdin: "ignore" });
1651
- const [out, code] = await Promise.all([new Response(run.stdout).text(), run.exited]);
1652
- return code === 0 ? out : undefined;
1734
+ const { code, stdout } = await compose(["config", "--format", "json"], { flags: ["-f", path], cwd: dirname5(path) });
1735
+ return code === 0 ? stdout : undefined;
1653
1736
  }
1654
1737
  function gainedBy(before, after, key) {
1655
1738
  const services = (config) => Object.entries(JSON.parse(config).services ?? {});
@@ -1667,7 +1750,7 @@ async function shutOthersOut(path, group = false) {
1667
1750
  }
1668
1751
  }
1669
1752
  async function fixCompose(path, group = false) {
1670
- const env = join4(dirname4(path), ".env");
1753
+ const env = join5(dirname5(path), ".env");
1671
1754
  const compose = await Bun.file(path).text();
1672
1755
  const envBefore = await Bun.file(env).exists() ? await Bun.file(env).text() : undefined;
1673
1756
  const dotenv = parseDotenv(envBefore ?? "");
@@ -1861,17 +1944,22 @@ var diffUsage = `ev diff <a> <b>
1861
1944
 
1862
1945
  Names the keys set in one file and not the other, never their values.
1863
1946
 
1947
+ --json prints {a, b, onlyA, onlyB}.
1948
+
1864
1949
  Exits 0 when both set the same keys, 1 when they differ, 2 on a usage error.`;
1865
1950
  var missingUsage = `ev missing [file]
1866
1951
 
1867
1952
  Names the keys the reference file sets that the file (.env by default) does not.
1868
1953
 
1954
+ --json prints {a, b, onlyA, onlyB} with the reference as a, so onlyA is what is missing.
1955
+
1869
1956
  Exits 0 when none is missing, 1 when some are, 2 on a usage error.`;
1957
+ var jsonFlag = { json: jsonOption() };
1870
1958
  async function keys(path) {
1871
1959
  return new Set(entries(await readEnv(path)).keys());
1872
1960
  }
1873
1961
  async function diff(args) {
1874
- const parsed = parse(args, diffUsage, {});
1962
+ const parsed = parse(args, diffUsage, jsonFlag);
1875
1963
  const [a, b] = parsed.positionals;
1876
1964
  if (a === undefined || b === undefined)
1877
1965
  fail(`needs two files
@@ -1879,10 +1967,13 @@ async function diff(args) {
1879
1967
  ${diffUsage}`);
1880
1968
  const left = await keys(a);
1881
1969
  const right = await keys(b);
1882
- const lines = [
1883
- ...[...left].filter((key) => !right.has(key)).map((key) => `only in ${a}: ${key}`),
1884
- ...[...right].filter((key) => !left.has(key)).map((key) => `only in ${b}: ${key}`)
1885
- ];
1970
+ const onlyA = [...left].filter((key) => !right.has(key));
1971
+ const onlyB = [...right].filter((key) => !left.has(key));
1972
+ if (parsed.values.json === true) {
1973
+ printJson({ a, b, onlyA, onlyB });
1974
+ return onlyA.length + onlyB.length === 0 ? 0 : 1;
1975
+ }
1976
+ const lines = [...onlyA.map((key) => `only in ${a}: ${key}`), ...onlyB.map((key) => `only in ${b}: ${key}`)];
1886
1977
  if (lines.length === 0)
1887
1978
  return 0;
1888
1979
  console.log(lines.join(`
@@ -1890,11 +1981,16 @@ ${diffUsage}`);
1890
1981
  return 1;
1891
1982
  }
1892
1983
  async function missing(args) {
1893
- const parsed = parse(args, missingUsage, { against: { type: "string", description: "the reference file (.env.example by default)" } });
1984
+ const parsed = parse(args, missingUsage, { against: { type: "string", description: "the reference file (.env.example by default)" }, ...jsonFlag });
1894
1985
  const [file = ".env"] = parsed.positionals;
1895
1986
  const against = parsed.values.against ?? ".env.example";
1896
1987
  const have = await keys(file);
1897
- const absent = [...await keys(against)].filter((key) => !have.has(key));
1988
+ const reference = await keys(against);
1989
+ const absent = [...reference].filter((key) => !have.has(key));
1990
+ if (parsed.values.json === true) {
1991
+ printJson({ a: against, b: file, onlyA: absent, onlyB: [...have].filter((key) => !reference.has(key)) });
1992
+ return absent.length === 0 ? 0 : 1;
1993
+ }
1898
1994
  if (absent.length === 0)
1899
1995
  return 0;
1900
1996
  console.log(absent.map((key) => `${key} (set in ${against}, not in ${file})`).join(`
@@ -2039,11 +2135,11 @@ ${cpUsage}`);
2039
2135
 
2040
2136
  // src/commands/pins.ts
2041
2137
  import { readdir as readdir4, stat as stat5 } from "fs/promises";
2042
- import { join as join6, resolve as resolve2 } from "path";
2138
+ import { join as join7, resolve as resolve2 } from "path";
2043
2139
 
2044
2140
  // src/pins.ts
2045
2141
  import { readdir as readdir3, readFile } from "fs/promises";
2046
- import { join as join5, relative as relative2 } from "path";
2142
+ import { join as join6, relative as relative2 } from "path";
2047
2143
  var OPTIONAL2 = /^\s*([A-Z][A-Z0-9_]*)\s*:\s*s\.Optional\(/gm;
2048
2144
  var REACHING = /(?:URL|URI|TOKEN|KEY|SECRET|PASSWORD|DSN|_HOST)(?:_FILE)?$/;
2049
2145
  var SELF = /(?:^|_)(?:PUBLIC|SITE|BASE|APP)_URL$/;
@@ -2073,7 +2169,7 @@ async function walk(folder, keep) {
2073
2169
  for (const entry of entries) {
2074
2170
  if (SKIPPED3.has(entry.name))
2075
2171
  continue;
2076
- const path = join5(folder, entry.name);
2172
+ const path = join6(folder, entry.name);
2077
2173
  if (entry.isDirectory())
2078
2174
  found.push(...await walk(path, keep));
2079
2175
  else if (entry.isFile() && keep(entry.name))
@@ -2084,7 +2180,7 @@ async function walk(folder, keep) {
2084
2180
  async function testFiles(folder) {
2085
2181
  const found = [];
2086
2182
  for (const root of TEST_ROOTS) {
2087
- found.push(...await walk(join5(folder, root), (name) => TEST_FILE.test(name)));
2183
+ found.push(...await walk(join6(folder, root), (name) => TEST_FILE.test(name)));
2088
2184
  }
2089
2185
  return found;
2090
2186
  }
@@ -2152,7 +2248,7 @@ function reachesOutside(name) {
2152
2248
  }
2153
2249
  async function schemaFile(folder) {
2154
2250
  for (const candidate of SCHEMA_CANDIDATES) {
2155
- const path = join5(folder, candidate);
2251
+ const path = join6(folder, candidate);
2156
2252
  if (await exists(path) && (await readFile(path, "utf8")).includes("defineEnv("))
2157
2253
  return path;
2158
2254
  }
@@ -2163,7 +2259,7 @@ async function testEnvKeys(folder) {
2163
2259
  for (const entry of await readdir3(folder, { withFileTypes: true })) {
2164
2260
  if (!entry.isFile() || !ENV_TEST.test(entry.name))
2165
2261
  continue;
2166
- for (const line of parseDotenv(await readFile(join5(folder, entry.name), "utf8")).lines) {
2262
+ for (const line of parseDotenv(await readFile(join6(folder, entry.name), "utf8")).lines) {
2167
2263
  if (line.key !== undefined)
2168
2264
  keys.add(line.key);
2169
2265
  }
@@ -2171,13 +2267,18 @@ async function testEnvKeys(folder) {
2171
2267
  return keys;
2172
2268
  }
2173
2269
  async function pinningPreload(folder) {
2174
- const path = join5(folder, "bunfig.toml");
2270
+ const path = join6(folder, "bunfig.toml");
2175
2271
  if (!await exists(path))
2176
2272
  return;
2177
- const config = Bun.TOML.parse(await readFile(path, "utf8"));
2273
+ let config;
2274
+ try {
2275
+ config = Bun.TOML.parse(await readFile(path, "utf8"));
2276
+ } catch {
2277
+ fail(`${path} is not valid TOML`);
2278
+ }
2178
2279
  const preloads = [config.test?.preload, config.preload].flat().filter((entry) => typeof entry === "string" && entry.startsWith("."));
2179
2280
  for (const preload of preloads) {
2180
- const file = join5(folder, preload);
2281
+ const file = join6(folder, preload);
2181
2282
  if (!await exists(file))
2182
2283
  continue;
2183
2284
  const source = await readFile(file, "utf8");
@@ -2239,7 +2340,7 @@ async function apps(dir, except) {
2239
2340
  for (const entry of (await readdir4(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
2240
2341
  if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules")
2241
2342
  continue;
2242
- const app = await checkApp(join6(dir, entry.name), except);
2343
+ const app = await checkApp(join7(dir, entry.name), except);
2243
2344
  if (app !== undefined)
2244
2345
  found.push(app);
2245
2346
  }
@@ -2286,16 +2387,32 @@ var listUsage = `ev list [file]
2286
2387
 
2287
2388
  Prints every key of the folder's .env* files, or of one file, with secret values masked: a few leading characters and the length under a key named like TOKEN, SECRET, PASSWORD, PASS, PWD, KEY, PRIVATE, DSN, AUTH, SALT or COOKIE, any value equal to a secret of the folder's .env* files, and the password and tokens of any URL.
2288
2389
 
2390
+ --json prints [{file, key, value, secret}], value masked and secret true when a value was.
2391
+
2289
2392
  Exits 0 when it printed them, 1 when there is no .env* file, 2 on a usage error.`;
2290
2393
  var getUsage = `ev get KEY [file]
2291
2394
 
2292
2395
  Prints the masked value of one key, from every .env* file that sets it or from one file.
2293
2396
 
2397
+ --json prints [{file, key, value, secret}] for each file that sets it.
2398
+
2294
2399
  Exits 0 when the key is set, 1 when it is not set anywhere, 2 on a usage error.`;
2295
2400
  function display(key, value, known) {
2296
2401
  return maskValue(key, value, known).replaceAll(`
2297
2402
  `, "\\n").replaceAll("\r", "\\r");
2298
2403
  }
2404
+ var jsonFlag2 = { json: jsonOption() };
2405
+ function row(file, key, value, known) {
2406
+ const shown = display(key, value, known);
2407
+ return { file, key, value: shown, secret: shown !== value.replaceAll(`
2408
+ `, "\\n").replaceAll("\r", "\\r") || isSecretKey(key) };
2409
+ }
2410
+ function printRows(rows, json, plain) {
2411
+ if (json)
2412
+ printJson(rows);
2413
+ else
2414
+ plain();
2415
+ }
2299
2416
  async function readAll(names) {
2300
2417
  const files = [];
2301
2418
  for (const name of names)
@@ -2303,7 +2420,7 @@ async function readAll(names) {
2303
2420
  return { files, known: await loadKnown(process.cwd(), files.map(([, file]) => file)) };
2304
2421
  }
2305
2422
  async function list(args) {
2306
- const parsed = parse(args, listUsage, {});
2423
+ const parsed = parse(args, listUsage, jsonFlag2);
2307
2424
  const [file] = parsed.positionals;
2308
2425
  const names = file === undefined ? await envFiles() : [file];
2309
2426
  if (names.length === 0)
@@ -2312,14 +2429,16 @@ async function list(args) {
2312
2429
  const { files, known } = await readAll(names);
2313
2430
  for (const [name, file] of files) {
2314
2431
  for (const [key, value] of entries(file))
2315
- rows.push([name, key, display(key, value, known)]);
2432
+ rows.push(row(name, key, value, known));
2316
2433
  }
2317
- if (rows.length > 0)
2318
- console.log(table(rows));
2434
+ printRows(rows, parsed.values.json === true, () => {
2435
+ if (rows.length > 0)
2436
+ console.log(table(rows.map((each) => [each.file, each.key, each.value])));
2437
+ });
2319
2438
  return 0;
2320
2439
  }
2321
2440
  async function get(args) {
2322
- const parsed = parse(args, getUsage, {});
2441
+ const parsed = parse(args, getUsage, jsonFlag2);
2323
2442
  const [key, file] = parsed.positionals;
2324
2443
  if (key === undefined)
2325
2444
  fail(`missing KEY
@@ -2331,26 +2450,30 @@ ${getUsage}`);
2331
2450
  for (const [name, file] of files) {
2332
2451
  const value = entries(file).get(key);
2333
2452
  if (value !== undefined)
2334
- rows.push([name, display(key, value, known)]);
2453
+ rows.push(row(name, key, value, known));
2335
2454
  }
2336
2455
  if (rows.length === 0)
2337
2456
  fail(`${key} is not set in ${file ?? "any .env* file"}`, 1);
2338
- console.log(file === undefined ? table(rows) : rows[0]?.[1]);
2457
+ printRows(rows, parsed.values.json === true, () => console.log(file === undefined ? table(rows.map((each) => [each.file, each.value])) : rows[0]?.value));
2339
2458
  return 0;
2340
2459
  }
2341
2460
  var grepUsage = `ev grep [-i] <regex> [file...]
2342
2461
 
2343
2462
  Prints the keys matching the regular expression, from the folder's .env* files or the files given, with their values masked as ev list does. The regex is matched against the key only, never the value: \`ev grep '^DATABASE_'\` instead of \`grep ^DATABASE_ .env\`.
2344
2463
 
2464
+ --json prints [{file, key, value, secret}].
2465
+
2345
2466
  Exits 0 when a key matches, 1 when none does, 2 on a usage error.`;
2346
2467
  var showUsage = `ev show <rev>:<file>
2347
2468
 
2348
2469
  Prints every key of an env file as a git revision holds it, values masked as ev list does: \`ev show HEAD~1:api/.env\` instead of \`git show HEAD~1:api/.env\`.
2349
2470
 
2471
+ --json prints [{file, key, value, secret}].
2472
+
2350
2473
  Exits 0 when it printed them, 1 when git cannot show the file, 2 on a usage error.`;
2351
2474
  var REVISION = /^([^:]+):(.+)$/;
2352
2475
  async function grep(args) {
2353
- const parsed = parse(args, grepUsage, { "ignore-case": { type: "boolean", short: "i", description: "match the key whatever its case" } });
2476
+ const parsed = parse(args, grepUsage, { "ignore-case": { type: "boolean", short: "i", description: "match the key whatever its case" }, ...jsonFlag2 });
2354
2477
  const [source, ...given] = parsed.positionals;
2355
2478
  if (source === undefined)
2356
2479
  fail(`missing the regex
@@ -2368,16 +2491,16 @@ ${grepUsage}`);
2368
2491
  for (const [name, file] of files) {
2369
2492
  for (const [key, value] of entries(file)) {
2370
2493
  if (pattern.test(key))
2371
- rows.push([name, key, display(key, value, known)]);
2494
+ rows.push(row(name, key, value, known));
2372
2495
  }
2373
2496
  }
2374
2497
  if (rows.length === 0)
2375
2498
  fail(`no key matches ${source} in ${names.join(", ") || "any .env* file"}`, 1);
2376
- console.log(table(rows));
2499
+ printRows(rows, parsed.values.json === true, () => console.log(table(rows.map((each) => [each.file, each.key, each.value]))));
2377
2500
  return 0;
2378
2501
  }
2379
2502
  async function show(args) {
2380
- const parsed = parse(args, showUsage, {});
2503
+ const parsed = parse(args, showUsage, jsonFlag2);
2381
2504
  const [target] = parsed.positionals;
2382
2505
  const [, revision, path] = REVISION.exec(target ?? "") ?? [];
2383
2506
  if (revision === undefined || path === undefined)
@@ -2391,16 +2514,17 @@ ${showUsage}`);
2391
2514
  fail(`git show ${revision}:${path} failed: ${shown.stderr.toString().trim()}`, 1);
2392
2515
  const file = parseDotenv(shown.stdout.toString());
2393
2516
  const known = await loadKnown(process.cwd(), [file]);
2394
- const rows = [...entries(file)].map(([key, value]) => [key, display(key, value, known)]);
2395
- if (rows.length > 0)
2396
- console.log(table(rows));
2517
+ const rows = [...entries(file)].map(([key, value]) => row(target ?? "", key, value, known));
2518
+ printRows(rows, parsed.values.json === true, () => {
2519
+ if (rows.length > 0)
2520
+ console.log(table(rows.map((each) => [each.key, each.value])));
2521
+ });
2397
2522
  return 0;
2398
2523
  }
2399
2524
 
2400
2525
  // src/ev.ts
2401
2526
  process11.exitCode = await runCli({
2402
2527
  name: "ev",
2403
- version,
2404
2528
  about: ".env files listed and edited with secrets masked",
2405
2529
  replaces: "cat .env, grep on env files and editing them by hand",
2406
2530
  examples: ["ev list", ["ev get DATABASE_URL", "one key, its value masked"]],