@kaynooo/cli-env 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/redact.js CHANGED
@@ -2,16 +2,16 @@
2
2
  // @bun
3
3
 
4
4
  // src/redact.ts
5
- import process10 from "process";
5
+ import process14 from "process";
6
6
  // ../kit/src/args.ts
7
- import process6 from "process";
7
+ import process9 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // ../kit/src/format.ts
11
- import process3 from "process";
11
+ import process6 from "process";
12
12
 
13
13
  // ../kit/src/style.ts
14
- import process2 from "process";
14
+ import process5 from "process";
15
15
 
16
16
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
17
  function x(s) {
@@ -274,36 +274,222 @@ function le(i = {}) {
274
274
  }
275
275
  var t = le();
276
276
 
277
- // ../kit/src/style.ts
278
- var MARKS = {
279
- ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
280
- warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
281
- problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
282
- note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
277
+ // ../kit/src/theme.ts
278
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
279
+ import { homedir as homedir2 } from "os";
280
+ import { join as join3, resolve as resolve2 } from "path";
281
+ import process4 from "process";
282
+
283
+ // ../kit/src/config.ts
284
+ import { existsSync } from "fs";
285
+ import { dirname, join, resolve } from "path";
286
+ import process2 from "process";
287
+ function findUp(names, from = process2.cwd(), stop = () => false) {
288
+ const wanted = typeof names === "string" ? [names] : names;
289
+ for (let dir = resolve(from);; dir = dirname(dir)) {
290
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
291
+ if (found !== undefined)
292
+ return found;
293
+ if (stop(dir) || dirname(dir) === dir)
294
+ return;
295
+ }
296
+ }
297
+
298
+ // ../kit/src/user-config.ts
299
+ import { homedir } from "os";
300
+ import { join as join2 } from "path";
301
+ import process3 from "process";
302
+ function configBase(where = {}) {
303
+ const xdg = where.xdg ?? (where.home === undefined ? process3.env.XDG_CONFIG_HOME : undefined);
304
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
305
+ }
306
+ function userConfigPath(bin, where = {}) {
307
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
308
+ }
309
+
310
+ // ../kit/src/theme.ts
311
+ var DEFAULT = {
312
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
313
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
314
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
315
+ bins: {}
283
316
  };
284
- function takesControlCodes(stream, env = process2.env) {
317
+ var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
318
+ var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
319
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
320
+ var PRESETS = {
321
+ default: {},
322
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
323
+ mono: { colors: MONO, accents: ["bold"] },
324
+ ascii: { glyphs: ASCII }
325
+ };
326
+ var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
327
+ var HEX = /^#[0-9a-f]{6}$/i;
328
+ var CONTROL = /\p{Cc}/u;
329
+ var MAX_FILE_BYTES = 64 * 1024;
330
+ var SPACES = /\s+/;
331
+ function isColorSpec(spec) {
332
+ if (typeof spec === "number")
333
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
334
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
335
+ }
336
+ function tinted(colors, spec) {
337
+ if (typeof spec === "number")
338
+ return colors.ansi256(spec);
339
+ return spec.trim().split(SPACES).reduce((chain, token) => HEX.test(token) ? chain.hex(token) : chain[token] ?? chain, colors);
340
+ }
341
+ function isRecord(value) {
342
+ return typeof value === "object" && value !== null && !Array.isArray(value);
343
+ }
344
+ function readThemeFile(path, warn) {
345
+ try {
346
+ const stat = statSync(path, { throwIfNoEntry: false });
347
+ if (stat === undefined)
348
+ return;
349
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
350
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
351
+ return;
352
+ }
353
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
354
+ if (isRecord(parsed))
355
+ return parsed;
356
+ warn(`${path} is not a JSON object, theme ignored`);
357
+ } catch (error) {
358
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
359
+ }
360
+ return;
361
+ }
362
+ function applyPreset(theme, name, warn, where) {
363
+ if (name === undefined)
364
+ return;
365
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
366
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
367
+ return;
368
+ }
369
+ const preset = PRESETS[name];
370
+ Object.assign(theme.colors, preset.colors);
371
+ Object.assign(theme.glyphs, preset.glyphs);
372
+ if (preset.accents !== undefined)
373
+ theme.accents = [...preset.accents];
374
+ return name;
375
+ }
376
+ function applyFile(theme, file, where, warn) {
377
+ if (isRecord(file.colors)) {
378
+ for (const [key, value] of Object.entries(file.colors)) {
379
+ if (!Object.hasOwn(DEFAULT.colors, key))
380
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
381
+ else if (!isColorSpec(value))
382
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
383
+ else
384
+ theme.colors[key] = value;
385
+ }
386
+ }
387
+ if (isRecord(file.glyphs)) {
388
+ for (const [key, value] of Object.entries(file.glyphs)) {
389
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
390
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
391
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
392
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
393
+ else
394
+ theme.glyphs[key] = value;
395
+ }
396
+ }
397
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
398
+ theme.accents = [...file.accents];
399
+ else if (file.accents !== undefined)
400
+ warn(`${where}: accents must be a non-empty list of colours`);
401
+ if (isRecord(file.bins)) {
402
+ for (const [bin, value] of Object.entries(file.bins)) {
403
+ if (isColorSpec(value))
404
+ theme.bins[bin] = value;
405
+ else
406
+ warn(`${where}: bin ${bin} has no valid colour`);
407
+ }
408
+ }
409
+ }
410
+ function endsWalk(home) {
411
+ return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
412
+ }
413
+ var warned = new Set;
414
+ function warnOnce(message) {
415
+ if (warned.has(message))
416
+ return;
417
+ warned.add(message);
418
+ console.error(`warning: theme ${message}`);
419
+ }
420
+ function isPath(chosen) {
421
+ return chosen.includes("/") || chosen.endsWith(".json");
422
+ }
423
+ function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(), warn = warnOnce } = {}) {
424
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
425
+ const sources = [];
426
+ const chosen = env.KIT_THEME ?? "";
427
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
428
+ if (isPath(chosen))
429
+ wanted.push(resolve2(from, chosen));
430
+ const files = [];
431
+ for (const path of wanted) {
432
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
433
+ if (path !== undefined && file !== undefined)
434
+ files.push({ path, file });
435
+ }
436
+ let preset = "default";
437
+ if (chosen !== "" && !isPath(chosen)) {
438
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
439
+ } else {
440
+ const named = files.findLast(({ file }) => file.preset !== undefined);
441
+ if (named !== undefined)
442
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
443
+ }
444
+ for (const { path, file } of files) {
445
+ applyFile(theme, file, path, warn);
446
+ sources.push(path);
447
+ }
448
+ return { theme, sources, preset };
449
+ }
450
+ var current;
451
+ var currentKey = "";
452
+ function activeTheme() {
453
+ const key = `${process4.cwd()}\x00${process4.env.KIT_THEME ?? ""}\x00${process4.env.XDG_CONFIG_HOME ?? ""}`;
454
+ if (current === undefined || key !== currentKey) {
455
+ current = loadTheme();
456
+ currentKey = key;
457
+ }
458
+ return current;
459
+ }
460
+
461
+ // ../kit/src/style.ts
462
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:" };
463
+ function takesControlCodes(stream, env = process5.env) {
285
464
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
286
465
  }
