@kaynooo/cli-stack 0.4.0 → 0.5.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/cli.js +397 -147
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -2,16 +2,15 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/cli.ts
|
|
5
|
-
import
|
|
6
|
-
|
|
5
|
+
import process10 from "process";
|
|
7
6
|
// ../kit/src/args.ts
|
|
8
|
-
import
|
|
7
|
+
import process4 from "process";
|
|
9
8
|
import { parseArgs } from "util";
|
|
10
9
|
|
|
11
10
|
// ../kit/src/style.ts
|
|
12
|
-
import
|
|
11
|
+
import process2 from "process";
|
|
13
12
|
|
|
14
|
-
// ../../node_modules/.bun/@kaynooo+utils@2.31.
|
|
13
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
15
14
|
function x(s) {
|
|
16
15
|
let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
|
|
17
16
|
if (!/^[a-f0-9]+$/.test(r))
|
|
@@ -231,7 +230,7 @@ class e {
|
|
|
231
230
|
}
|
|
232
231
|
}
|
|
233
232
|
|
|
234
|
-
// ../../node_modules/.bun/@kaynooo+utils@2.31.
|
|
233
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
|
|
235
234
|
var r = 39;
|
|
236
235
|
var o = 49;
|
|
237
236
|
var f2 = "\x1B[";
|
|
@@ -279,13 +278,13 @@ var MARKS = {
|
|
|
279
278
|
problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
|
|
280
279
|
note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
|
|
281
280
|
};
|
|
282
|
-
function takesControlCodes(stream, env =
|
|
281
|
+
function takesControlCodes(stream, env = process2.env) {
|
|
283
282
|
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
284
283
|
}
|
|
285
|
-
function paint(stream, env =
|
|
284
|
+
function paint(stream, env = process2.env) {
|
|
286
285
|
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
287
286
|
}
|
|
288
|
-
function marked(mark, text, stream, detail, env =
|
|
287
|
+
function marked(mark, text, stream, detail, env = process2.env) {
|
|
289
288
|
const colors = paint(stream, env);
|
|
290
289
|
const { symbol, word, paint: tint } = MARKS[mark];
|
|
291
290
|
const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
|
|
@@ -310,6 +309,63 @@ function printJson(value) {
|
|
|
310
309
|
console.log(JSON.stringify(value, undefined, 2));
|
|
311
310
|
}
|
|
312
311
|
|
|
312
|
+
// ../kit/src/help.ts
|
|
313
|
+
import process3 from "process";
|
|
314
|
+
var OPTIONAL = /\[[^\]]+\]/g;
|
|
315
|
+
var USAGE_PREFIX = /^usage:\s*/i;
|
|
316
|
+
var FULL_STOP = /\.$/;
|
|
317
|
+
function usageLine(usage, colors = paint(process3.stdout)) {
|
|
318
|
+
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
319
|
+
}
|
|
320
|
+
function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
321
|
+
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
322
|
+
`);
|
|
323
|
+
}
|
|
324
|
+
function exitRows(exits, colors = paint(process3.stdout)) {
|
|
325
|
+
if (exits.length === 0)
|
|
326
|
+
return [];
|
|
327
|
+
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
328
|
+
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
329
|
+
}
|
|
330
|
+
function replacesRows(replaces, colors = paint(process3.stdout)) {
|
|
331
|
+
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
332
|
+
}
|
|
333
|
+
function wantsHelpJson(env = process3.env) {
|
|
334
|
+
return env.KIT_HELP === "json";
|
|
335
|
+
}
|
|
336
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
337
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
338
|
+
`);
|
|
339
|
+
const first = lines[0];
|
|
340
|
+
const colon = first.indexOf(": ");
|
|
341
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
342
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
343
|
+
return {
|
|
344
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
345
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
346
|
+
...replaces === undefined ? {} : { replaces },
|
|
347
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
348
|
+
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
349
|
+
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
function exampleRows(examples, colors = paint(process3.stdout)) {
|
|
353
|
+
if (examples.length === 0)
|
|
354
|
+
return [];
|
|
355
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
356
|
+
}
|
|
357
|
+
function optionRows(options, colors = paint(process3.stdout)) {
|
|
358
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
359
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
360
|
+
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
361
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
362
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
363
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
|
|
364
|
+
});
|
|
365
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
366
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
367
|
+
}
|
|
368
|
+
|
|
313
369
|
// ../kit/src/text.ts
|
|
314
370
|
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
315
371
|
function distance(a, b) {
|
|
@@ -329,8 +385,19 @@ function closest(name, names) {
|
|
|
329
385
|
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
330
386
|
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
331
387
|
}
|
|
388
|
+
// ../kit/src/input.ts
|
|
389
|
+
var WHOLE = /^\d+$/;
|
|
390
|
+
function wholeNumber(value, name, fallback, min = 1) {
|
|
391
|
+
if (value === undefined)
|
|
392
|
+
return fallback;
|
|
393
|
+
const number = Number(value);
|
|
394
|
+
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
395
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
396
|
+
return number;
|
|
397
|
+
}
|
|
332
398
|
|
|
333
399
|
// ../kit/src/args.ts
|
|
400
|
+
var DASHES = /^-+/;
|
|
334
401
|
function jsonOption(holds) {
|
|
335
402
|
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
336
403
|
}
|
|
@@ -365,61 +432,20 @@ class HelpShown extends Exit {
|
|
|
365
432
|
|
|
366
433
|
class Completing {
|
|
367
434
|
options;
|
|
368
|
-
|
|
435
|
+
positionals;
|
|
436
|
+
candidates;
|
|
437
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
369
438
|
this.options = options;
|
|
439
|
+
this.positionals = positionals;
|
|
440
|
+
this.candidates = candidates;
|
|
370
441
|
}
|
|
371
442
|
}
|
|
372
443
|
var completion = { active: false };
|
|
373
|
-
var OPTIONAL = /\[[^\]]+\]/g;
|
|
374
|
-
var USAGE_PREFIX = /^usage:\s*/i;
|
|
375
|
-
var FULL_STOP = /\.$/;
|
|
376
|
-
var DASHES = /^-+/;
|
|
377
|
-
function usageLine(usage, colors = paint(process2.stdout)) {
|
|
378
|
-
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
379
|
-
}
|
|
380
|
-
function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
|
|
381
|
-
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
|
|
382
|
-
`);
|
|
383
|
-
}
|
|
384
|
-
function replacesRows(replaces, colors = paint(process2.stdout)) {
|
|
385
|
-
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
386
|
-
}
|
|
387
|
-
function wantsHelpJson(env = process2.env) {
|
|
388
|
-
return env.KIT_HELP === "json";
|
|
389
|
-
}
|
|
390
|
-
function description(usage, { examples = [], replaces } = {}) {
|
|
391
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
392
|
-
`);
|
|
393
|
-
const first = lines[0];
|
|
394
|
-
const colon = first.indexOf(": ");
|
|
395
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
396
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
397
|
-
return {
|
|
398
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
399
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
400
|
-
...replaces === undefined ? {} : { replaces },
|
|
401
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
402
|
-
};
|
|
403
|
-
}
|
|
404
|
-
function exampleRows(examples, colors = paint(process2.stdout)) {
|
|
405
|
-
if (examples.length === 0)
|
|
406
|
-
return [];
|
|
407
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
408
|
-
}
|
|
409
|
-
function optionRows(options, colors = paint(process2.stdout)) {
|
|
410
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
411
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
412
|
-
const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
|
|
413
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
|
|
414
|
-
});
|
|
415
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
416
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
417
|
-
}
|
|
418
444
|
var OUTPUT_OPTIONS = {
|
|
419
445
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
420
446
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
421
447
|
};
|
|
422
|
-
function applyOutput(color, plain, env =
|
|
448
|
+
function applyOutput(color, plain, env = process4.env) {
|
|
423
449
|
const when = plain === true ? "never" : color ?? "auto";
|
|
424
450
|
if (when === "auto")
|
|
425
451
|
return;
|
|
@@ -436,14 +462,13 @@ function applyOutput(color, plain, env = process2.env) {
|
|
|
436
462
|
function parse(args, usage, options, settings = {}) {
|
|
437
463
|
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
438
464
|
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
465
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
439
466
|
if (completion.active)
|
|
440
|
-
throw new Completing(
|
|
441
|
-
const
|
|
442
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
443
|
-
const rest = separator === -1 ? undefined : args.slice(separator + 1);
|
|
467
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
468
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
444
469
|
let parsed;
|
|
445
470
|
try {
|
|
446
|
-
parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
471
|
+
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
447
472
|
} catch (error) {
|
|
448
473
|
const message = parseError(error);
|
|
449
474
|
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
@@ -451,12 +476,96 @@ function parse(args, usage, options, settings = {}) {
|
|
|
451
476
|
const values = parsed.values;
|
|
452
477
|
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
453
478
|
if (values.help === true) {
|
|
454
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage,
|
|
479
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
455
480
|
throw new HelpShown;
|
|
456
481
|
}
|
|
482
|
+
checkChoices(parsed.values, all);
|
|
483
|
+
checkConflicts(parsed.values, all);
|
|
457
484
|
if (settings.positionals !== undefined)
|
|
458
485
|
checkPositionals(parsed.positionals, settings.positionals);
|
|
459
|
-
return { ...parsed, positionals: parsed.positionals, rest };
|
|
486
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
487
|
+
}
|
|
488
|
+
function splitRest(args, passes) {
|
|
489
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
490
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
491
|
+
}
|
|
492
|
+
function splitTrailing(args, options, count) {
|
|
493
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
494
|
+
let seen = 0;
|
|
495
|
+
if (count === 0)
|
|
496
|
+
return { own: args, rest: undefined };
|
|
497
|
+
for (let at = 0;at < args.length; at++) {
|
|
498
|
+
const word = args[at];
|
|
499
|
+
if (word === "--")
|
|
500
|
+
break;
|
|
501
|
+
if (word.startsWith("-")) {
|
|
502
|
+
if (takesValue(word))
|
|
503
|
+
at++;
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
seen++;
|
|
507
|
+
if (seen === count)
|
|
508
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
509
|
+
}
|
|
510
|
+
return { own: args, rest: undefined };
|
|
511
|
+
}
|
|
512
|
+
function listed(options, allowNegative) {
|
|
513
|
+
if (!allowNegative)
|
|
514
|
+
return options;
|
|
515
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
516
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
517
|
+
return [[name, option]];
|
|
518
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
519
|
+
}));
|
|
520
|
+
}
|
|
521
|
+
function withAliases(args, options) {
|
|
522
|
+
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
523
|
+
if (named.size === 0)
|
|
524
|
+
return args;
|
|
525
|
+
const separator = args.indexOf("--");
|
|
526
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
527
|
+
return [...own.map((arg) => {
|
|
528
|
+
const at = arg.indexOf("=");
|
|
529
|
+
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
530
|
+
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
531
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
532
|
+
}
|
|
533
|
+
function withBare(args, options) {
|
|
534
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
535
|
+
if (bare.size === 0)
|
|
536
|
+
return args;
|
|
537
|
+
const separator = args.indexOf("--");
|
|
538
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
539
|
+
return [...own.flatMap((arg, index) => {
|
|
540
|
+
const optional = bare.get(arg);
|
|
541
|
+
const next = own[index + 1];
|
|
542
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
543
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
544
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
545
|
+
}
|
|
546
|
+
function checkConflicts(values, options) {
|
|
547
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
548
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
549
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
550
|
+
if (other !== undefined)
|
|
551
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
function checkChoices(values, options) {
|
|
555
|
+
for (const [name, option] of Object.entries(options)) {
|
|
556
|
+
if (option.choices === undefined)
|
|
557
|
+
continue;
|
|
558
|
+
const given = values[name];
|
|
559
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
560
|
+
if (typeof value === "string")
|
|
561
|
+
oneOf(value, name, option.choices);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
function oneOf(value, name, choices) {
|
|
566
|
+
if (!choices.includes(value))
|
|
567
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
568
|
+
return value;
|
|
460
569
|
}
|
|
461
570
|
function checkPositionals(given, names) {
|
|
462
571
|
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
@@ -505,29 +614,75 @@ function nearestOption(message, options, allowNegative) {
|
|
|
505
614
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
506
615
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
507
616
|
}
|
|
508
|
-
var WHOLE = /^\d+$/;
|
|
509
|
-
function wholeNumber(value, name, fallback, min = 1) {
|
|
510
|
-
if (value === undefined)
|
|
511
|
-
return fallback;
|
|
512
|
-
const number = Number(value);
|
|
513
|
-
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
514
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
515
|
-
return number;
|
|
516
|
-
}
|
|
517
617
|
// ../kit/src/progress.ts
|
|
518
618
|
var ESC = String.fromCharCode(27);
|
|
519
619
|
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
520
620
|
var RESET_STYLE = `${ESC}[0m`;
|
|
521
621
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
522
622
|
// ../kit/src/cli.ts
|
|
523
|
-
import
|
|
623
|
+
import { readFileSync, realpathSync } from "fs";
|
|
624
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
625
|
+
import process6 from "process";
|
|
626
|
+
|
|
627
|
+
// ../kit/src/usage.ts
|
|
628
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
629
|
+
import { homedir } from "os";
|
|
630
|
+
import { dirname, isAbsolute, join } from "path";
|
|
631
|
+
import process5 from "process";
|
|
632
|
+
|
|
633
|
+
// ../kit/src/logs.ts
|
|
634
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
635
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
636
|
+
|
|
637
|
+
// ../kit/src/usage.ts
|
|
638
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
639
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
640
|
+
var LONGEST_NAME = 40;
|
|
641
|
+
var usageError;
|
|
642
|
+
function noteUsageError(message) {
|
|
643
|
+
usageError = message;
|
|
644
|
+
}
|
|
645
|
+
function stateHome(env = process5.env) {
|
|
646
|
+
const dir = env.XDG_STATE_HOME;
|
|
647
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
648
|
+
}
|
|
649
|
+
function usagePath(env = process5.env) {
|
|
650
|
+
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
651
|
+
}
|
|
652
|
+
function usageRecorded(env = process5.env) {
|
|
653
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
654
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
655
|
+
}
|
|
656
|
+
function flagNames(argv) {
|
|
657
|
+
const end = argv.indexOf("--");
|
|
658
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
659
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
660
|
+
}
|
|
661
|
+
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
662
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
663
|
+
usageError = undefined;
|
|
664
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
665
|
+
}
|
|
666
|
+
function recordUsage(entry, env = process5.env) {
|
|
667
|
+
if (!usageRecorded(env))
|
|
668
|
+
return;
|
|
669
|
+
try {
|
|
670
|
+
const path = usagePath(env);
|
|
671
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
672
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
673
|
+
`, { mode: 384 });
|
|
674
|
+
} catch {}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// ../kit/src/cli.ts
|
|
524
678
|
var LEVEL_OPTIONS = {
|
|
525
679
|
...OUTPUT_OPTIONS,
|
|
526
680
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
527
681
|
};
|
|
528
682
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
529
|
-
async function commandRows(
|
|
530
|
-
const
|
|
683
|
+
async function commandRows(all, colors) {
|
|
684
|
+
const commands = shown(all);
|
|
685
|
+
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
531
686
|
const groups = new Map([["Commands:", []]]);
|
|
532
687
|
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
533
688
|
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
@@ -538,6 +693,9 @@ async function commandRows(commands, colors) {
|
|
|
538
693
|
}
|
|
539
694
|
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
540
695
|
}
|
|
696
|
+
function shown(commands) {
|
|
697
|
+
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
698
|
+
}
|
|
541
699
|
function takeOutputFlags(argv) {
|
|
542
700
|
let index = 0;
|
|
543
701
|
for (;index < argv.length; index++) {
|
|
@@ -569,7 +727,7 @@ async function expand(scope, words) {
|
|
|
569
727
|
}
|
|
570
728
|
return { ...scope, commands, lazy: [] };
|
|
571
729
|
}
|
|
572
|
-
async function
|
|
730
|
+
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
573
731
|
const colors = paint(stream);
|
|
574
732
|
const prefix = path.join(" ");
|
|
575
733
|
const summary = await resolveSummary(lazySummary);
|
|
@@ -596,8 +754,8 @@ async function help({ path, header, summary: lazySummary, commands, defaultComma
|
|
|
596
754
|
`);
|
|
597
755
|
}
|
|
598
756
|
function printError(prefix, message, hint, cause) {
|
|
599
|
-
const colors = paint(
|
|
600
|
-
const styled = takesControlCodes(
|
|
757
|
+
const colors = paint(process6.stderr);
|
|
758
|
+
const styled = takesControlCodes(process6.stderr);
|
|
601
759
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
602
760
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
603
761
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -616,6 +774,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
616
774
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
617
775
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
618
776
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
777
|
+
if (error instanceof UsageError)
|
|
778
|
+
noteUsageError(error.message);
|
|
619
779
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
620
780
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
621
781
|
return error instanceof Exit ? error.code : 1;
|
|
@@ -629,12 +789,20 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
629
789
|
return reportThrown(prefix, error);
|
|
630
790
|
}
|
|
631
791
|
const [name, ...args] = argv;
|
|
792
|
+
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
793
|
+
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
794
|
+
try {
|
|
795
|
+
return await fallback.run([]);
|
|
796
|
+
} catch (error) {
|
|
797
|
+
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
632
800
|
if (name === undefined && level.path.length > 1) {
|
|
633
|
-
console.error(await
|
|
801
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process6.stderr));
|
|
634
802
|
return 2;
|
|
635
803
|
}
|
|
636
804
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
637
|
-
console.log(await
|
|
805
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process6.stdout));
|
|
638
806
|
return 0;
|
|
639
807
|
}
|
|
640
808
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -643,6 +811,7 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
643
811
|
}
|
|
644
812
|
let command = level.commands[level.aliases?.[name] ?? name];
|
|
645
813
|
let rest = args;
|
|
814
|
+
let ran = name;
|
|
646
815
|
if (command === undefined && level.lazy.length > 0) {
|
|
647
816
|
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
648
817
|
command = level.commands[level.aliases?.[name] ?? name];
|
|
@@ -650,40 +819,77 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
650
819
|
if (command === undefined && level.defaultCommand !== undefined) {
|
|
651
820
|
command = level.commands[level.defaultCommand];
|
|
652
821
|
rest = argv;
|
|
822
|
+
ran = level.defaultCommand;
|
|
653
823
|
}
|
|
654
824
|
if (command === undefined) {
|
|
655
|
-
const meant = closest(name, Object.keys(level.commands));
|
|
825
|
+
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
656
826
|
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
657
827
|
return 2;
|
|
658
828
|
}
|
|
659
829
|
if ("commands" in command) {
|
|
660
830
|
const { summary } = command;
|
|
661
|
-
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 });
|
|
831
|
+
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 });
|
|
662
832
|
}
|
|
663
833
|
try {
|
|
664
834
|
return await command.run(rest);
|
|
665
835
|
} catch (error) {
|
|
666
|
-
return reportThrown(`${prefix} ${
|
|
836
|
+
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
667
837
|
}
|
|
668
838
|
}
|
|
669
839
|
var COMPLETE = "__complete";
|
|
670
840
|
var FILES = "__files__";
|
|
671
|
-
async function
|
|
841
|
+
async function completingOf(run) {
|
|
672
842
|
completion.active = true;
|
|
673
843
|
try {
|
|
674
844
|
await run([]);
|
|
675
845
|
} catch (error) {
|
|
676
846
|
if (error instanceof Completing)
|
|
677
|
-
return error
|
|
847
|
+
return error;
|
|
678
848
|
} finally {
|
|
679
849
|
completion.active = false;
|
|
680
850
|
}
|
|
681
|
-
return {};
|
|
851
|
+
return new Completing({});
|
|
852
|
+
}
|
|
853
|
+
async function optionsOf(run) {
|
|
854
|
+
return (await completingOf(run)).options;
|
|
855
|
+
}
|
|
856
|
+
function candidateLine(candidate) {
|
|
857
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
858
|
+
}
|
|
859
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
860
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
861
|
+
let index = 0;
|
|
862
|
+
let at = 0;
|
|
863
|
+
while (at < before.length) {
|
|
864
|
+
const word = before[at];
|
|
865
|
+
if (word === "--") {
|
|
866
|
+
index += before.length - at - 1;
|
|
867
|
+
break;
|
|
868
|
+
}
|
|
869
|
+
if (!word.startsWith("-"))
|
|
870
|
+
index++;
|
|
871
|
+
else if (takesValue(word))
|
|
872
|
+
at++;
|
|
873
|
+
at++;
|
|
874
|
+
}
|
|
875
|
+
const last = positionals.at(-1);
|
|
876
|
+
if (index < positionals.length)
|
|
877
|
+
return positionals[index];
|
|
878
|
+
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
682
879
|
}
|
|
683
880
|
async function leafCandidates(run, words) {
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
881
|
+
const completing = await completingOf(run);
|
|
882
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
883
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
884
|
+
const flag = words.at(-2);
|
|
885
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
886
|
+
if (option?.type === "string") {
|
|
887
|
+
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
888
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
889
|
+
}
|
|
890
|
+
const name = positionalBeingTyped(words.slice(0, -1), completing);
|
|
891
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
892
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
687
893
|
}
|
|
688
894
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
689
895
|
const [word = "", ...rest] = words;
|
|
@@ -694,8 +900,13 @@ async function candidates(scope, defaultCommand, words, before = []) {
|
|
|
694
900
|
({ commands, aliases } = await expand(scope, [...before, ...words]));
|
|
695
901
|
command = commands[aliases?.[word] ?? word];
|
|
696
902
|
}
|
|
697
|
-
if (listing)
|
|
698
|
-
|
|
903
|
+
if (listing) {
|
|
904
|
+
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
905
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
906
|
+
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
907
|
+
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
908
|
+
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
|
|
909
|
+
}
|
|
699
910
|
if (command === undefined) {
|
|
700
911
|
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
701
912
|
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
@@ -707,15 +918,62 @@ async function printCandidates(found) {
|
|
|
707
918
|
console.log(line);
|
|
708
919
|
return 0;
|
|
709
920
|
}
|
|
710
|
-
|
|
921
|
+
function packageVersion(entry = Bun.main) {
|
|
922
|
+
for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
|
|
923
|
+
try {
|
|
924
|
+
const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
|
|
925
|
+
if (typeof version === "string")
|
|
926
|
+
return version;
|
|
927
|
+
} catch {}
|
|
928
|
+
if (dirname2(dir) === dir)
|
|
929
|
+
return "0.0.0";
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
async function runCli(cli, argv = process6.argv.slice(2)) {
|
|
933
|
+
const version = cli.version ?? packageVersion();
|
|
711
934
|
if (argv[0] === COMPLETE)
|
|
712
935
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
713
|
-
|
|
936
|
+
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 });
|
|
937
|
+
if (cli.usage !== false) {
|
|
938
|
+
try {
|
|
939
|
+
recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
|
|
940
|
+
} catch {}
|
|
941
|
+
}
|
|
942
|
+
return code;
|
|
943
|
+
}
|
|
944
|
+
function commandPath(scope, argv) {
|
|
945
|
+
const path = [];
|
|
946
|
+
let level = scope;
|
|
947
|
+
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
948
|
+
const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
|
|
949
|
+
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
950
|
+
if (command === undefined)
|
|
951
|
+
break;
|
|
952
|
+
path.push(word);
|
|
953
|
+
if (!("commands" in command))
|
|
954
|
+
break;
|
|
955
|
+
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
956
|
+
}
|
|
957
|
+
return path.length === 0 ? undefined : path.join(" ");
|
|
958
|
+
}
|
|
959
|
+
// ../kit/src/compose.ts
|
|
960
|
+
async function captureOutput(argv, { cwd, env } = {}) {
|
|
961
|
+
const run = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, env: { ...process.env, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
|
|
962
|
+
const [stdout, stderr, code] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
|
|
963
|
+
return { code, stdout, stderr };
|
|
964
|
+
}
|
|
965
|
+
async function compose(args, { flags = [], ...options } = {}) {
|
|
966
|
+
return captureOutput(["docker", "compose", ...flags, ...args], options);
|
|
967
|
+
}
|
|
968
|
+
function composeError({ code, stderr }) {
|
|
969
|
+
const last = stderr.trim().split(`
|
|
970
|
+
`).at(-1) ?? "";
|
|
971
|
+
return last === "" ? `exit ${code}` : last;
|
|
714
972
|
}
|
|
715
973
|
// ../kit/src/limit.ts
|
|
716
974
|
function limitOptions(fallback) {
|
|
717
975
|
return {
|
|
718
|
-
limit: { type: "string", description: `show at most this many rows, the rest counted (${fallback})` },
|
|
976
|
+
limit: { type: "string", short: "n", description: `show at most this many rows, the rest counted (${fallback})` },
|
|
719
977
|
full: { type: "boolean", description: "show every row" }
|
|
720
978
|
};
|
|
721
979
|
}
|
|
@@ -733,40 +991,30 @@ function capped(rows, limit) {
|
|
|
733
991
|
const more = rows.length - limit;
|
|
734
992
|
return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
|
|
735
993
|
}
|
|
736
|
-
// ../kit/src/logs.ts
|
|
737
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
738
994
|
// ../kit/src/secrets.ts
|
|
739
995
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
740
996
|
// ../kit/src/sessions.ts
|
|
741
997
|
var {Glob } = globalThis.Bun;
|
|
742
998
|
var SESSION_FILES = new Glob("*.json");
|
|
743
999
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
744
|
-
// package.json
|
|
745
|
-
var version = "0.4.0";
|
|
746
|
-
|
|
747
1000
|
// src/commands/audit.ts
|
|
748
|
-
import { homedir } from "os";
|
|
1001
|
+
import { homedir as homedir2 } from "os";
|
|
749
1002
|
import { resolve as resolve2 } from "path";
|
|
750
|
-
import
|
|
1003
|
+
import process9 from "process";
|
|
751
1004
|
|
|
752
1005
|
// src/audit/compose.ts
|
|
753
|
-
import { join } from "path";
|
|
754
|
-
import process5 from "process";
|
|
1006
|
+
import { join as join3 } from "path";
|
|
755
1007
|
var dockerCompose = async (root, files) => {
|
|
756
|
-
const
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
`).at(-1) ?? "";
|
|
761
|
-
if (code !== 0)
|
|
762
|
-
throw new Error(last !== "" ? last : `exited with ${code}`);
|
|
763
|
-
return JSON.parse(out);
|
|
1008
|
+
const result = await compose(["config", "--no-interpolate", "--format", "json"], { flags: ["--project-directory", root, ...files.flatMap((file) => ["-f", join3(root, file)])], env: { COMPOSE_FILE: "" } });
|
|
1009
|
+
if (result.code !== 0)
|
|
1010
|
+
throw new Error(composeError(result));
|
|
1011
|
+
return JSON.parse(result.stdout);
|
|
764
1012
|
};
|
|
765
1013
|
|
|
766
1014
|
// src/audit/render.ts
|
|
767
1015
|
import { basename } from "path";
|
|
768
|
-
import
|
|
769
|
-
var line = (finding) => ` ${marked(finding.level === "error" ? "problem" : "warn", `[${finding.check}] ${finding.message}`,
|
|
1016
|
+
import process8 from "process";
|
|
1017
|
+
var line = (finding) => ` ${marked(finding.level === "error" ? "problem" : "warn", `[${finding.check}] ${finding.message}`, process8.stdout)}`;
|
|
770
1018
|
function errorsOf(result) {
|
|
771
1019
|
return result.findings.filter((finding) => finding.level === "error");
|
|
772
1020
|
}
|
|
@@ -778,7 +1026,7 @@ function render(result, limit = Number.POSITIVE_INFINITY) {
|
|
|
778
1026
|
const errors = errorsOf(result);
|
|
779
1027
|
const warnings = result.findings.filter((finding) => finding.level === "warn");
|
|
780
1028
|
if (result.findings.length === 0)
|
|
781
|
-
return marked("ok", `${basename(result.root)}: compose ${result.composeFiles.join(", ")} and release.config.ts agree.`,
|
|
1029
|
+
return marked("ok", `${basename(result.root)}: compose ${result.composeFiles.join(", ")} and release.config.ts agree.`, process8.stdout);
|
|
782
1030
|
return [
|
|
783
1031
|
...section("Errors", errors, limit),
|
|
784
1032
|
...section("Warnings", warnings, limit),
|
|
@@ -789,11 +1037,11 @@ function render(result, limit = Number.POSITIVE_INFINITY) {
|
|
|
789
1037
|
|
|
790
1038
|
// src/audit/run.ts
|
|
791
1039
|
import { existsSync as existsSync3 } from "fs";
|
|
792
|
-
import { join as
|
|
1040
|
+
import { join as join6 } from "path";
|
|
793
1041
|
|
|
794
1042
|
// src/audit/checks.ts
|
|
795
|
-
import { existsSync, readFileSync } from "fs";
|
|
796
|
-
import { isAbsolute, join as
|
|
1043
|
+
import { existsSync, readFileSync as readFileSync2 } from "fs";
|
|
1044
|
+
import { isAbsolute as isAbsolute2, join as join4, relative, resolve } from "path";
|
|
797
1045
|
var ENV_REF = /(?<!\$)\$(?:\{([A-Z_]\w*)(\s*:?[-?+][^}]*)?\}|([A-Z_]\w*))/gi;
|
|
798
1046
|
var REQUIRED_OPERATOR = /^\s*:?\?/;
|
|
799
1047
|
var COMMENT_START = /(?:^|\s)#.*$/;
|
|
@@ -809,18 +1057,18 @@ function before(text, separator) {
|
|
|
809
1057
|
}
|
|
810
1058
|
var stripDotSlash = (file) => file.replace(LEADING_DOT_SLASH, "");
|
|
811
1059
|
function composeLayout(root, config) {
|
|
812
|
-
const composeFiles = (config.deploySyncFiles ?? []).map(stripDotSlash).filter((file) => YAML_FILE.test(file) && existsSync(
|
|
1060
|
+
const composeFiles = (config.deploySyncFiles ?? []).map(stripDotSlash).filter((file) => YAML_FILE.test(file) && existsSync(join4(root, file)));
|
|
813
1061
|
const [base] = composeFiles.toSorted((a, b) => a.length - b.length);
|
|
814
1062
|
return { composeFiles, base, overlays: composeFiles.filter((file) => file !== base) };
|
|
815
1063
|
}
|
|
816
1064
|
function syncFindings(root, config) {
|
|
817
|
-
return (config.deploySyncFiles ?? []).filter((file) => !existsSync(
|
|
1065
|
+
return (config.deploySyncFiles ?? []).filter((file) => !existsSync(join4(root, stripDotSlash(file)))).map((file) => ({ level: "error", check: "sync", message: `deploySyncFiles entry does not exist: ${file}` }));
|
|
818
1066
|
}
|
|
819
1067
|
function buildFindings(root, releases, env, home) {
|
|
820
1068
|
const findings = [];
|
|
821
1069
|
const missing = (release, key) => {
|
|
822
1070
|
const path = release[key];
|
|
823
|
-
if (path !== undefined && path !== "" && !existsSync(
|
|
1071
|
+
if (path !== undefined && path !== "" && !existsSync(join4(root, path)))
|
|
824
1072
|
findings.push({ level: "error", check: "build", message: `${release.slug}: ${key} does not exist: ${path}` });
|
|
825
1073
|
};
|
|
826
1074
|
for (const release of releases) {
|
|
@@ -829,7 +1077,7 @@ function buildFindings(root, releases, env, home) {
|
|
|
829
1077
|
missing(release, "dockerfile");
|
|
830
1078
|
for (const secret of release.buildSecrets ?? []) {
|
|
831
1079
|
if (secret.src !== undefined && secret.src !== "") {
|
|
832
|
-
const path = secret.src.startsWith("~") ?
|
|
1080
|
+
const path = secret.src.startsWith("~") ? join4(home, secret.src.slice(1)) : resolve(root, secret.src);
|
|
833
1081
|
if (!existsSync(path))
|
|
834
1082
|
findings.push({ level: "error", check: "build", message: `${release.slug}: buildSecret "${secret.id}" src does not exist: ${secret.src}` });
|
|
835
1083
|
}
|
|
@@ -847,7 +1095,7 @@ function withoutComment(line) {
|
|
|
847
1095
|
}
|
|
848
1096
|
function envRefs(root, composeFiles) {
|
|
849
1097
|
return composeFiles.flatMap((file) => {
|
|
850
|
-
const text =
|
|
1098
|
+
const text = readFileSync2(join4(root, file), "utf8").split(`
|
|
851
1099
|
`).map(withoutComment).join(`
|
|
852
1100
|
`);
|
|
853
1101
|
return [...text.matchAll(ENV_REF)].map((match) => ({ name: match[1] ?? match[3], defaulted: match[2] !== undefined && !REQUIRED_OPERATOR.test(match[2]), file }));
|
|
@@ -894,7 +1142,9 @@ function imageFindings(config, releases, model) {
|
|
|
894
1142
|
return findings;
|
|
895
1143
|
}
|
|
896
1144
|
function restartFindings(config, releases, model, base) {
|
|
897
|
-
|
|
1145
|
+
if (model === undefined)
|
|
1146
|
+
return [];
|
|
1147
|
+
const known = new Set(Object.keys(model.services ?? {}));
|
|
898
1148
|
const findings = [];
|
|
899
1149
|
for (const release of releases) {
|
|
900
1150
|
for (const service of release.restartServices ?? []) {
|
|
@@ -913,7 +1163,9 @@ function restartFindings(config, releases, model, base) {
|
|
|
913
1163
|
return findings;
|
|
914
1164
|
}
|
|
915
1165
|
function postDeployFindings(releases, model, base) {
|
|
916
|
-
|
|
1166
|
+
if (model === undefined)
|
|
1167
|
+
return [];
|
|
1168
|
+
const known = new Set(Object.keys(model.services ?? {}));
|
|
917
1169
|
const findings = [];
|
|
918
1170
|
for (const release of releases) {
|
|
919
1171
|
for (const command of release.postDeployCommands ?? []) {
|
|
@@ -959,12 +1211,12 @@ function relativeSource(root, source) {
|
|
|
959
1211
|
if (source.startsWith("."))
|
|
960
1212
|
return source;
|
|
961
1213
|
const inRoot = relative(resolve(root), source);
|
|
962
|
-
return
|
|
1214
|
+
return isAbsolute2(source) && inRoot !== "" && !inRoot.startsWith("..") ? `./${inRoot}` : undefined;
|
|
963
1215
|
}
|
|
964
1216
|
function layoutFindings(root, base, model) {
|
|
965
1217
|
if (base === undefined)
|
|
966
1218
|
return [];
|
|
967
|
-
const header =
|
|
1219
|
+
const header = readFileSync2(join4(root, base), "utf8").split(SERVICES_KEY)[0] ?? "";
|
|
968
1220
|
const findings = [];
|
|
969
1221
|
for (const [name, service] of services(model)) {
|
|
970
1222
|
for (const volume of service.volumes ?? []) {
|
|
@@ -976,14 +1228,14 @@ function layoutFindings(root, base, model) {
|
|
|
976
1228
|
return findings;
|
|
977
1229
|
}
|
|
978
1230
|
function gitignoreFindings(root) {
|
|
979
|
-
const path =
|
|
980
|
-
const text = existsSync(path) ?
|
|
1231
|
+
const path = join4(root, ".gitignore");
|
|
1232
|
+
const text = existsSync(path) ? readFileSync2(path, "utf8") : "";
|
|
981
1233
|
return [".release-logs", ".release-worktrees"].filter((entry) => !text.includes(entry)).map((entry) => ({ level: "warn", check: "gitignore", message: `${entry}/ is not in .gitignore` }));
|
|
982
1234
|
}
|
|
983
1235
|
|
|
984
1236
|
// src/audit/nuxt.ts
|
|
985
|
-
import { existsSync as existsSync2, readFileSync as
|
|
986
|
-
import { basename as basename2, join as
|
|
1237
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
|
|
1238
|
+
import { basename as basename2, join as join5 } from "path";
|
|
987
1239
|
var CAMEL_BOUNDARY = /([a-z0-9])([A-Z])/g;
|
|
988
1240
|
var KEY = /([A-Z_]\w*)\s*(?:\?\s*)?:/gi;
|
|
989
1241
|
var OPENS_BRACE = /^\s*\{/;
|
|
@@ -1026,21 +1278,21 @@ function schemaEnvNames(schema, iface, prefix) {
|
|
|
1026
1278
|
}
|
|
1027
1279
|
function nuxtFindings(root, releases, model) {
|
|
1028
1280
|
const findings = [];
|
|
1029
|
-
const dirs = [...new Set(releases.map((release) => release.buildContext).filter((context) => context !== undefined && context !== ""))].map((dir) =>
|
|
1281
|
+
const dirs = [...new Set(releases.map((release) => release.buildContext).filter((context) => context !== undefined && context !== ""))].map((dir) => join5(root, dir)).filter((dir) => existsSync2(join5(dir, "nuxt.config.ts")));
|
|
1030
1282
|
for (const dir of dirs) {
|
|
1031
|
-
const schemaPath = [
|
|
1283
|
+
const schemaPath = [join5(dir, ".nuxt/types/schema.d.ts"), join5(dir, ".nuxt/types/runtime-config.d.ts")].find((path) => existsSync2(path));
|
|
1032
1284
|
let allowed;
|
|
1033
1285
|
let level = "error";
|
|
1034
1286
|
let source;
|
|
1035
1287
|
if (schemaPath !== undefined) {
|
|
1036
|
-
const schema =
|
|
1288
|
+
const schema = readFileSync3(schemaPath, "utf8");
|
|
1037
1289
|
allowed = new Set([
|
|
1038
1290
|
...schemaEnvNames(schema, "SharedRuntimeConfig", "NUXT_"),
|
|
1039
1291
|
...schemaEnvNames(schema, "SharedPublicRuntimeConfig", "NUXT_PUBLIC_")
|
|
1040
1292
|
]);
|
|
1041
1293
|
source = `${basename2(dir)}/${schemaPath.slice(dir.length + 1)}`;
|
|
1042
1294
|
} else {
|
|
1043
|
-
const config =
|
|
1295
|
+
const config = readFileSync3(join5(dir, "nuxt.config.ts"), "utf8");
|
|
1044
1296
|
const at = config.indexOf("runtimeConfig:");
|
|
1045
1297
|
const block = at < 0 ? undefined : braceBody(config, at);
|
|
1046
1298
|
if (block === undefined)
|
|
@@ -1071,7 +1323,7 @@ function installed(specifier, root) {
|
|
|
1071
1323
|
}
|
|
1072
1324
|
}
|
|
1073
1325
|
async function loadConfig(root) {
|
|
1074
|
-
const specifier = DEFINE_CONFIG_IMPORT.exec(await Bun.file(
|
|
1326
|
+
const specifier = DEFINE_CONFIG_IMPORT.exec(await Bun.file(join6(root, CONFIG_FILE)).text())?.[1];
|
|
1075
1327
|
if (specifier !== undefined && !installed(specifier, root)) {
|
|
1076
1328
|
Bun.plugin({
|
|
1077
1329
|
name: "release-stand-in",
|
|
@@ -1080,7 +1332,7 @@ async function loadConfig(root) {
|
|
|
1080
1332
|
}
|
|
1081
1333
|
});
|
|
1082
1334
|
}
|
|
1083
|
-
const config = (await import(
|
|
1335
|
+
const config = (await import(join6(root, CONFIG_FILE))).default;
|
|
1084
1336
|
if (config === undefined)
|
|
1085
1337
|
fail(`${CONFIG_FILE} has no default export`);
|
|
1086
1338
|
return config;
|
|
@@ -1129,10 +1381,10 @@ async function audit(config, options) {
|
|
|
1129
1381
|
];
|
|
1130
1382
|
return { root, composeFiles, findings };
|
|
1131
1383
|
}
|
|
1132
|
-
var hasConfig = (root) => existsSync3(
|
|
1384
|
+
var hasConfig = (root) => existsSync3(join6(root, CONFIG_FILE));
|
|
1133
1385
|
|
|
1134
1386
|
// src/commands/audit.ts
|
|
1135
|
-
var
|
|
1387
|
+
var usage2 = `stack audit [dir]
|
|
1136
1388
|
|
|
1137
1389
|
Cross-checks ${CONFIG_FILE} in dir (the current directory) against the compose files it syncs: sync files and build inputs exist, env variables are required or defaulted, versionEnv matches the compose interpolation, restart and post-deploy services exist, healthchecks, routing in overlays, bind mounts documented in the header, Nuxt runtimeConfig keys and .gitignore.
|
|
1138
1390
|
Lists at most 25 errors and 25 warnings, the count of the rest after them (--limit <n>, --full for all); --json is never cut.
|
|
@@ -1145,13 +1397,12 @@ var options = {
|
|
|
1145
1397
|
json: jsonOption("{ root, composeFiles, findings }")
|
|
1146
1398
|
};
|
|
1147
1399
|
async function audit2(args, overrides = {}) {
|
|
1148
|
-
const parsed = parse(args,
|
|
1400
|
+
const parsed = parse(args, usage2, options);
|
|
1149
1401
|
const root = resolve2(parsed.positionals[0] ?? ".");
|
|
1150
1402
|
if (!hasConfig(root)) {
|
|
1151
|
-
|
|
1152
|
-
return 2;
|
|
1403
|
+
fail(`no ${CONFIG_FILE} in ${root}`);
|
|
1153
1404
|
}
|
|
1154
|
-
const result = await audit(await loadConfig(root), { root, loadCompose: dockerCompose, env:
|
|
1405
|
+
const result = await audit(await loadConfig(root), { root, loadCompose: dockerCompose, env: process9.env, home: homedir2(), ...overrides });
|
|
1155
1406
|
if (parsed.values.json === true)
|
|
1156
1407
|
printJson(result);
|
|
1157
1408
|
else
|
|
@@ -1183,7 +1434,7 @@ function isListening(port) {
|
|
|
1183
1434
|
}
|
|
1184
1435
|
|
|
1185
1436
|
// src/commands/port.ts
|
|
1186
|
-
var
|
|
1437
|
+
var usage3 = `stack port <name>
|
|
1187
1438
|
|
|
1188
1439
|
Prints the port a name always hashes to (32-bit FNV-1a, ${MIN_PORT}-${DEFAULT_MAX_PORT} by default, below Linux's ephemeral range), so a service keeps the same port on every machine.
|
|
1189
1440
|
Says on stderr when something already listens on it; the exit code stays 0.
|
|
@@ -1195,12 +1446,12 @@ var options2 = {
|
|
|
1195
1446
|
json: jsonOption("{name, port, listening}")
|
|
1196
1447
|
};
|
|
1197
1448
|
async function port(args) {
|
|
1198
|
-
const parsed = parse(args,
|
|
1449
|
+
const parsed = parse(args, usage3, options2);
|
|
1199
1450
|
const [name] = parsed.positionals;
|
|
1200
1451
|
if (name === undefined)
|
|
1201
1452
|
fail("a name is needed");
|
|
1202
1453
|
const min = wholeNumber(parsed.values.min, "min", MIN_PORT, MIN_PORT);
|
|
1203
|
-
const max = wholeNumber(parsed.values.max, "max", DEFAULT_MAX_PORT, min);
|
|
1454
|
+
const max = wholeNumber(parsed.values.max, "max", Math.max(DEFAULT_MAX_PORT, min), min);
|
|
1204
1455
|
if (max > MAX_PORT)
|
|
1205
1456
|
fail(`--max goes up to ${MAX_PORT}, not ${max}`);
|
|
1206
1457
|
const number = stringToPort(name, min, max);
|
|
@@ -1215,9 +1466,8 @@ async function port(args) {
|
|
|
1215
1466
|
}
|
|
1216
1467
|
|
|
1217
1468
|
// src/cli.ts
|
|
1218
|
-
|
|
1469
|
+
process10.exitCode = await runCli({
|
|
1219
1470
|
name: "stack",
|
|
1220
|
-
version,
|
|
1221
1471
|
about: "a stable port per service name, and a compose release audit",
|
|
1222
1472
|
replaces: "picking a free host port by hand, and reading compose files against release.config.ts",
|
|
1223
1473
|
examples: ["stack port api", ["stack audit", "this folder's release setup"]],
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-stack",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.5.0",
|
|
5
5
|
"description": "stack: a stable port per service name, and an audit of a compose release setup against its release.config.ts.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -28,6 +28,6 @@
|
|
|
28
28
|
"stack": "$npm_execpath src/cli.ts"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
|
-
"@kaynooo/cli-kit": "0.
|
|
31
|
+
"@kaynooo/cli-kit": "0.21.0"
|
|
32
32
|
}
|
|
33
33
|
}
|