@kaynooo/cli-env 0.8.0 → 0.8.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 +348 -134
- package/dist/redact.js +320 -106
- package/package.json +2 -2
package/dist/ev.js
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/ev.ts
|
|
5
|
-
import
|
|
5
|
+
import process11 from "process";
|
|
6
6
|
|
|
7
7
|
// ../kit/src/args.ts
|
|
8
|
-
import
|
|
8
|
+
import process6 from "process";
|
|
9
9
|
import { parseArgs } from "util";
|
|
10
10
|
|
|
11
11
|
// ../kit/src/format.ts
|
|
@@ -14,7 +14,7 @@ import process3 from "process";
|
|
|
14
14
|
// ../kit/src/style.ts
|
|
15
15
|
import process2 from "process";
|
|
16
16
|
|
|
17
|
-
// ../../node_modules/.bun/@kaynooo+utils@2.31.
|
|
17
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
18
18
|
function x(s) {
|
|
19
19
|
let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
|
|
20
20
|
if (!/^[a-f0-9]+$/.test(r))
|
|
@@ -234,7 +234,7 @@ class e {
|
|
|
234
234
|
}
|
|
235
235
|
}
|
|
236
236
|
|
|
237
|
-
// ../../node_modules/.bun/@kaynooo+utils@2.31.
|
|
237
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
|
|
238
238
|
var r = 39;
|
|
239
239
|
var o = 49;
|
|
240
240
|
var f2 = "\x1B[";
|
|
@@ -358,6 +358,55 @@ function printJson(value) {
|
|
|
358
358
|
console.log(JSON.stringify(value, undefined, 2));
|
|
359
359
|
}
|
|
360
360
|
|
|
361
|
+
// ../kit/src/help.ts
|
|
362
|
+
import process4 from "process";
|
|
363
|
+
var OPTIONAL = /\[[^\]]+\]/g;
|
|
364
|
+
var USAGE_PREFIX = /^usage:\s*/i;
|
|
365
|
+
var FULL_STOP = /\.$/;
|
|
366
|
+
function usageLine(usage, colors = paint(process4.stdout)) {
|
|
367
|
+
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
368
|
+
}
|
|
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(`
|
|
371
|
+
`);
|
|
372
|
+
}
|
|
373
|
+
function replacesRows(replaces, colors = paint(process4.stdout)) {
|
|
374
|
+
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
375
|
+
}
|
|
376
|
+
function wantsHelpJson(env = process4.env) {
|
|
377
|
+
return env.KIT_HELP === "json";
|
|
378
|
+
}
|
|
379
|
+
function description(usage, { examples = [], replaces } = {}) {
|
|
380
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
381
|
+
`);
|
|
382
|
+
const first = lines[0];
|
|
383
|
+
const colon = first.indexOf(": ");
|
|
384
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
385
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
386
|
+
return {
|
|
387
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
388
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
389
|
+
...replaces === undefined ? {} : { replaces },
|
|
390
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
function exampleRows(examples, colors = paint(process4.stdout)) {
|
|
394
|
+
if (examples.length === 0)
|
|
395
|
+
return [];
|
|
396
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
397
|
+
}
|
|
398
|
+
function optionRows(options, colors = paint(process4.stdout)) {
|
|
399
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
400
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
401
|
+
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
402
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
403
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
404
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
|
|
405
|
+
});
|
|
406
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
407
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
408
|
+
}
|
|
409
|
+
|
|
361
410
|
// ../kit/src/text.ts
|
|
362
411
|
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
363
412
|
function distance(a, b) {
|
|
@@ -377,8 +426,22 @@ function closest(name, names) {
|
|
|
377
426
|
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
378
427
|
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
379
428
|
}
|
|
429
|
+
// ../kit/src/input.ts
|
|
430
|
+
import process5 from "process";
|
|
431
|
+
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
432
|
+
if (path === "-") {
|
|
433
|
+
if (process5.stdin.isTTY)
|
|
434
|
+
fail(noStdin);
|
|
435
|
+
return Bun.stdin.text();
|
|
436
|
+
}
|
|
437
|
+
const file = Bun.file(path);
|
|
438
|
+
if (!await file.exists())
|
|
439
|
+
fail(`no file ${path}`);
|
|
440
|
+
return file.text();
|
|
441
|
+
}
|
|
380
442
|
|
|
381
443
|
// ../kit/src/args.ts
|
|
444
|
+
var DASHES = /^-+/;
|
|
382
445
|
function jsonOption(holds) {
|
|
383
446
|
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
384
447
|
}
|
|
@@ -413,61 +476,20 @@ class HelpShown extends Exit {
|
|
|
413
476
|
|
|
414
477
|
class Completing {
|
|
415
478
|
options;
|
|
416
|
-
|
|
479
|
+
positionals;
|
|
480
|
+
candidates;
|
|
481
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
417
482
|
this.options = options;
|
|
483
|
+
this.positionals = positionals;
|
|
484
|
+
this.candidates = candidates;
|
|
418
485
|
}
|
|
419
486
|
}
|
|
420
487
|
var completion = { active: false };
|
|
421
|
-
var OPTIONAL = /\[[^\]]+\]/g;
|
|
422
|
-
var USAGE_PREFIX = /^usage:\s*/i;
|
|
423
|
-
var FULL_STOP = /\.$/;
|
|
424
|
-
var DASHES = /^-+/;
|
|
425
|
-
function usageLine(usage, colors = paint(process4.stdout)) {
|
|
426
|
-
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
427
|
-
}
|
|
428
|
-
function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces } = {}) {
|
|
429
|
-
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
|
|
430
|
-
`);
|
|
431
|
-
}
|
|
432
|
-
function replacesRows(replaces, colors = paint(process4.stdout)) {
|
|
433
|
-
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
434
|
-
}
|
|
435
|
-
function wantsHelpJson(env = process4.env) {
|
|
436
|
-
return env.KIT_HELP === "json";
|
|
437
|
-
}
|
|
438
|
-
function description(usage, { examples = [], replaces } = {}) {
|
|
439
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
440
|
-
`);
|
|
441
|
-
const first = lines[0];
|
|
442
|
-
const colon = first.indexOf(": ");
|
|
443
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
444
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
445
|
-
return {
|
|
446
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
447
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
448
|
-
...replaces === undefined ? {} : { replaces },
|
|
449
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
450
|
-
};
|
|
451
|
-
}
|
|
452
|
-
function exampleRows(examples, colors = paint(process4.stdout)) {
|
|
453
|
-
if (examples.length === 0)
|
|
454
|
-
return [];
|
|
455
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
456
|
-
}
|
|
457
|
-
function optionRows(options, colors = paint(process4.stdout)) {
|
|
458
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
459
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
460
|
-
const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
|
|
461
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
|
|
462
|
-
});
|
|
463
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
464
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
465
|
-
}
|
|
466
488
|
var OUTPUT_OPTIONS = {
|
|
467
489
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
468
490
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
469
491
|
};
|
|
470
|
-
function applyOutput(color, plain, env =
|
|
492
|
+
function applyOutput(color, plain, env = process6.env) {
|
|
471
493
|
const when = plain === true ? "never" : color ?? "auto";
|
|
472
494
|
if (when === "auto")
|
|
473
495
|
return;
|
|
@@ -484,14 +506,13 @@ function applyOutput(color, plain, env = process4.env) {
|
|
|
484
506
|
function parse(args, usage, options, settings = {}) {
|
|
485
507
|
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
486
508
|
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
509
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
487
510
|
if (completion.active)
|
|
488
|
-
throw new Completing(
|
|
489
|
-
const
|
|
490
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
491
|
-
const rest = separator === -1 ? undefined : args.slice(separator + 1);
|
|
511
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
512
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
492
513
|
let parsed;
|
|
493
514
|
try {
|
|
494
|
-
parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
515
|
+
parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
495
516
|
} catch (error) {
|
|
496
517
|
const message = parseError(error);
|
|
497
518
|
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
@@ -499,12 +520,84 @@ function parse(args, usage, options, settings = {}) {
|
|
|
499
520
|
const values = parsed.values;
|
|
500
521
|
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
501
522
|
if (values.help === true) {
|
|
502
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage,
|
|
523
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
|
|
503
524
|
throw new HelpShown;
|
|
504
525
|
}
|
|
526
|
+
checkChoices(parsed.values, all);
|
|
527
|
+
checkConflicts(parsed.values, all);
|
|
505
528
|
if (settings.positionals !== undefined)
|
|
506
529
|
checkPositionals(parsed.positionals, settings.positionals);
|
|
507
|
-
return { ...parsed, positionals: parsed.positionals, rest };
|
|
530
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
531
|
+
}
|
|
532
|
+
function splitRest(args, passes) {
|
|
533
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
534
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
535
|
+
}
|
|
536
|
+
function splitTrailing(args, options, count) {
|
|
537
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
538
|
+
let seen = 0;
|
|
539
|
+
if (count === 0)
|
|
540
|
+
return { own: args, rest: undefined };
|
|
541
|
+
for (let at = 0;at < args.length; at++) {
|
|
542
|
+
const word = args[at];
|
|
543
|
+
if (word === "--")
|
|
544
|
+
break;
|
|
545
|
+
if (word.startsWith("-")) {
|
|
546
|
+
if (takesValue(word))
|
|
547
|
+
at++;
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
seen++;
|
|
551
|
+
if (seen === count)
|
|
552
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
553
|
+
}
|
|
554
|
+
return { own: args, rest: undefined };
|
|
555
|
+
}
|
|
556
|
+
function listed(options, allowNegative) {
|
|
557
|
+
if (!allowNegative)
|
|
558
|
+
return options;
|
|
559
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
560
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
561
|
+
return [[name, option]];
|
|
562
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
563
|
+
}));
|
|
564
|
+
}
|
|
565
|
+
function withBare(args, options) {
|
|
566
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
567
|
+
if (bare.size === 0)
|
|
568
|
+
return args;
|
|
569
|
+
const separator = args.indexOf("--");
|
|
570
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
571
|
+
return [...own.flatMap((arg, index) => {
|
|
572
|
+
const optional = bare.get(arg);
|
|
573
|
+
const next = own[index + 1];
|
|
574
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
575
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
576
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
577
|
+
}
|
|
578
|
+
function checkConflicts(values, options) {
|
|
579
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
580
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
581
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
582
|
+
if (other !== undefined)
|
|
583
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
function checkChoices(values, options) {
|
|
587
|
+
for (const [name, option] of Object.entries(options)) {
|
|
588
|
+
if (option.choices === undefined)
|
|
589
|
+
continue;
|
|
590
|
+
const given = values[name];
|
|
591
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
592
|
+
if (typeof value === "string")
|
|
593
|
+
oneOf(value, name, option.choices);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function oneOf(value, name, choices) {
|
|
598
|
+
if (!choices.includes(value))
|
|
599
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
600
|
+
return value;
|
|
508
601
|
}
|
|
509
602
|
function checkPositionals(given, names) {
|
|
510
603
|
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
@@ -553,31 +646,73 @@ function nearestOption(message, options, allowNegative) {
|
|
|
553
646
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
554
647
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
555
648
|
}
|
|
556
|
-
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
557
|
-
if (path === "-") {
|
|
558
|
-
if (process4.stdin.isTTY)
|
|
559
|
-
fail(noStdin);
|
|
560
|
-
return Bun.stdin.text();
|
|
561
|
-
}
|
|
562
|
-
const file = Bun.file(path);
|
|
563
|
-
if (!await file.exists())
|
|
564
|
-
fail(`no file ${path}`);
|
|
565
|
-
return file.text();
|
|
566
|
-
}
|
|
567
649
|
// ../kit/src/progress.ts
|
|
568
650
|
var ESC = String.fromCharCode(27);
|
|
569
651
|
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
570
652
|
var RESET_STYLE = `${ESC}[0m`;
|
|
571
653
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
572
654
|
// ../kit/src/cli.ts
|
|
573
|
-
import
|
|
655
|
+
import process8 from "process";
|
|
656
|
+
|
|
657
|
+
// ../kit/src/usage.ts
|
|
658
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
659
|
+
import { homedir } from "os";
|
|
660
|
+
import { dirname, isAbsolute, join } from "path";
|
|
661
|
+
import process7 from "process";
|
|
662
|
+
|
|
663
|
+
// ../kit/src/logs.ts
|
|
664
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
665
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
666
|
+
|
|
667
|
+
// ../kit/src/usage.ts
|
|
668
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
669
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
670
|
+
var LONGEST_NAME = 40;
|
|
671
|
+
var usageError;
|
|
672
|
+
function noteUsageError(message) {
|
|
673
|
+
usageError = message;
|
|
674
|
+
}
|
|
675
|
+
function stateHome(env = process7.env) {
|
|
676
|
+
const dir = env.XDG_STATE_HOME;
|
|
677
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
678
|
+
}
|
|
679
|
+
function usagePath(env = process7.env) {
|
|
680
|
+
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
681
|
+
}
|
|
682
|
+
function usageRecorded(env = process7.env) {
|
|
683
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
684
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
685
|
+
}
|
|
686
|
+
function flagNames(argv) {
|
|
687
|
+
const end = argv.indexOf("--");
|
|
688
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
689
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
690
|
+
}
|
|
691
|
+
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
692
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
693
|
+
usageError = undefined;
|
|
694
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
695
|
+
}
|
|
696
|
+
function recordUsage(entry, env = process7.env) {
|
|
697
|
+
if (!usageRecorded(env))
|
|
698
|
+
return;
|
|
699
|
+
try {
|
|
700
|
+
const path = usagePath(env);
|
|
701
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
702
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
703
|
+
`, { mode: 384 });
|
|
704
|
+
} catch {}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// ../kit/src/cli.ts
|
|
574
708
|
var LEVEL_OPTIONS = {
|
|
575
709
|
...OUTPUT_OPTIONS,
|
|
576
710
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
577
711
|
};
|
|
578
712
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
579
|
-
async function commandRows(
|
|
580
|
-
const
|
|
713
|
+
async function commandRows(all, colors) {
|
|
714
|
+
const commands = shown(all);
|
|
715
|
+
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
581
716
|
const groups = new Map([["Commands:", []]]);
|
|
582
717
|
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
583
718
|
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
@@ -588,6 +723,9 @@ async function commandRows(commands, colors) {
|
|
|
588
723
|
}
|
|
589
724
|
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
590
725
|
}
|
|
726
|
+
function shown(commands) {
|
|
727
|
+
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
728
|
+
}
|
|
591
729
|
function takeOutputFlags(argv) {
|
|
592
730
|
let index = 0;
|
|
593
731
|
for (;index < argv.length; index++) {
|
|
@@ -619,7 +757,7 @@ async function expand(scope, words) {
|
|
|
619
757
|
}
|
|
620
758
|
return { ...scope, commands, lazy: [] };
|
|
621
759
|
}
|
|
622
|
-
async function
|
|
760
|
+
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
623
761
|
const colors = paint(stream);
|
|
624
762
|
const prefix = path.join(" ");
|
|
625
763
|
const summary = await resolveSummary(lazySummary);
|
|
@@ -646,8 +784,8 @@ async function help({ path, header, summary: lazySummary, commands, defaultComma
|
|
|
646
784
|
`);
|
|
647
785
|
}
|
|
648
786
|
function printError(prefix, message, hint, cause) {
|
|
649
|
-
const colors = paint(
|
|
650
|
-
const styled = takesControlCodes(
|
|
787
|
+
const colors = paint(process8.stderr);
|
|
788
|
+
const styled = takesControlCodes(process8.stderr);
|
|
651
789
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
652
790
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
653
791
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -666,6 +804,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
666
804
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
667
805
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
668
806
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
807
|
+
if (error instanceof UsageError)
|
|
808
|
+
noteUsageError(error.message);
|
|
669
809
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
670
810
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
671
811
|
return error instanceof Exit ? error.code : 1;
|
|
@@ -679,12 +819,20 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
679
819
|
return reportThrown(prefix, error);
|
|
680
820
|
}
|
|
681
821
|
const [name, ...args] = argv;
|
|
822
|
+
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
823
|
+
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
824
|
+
try {
|
|
825
|
+
return await fallback.run([]);
|
|
826
|
+
} catch (error) {
|
|
827
|
+
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
682
830
|
if (name === undefined && level.path.length > 1) {
|
|
683
|
-
console.error(await
|
|
831
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
|
|
684
832
|
return 2;
|
|
685
833
|
}
|
|
686
834
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
687
|
-
console.log(await
|
|
835
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
|
|
688
836
|
return 0;
|
|
689
837
|
}
|
|
690
838
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -693,6 +841,7 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
693
841
|
}
|
|
694
842
|
let command = level.commands[level.aliases?.[name] ?? name];
|
|
695
843
|
let rest = args;
|
|
844
|
+
let ran = name;
|
|
696
845
|
if (command === undefined && level.lazy.length > 0) {
|
|
697
846
|
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
698
847
|
command = level.commands[level.aliases?.[name] ?? name];
|
|
@@ -700,40 +849,77 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
700
849
|
if (command === undefined && level.defaultCommand !== undefined) {
|
|
701
850
|
command = level.commands[level.defaultCommand];
|
|
702
851
|
rest = argv;
|
|
852
|
+
ran = level.defaultCommand;
|
|
703
853
|
}
|
|
704
854
|
if (command === undefined) {
|
|
705
|
-
const meant = closest(name, Object.keys(level.commands));
|
|
855
|
+
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
706
856
|
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
707
857
|
return 2;
|
|
708
858
|
}
|
|
709
859
|
if ("commands" in command) {
|
|
710
860
|
const { summary } = command;
|
|
711
|
-
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
861
|
+
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
712
862
|
}
|
|
713
863
|
try {
|
|
714
864
|
return await command.run(rest);
|
|
715
865
|
} catch (error) {
|
|
716
|
-
return reportThrown(`${prefix} ${
|
|
866
|
+
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
717
867
|
}
|
|
718
868
|
}
|
|
719
869
|
var COMPLETE = "__complete";
|
|
720
870
|
var FILES = "__files__";
|
|
721
|
-
async function
|
|
871
|
+
async function completingOf(run) {
|
|
722
872
|
completion.active = true;
|
|
723
873
|
try {
|
|
724
874
|
await run([]);
|
|
725
875
|
} catch (error) {
|
|
726
876
|
if (error instanceof Completing)
|
|
727
|
-
return error
|
|
877
|
+
return error;
|
|
728
878
|
} finally {
|
|
729
879
|
completion.active = false;
|
|
730
880
|
}
|
|
731
|
-
return {};
|
|
881
|
+
return new Completing({});
|
|
882
|
+
}
|
|
883
|
+
async function optionsOf(run) {
|
|
884
|
+
return (await completingOf(run)).options;
|
|
885
|
+
}
|
|
886
|
+
function candidateLine(candidate) {
|
|
887
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
888
|
+
}
|
|
889
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
890
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
891
|
+
let index = 0;
|
|
892
|
+
let at = 0;
|
|
893
|
+
while (at < before.length) {
|
|
894
|
+
const word = before[at];
|
|
895
|
+
if (word === "--") {
|
|
896
|
+
index += before.length - at - 1;
|
|
897
|
+
break;
|
|
898
|
+
}
|
|
899
|
+
if (!word.startsWith("-"))
|
|
900
|
+
index++;
|
|
901
|
+
else if (takesValue(word))
|
|
902
|
+
at++;
|
|
903
|
+
at++;
|
|
904
|
+
}
|
|
905
|
+
const last = positionals.at(-1);
|
|
906
|
+
if (index < positionals.length)
|
|
907
|
+
return positionals[index];
|
|
908
|
+
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
732
909
|
}
|
|
733
910
|
async function leafCandidates(run, words) {
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
911
|
+
const completing = await completingOf(run);
|
|
912
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
913
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
914
|
+
const flag = words.at(-2);
|
|
915
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
916
|
+
if (option?.type === "string") {
|
|
917
|
+
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
918
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
919
|
+
}
|
|
920
|
+
const name = positionalBeingTyped(words.slice(0, -1), completing);
|
|
921
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
922
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
737
923
|
}
|
|
738
924
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
739
925
|
const [word = "", ...rest] = words;
|
|
@@ -744,8 +930,13 @@ async function candidates(scope, defaultCommand, words, before = []) {
|
|
|
744
930
|
({ commands, aliases } = await expand(scope, [...before, ...words]));
|
|
745
931
|
command = commands[aliases?.[word] ?? word];
|
|
746
932
|
}
|
|
747
|
-
if (listing)
|
|
748
|
-
|
|
933
|
+
if (listing) {
|
|
934
|
+
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
935
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
936
|
+
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
937
|
+
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
938
|
+
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
|
|
939
|
+
}
|
|
749
940
|
if (command === undefined) {
|
|
750
941
|
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
751
942
|
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
@@ -757,26 +948,49 @@ async function printCandidates(found) {
|
|
|
757
948
|
console.log(line);
|
|
758
949
|
return 0;
|
|
759
950
|
}
|
|
760
|
-
async function runCli(cli, argv =
|
|
951
|
+
async function runCli(cli, argv = process8.argv.slice(2)) {
|
|
761
952
|
if (argv[0] === COMPLETE)
|
|
762
953
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
763
|
-
|
|
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 });
|
|
955
|
+
if (cli.usage !== false) {
|
|
956
|
+
try {
|
|
957
|
+
recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
|
|
958
|
+
} catch {}
|
|
959
|
+
}
|
|
960
|
+
return code;
|
|
961
|
+
}
|
|
962
|
+
function commandPath(scope, argv) {
|
|
963
|
+
const path = [];
|
|
964
|
+
let level = scope;
|
|
965
|
+
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
966
|
+
const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
|
|
967
|
+
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
968
|
+
if (command === undefined)
|
|
969
|
+
break;
|
|
970
|
+
path.push(word);
|
|
971
|
+
if (!("commands" in command))
|
|
972
|
+
break;
|
|
973
|
+
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
974
|
+
}
|
|
975
|
+
return path.length === 0 ? undefined : path.join(" ");
|
|
764
976
|
}
|
|
765
|
-
async function runMain({ name, version, run, redact }, argv =
|
|
977
|
+
async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
|
|
766
978
|
if (argv[0] === COMPLETE)
|
|
767
979
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
768
980
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
769
981
|
console.log(version);
|
|
770
982
|
return 0;
|
|
771
983
|
}
|
|
984
|
+
let code;
|
|
772
985
|
try {
|
|
773
|
-
|
|
986
|
+
code = await run(argv);
|
|
774
987
|
} catch (error) {
|
|
775
|
-
|
|
988
|
+
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
776
989
|
}
|
|
990
|
+
if (usage !== false)
|
|
991
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
992
|
+
return code;
|
|
777
993
|
}
|
|
778
|
-
// ../kit/src/logs.ts
|
|
779
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
780
994
|
// ../kit/src/secrets.ts
|
|
781
995
|
var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
|
|
782
996
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
@@ -789,12 +1003,12 @@ var {Glob } = globalThis.Bun;
|
|
|
789
1003
|
var SESSION_FILES = new Glob("*.json");
|
|
790
1004
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
791
1005
|
// package.json
|
|
792
|
-
var version = "0.8.
|
|
1006
|
+
var version = "0.8.1";
|
|
793
1007
|
|
|
794
1008
|
// src/commands/audit.ts
|
|
795
1009
|
import { stat as stat4 } from "fs/promises";
|
|
796
1010
|
import { relative, resolve } from "path";
|
|
797
|
-
import
|
|
1011
|
+
import process10 from "process";
|
|
798
1012
|
|
|
799
1013
|
// ../kit/src/shell.ts
|
|
800
1014
|
var SEPARATORS = new Set([`
|
|
@@ -837,12 +1051,12 @@ function shellQuote(word) {
|
|
|
837
1051
|
|
|
838
1052
|
// src/audit.ts
|
|
839
1053
|
import { readdir as readdir2, stat as stat2 } from "fs/promises";
|
|
840
|
-
import { dirname as
|
|
1054
|
+
import { dirname as dirname3, join as join3 } from "path";
|
|
841
1055
|
var {$ } = globalThis.Bun;
|
|
842
1056
|
|
|
843
1057
|
// src/files.ts
|
|
844
1058
|
import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
|
|
845
|
-
import { basename, dirname, join } from "path";
|
|
1059
|
+
import { basename, dirname as dirname2, join as join2 } from "path";
|
|
846
1060
|
|
|
847
1061
|
// src/dotenv.ts
|
|
848
1062
|
var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
|
|
@@ -1148,7 +1362,7 @@ async function envFiles(folder = process.cwd()) {
|
|
|
1148
1362
|
const found = await readdir(folder, { withFileTypes: true });
|
|
1149
1363
|
const names = [];
|
|
1150
1364
|
for (const entry of found) {
|
|
1151
|
-
if (ENV_FILE.test(entry.name) && await isFileEntry(entry,
|
|
1365
|
+
if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join2(folder, entry.name)))
|
|
1152
1366
|
names.push(entry.name);
|
|
1153
1367
|
}
|
|
1154
1368
|
return names.sort();
|
|
@@ -1172,7 +1386,7 @@ async function writeAtomic(path, text) {
|
|
|
1172
1386
|
if (error.code !== "ENOENT")
|
|
1173
1387
|
throw error;
|
|
1174
1388
|
}
|
|
1175
|
-
const temp =
|
|
1389
|
+
const temp = join2(dirname2(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
|
|
1176
1390
|
try {
|
|
1177
1391
|
await writeFile(temp, text, { mode: 384, flag: "wx" });
|
|
1178
1392
|
if (owner !== undefined)
|
|
@@ -1210,7 +1424,7 @@ async function acquire(path) {
|
|
|
1210
1424
|
try {
|
|
1211
1425
|
real = await realpath(path);
|
|
1212
1426
|
} catch {}
|
|
1213
|
-
const lock =
|
|
1427
|
+
const lock = join2(dirname2(real), `.${basename(real)}.lock`);
|
|
1214
1428
|
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
1215
1429
|
while (true) {
|
|
1216
1430
|
try {
|
|
@@ -1248,7 +1462,7 @@ async function envFilesBelow(folder, depth = 0) {
|
|
|
1248
1462
|
return found;
|
|
1249
1463
|
}
|
|
1250
1464
|
for (const entry of children) {
|
|
1251
|
-
const path =
|
|
1465
|
+
const path = join2(folder, entry.name);
|
|
1252
1466
|
if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
|
|
1253
1467
|
found.push(...await envFilesBelow(path, depth + 1));
|
|
1254
1468
|
else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
|
|
@@ -1290,7 +1504,7 @@ function inlineSecrets(compose) {
|
|
|
1290
1504
|
async function openToOthers(path) {
|
|
1291
1505
|
if (((await stat2(path)).mode & 4) === 0)
|
|
1292
1506
|
return false;
|
|
1293
|
-
for (let dir =
|
|
1507
|
+
for (let dir = dirname3(path);dir !== "/"; dir = dirname3(dir)) {
|
|
1294
1508
|
if (((await stat2(dir)).mode & 1) === 0)
|
|
1295
1509
|
return false;
|
|
1296
1510
|
}
|
|
@@ -1301,7 +1515,7 @@ async function sharedWith(path) {
|
|
|
1301
1515
|
const shared = (info.mode & 32) !== 0 && info.gid !== info.uid && info.gid !== process.getgid?.();
|
|
1302
1516
|
if (!shared && (Bun.which("getfacl") === null || !await hasAclReader(path)))
|
|
1303
1517
|
return false;
|
|
1304
|
-
for (let dir =
|
|
1518
|
+
for (let dir = dirname3(path);dir !== "/"; dir = dirname3(dir)) {
|
|
1305
1519
|
if (((await stat2(dir)).mode & 9) === 0)
|
|
1306
1520
|
return false;
|
|
1307
1521
|
}
|
|
@@ -1313,7 +1527,7 @@ async function hasAclReader(path) {
|
|
|
1313
1527
|
`).some((line) => ACL_READER.test(line));
|
|
1314
1528
|
}
|
|
1315
1529
|
async function tracked(path) {
|
|
1316
|
-
const run = await $`git ls-files --error-unmatch -- ${path}`.cwd(
|
|
1530
|
+
const run = await $`git ls-files --error-unmatch -- ${path}`.cwd(dirname3(path)).quiet().nothrow();
|
|
1317
1531
|
const error = run.stderr.toString();
|
|
1318
1532
|
if (run.exitCode === 0)
|
|
1319
1533
|
return true;
|
|
@@ -1330,7 +1544,7 @@ async function* candidates2(root, unread, depth = 0) {
|
|
|
1330
1544
|
return;
|
|
1331
1545
|
}
|
|
1332
1546
|
for (const entry of found) {
|
|
1333
|
-
const path =
|
|
1547
|
+
const path = join3(root, entry.name);
|
|
1334
1548
|
if (entry.isDirectory() && depth < MAX_DEPTH && !SKIPPED2.has(entry.name))
|
|
1335
1549
|
yield* candidates2(path, unread, depth + 1);
|
|
1336
1550
|
else if (!TEMPLATE.test(entry.name) && (ENV_FILE.test(entry.name) || COMPOSE_FILE.test(entry.name)) && await isFileEntry(entry, path))
|
|
@@ -1362,7 +1576,7 @@ async function audit(roots) {
|
|
|
1362
1576
|
|
|
1363
1577
|
// src/fix.ts
|
|
1364
1578
|
import { chmod as chmod2, chown as chown2, lstat, rm as rm2, stat as stat3 } from "fs/promises";
|
|
1365
|
-
import { dirname as
|
|
1579
|
+
import { dirname as dirname4, join as join4 } from "path";
|
|
1366
1580
|
var MAP_ENTRY = /^(\s*)(["']?)([A-Z0-9_]+)\2(\s*:)(.*)$/;
|
|
1367
1581
|
var LIST_ENTRY = /^(\s*-[ \t]*)(["']?)([A-Z0-9_]+)=(.*)$/;
|
|
1368
1582
|
var TRAILING = /^\s*(?:#.*)?$/;
|
|
@@ -1433,7 +1647,7 @@ async function isLink(path) {
|
|
|
1433
1647
|
}
|
|
1434
1648
|
}
|
|
1435
1649
|
async function resolved(path) {
|
|
1436
|
-
const run = Bun.spawn(["docker", "compose", "-f", path, "config", "--format", "json"], { cwd:
|
|
1650
|
+
const run = Bun.spawn(["docker", "compose", "-f", path, "config", "--format", "json"], { cwd: dirname4(path), stdout: "pipe", stderr: "ignore", stdin: "ignore" });
|
|
1437
1651
|
const [out, code] = await Promise.all([new Response(run.stdout).text(), run.exited]);
|
|
1438
1652
|
return code === 0 ? out : undefined;
|
|
1439
1653
|
}
|
|
@@ -1453,7 +1667,7 @@ async function shutOthersOut(path, group = false) {
|
|
|
1453
1667
|
}
|
|
1454
1668
|
}
|
|
1455
1669
|
async function fixCompose(path, group = false) {
|
|
1456
|
-
const env =
|
|
1670
|
+
const env = join4(dirname4(path), ".env");
|
|
1457
1671
|
const compose = await Bun.file(path).text();
|
|
1458
1672
|
const envBefore = await Bun.file(env).exists() ? await Bun.file(env).text() : undefined;
|
|
1459
1673
|
const dotenv = parseDotenv(envBefore ?? "");
|
|
@@ -1546,7 +1760,7 @@ async function move(fix, compose, composeAfter, envBefore, envAfter) {
|
|
|
1546
1760
|
}
|
|
1547
1761
|
|
|
1548
1762
|
// src/commands/audit.ts
|
|
1549
|
-
var
|
|
1763
|
+
var usage2 = `ev audit [dir...] [--fix]
|
|
1550
1764
|
|
|
1551
1765
|
Lists the .env files any account on the machine can read or git tracks, and the compose files any account can read that write a secret out (a secret-named value or a URL password) instead of reading it from a .env, never printing a value.
|
|
1552
1766
|
Looks under each folder (the current one by default) down to 5 levels, skipping node_modules, vendor and .git, and leaves .example, .sample, .template and .dist files out. A folder it cannot read is named on stderr.
|
|
@@ -1570,8 +1784,8 @@ async function isFolder(path) {
|
|
|
1570
1784
|
return false;
|
|
1571
1785
|
}
|
|
1572
1786
|
}
|
|
1573
|
-
function
|
|
1574
|
-
return path.startsWith(`${
|
|
1787
|
+
function shown2(path) {
|
|
1788
|
+
return path.startsWith(`${process10.cwd()}/`) ? relative(process10.cwd(), path) : path;
|
|
1575
1789
|
}
|
|
1576
1790
|
async function fixAll(exposed, json) {
|
|
1577
1791
|
const fixed = [];
|
|
@@ -1585,21 +1799,21 @@ async function fixAll(exposed, json) {
|
|
|
1585
1799
|
if (json)
|
|
1586
1800
|
continue;
|
|
1587
1801
|
const lines = [
|
|
1588
|
-
...fix === undefined || fix.moved.length === 0 ? [] : [`moved ${fix.moved.join(", ")} into ${
|
|
1802
|
+
...fix === undefined || fix.moved.length === 0 ? [] : [`moved ${fix.moved.join(", ")} into ${shown2(fix.env)}`],
|
|
1589
1803
|
...fix?.left.map(({ key, why }) => `left ${key} in place: ${why}`) ?? [],
|
|
1590
1804
|
...fix?.check === undefined ? [] : [CHECKS[fix.check]],
|
|
1591
|
-
...open.map((file) => `another account owns ${file === path ? "it" :
|
|
1805
|
+
...open.map((file) => `another account owns ${file === path ? "it" : shown2(file)}, so it stays readable: sudo chmod go-rwx ${shellQuote(shown2(file))}`),
|
|
1592
1806
|
...readable && !open.includes(path) ? ["now unreadable by other accounts"] : [],
|
|
1593
|
-
...tracked ? [`tracked by git: git rm --cached ${shellQuote(
|
|
1807
|
+
...tracked ? [`tracked by git: git rm --cached ${shellQuote(shown2(path))}, then ignore it`] : []
|
|
1594
1808
|
];
|
|
1595
|
-
console.log(`${
|
|
1809
|
+
console.log(`${shown2(path)}
|
|
1596
1810
|
${lines.join(`
|
|
1597
1811
|
`)}`);
|
|
1598
1812
|
}
|
|
1599
1813
|
return { fixed, left };
|
|
1600
1814
|
}
|
|
1601
1815
|
async function audit2(args) {
|
|
1602
|
-
const parsed = parse(args,
|
|
1816
|
+
const parsed = parse(args, usage2, options);
|
|
1603
1817
|
const roots = (parsed.positionals.length > 0 ? parsed.positionals : ["."]).map((dir) => resolve(dir));
|
|
1604
1818
|
for (const dir of roots) {
|
|
1605
1819
|
if (!await isFolder(dir))
|
|
@@ -1627,15 +1841,15 @@ async function audit2(args) {
|
|
|
1627
1841
|
console.log("no exposed .env file nor compose file writing a secret out");
|
|
1628
1842
|
return 0;
|
|
1629
1843
|
}
|
|
1630
|
-
const uid =
|
|
1844
|
+
const uid = process10.getuid?.();
|
|
1631
1845
|
for (const { path, readable, group, tracked, secrets } of exposed) {
|
|
1632
1846
|
const sudo = uid !== undefined && uid !== 0 && (await stat4(path)).uid !== uid ? "sudo " : "";
|
|
1633
1847
|
const problems = [
|
|
1634
1848
|
...secrets === undefined ? [] : [`writes out ${secrets.join(", ")}: ev audit --fix moves the values into a .env beside it`],
|
|
1635
|
-
...readable ? [group === true ? `readable by its group or an ACL: ${sudo}chmod go-rwx ${shellQuote(
|
|
1636
|
-
...tracked ? [`tracked by git: git rm --cached ${shellQuote(
|
|
1849
|
+
...readable ? [group === true ? `readable by its group or an ACL: ${sudo}chmod go-rwx ${shellQuote(shown2(path))}` : `readable by any account: ${sudo}chmod o-rwx ${shellQuote(shown2(path))}`] : [],
|
|
1850
|
+
...tracked ? [`tracked by git: git rm --cached ${shellQuote(shown2(path))}, then ignore it`] : []
|
|
1637
1851
|
];
|
|
1638
|
-
console.log(`${
|
|
1852
|
+
console.log(`${shown2(path)}
|
|
1639
1853
|
${problems.join(`
|
|
1640
1854
|
`)}`);
|
|
1641
1855
|
}
|
|
@@ -1825,11 +2039,11 @@ ${cpUsage}`);
|
|
|
1825
2039
|
|
|
1826
2040
|
// src/commands/pins.ts
|
|
1827
2041
|
import { readdir as readdir4, stat as stat5 } from "fs/promises";
|
|
1828
|
-
import { join as
|
|
2042
|
+
import { join as join6, resolve as resolve2 } from "path";
|
|
1829
2043
|
|
|
1830
2044
|
// src/pins.ts
|
|
1831
2045
|
import { readdir as readdir3, readFile } from "fs/promises";
|
|
1832
|
-
import { join as
|
|
2046
|
+
import { join as join5, relative as relative2 } from "path";
|
|
1833
2047
|
var OPTIONAL2 = /^\s*([A-Z][A-Z0-9_]*)\s*:\s*s\.Optional\(/gm;
|
|
1834
2048
|
var REACHING = /(?:URL|URI|TOKEN|KEY|SECRET|PASSWORD|DSN|_HOST)(?:_FILE)?$/;
|
|
1835
2049
|
var SELF = /(?:^|_)(?:PUBLIC|SITE|BASE|APP)_URL$/;
|
|
@@ -1859,7 +2073,7 @@ async function walk(folder, keep) {
|
|
|
1859
2073
|
for (const entry of entries) {
|
|
1860
2074
|
if (SKIPPED3.has(entry.name))
|
|
1861
2075
|
continue;
|
|
1862
|
-
const path =
|
|
2076
|
+
const path = join5(folder, entry.name);
|
|
1863
2077
|
if (entry.isDirectory())
|
|
1864
2078
|
found.push(...await walk(path, keep));
|
|
1865
2079
|
else if (entry.isFile() && keep(entry.name))
|
|
@@ -1870,7 +2084,7 @@ async function walk(folder, keep) {
|
|
|
1870
2084
|
async function testFiles(folder) {
|
|
1871
2085
|
const found = [];
|
|
1872
2086
|
for (const root of TEST_ROOTS) {
|
|
1873
|
-
found.push(...await walk(
|
|
2087
|
+
found.push(...await walk(join5(folder, root), (name) => TEST_FILE.test(name)));
|
|
1874
2088
|
}
|
|
1875
2089
|
return found;
|
|
1876
2090
|
}
|
|
@@ -1938,7 +2152,7 @@ function reachesOutside(name) {
|
|
|
1938
2152
|
}
|
|
1939
2153
|
async function schemaFile(folder) {
|
|
1940
2154
|
for (const candidate of SCHEMA_CANDIDATES) {
|
|
1941
|
-
const path =
|
|
2155
|
+
const path = join5(folder, candidate);
|
|
1942
2156
|
if (await exists(path) && (await readFile(path, "utf8")).includes("defineEnv("))
|
|
1943
2157
|
return path;
|
|
1944
2158
|
}
|
|
@@ -1949,7 +2163,7 @@ async function testEnvKeys(folder) {
|
|
|
1949
2163
|
for (const entry of await readdir3(folder, { withFileTypes: true })) {
|
|
1950
2164
|
if (!entry.isFile() || !ENV_TEST.test(entry.name))
|
|
1951
2165
|
continue;
|
|
1952
|
-
for (const line of parseDotenv(await readFile(
|
|
2166
|
+
for (const line of parseDotenv(await readFile(join5(folder, entry.name), "utf8")).lines) {
|
|
1953
2167
|
if (line.key !== undefined)
|
|
1954
2168
|
keys.add(line.key);
|
|
1955
2169
|
}
|
|
@@ -1957,13 +2171,13 @@ async function testEnvKeys(folder) {
|
|
|
1957
2171
|
return keys;
|
|
1958
2172
|
}
|
|
1959
2173
|
async function pinningPreload(folder) {
|
|
1960
|
-
const path =
|
|
2174
|
+
const path = join5(folder, "bunfig.toml");
|
|
1961
2175
|
if (!await exists(path))
|
|
1962
2176
|
return;
|
|
1963
2177
|
const config = Bun.TOML.parse(await readFile(path, "utf8"));
|
|
1964
2178
|
const preloads = [config.test?.preload, config.preload].flat().filter((entry) => typeof entry === "string" && entry.startsWith("."));
|
|
1965
2179
|
for (const preload of preloads) {
|
|
1966
|
-
const file =
|
|
2180
|
+
const file = join5(folder, preload);
|
|
1967
2181
|
if (!await exists(file))
|
|
1968
2182
|
continue;
|
|
1969
2183
|
const source = await readFile(file, "utf8");
|
|
@@ -1998,7 +2212,7 @@ async function checkApp(folder, except = new Set) {
|
|
|
1998
2212
|
}
|
|
1999
2213
|
|
|
2000
2214
|
// src/commands/pins.ts
|
|
2001
|
-
var
|
|
2215
|
+
var usage3 = `ev pins [dir] [--except NAME,...]
|
|
2002
2216
|
|
|
2003
2217
|
Checks that an app's tests pin the env that reaches outside.
|
|
2004
2218
|
Reads the app's env schema (the file calling defineEnv, src/env.ts) and lists its optional URL, key, token, secret, password and host variables, then the ones no \`.env.test\` entry, test-level overrideEnv or local bunfig preload dropping what .env sets pins, and each test file that calls testSite or proxyKeyTests without pinning them all.
|
|
@@ -2025,7 +2239,7 @@ async function apps(dir, except) {
|
|
|
2025
2239
|
for (const entry of (await readdir4(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
2026
2240
|
if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules")
|
|
2027
2241
|
continue;
|
|
2028
|
-
const app = await checkApp(
|
|
2242
|
+
const app = await checkApp(join6(dir, entry.name), except);
|
|
2029
2243
|
if (app !== undefined)
|
|
2030
2244
|
found.push(app);
|
|
2031
2245
|
}
|
|
@@ -2038,7 +2252,7 @@ function name(app, root) {
|
|
|
2038
2252
|
return app.app === root ? app.app.split("/").at(-1) ?? app.app : app.app.slice(root.length + 1);
|
|
2039
2253
|
}
|
|
2040
2254
|
async function pins(args) {
|
|
2041
|
-
const parsed = parse(args,
|
|
2255
|
+
const parsed = parse(args, usage3, options2, { positionals: ["[dir]"] });
|
|
2042
2256
|
const json = parsed.values.json === true;
|
|
2043
2257
|
const root = resolve2(parsed.positionals[0] ?? ".");
|
|
2044
2258
|
const except = new Set((parsed.values.except ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry !== ""));
|
|
@@ -2184,7 +2398,7 @@ ${showUsage}`);
|
|
|
2184
2398
|
}
|
|
2185
2399
|
|
|
2186
2400
|
// src/ev.ts
|
|
2187
|
-
|
|
2401
|
+
process11.exitCode = await runCli({
|
|
2188
2402
|
name: "ev",
|
|
2189
2403
|
version,
|
|
2190
2404
|
about: ".env files listed and edited with secrets masked",
|