287
- function paint(stream, env = process2.env) {
466
+ function paint(stream, env = process5.env) {
288
467
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
289
468
  }
290
- function marked(mark, text, stream, detail, env = process2.env) {
469
+ function marked(mark, text, stream, detail, env = process5.env) {
291
470
  const colors = paint(stream, env);
292
- const { symbol, word, paint: tint } = MARKS[mark];
293
- const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
471
+ let head = MARK_WORDS[mark];
472
+ if (takesControlCodes(stream, env)) {
473
+ const { theme } = activeTheme();
474
+ head = tinted(colors.bold, theme.colors[mark])(theme.glyphs[mark]);
475
+ }
294
476
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
295
477
  }
296
478
  function ok(text, detail) {
297
- console.log(marked("ok", text, process2.stdout, detail));
298
- }
299
- var STATUSES = {
300
- passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
301
- failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
302
- running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
303
- queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
304
- skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
479
+ console.log(marked("ok", text, process5.stdout, detail));
480
+ }
481
+ function role(name, stream, env = process5.env) {
482
+ const colors = paint(stream, env);
483
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name]) : colors;
484
+ }
485
+ var STATUS_WORDS = {
486
+ passed: ["passed", "success", "succeeded", "ok"],
487
+ failed: ["failed", "failure", "error", "errored"],
488
+ running: ["running", "in_progress", "started"],
489
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
490
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
305
491
  };
306
- var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
492
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
307
493
 
308
494
  // ../kit/src/format.ts
309
495
  function upTo(text, separator) {
@@ -318,7 +504,7 @@ var ESCAPE = String.fromCharCode(27);
318
504
  function textWidth(text) {
319
505
  return Bun.stringWidth(text);
320
506
  }
321
- function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
507
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process6.stdout } = {}) {
322
508
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
323
509
  const widths = [];
324
510
  for (const row of cells) {
@@ -326,7 +512,7 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
326
512
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
327
513
  }
328
514
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
329
- const colors = paint(process3.stdout);
515
+ const colors = paint(stream);
330
516
  const lines = shown.map((row) => row.map((cell, index) => {
331
517
  const width = widths[index] ?? 0;
332
518
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -334,7 +520,8 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
334
520
  return `${gap}${cell}`;
335
521
  return index === row.length - 1 ? cell : `${cell}${gap}`;
336
522
  }).join(" ").trimEnd());
337
- return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
523
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
524
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
338
525
  `);
339
526
  }
340
527
  function narrow(rows, widths, limit) {
@@ -358,27 +545,27 @@ function printJson(value) {
358
545
  }
359
546
 
360
547
  // ../kit/src/help.ts
361
- import process4 from "process";
548
+ import process7 from "process";
362
549
  var OPTIONAL = /\[[^\]]+\]/g;
363
550
  var USAGE_PREFIX = /^usage:\s*/i;
364
551
  var FULL_STOP = /\.$/;
365
- function usageLine(usage, colors = paint(process4.stdout)) {
552
+ function usageLine(usage, colors = paint(process7.stdout)) {
366
553
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
367
554
  }
368
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
555
+ function helpText(usage, options, colors = paint(process7.stdout), { examples = [], replaces, exits = [] } = {}) {
369
556
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
370
557
  `);
371
558
  }
372
- function exitRows(exits, colors = paint(process4.stdout)) {
559
+ function exitRows(exits, colors = paint(process7.stdout)) {
373
560
  if (exits.length === 0)
374
561
  return [];
375
562
  const width = Math.max(...exits.map(([code]) => String(code).length));
376
563
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
377
564
  }
378
- function replacesRows(replaces, colors = paint(process4.stdout)) {
565
+ function replacesRows(replaces, colors = paint(process7.stdout)) {
379
566
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
380
567
  }
381
- function wantsHelpJson(env = process4.env) {
568
+ function wantsHelpJson(env = process7.env) {
382
569
  return env.KIT_HELP === "json";
383
570
  }
384
571
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -397,12 +584,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
397
584
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
398
585
  };
399
586
  }
400
- function exampleRows(examples, colors = paint(process4.stdout)) {
587
+ function exampleRows(examples, colors = paint(process7.stdout)) {
401
588
  if (examples.length === 0)
402
589
  return [];
403
590
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
404
591
  }
405
- function optionRows(options, colors = paint(process4.stdout)) {
592
+ function optionRows(options, colors = paint(process7.stdout)) {
406
593
  const rows = Object.entries(options).map(([name, option]) => {
407
594
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
408
595
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -434,10 +621,10 @@ function closest(name, names) {
434
621
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
435
622
  }
436
623
  // ../kit/src/input.ts
437
- import process5 from "process";
624
+ import process8 from "process";
438
625
  async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
439
626
  if (path === "-") {
440
- if (process5.stdin.isTTY)
627
+ if (process8.stdin.isTTY)
441
628
  fail(noStdin);
442
629
  return Bun.stdin.text();
443
630
  }
@@ -496,7 +683,7 @@ var OUTPUT_OPTIONS = {
496
683
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
497
684
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
498
685
  };
499
- function applyOutput(color, plain, env = process6.env) {
686
+ function applyOutput(color, plain, env = process9.env) {
500
687
  const when = plain === true ? "never" : color ?? "auto";
501
688
  if (when === "auto")
502
689
  return;
@@ -671,15 +858,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
671
858
  var RESET_STYLE = `${ESC}[0m`;
672
859
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
673
860
  // ../kit/src/cli.ts
674
- import { readFileSync, realpathSync } from "fs";
675
- import { dirname as dirname2, join as join2 } from "path";
676
- import process8 from "process";
861
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
862
+ import { dirname as dirname3, join as join5 } from "path";
863
+ import process11 from "process";
677
864
 
678
865
  // ../kit/src/usage.ts
679
866
  import { appendFileSync, mkdirSync } from "fs";
680
- import { homedir } from "os";
681
- import { dirname, isAbsolute, join } from "path";
682
- import process7 from "process";
867
+ import { homedir as homedir3 } from "os";
868
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
869
+ import process10 from "process";
683
870
 
684
871
  // ../kit/src/logs.ts
685
872
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -693,14 +880,14 @@ var usageError;
693
880
  function noteUsageError(message) {
694
881
  usageError = message;
695
882
  }
696
- function stateHome(env = process7.env) {
883
+ function stateHome(env = process10.env) {
697
884
  const dir = env.XDG_STATE_HOME;
698
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
885
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
699
886
  }
700
- function usagePath(env = process7.env) {
701
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
887
+ function usagePath(env = process10.env) {
888
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
702
889
  }
703
- function usageRecorded(env = process7.env) {
890
+ function usageRecorded(env = process10.env) {
704
891
  const off = env.KAYNOOO_CLI_NO_USAGE;
705
892
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
706
893
  }
@@ -714,12 +901,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
714
901
  usageError = undefined;
715
902
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
716
903
  }
717
- function recordUsage(entry, env = process7.env) {
904
+ function recordUsage(entry, env = process10.env) {
718
905
  if (!usageRecorded(env))
719
906
  return;
720
907
  try {
721
908
  const path = usagePath(env);
722
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
909
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
723
910
  appendFileSync(path, `${JSON.stringify(entry)}
724
911
  `, { mode: 384 });
725
912
  } catch {}
@@ -805,8 +992,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
805
992
  `);
806
993
  }
807
994
  function printError(prefix, message, hint, cause) {
808
- const colors = paint(process8.stderr);
809
- const styled = takesControlCodes(process8.stderr);
995
+ const colors = paint(process11.stderr);
996
+ const styled = takesControlCodes(process11.stderr);
810
997
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
811
998
  const under = (label, text, tint) => text === undefined ? "" : `
812
999
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -825,7 +1012,7 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
825
1012
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
826
1013
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
827
1014
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
828
- if (error instanceof UsageError)
1015
+ if (error instanceof Exit && error.code === 2)
829
1016
  noteUsageError(error.message);
830
1017
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
831
1018
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
@@ -849,11 +1036,11 @@ async function dispatch(level, typed, { version, redact }) {
849
1036
  }
850
1037
  }
851
1038
  if (name === undefined && level.path.length > 1) {
852
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
1039
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stderr));
853
1040
  return 2;
854
1041
  }
855
1042
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
856
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
1043
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stdout));
857
1044
  return 0;
858
1045
  }
859
1046
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -970,17 +1157,17 @@ async function printCandidates(found) {
970
1157
  return 0;
971
1158
  }
972
1159
  function packageVersion(entry = Bun.main) {
973
- for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1160
+ for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
974
1161
  try {
975
- const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1162
+ const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
976
1163
  if (typeof version === "string")
977
1164
  return version;
978
1165
  } catch {}
979
- if (dirname2(dir) === dir)
1166
+ if (dirname3(dir) === dir)
980
1167
  return "0.0.0";
981
1168
  }
982
1169
  }
983
- async function runCli(cli, argv = process8.argv.slice(2)) {
1170
+ async function runCli(cli, argv = process11.argv.slice(2)) {
984
1171
  const version = cli.version ?? packageVersion();
985
1172
  if (argv[0] === COMPLETE)
986
1173
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -1007,7 +1194,7 @@ function commandPath(scope, argv) {
1007
1194
  }
1008
1195
  return path.length === 0 ? undefined : path.join(" ");
1009
1196
  }
1010
- async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
1197
+ async function runMain({ name, version, run, redact, usage }, argv = process11.argv.slice(2)) {
1011
1198
  if (argv[0] === COMPLETE)
1012
1199
  return printCandidates(leafCandidates(run, argv.slice(1)));
1013
1200
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1047,9 +1234,12 @@ function isSecretName(name) {
1047
1234
  var {Glob } = globalThis.Bun;
1048
1235
  var SESSION_FILES = new Glob("*.json");
1049
1236
  var ACCOUNT_DIRS = new Glob("*/sessions");
1237
+ // src/commands/redact.ts
1238
+ import process13 from "process";
1239
+
1050
1240
  // src/files.ts
1051
1241
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
1052
- import { basename, dirname as dirname3, join as join3 } from "path";
1242
+ import { basename, dirname as dirname4, join as join6 } from "path";
1053
1243
 
1054
1244
  // src/dotenv.ts
1055
1245
  var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
@@ -1361,7 +1551,7 @@ async function envFiles(folder = process.cwd()) {
1361
1551
  const found = await readdir(folder, { withFileTypes: true });
1362
1552
  const names = [];
1363
1553
  for (const entry of found) {
1364
- if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join3(folder, entry.name)))
1554
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join6(folder, entry.name)))
1365
1555
  names.push(entry.name);
1366
1556
  }
1367
1557
  return names.sort();
@@ -1385,7 +1575,7 @@ async function writeAtomic(path, text) {
1385
1575
  if (error.code !== "ENOENT")
1386
1576
  throw error;
1387
1577
  }
1388
- const temp = join3(dirname3(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1578
+ const temp = join6(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1389
1579
  try {
1390
1580
  await writeFile(temp, text, { mode: 384, flag: "wx" });
1391
1581
  if (owner !== undefined)
@@ -1441,7 +1631,7 @@ async function acquire(path) {
1441
1631
  try {
1442
1632
  real = await realpath(path);
1443
1633
  } catch {}
1444
- const lock = join3(dirname3(real), `.${basename(real)}.lock`);
1634
+ const lock = join6(dirname4(real), `.${basename(real)}.lock`);
1445
1635
  const deadline = Date.now() + LOCK_WAIT_MS;
1446
1636
  while (true) {
1447
1637
  try {
@@ -1476,7 +1666,7 @@ async function envFilesBelow(folder, depth = 0) {
1476
1666
  return found;
1477
1667
  }
1478
1668
  for (const entry of children) {
1479
- const path = join3(folder, entry.name);
1669
+ const path = join6(folder, entry.name);
1480
1670
  if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1481
1671
  found.push(...await envFilesBelow(path, depth + 1));
1482
1672
  else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
@@ -1609,7 +1799,7 @@ function check(text, known) {
1609
1799
  return findings;
1610
1800
  }
1611
1801
 
1612
- // src/redact.ts
1802
+ // src/commands/redact.ts
1613
1803
  var usage2 = `redact [--check]
1614
1804
 
1615
1805
  Copies stdin to stdout line by line with secrets masked: known token formats (GitHub, GitLab, Slack, AWS, npm, Stripe, Google and SendGrid keys, sk-, JWTs, Authorization headers, password= and secret= pairs), private key blocks, the password and the tokens of any URL and the values of secret-looking keys in this folder's .env* files.
@@ -1620,7 +1810,7 @@ var options = {
1620
1810
  check: { type: "boolean", description: "list where secrets are instead of masking them, exit 1 when found" },
1621
1811
  "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
1622
1812
  };
1623
- async function run(args) {
1813
+ async function redact(args) {
1624
1814
  const parsed = parse(args, usage2, options, { replaces: "printing a command's secrets into a log or a transcript", examples: [["docker compose config | redact", "the resolved compose file, secrets masked"], ["git diff --cached | redact --check", "refuse a commit carrying a secret"]] });
1625
1815
  const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
1626
1816
  if (parsed.values.check === true) {
@@ -1632,8 +1822,10 @@ async function run(args) {
1632
1822
  const redactor = new Redactor(known);
1633
1823
  const decoder = new TextDecoder;
1634
1824
  for await (const chunk of Bun.stdin.stream())
1635
- process10.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1636
- process10.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1825
+ process13.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1826
+ process13.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1637
1827
  return 0;
1638
1828
  }
1639
- process10.exitCode = await runMain({ name: "redact", run });
1829
+
1830
+ // src/redact.ts
1831
+ process14.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.9.1",
4
+ "version": "0.11.0",
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",
@@ -37,6 +37,6 @@
37
37
  "redact": "$npm_execpath src/redact.ts"
38
38
  },
39
39
  "devDependencies": {
40
- "@kaynooo/cli-kit": "0.21.0"
40
+ "@kaynooo/cli-kit": "0.21.1"
41
41
  }
42
42
  }
@@ -1,6 +1,6 @@
1
1
  import type { Dotenv } from '../dotenv'
2
2
  import type { KnownSecrets } from '../mask'
3
- import { fail, jsonOption, parse, printJson, table } from '@kaynooo/cli-kit'
3
+ import { fail, jsonOption, parse, printJson, role, table } from '@kaynooo/cli-kit'
4
4
  import { $ } from 'bun'
5
5
  import { entries, parseDotenv } from '../dotenv'
6
6
  import { envFiles, loadKnown, readEnv } from '../files'
@@ -30,6 +30,20 @@ const jsonFlag = { json: jsonOption() } as const
30
30
 
31
31
  interface Row { file: string, key: string, value: string, secret: boolean }
32
32
 
33
+ // A row per key with its file name in the path colour and the key bold on a terminal.
34
+ function keyTable(rows: Row[]): string {
35
+ const path = role('path', process.stdout)
36
+ const key = role('value', process.stdout)
37
+
38
+ return table(rows.map(each => [path(each.file), key(each.key), each.value]))
39
+ }
40
+
41
+ function fileTable(rows: Row[]): string {
42
+ const path = role('path', process.stdout)
43
+
44
+ return table(rows.map(each => [path(each.file), each.value]))
45
+ }
46
+
33
47
  // A value is secret when it is masked, or when its key is named like a secret even with nothing to mask.
34
48
  function row(file: string, key: string, value: string, known: KnownSecrets): Row {
35
49
  const shown = display(key, value, known)
@@ -74,7 +88,7 @@ export async function list(args: string[]): Promise<number> {
74
88
 
75
89
  printRows(rows, parsed.values.json === true, () => {
76
90
  if (rows.length > 0)
77
- console.log(table(rows.map(each => [each.file, each.key, each.value])))
91
+ console.log(keyTable(rows))
78
92
  })
79
93
 
80
94
  return 0
@@ -103,7 +117,7 @@ export async function get(args: string[]): Promise<number> {
103
117
  if (rows.length === 0)
104
118
  fail(`${key} is not set in ${file ?? 'any .env* file'}`, 1)
105
119
 
106
- printRows(rows, parsed.values.json === true, () => console.log(file === undefined ? table(rows.map(each => [each.file, each.value])) : rows[0]?.value))
120
+ printRows(rows, parsed.values.json === true, () => console.log(file === undefined ? fileTable(rows) : rows[0]?.value))
107
121
 
108
122
  return 0
109
123
  }
@@ -158,7 +172,7 @@ export async function grep(args: string[]): Promise<number> {
158
172
  if (rows.length === 0)
159
173
  fail(`no key matches ${source} in ${names.join(', ') || 'any .env* file'}`, 1)
160
174
 
161
- printRows(rows, parsed.values.json === true, () => console.log(table(rows.map(each => [each.file, each.key, each.value]))))
175
+ printRows(rows, parsed.values.json === true, () => console.log(keyTable(rows)))
162
176
 
163
177
  return 0
164
178
  }