@kaynooo/cli-dev 0.0.0-stage → 0.1.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +34 -2
  3. package/dist/cli.js +1421 -0
  4. package/package.json +39 -4
package/dist/cli.js ADDED
@@ -0,0 +1,1421 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/cli.ts
5
+ import process7 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process3 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/style.ts
12
+ import process from "process";
13
+
14
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
+ function x(s) {
16
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
17
+ if (!/^[a-f0-9]+$/.test(r))
18
+ return [0, 0, 0];
19
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
20
+ if (t === 3 || t === 4) {
21
+ let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
22
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
23
+ }
24
+ if (t !== 6 && t !== 8)
25
+ throw Error(`Invalid hex color length: ${t}`);
26
+ let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
27
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
28
+ throw Error(`Invalid hex color value: ${s}`);
29
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
30
+ }
31
+ function A(s) {
32
+ let [r, t, n, a] = s;
33
+ if (a)
34
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
35
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
36
+ }
37
+ function R(s, r, t) {
38
+ s = (s % 360 + 360) % 360, t /= 100;
39
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
40
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
41
+ return Math.round(255 * y);
42
+ };
43
+ return [a(0), a(8), a(4)];
44
+ }
45
+ function k(s) {
46
+ let [r, t, n] = s;
47
+ r /= 255, t /= 255, n /= 255;
48
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
49
+ if (a !== b) {
50
+ let u = a - b;
51
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
52
+ o = (t - n) / u + (t < n ? 6 : 0);
53
+ else if (a === t)
54
+ o = (n - r) / u + 2;
55
+ else
56
+ o = (r - t) / u + 4;
57
+ o /= 6;
58
+ }
59
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
60
+ }
61
+ function H(s, r, t) {
62
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
63
+ let n = (a) => {
64
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
65
+ return Math.round(255 * o);
66
+ };
67
+ return [n(5), n(3), n(1)];
68
+ }
69
+ function f(s) {
70
+ let [r, t, n] = s;
71
+ r /= 255, t /= 255, n /= 255;
72
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
73
+ if (o !== 0) {
74
+ if (a === r)
75
+ y = (t - n) / o + (t < n ? 6 : 0);
76
+ else if (a === t)
77
+ y = (n - r) / o + 2;
78
+ else
79
+ y = (r - t) / o + 4;
80
+ y /= 6;
81
+ }
82
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
83
+ }
84
+ function O(s) {
85
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
86
+ if (a === 1)
87
+ return [0, 0, 0, 100];
88
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
89
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
90
+ }
91
+ function v(s, r, t, n) {
92
+ return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
93
+ }
94
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
95
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
96
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
97
+ function T(s) {
98
+ let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
99
+ return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
100
+ }
101
+ function M(s, r, t) {
102
+ let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
103
+ return [u(o), u(y), u(c)];
104
+ }
105
+ function d(s) {
106
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
107
+ return [i(r, 4), i(a, 4), i(b, 2)];
108
+ }
109
+ function C(s, r, t) {
110
+ let n = t * Math.PI / 180;
111
+ return M(s, r * Math.cos(n), r * Math.sin(n));
112
+ }
113
+ function l(s) {
114
+ let r = s / 255;
115
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
116
+ }
117
+
118
+ class e {
119
+ r;
120
+ g;
121
+ b;
122
+ a;
123
+ constructor(s, r, t, n = 1) {
124
+ this.r = s, this.g = r, this.b = t, this.a = n;
125
+ }
126
+ static from(s, r) {
127
+ if (s === "hex") {
128
+ let [t, n, a, b] = x(r);
129
+ return new e(t, n, a, b);
130
+ }
131
+ if (s === "rgb") {
132
+ if (Array.isArray(r)) {
133
+ let [o, y, c, u] = r;
134
+ return new e(o, y, c, u);
135
+ }
136
+ let { r: t, g: n, b: a, a: b } = r;
137
+ return new e(t, n, a, b);
138
+ }
139
+ if (s === "hsl") {
140
+ let t, n, a, b;
141
+ if (Array.isArray(r))
142
+ [t, n, a, b] = r;
143
+ else
144
+ ({ h: t, s: n, l: a, a: b } = r);
145
+ let [o, y, c] = R(t, n, a);
146
+ return new e(o, y, c, b);
147
+ }
148
+ if (s === "hsv") {
149
+ let t, n, a, b;
150
+ if (Array.isArray(r))
151
+ [t, n, a, b] = r;
152
+ else
153
+ ({ h: t, s: n, v: a, a: b } = r);
154
+ let [o, y, c] = H(t, n, a);
155
+ return new e(o, y, c, b);
156
+ }
157
+ if (s === "cmyk") {
158
+ let t, n, a, b, o;
159
+ if (Array.isArray(r))
160
+ [t, n, a, b, o] = r;
161
+ else
162
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
163
+ let [y, c, u] = v(t, n, a, b);
164
+ return new e(y, c, u, o);
165
+ }
166
+ if (s === "oklch") {
167
+ let t, n, a, b;
168
+ if (Array.isArray(r))
169
+ [t, n, a, b] = r;
170
+ else
171
+ ({ l: t, c: n, h: a, a: b } = r);
172
+ let [o, y, c] = C(t, n, a);
173
+ return new e(o, y, c, b);
174
+ }
175
+ if (s === "oklab") {
176
+ let t, n, a, b;
177
+ if (Array.isArray(r))
178
+ [t, n, a, b] = r;
179
+ else
180
+ ({ l: t, a: n, b: a, alpha: b } = r);
181
+ let [o, y, c] = M(t, n, a);
182
+ return new e(o, y, c, b);
183
+ }
184
+ throw Error("Invalid input");
185
+ }
186
+ to(s) {
187
+ switch (s) {
188
+ case "rgb":
189
+ return [this.r, this.g, this.b];
190
+ case "rgba":
191
+ return [this.r, this.g, this.b, this.a];
192
+ case "hex":
193
+ return A([this.r, this.g, this.b]);
194
+ case "hexa":
195
+ return A([this.r, this.g, this.b, this.a]);
196
+ case "hsl":
197
+ return k([this.r, this.g, this.b]);
198
+ case "hsla":
199
+ return [...k([this.r, this.g, this.b]), this.a];
200
+ case "hsv":
201
+ return f([this.r, this.g, this.b]);
202
+ case "hsva":
203
+ return [...f([this.r, this.g, this.b]), this.a];
204
+ case "cmyk":
205
+ return O([this.r, this.g, this.b]);
206
+ case "cmyka":
207
+ return [...O([this.r, this.g, this.b]), this.a];
208
+ case "oklch":
209
+ return d([this.r, this.g, this.b]);
210
+ case "oklcha":
211
+ return [...d([this.r, this.g, this.b]), this.a];
212
+ case "oklab":
213
+ return T([this.r, this.g, this.b]);
214
+ case "oklaba":
215
+ return [...T([this.r, this.g, this.b]), this.a];
216
+ default:
217
+ return [this.r, this.g, this.b];
218
+ }
219
+ }
220
+ getLuminance() {
221
+ let s = l(this.r), r = l(this.g), t = l(this.b);
222
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
223
+ }
224
+ contrastRatio(s) {
225
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
226
+ return (n + 0.05) / (a + 0.05);
227
+ }
228
+ bestContrastForeground() {
229
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
230
+ return t >= n ? s : r;
231
+ }
232
+ }
233
+
234
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
235
+ var r = 39;
236
+ var o = 49;
237
+ var f2 = "\x1B[";
238
+ var C2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
239
+ let [a, l, s] = e.from("hex", i).to("rgb");
240
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
241
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
242
+ var b = new Set(["", "1", "2", "3", "true"]);
243
+ function h(i, n = globalThis.process?.env ?? {}) {
244
+ if (n.FORCE_COLOR !== undefined)
245
+ return b.has(n.FORCE_COLOR);
246
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
247
+ return false;
248
+ return i?.isTTY === true;
249
+ }
250
+ function d2(i, n, a) {
251
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
252
+ return n;
253
+ let l = "", s = "";
254
+ for (let g = 0, y = i.length;g < y; g++) {
255
+ let [c, p] = i[g];
256
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
257
+ }
258
+ return l + n + s;
259
+ }
260
+ function u(i, n = []) {
261
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
262
+ let g = C2[s];
263
+ if (Array.isArray(g))
264
+ return u(i, [...n, g]);
265
+ if (typeof g === "function")
266
+ return (...y) => u(i, [...n, g(...y)]);
267
+ throw Error(`Unknown style: ${String(s)}`);
268
+ } });
269
+ }
270
+ function le(i = {}) {
271
+ return u(i);
272
+ }
273
+ var t = le();
274
+
275
+ // ../kit/src/style.ts
276
+ function takesControlCodes(stream, env = process.env) {
277
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
278
+ }
279
+ function paint(stream, env = process.env) {
280
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
281
+ }
282
+ var STATUSES = {
283
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
284
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
285
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
286
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
287
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
288
+ };
289
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
290
+
291
+ // ../kit/src/format.ts
292
+ function upTo(text, separator) {
293
+ const end = text.indexOf(separator);
294
+ return end === -1 ? text : text.slice(0, end);
295
+ }
296
+ var ESCAPE = String.fromCharCode(27);
297
+ function printJson(value) {
298
+ console.log(JSON.stringify(value, undefined, 2));
299
+ }
300
+
301
+ // ../kit/src/help.ts
302
+ import process2 from "process";
303
+ var OPTIONAL = /\[[^\]]+\]/g;
304
+ var USAGE_PREFIX = /^usage:\s*/i;
305
+ var FULL_STOP = /\.$/;
306
+ function usageLine(usage, colors = paint(process2.stdout)) {
307
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
308
+ }
309
+ function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
310
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
311
+ `);
312
+ }
313
+ function replacesRows(replaces, colors = paint(process2.stdout)) {
314
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
315
+ }
316
+ function wantsHelpJson(env = process2.env) {
317
+ return env.KIT_HELP === "json";
318
+ }
319
+ function description(usage, { examples = [], replaces } = {}) {
320
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
321
+ `);
322
+ const first = lines[0];
323
+ const colon = first.indexOf(": ");
324
+ const prose = lines[lines.indexOf("") + 1] ?? "";
325
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
326
+ return {
327
+ synopsis: colon === -1 ? first : first.slice(0, colon),
328
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
329
+ ...replaces === undefined ? {} : { replaces },
330
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
331
+ };
332
+ }
333
+ function exampleRows(examples, colors = paint(process2.stdout)) {
334
+ if (examples.length === 0)
335
+ return [];
336
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
337
+ }
338
+ function optionRows(options, colors = paint(process2.stdout)) {
339
+ const rows = Object.entries(options).map(([name, option]) => {
340
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
341
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
342
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
343
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
344
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
345
+ });
346
+ const width = Math.max(0, ...rows.map((row) => row.width));
347
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
348
+ }
349
+
350
+ // ../kit/src/text.ts
351
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
352
+ function distance(a, b) {
353
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
354
+ for (const [i, left] of [...a].entries()) {
355
+ const current = [i + 1];
356
+ for (const [j, right] of [...b].entries())
357
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
358
+ previous = current;
359
+ }
360
+ return previous[b.length] ?? 0;
361
+ }
362
+ function closest(name, names) {
363
+ const started = names.find((known) => known.startsWith(name));
364
+ if (started !== undefined)
365
+ return started;
366
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
367
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
368
+ }
369
+ // ../kit/src/input.ts
370
+ import { fstatSync } from "fs";
371
+ var WHOLE = /^\d+$/;
372
+ function wholeNumber(value, name, fallback, min = 1) {
373
+ if (value === undefined)
374
+ return fallback;
375
+ const number = Number(value);
376
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
377
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
378
+ return number;
379
+ }
380
+ function isStdinPiped() {
381
+ const stat = fstatSync(0);
382
+ return stat.isFIFO() || stat.isFile();
383
+ }
384
+
385
+ // ../kit/src/args.ts
386
+ var DASHES = /^-+/;
387
+ function jsonOption(holds) {
388
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
389
+ }
390
+
391
+ class Exit extends Error {
392
+ code;
393
+ hint;
394
+ constructor(message, code, hint) {
395
+ super(message);
396
+ this.code = code;
397
+ this.hint = hint;
398
+ }
399
+ }
400
+ function fail(message, code = 2, hint) {
401
+ throw new Exit(message, code, hint);
402
+ }
403
+
404
+ class UsageError extends Exit {
405
+ constructor(message, hint) {
406
+ super(message, 2, hint);
407
+ }
408
+ }
409
+ function badUsage(message) {
410
+ throw new UsageError(message);
411
+ }
412
+
413
+ class HelpShown extends Exit {
414
+ constructor() {
415
+ super("help shown", 0);
416
+ }
417
+ }
418
+
419
+ class Completing {
420
+ options;
421
+ positionals;
422
+ candidates;
423
+ constructor(options, positionals = [], candidates = {}) {
424
+ this.options = options;
425
+ this.positionals = positionals;
426
+ this.candidates = candidates;
427
+ }
428
+ }
429
+ var completion = { active: false };
430
+ var OUTPUT_OPTIONS = {
431
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
432
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
433
+ };
434
+ function applyOutput(color, plain, env = process3.env) {
435
+ const when = plain === true ? "never" : color ?? "auto";
436
+ if (when === "auto")
437
+ return;
438
+ if (when !== "always" && when !== "never")
439
+ badUsage(`--color takes auto, always or never, not ${when}`);
440
+ if (when === "always") {
441
+ env.FORCE_COLOR = "1";
442
+ delete env.NO_COLOR;
443
+ } else {
444
+ env.NO_COLOR = "1";
445
+ delete env.FORCE_COLOR;
446
+ }
447
+ }
448
+ function parse(args, usage, options, settings = {}) {
449
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
450
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
451
+ const listing = listed(all, settings.allowNegative === true);
452
+ if (completion.active)
453
+ throw new Completing(listing, settings.positionals, settings.candidates);
454
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
455
+ let parsed;
456
+ try {
457
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
458
+ } catch (error) {
459
+ const message = parseError(error);
460
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
461
+ }
462
+ const values = parsed.values;
463
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
464
+ if (values.help === true) {
465
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
466
+ throw new HelpShown;
467
+ }
468
+ checkChoices(parsed.values, all);
469
+ checkConflicts(parsed.values, all);
470
+ if (settings.positionals !== undefined)
471
+ checkPositionals(parsed.positionals, settings.positionals);
472
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
473
+ }
474
+ function splitRest(args, passes) {
475
+ const separator = passes ? args.indexOf("--") : -1;
476
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
477
+ }
478
+ function splitTrailing(args, options, count) {
479
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
480
+ let seen = 0;
481
+ if (count === 0)
482
+ return { own: args, rest: undefined };
483
+ for (let at = 0;at < args.length; at++) {
484
+ const word = args[at];
485
+ if (word === "--")
486
+ break;
487
+ if (word.startsWith("-")) {
488
+ if (takesValue(word))
489
+ at++;
490
+ continue;
491
+ }
492
+ seen++;
493
+ if (seen === count)
494
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
495
+ }
496
+ return { own: args, rest: undefined };
497
+ }
498
+ function listed(options, allowNegative) {
499
+ if (!allowNegative)
500
+ return options;
501
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
502
+ if (option.type !== "boolean" || option.negative === undefined)
503
+ return [[name, option]];
504
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
505
+ }));
506
+ }
507
+ function withBare(args, options) {
508
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
509
+ if (bare.size === 0)
510
+ return args;
511
+ const separator = args.indexOf("--");
512
+ const own = separator === -1 ? args : args.slice(0, separator);
513
+ return [...own.flatMap((arg, index) => {
514
+ const optional = bare.get(arg);
515
+ const next = own[index + 1];
516
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
517
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
518
+ }), ...separator === -1 ? [] : args.slice(separator)];
519
+ }
520
+ function checkConflicts(values, options) {
521
+ const given = (name) => values[name] !== undefined && values[name] !== false;
522
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
523
+ const other = given(name) ? conflicts.find(given) : undefined;
524
+ if (other !== undefined)
525
+ badUsage(`--${name} cannot be used with --${other}`);
526
+ }
527
+ }
528
+ function checkChoices(values, options) {
529
+ for (const [name, option] of Object.entries(options)) {
530
+ if (option.choices === undefined)
531
+ continue;
532
+ const given = values[name];
533
+ for (const value of Array.isArray(given) ? given : [given]) {
534
+ if (typeof value === "string")
535
+ oneOf(value, name, option.choices);
536
+ }
537
+ }
538
+ }
539
+ function oneOf(value, name, choices) {
540
+ if (!choices.includes(value))
541
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
542
+ return value;
543
+ }
544
+ function checkPositionals(given, names) {
545
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
546
+ const required = names.filter((name) => !name.startsWith("[")).length;
547
+ if (given.length < required)
548
+ badUsage(`missing ${names[given.length]}`);
549
+ if (!variadic && given.length > names.length)
550
+ badUsage(`unexpected argument ${given[names.length]}`);
551
+ }
552
+ function joinDashValues(args, options) {
553
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
554
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
555
+ const joined = [];
556
+ for (let i = 0;i < args.length; i++) {
557
+ const arg = args[i] ?? "";
558
+ if (arg === "--")
559
+ return [...joined, ...args.slice(i)];
560
+ const name = longOf.get(arg);
561
+ const next = args[i + 1];
562
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
563
+ joined.push(`--${name}=${next}`);
564
+ i++;
565
+ } else {
566
+ joined.push(arg);
567
+ }
568
+ }
569
+ return joined;
570
+ }
571
+ function parseError(error) {
572
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
573
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
574
+ }
575
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
576
+ function nearestOption(message, options, allowNegative) {
577
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
578
+ if (typed === undefined)
579
+ return;
580
+ const word = typed.replace(DASHES, "");
581
+ if (word.length < 2 && !typed.startsWith("--"))
582
+ return;
583
+ const known = Object.entries(options).flatMap(([name, option]) => [
584
+ ...option.short === undefined ? [] : [`-${option.short}`],
585
+ `--${name}`,
586
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
587
+ ]);
588
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
589
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
590
+ }
591
+ // ../kit/src/progress.ts
592
+ var ESC = String.fromCharCode(27);
593
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
594
+ var RESET_STYLE = `${ESC}[0m`;
595
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
596
+ // ../kit/src/cli.ts
597
+ import process5 from "process";
598
+
599
+ // ../kit/src/usage.ts
600
+ import { appendFileSync, mkdirSync } from "fs";
601
+ import { homedir } from "os";
602
+ import { dirname, isAbsolute, join } from "path";
603
+ import process4 from "process";
604
+
605
+ // ../kit/src/logs.ts
606
+ var DAY_MS = 24 * 60 * 60 * 1000;
607
+ var CLI_FOLDER = "kaynooo-cli";
608
+
609
+ // ../kit/src/usage.ts
610
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
611
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
612
+ var LONGEST_NAME = 40;
613
+ var usageError;
614
+ function noteUsageError(message) {
615
+ usageError = message;
616
+ }
617
+ function stateHome(env = process4.env) {
618
+ const dir = env.XDG_STATE_HOME;
619
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
620
+ }
621
+ function usagePath(env = process4.env) {
622
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
623
+ }
624
+ function usageRecorded(env = process4.env) {
625
+ const off = env.KAYNOOO_CLI_NO_USAGE;
626
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
627
+ }
628
+ function flagNames(argv) {
629
+ const end = argv.indexOf("--");
630
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
631
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
632
+ }
633
+ function usageEntry(bin, command, argv, code, now = new Date) {
634
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
635
+ usageError = undefined;
636
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
637
+ }
638
+ function recordUsage(entry, env = process4.env) {
639
+ if (!usageRecorded(env))
640
+ return;
641
+ try {
642
+ const path = usagePath(env);
643
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
644
+ appendFileSync(path, `${JSON.stringify(entry)}
645
+ `, { mode: 384 });
646
+ } catch {}
647
+ }
648
+
649
+ // ../kit/src/cli.ts
650
+ var LEVEL_OPTIONS = {
651
+ ...OUTPUT_OPTIONS,
652
+ help: { type: "boolean", short: "h", description: "show this help" }
653
+ };
654
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
655
+ async function commandRows(all, colors) {
656
+ const commands = shown(all);
657
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
658
+ const groups = new Map([["Commands:", []]]);
659
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
660
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
661
+ const heading = group === undefined ? "Commands:" : `${group}:`;
662
+ const rows = groups.get(heading) ?? [];
663
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
664
+ groups.set(heading, rows);
665
+ }
666
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
667
+ }
668
+ function shown(commands) {
669
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
670
+ }
671
+ function takeOutputFlags(argv) {
672
+ let index = 0;
673
+ for (;index < argv.length; index++) {
674
+ const word = argv[index];
675
+ if (word === "--plain")
676
+ applyOutput(undefined, true);
677
+ else if (word.startsWith("--color="))
678
+ applyOutput(word.slice("--color=".length), undefined);
679
+ else if (word === "--color" && argv[index + 1] !== undefined)
680
+ applyOutput(argv[++index], undefined);
681
+ else
682
+ break;
683
+ }
684
+ return argv.slice(index);
685
+ }
686
+ async function resolveSummary(summary) {
687
+ return typeof summary === "string" ? summary : summary();
688
+ }
689
+ function scopeOf(commands, extra, aliases) {
690
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
691
+ }
692
+ async function expand(scope, words) {
693
+ if (scope.lazy.length === 0)
694
+ return scope;
695
+ const commands = { ...scope.commands };
696
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
697
+ for (const [name, command] of Object.entries(added))
698
+ commands[name] ??= command;
699
+ }
700
+ return { ...scope, commands, lazy: [] };
701
+ }
702
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
703
+ const colors = paint(stream);
704
+ const prefix = path.join(" ");
705
+ const summary = await resolveSummary(lazySummary);
706
+ if (wantsHelpJson())
707
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
708
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
709
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
710
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
711
+ return [
712
+ header(colors, summary),
713
+ "",
714
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
715
+ ...replacesRows(replaces, colors),
716
+ "",
717
+ ...await commandRows(commands, colors),
718
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
719
+ "",
720
+ colors.bold("Options:"),
721
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
722
+ ...exampleRows(examples ?? [], colors),
723
+ "",
724
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
725
+ ].join(`
726
+ `);
727
+ }
728
+ function printError(prefix, message, hint, cause) {
729
+ const colors = paint(process5.stderr);
730
+ const styled = takesControlCodes(process5.stderr);
731
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
732
+ const under = (label, text, tint) => text === undefined ? "" : `
733
+ ${styled ? tint(label) : `${label}:`} ${text}`;
734
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
735
+ }
736
+ function printJsonError(message, hint, cause) {
737
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
738
+ }
739
+ function wantsJson(argv) {
740
+ const end = argv.indexOf("--");
741
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
742
+ }
743
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
744
+ if (error instanceof HelpShown)
745
+ return 0;
746
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
747
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
748
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
749
+ if (error instanceof UsageError)
750
+ noteUsageError(error.message);
751
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
752
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
753
+ return error instanceof Exit ? error.code : 1;
754
+ }
755
+ async function dispatch(level, typed, { version, redact }) {
756
+ const prefix = level.path.join(" ");
757
+ let argv;
758
+ try {
759
+ argv = takeOutputFlags(typed);
760
+ } catch (error) {
761
+ return reportThrown(prefix, error);
762
+ }
763
+ const [name, ...args] = argv;
764
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
765
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
766
+ try {
767
+ return await fallback.run([]);
768
+ } catch (error) {
769
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
770
+ }
771
+ }
772
+ if (name === undefined && level.path.length > 1) {
773
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
774
+ return 2;
775
+ }
776
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
777
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
778
+ return 0;
779
+ }
780
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
781
+ console.log(version);
782
+ return 0;
783
+ }
784
+ let command = level.commands[level.aliases?.[name] ?? name];
785
+ let rest = args;
786
+ let ran = name;
787
+ if (command === undefined && level.lazy.length > 0) {
788
+ level = await expand(level, [...level.path.slice(1), ...argv]);
789
+ command = level.commands[level.aliases?.[name] ?? name];
790
+ }
791
+ if (command === undefined && level.defaultCommand !== undefined) {
792
+ command = level.commands[level.defaultCommand];
793
+ rest = argv;
794
+ ran = level.defaultCommand;
795
+ }
796
+ if (command === undefined) {
797
+ const meant = closest(name, Object.keys(shown(level.commands)));
798
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
799
+ return 2;
800
+ }
801
+ if ("commands" in command) {
802
+ const { summary } = command;
803
+ 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 });
804
+ }
805
+ try {
806
+ return await command.run(rest);
807
+ } catch (error) {
808
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
809
+ }
810
+ }
811
+ var COMPLETE = "__complete";
812
+ var FILES = "__files__";
813
+ async function completingOf(run) {
814
+ completion.active = true;
815
+ try {
816
+ await run([]);
817
+ } catch (error) {
818
+ if (error instanceof Completing)
819
+ return error;
820
+ } finally {
821
+ completion.active = false;
822
+ }
823
+ return new Completing({});
824
+ }
825
+ async function optionsOf(run) {
826
+ return (await completingOf(run)).options;
827
+ }
828
+ function candidateLine(candidate) {
829
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
830
+ }
831
+ function positionalBeingTyped(before, { options, positionals }) {
832
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
833
+ let index = 0;
834
+ let at = 0;
835
+ while (at < before.length) {
836
+ const word = before[at];
837
+ if (word === "--") {
838
+ index += before.length - at - 1;
839
+ break;
840
+ }
841
+ if (!word.startsWith("-"))
842
+ index++;
843
+ else if (takesValue(word))
844
+ at++;
845
+ at++;
846
+ }
847
+ const last = positionals.at(-1);
848
+ if (index < positionals.length)
849
+ return positionals[index];
850
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
851
+ }
852
+ async function leafCandidates(run, words) {
853
+ const completing = await completingOf(run);
854
+ if ((words.at(-1) ?? "").startsWith("-"))
855
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
856
+ const flag = words.at(-2);
857
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
858
+ if (option?.type === "string") {
859
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
860
+ return values === undefined ? [FILES] : values.map(candidateLine);
861
+ }
862
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
863
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
864
+ return values === undefined ? [FILES] : values.map(candidateLine);
865
+ }
866
+ async function candidates(scope, defaultCommand, words, before = []) {
867
+ const [word = "", ...rest] = words;
868
+ const listing = rest.length === 0 && !word.startsWith("-");
869
+ let { commands, aliases } = scope;
870
+ let command = commands[aliases?.[word] ?? word];
871
+ if (listing || command === undefined) {
872
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
873
+ command = commands[aliases?.[word] ?? word];
874
+ }
875
+ if (listing) {
876
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
877
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
878
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
879
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
880
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
881
+ }
882
+ if (command === undefined) {
883
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
884
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
885
+ }
886
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
887
+ }
888
+ async function printCandidates(found) {
889
+ for (const line of await found)
890
+ console.log(line);
891
+ return 0;
892
+ }
893
+ async function runCli(cli, argv = process5.argv.slice(2)) {
894
+ if (argv[0] === COMPLETE)
895
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
896
+ 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 });
897
+ if (cli.usage !== false) {
898
+ try {
899
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
900
+ } catch {}
901
+ }
902
+ return code;
903
+ }
904
+ function commandPath(scope, argv) {
905
+ const path = [];
906
+ let level = scope;
907
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
908
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
909
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
910
+ if (command === undefined)
911
+ break;
912
+ path.push(word);
913
+ if (!("commands" in command))
914
+ break;
915
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
916
+ }
917
+ return path.length === 0 ? undefined : path.join(" ");
918
+ }
919
+ // ../kit/src/secrets.ts
920
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
921
+ // ../kit/src/sessions.ts
922
+ var {Glob } = globalThis.Bun;
923
+ var SESSION_FILES = new Glob("*.json");
924
+ var ACCOUNT_DIRS = new Glob("*/sessions");
925
+ // package.json
926
+ var version = "0.1.0";
927
+
928
+ // src/encode.ts
929
+ function b64Encode(bytes, url = false) {
930
+ return Buffer.from(bytes).toString(url ? "base64url" : "base64");
931
+ }
932
+ var WHITESPACE = /\s+/g;
933
+ var TRAILING_PADDING = /=+$/;
934
+ var ALPHABET = /^[\w+/-]*={0,2}$/;
935
+ function b64Decode(text) {
936
+ const clean = text.replace(WHITESPACE, "");
937
+ if (!ALPHABET.test(clean) || clean.replace(TRAILING_PADDING, "").length % 4 === 1)
938
+ throw new Error("not valid base64");
939
+ return Buffer.from(clean, "base64");
940
+ }
941
+
942
+ // src/hash.ts
943
+ var ALGORITHMS = ["sha256", "sha1", "md5", "sha512"];
944
+ function hashHex(algorithm, bytes) {
945
+ return new Bun.CryptoHasher(algorithm).update(bytes).digest("hex");
946
+ }
947
+
948
+ // src/ids.ts
949
+ var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
950
+ function randomBytes(length) {
951
+ return crypto.getRandomValues(new Uint8Array(length));
952
+ }
953
+ function uuidV7(now = Date.now(), random = randomBytes(10)) {
954
+ const bytes = new Uint8Array(16);
955
+ for (let i = 0;i < 6; i++)
956
+ bytes[i] = Math.floor(now / 2 ** (8 * (5 - i))) & 255;
957
+ bytes.set(random.subarray(0, 10), 6);
958
+ bytes[6] = bytes[6] & 15 | 112;
959
+ bytes[8] = bytes[8] & 63 | 128;
960
+ const hex = Buffer.from(bytes).toString("hex");
961
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
962
+ }
963
+ function ulid(now = Date.now(), random = randomBytes(16)) {
964
+ let time = "";
965
+ let rest = now;
966
+ for (let i = 0;i < 10; i++) {
967
+ time = CROCKFORD[rest % 32] + time;
968
+ rest = Math.floor(rest / 32);
969
+ }
970
+ return time + Array.from(random.subarray(0, 16), (byte) => CROCKFORD[byte & 31]).join("");
971
+ }
972
+ function uuidV4() {
973
+ return crypto.randomUUID();
974
+ }
975
+
976
+ // src/time.ts
977
+ var UNITS = [["d", 86400000], ["h", 3600000], ["m", 60000], ["s", 1000]];
978
+ var DURATION_UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
979
+ function parts(ms, timeZone) {
980
+ const formatter = new Intl.DateTimeFormat("en-US", { timeZone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", timeZoneName: "longOffset" });
981
+ return Object.fromEntries(formatter.formatToParts(new Date(ms)).map((part) => [part.type, part.value]));
982
+ }
983
+ function formatZoned(ms, timeZone) {
984
+ const p = parts(ms, timeZone);
985
+ const offset = p.timeZoneName === "GMT" ? "+00:00" : (p.timeZoneName ?? "").replace("GMT", "");
986
+ return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second} ${timeZone === "UTC" ? "UTC" : offset}`;
987
+ }
988
+ function zoned(ms, timeZone) {
989
+ return { local: formatZoned(ms, timeZone), utc: formatZoned(ms, "UTC") };
990
+ }
991
+ function offsetAt(ms, timeZone) {
992
+ const p = parts(ms, timeZone);
993
+ return Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day), Number(p.hour), Number(p.minute), Number(p.second)) - Math.floor(ms / 1000) * 1000;
994
+ }
995
+ function humanDuration(ms) {
996
+ let rest = Math.floor(Math.abs(ms) / 1000) * 1000;
997
+ const out = [];
998
+ for (const [name, size] of UNITS) {
999
+ const count = Math.floor(rest / size);
1000
+ if (count > 0) {
1001
+ out.push(`${count}${name}`);
1002
+ rest -= count * size;
1003
+ }
1004
+ }
1005
+ return out.slice(0, 2).join(" ") || "0s";
1006
+ }
1007
+ function relative(ms, now) {
1008
+ const delta = ms - now;
1009
+ if (Math.abs(delta) < 1000)
1010
+ return "now";
1011
+ return delta > 0 ? `in ${humanDuration(delta)}` : `${humanDuration(delta)} ago`;
1012
+ }
1013
+ var DURATION = /^(?:\d+(?:\.\d+)?(?:ms|[dhms]))+$/;
1014
+ var DURATION_PART = /(\d+(?:\.\d+)?)(ms|[dhms])/g;
1015
+ function parseDuration(text) {
1016
+ if (!DURATION.test(text))
1017
+ return;
1018
+ let total = 0;
1019
+ for (const [, count, unit] of text.matchAll(DURATION_PART))
1020
+ total += Number(count) * DURATION_UNIT_MS[unit];
1021
+ return total;
1022
+ }
1023
+ var ZONELESS = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?)?$/;
1024
+ var DATE_SPACE = /^(\d{4}-\d{2}-\d{2}) /;
1025
+ var WHITESPACE2 = /\s+/g;
1026
+ var ZONED = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:Z|[+-]\d{2}(?::?\d{2})?)$/i;
1027
+ function parseDate(text, timeZone) {
1028
+ const match = ZONELESS.exec(text);
1029
+ if (match === null) {
1030
+ const ms = ZONED.test(text) ? Date.parse(text.replace(DATE_SPACE, "$1T").replace(WHITESPACE2, "")) : Number.NaN;
1031
+ return Number.isNaN(ms) ? undefined : ms;
1032
+ }
1033
+ const [, year, month, day, hour = "0", minute = "0", second = "0", fraction = "0"] = match;
1034
+ const wall = Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), Number(second), Number(fraction.padEnd(3, "0")));
1035
+ const back = new Date(wall);
1036
+ if (back.getUTCFullYear() !== Number(year) || back.getUTCMonth() !== Number(month) - 1 || back.getUTCDate() !== Number(day) || back.getUTCHours() !== Number(hour) || back.getUTCMinutes() !== Number(minute) || back.getUTCSeconds() !== Number(second))
1037
+ return;
1038
+ const first = wall - offsetAt(wall, timeZone);
1039
+ return wall - offsetAt(first, timeZone);
1040
+ }
1041
+
1042
+ // src/jwt.ts
1043
+ var BEARER = /^Bearer\s+/i;
1044
+ var TIME_CLAIMS = ["iat", "nbf", "exp"];
1045
+ function segment(text, name) {
1046
+ let value;
1047
+ try {
1048
+ value = JSON.parse(Buffer.from(text, "base64url").toString("utf8"));
1049
+ } catch {
1050
+ throw new Error(`the ${name} is not base64url JSON`);
1051
+ }
1052
+ if (typeof value !== "object" || value === null || Array.isArray(value))
1053
+ throw new Error(`the ${name} is not a JSON object`);
1054
+ return value;
1055
+ }
1056
+ function decodeJwt(token) {
1057
+ const parts = token.trim().replace(BEARER, "").split(".");
1058
+ if (parts.length !== 3)
1059
+ throw new Error(`a JWT has 3 dot-separated parts, this has ${parts.length}`);
1060
+ const [header = "", payload = "", signature = ""] = parts;
1061
+ return { header: segment(header, "header"), payload: segment(payload, "payload"), signatureBytes: Buffer.from(signature, "base64url").length };
1062
+ }
1063
+ function claimTimes(payload, now = Date.now(), timeZone) {
1064
+ return TIME_CLAIMS.flatMap((claim) => {
1065
+ const epoch = payload[claim];
1066
+ return typeof epoch === "number" && Number.isFinite(epoch) ? [{ claim, epoch, ...zoned(epoch * 1000, timeZone), relative: relative(epoch * 1000, now) }] : [];
1067
+ });
1068
+ }
1069
+
1070
+ // src/password.ts
1071
+ var FORMATS = ["hex", "base64", "base64url"];
1072
+ var DEFAULT_LENGTH = 32;
1073
+ function generatePassword(length, format, random = (bytes) => crypto.getRandomValues(bytes)) {
1074
+ const buffer = Buffer.from(random(new Uint8Array(length)));
1075
+ return buffer.toString(format);
1076
+ }
1077
+ async function bcryptHash(password) {
1078
+ const hash = await Bun.password.hash(password, { algorithm: "bcrypt", cost: 10 });
1079
+ return `$2y$${hash.slice("$2b$".length)}`;
1080
+ }
1081
+
1082
+ // src/ts.ts
1083
+ var NUMBER = /^-?\d+(?:\.\d+)?$/;
1084
+ var MILLISECONDS_FROM = 100000000000;
1085
+ function instant(kind, ms, now, timeZone) {
1086
+ if (Number.isNaN(new Date(ms).getTime()))
1087
+ throw new Error("the date is out of range");
1088
+ return { kind, ...zoned(ms, timeZone), ms, seconds: Math.floor(ms / 1000), relative: relative(ms, now) };
1089
+ }
1090
+ function convert(value, { now = Date.now(), timeZone } = {}) {
1091
+ const text = value?.trim() ?? "";
1092
+ if (text === "")
1093
+ return instant("now", now, now, timeZone);
1094
+ if (NUMBER.test(text)) {
1095
+ const number = Number(text);
1096
+ return Math.abs(number) >= MILLISECONDS_FROM ? instant("epoch-milliseconds", Math.round(number), now, timeZone) : instant("epoch-seconds", Math.round(number * 1000), now, timeZone);
1097
+ }
1098
+ const duration = parseDuration(text);
1099
+ if (duration !== undefined)
1100
+ return { kind: "duration", ms: duration, seconds: duration / 1000, human: humanDuration(duration), fromNow: zoned(now + duration, timeZone) };
1101
+ const date = parseDate(text, timeZone);
1102
+ if (date === undefined)
1103
+ throw new Error(`${text} is not an epoch, an ISO date or a duration such as 90m or 2h30m`);
1104
+ return instant("date", date, now, timeZone);
1105
+ }
1106
+
1107
+ // src/url.ts
1108
+ var TRAILING_COLON = /:$/;
1109
+ var LEADING_HASH = /^#/;
1110
+ function decode(value) {
1111
+ try {
1112
+ return decodeURIComponent(value);
1113
+ } catch {
1114
+ return value;
1115
+ }
1116
+ }
1117
+ function urlParts(text) {
1118
+ let url;
1119
+ try {
1120
+ url = new URL(text.trim());
1121
+ } catch {
1122
+ throw new Error(`${text.trim()} is not a URL (include the scheme, as https://...)`);
1123
+ }
1124
+ return {
1125
+ href: url.href,
1126
+ protocol: url.protocol.replace(TRAILING_COLON, ""),
1127
+ username: decode(url.username),
1128
+ password: decode(url.password),
1129
+ host: url.host,
1130
+ hostname: url.hostname,
1131
+ port: url.port,
1132
+ pathname: decode(url.pathname),
1133
+ query: Array.from(url.searchParams, ([key, value]) => ({ key, value })),
1134
+ hash: decode(url.hash.replace(LEADING_HASH, ""))
1135
+ };
1136
+ }
1137
+
1138
+ // src/cli.ts
1139
+ var MAX_PASSWORD_BYTES = 65536;
1140
+ var ZONE_OPTION = { type: "string", description: "the IANA zone of the local dates, such as Europe/Paris (default: this host's)" };
1141
+ function reading(read) {
1142
+ try {
1143
+ return read();
1144
+ } catch (error) {
1145
+ return fail(error instanceof Error ? error.message : String(error), 1);
1146
+ }
1147
+ }
1148
+ function zoneOf(zone) {
1149
+ if (zone === undefined)
1150
+ return;
1151
+ try {
1152
+ new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(0);
1153
+ } catch {
1154
+ badUsage(`--zone takes an IANA zone such as Europe/Paris, not ${zone}`);
1155
+ }
1156
+ return zone;
1157
+ }
1158
+ async function textInput(argument, what) {
1159
+ if (argument !== undefined)
1160
+ return argument;
1161
+ return !isStdinPiped() ? fail(`give ${what} as an argument or pipe it on stdin`, 2) : Bun.stdin.text();
1162
+ }
1163
+ async function bytesInput(argument, what) {
1164
+ if (argument !== undefined)
1165
+ return new TextEncoder().encode(argument);
1166
+ if (!isStdinPiped())
1167
+ return fail(`give ${what} as an argument or pipe it on stdin`, 2);
1168
+ return new Uint8Array(await Bun.stdin.arrayBuffer());
1169
+ }
1170
+ async function copyToClipboard(text) {
1171
+ if (Bun.which("wl-copy") === null)
1172
+ return false;
1173
+ const copy = Bun.spawn(["wl-copy"], { stdin: new Blob([text]), stdout: "ignore", stderr: "ignore" });
1174
+ return await copy.exited === 0;
1175
+ }
1176
+ function printRows(rows) {
1177
+ const { cyan } = paint(process7.stdout);
1178
+ const width = Math.max(...rows.map(([label]) => label.length));
1179
+ for (const [label, value] of rows)
1180
+ console.log(`${cyan(label.padEnd(width))} ${value}`);
1181
+ }
1182
+ var PASSWORD_USAGE = `dev password [length] [format] [-b|--bcrypt [password]]: a random password of <length> bytes (default ${DEFAULT_LENGTH}) as hex, base64 (default) or base64url
1183
+
1184
+ Printed on stdout and copied to the clipboard with wl-copy when it exists (the copy is said on stderr). With --bcrypt it is the bcrypt hash (cost 10) that prints: of the password given, or of a generated one, which then prints on stderr and is the one copied. Bun writes bcrypt as $2b$, the hash prints with the $2y$ prefix htpasswd -B writes, the one Apache, nginx and traefik basic auth all accept.
1185
+ Exits 0 when it printed the password or hash, 2 on a usage error.`;
1186
+ var PASSWORD_OPTIONS = {
1187
+ bcrypt: { type: "string", short: "b", optional: { bare: "" }, description: "print the bcrypt hash of the password given, or of a generated one" },
1188
+ "no-copy": { type: "boolean", description: "leave the clipboard alone" },
1189
+ json: jsonOption("{password?, hash?, format, bytes, copied}")
1190
+ };
1191
+ var FORMAT_NOTES = { hex: "hexadecimal", base64: "base64", base64url: "url-safe base64" };
1192
+ async function password(args) {
1193
+ const { values, positionals } = parse(args, PASSWORD_USAGE, PASSWORD_OPTIONS, {
1194
+ positionals: ["[length]", "[format]"],
1195
+ candidates: { "[length]": () => ["16", "24", "32", "48", "64"], "[format]": () => FORMATS.map((format) => [format, FORMAT_NOTES[format]]) },
1196
+ replaces: 'openssl rand -base64 32 and htpasswd -bnBC 10 "" <password>',
1197
+ examples: ["dev password", ["dev password 16 hex", "16 random bytes as 32 hex characters"], ["dev password --bcrypt hunter2", "the hash to paste into a basic auth file"]]
1198
+ });
1199
+ const bytes = wholeNumber(positionals[0], "<length>", DEFAULT_LENGTH);
1200
+ const format = oneOf(positionals[1] ?? "base64", "<format>", FORMATS);
1201
+ if (bytes > MAX_PASSWORD_BYTES)
1202
+ badUsage(`<length> takes at most ${MAX_PASSWORD_BYTES}, not ${bytes}`);
1203
+ const given = values.bcrypt === undefined || values.bcrypt === "" ? undefined : values.bcrypt;
1204
+ const secret = given ?? generatePassword(bytes, format);
1205
+ const hash = values.bcrypt === undefined ? undefined : await bcryptHash(secret);
1206
+ const copied = values["no-copy"] === true ? false : await copyToClipboard(given === undefined ? secret : hash ?? secret);
1207
+ if (values.json === true) {
1208
+ printJson({ ...hash === undefined ? {} : { hash }, ...given === undefined ? { password: secret } : {}, format, bytes, copied });
1209
+ return 0;
1210
+ }
1211
+ if (copied)
1212
+ console.error(paint(process7.stderr).dim("copied to clipboard"));
1213
+ if (hash !== undefined && given === undefined)
1214
+ console.error(secret);
1215
+ console.log(hash ?? secret);
1216
+ return 0;
1217
+ }
1218
+ var JWT_USAGE = `dev jwt [token]: the header and payload of a JWT, with iat, nbf and exp as local and UTC dates and how far from now
1219
+
1220
+ The token is the argument or what is piped on stdin, a leading "Bearer " is ignored. The signature is not verified.
1221
+ Exits 0 when it decoded the token, 1 when it is not a JWT, 2 on a usage error.`;
1222
+ var JWT_OPTIONS = {
1223
+ zone: ZONE_OPTION,
1224
+ json: jsonOption("{header, payload, claims: [{claim, epoch, local, utc, relative}], signatureBytes}")
1225
+ };
1226
+ async function jwt(args) {
1227
+ const { values, positionals } = parse(args, JWT_USAGE, JWT_OPTIONS, {
1228
+ positionals: ["[token]"],
1229
+ replaces: "pasting a token into jwt.io or decoding its segments with base64 and jq",
1230
+ examples: ["dev jwt eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDAwMDAwMDB9.c2ln", ["pbpaste | dev jwt --json", "for a script"]]
1231
+ });
1232
+ const zone = zoneOf(values.zone);
1233
+ const token = await textInput(positionals[0], "the token");
1234
+ const decoded = reading(() => decodeJwt(token));
1235
+ const claims = claimTimes(decoded.payload, Date.now(), zone);
1236
+ if (values.json === true) {
1237
+ printJson({ header: decoded.header, payload: decoded.payload, claims, signatureBytes: decoded.signatureBytes });
1238
+ return 0;
1239
+ }
1240
+ const { bold } = paint(process7.stdout);
1241
+ console.log(`${bold("header")}
1242
+ ${JSON.stringify(decoded.header, null, 2)}
1243
+
1244
+ ${bold("payload")}
1245
+ ${JSON.stringify(decoded.payload, null, 2)}`);
1246
+ if (claims.length > 0) {
1247
+ console.log("");
1248
+ printRows(claims.map(({ claim, local, utc, relative }) => [claim, `${local} ${utc} ${relative}`]));
1249
+ }
1250
+ return 0;
1251
+ }
1252
+ var TS_USAGE = `dev ts [value]: a time as local and UTC dates, whatever it is written as
1253
+
1254
+ The value is epoch seconds or milliseconds (told apart by size: from 1e11 up it is milliseconds), an ISO date or date-time (read in the local zone when it gives none), or a duration such as 90m or 2h30m, shown with the date that far from now. Without a value it is now; "-" reads the value on stdin.
1255
+ Exits 0 when it converted the value, 1 when it is none of those, 2 on a usage error.`;
1256
+ var TS_OPTIONS = {
1257
+ zone: ZONE_OPTION,
1258
+ json: jsonOption("{kind, ms, seconds, local, utc, relative} or, for a duration, {kind, ms, seconds, human, fromNow}")
1259
+ };
1260
+ async function ts(args) {
1261
+ const { values, positionals } = parse(args, TS_USAGE, TS_OPTIONS, {
1262
+ positionals: ["[value]"],
1263
+ replaces: "date -d @<seconds> and date -u, and doing the milliseconds division by hand",
1264
+ examples: ["dev ts 1700000000", ["dev ts 2h30m", "the date 2h30m from now"], ["dev ts 2024-05-06T08:09:10Z --zone Europe/Paris", "that instant in Paris"]]
1265
+ });
1266
+ const zone = zoneOf(values.zone);
1267
+ const value = positionals[0] === "-" ? await textInput(undefined, "the value") : positionals[0];
1268
+ const converted = reading(() => convert(value, { timeZone: zone }));
1269
+ if (values.json === true) {
1270
+ printJson(converted);
1271
+ return 0;
1272
+ }
1273
+ if (converted.kind === "duration") {
1274
+ printRows([["human", converted.human], ["seconds", String(converted.seconds)], ["ms", String(converted.ms)], ["from now", `${converted.fromNow.local} ${converted.fromNow.utc}`]]);
1275
+ return 0;
1276
+ }
1277
+ printRows([["local", converted.local], ["utc", converted.utc], ["seconds", String(converted.seconds)], ["ms", String(converted.ms)], ["relative", converted.relative]]);
1278
+ return 0;
1279
+ }
1280
+ var UUID_USAGE = `dev uuid [-n <count>] [--v7]: random UUIDs, version 4 or, with --v7, version 7 (time-ordered)
1281
+
1282
+ Exits 0 when it printed them, 2 on a usage error.`;
1283
+ var COUNT_OPTION = { type: "string", short: "n", description: "how many to print (default 1)" };
1284
+ function uuid(args) {
1285
+ const { values } = parse(args, UUID_USAGE, { n: COUNT_OPTION, v7: { type: "boolean", description: "a version 7 UUID, which sorts by creation time" }, json: jsonOption('["uuid"]') }, {
1286
+ positionals: [],
1287
+ replaces: 'uuidgen and python -c "import uuid"',
1288
+ examples: ["dev uuid", ["dev uuid -n 5 --v7", "five time-ordered UUIDs"]]
1289
+ });
1290
+ const ids = Array.from({ length: wholeNumber(values.n, "n", 1) }, () => values.v7 === true ? uuidV7() : uuidV4());
1291
+ printIds(ids, values.json === true);
1292
+ return 0;
1293
+ }
1294
+ var ULID_USAGE = `dev ulid [-n <count>]: random ULIDs, 26 sortable characters of time and randomness
1295
+
1296
+ Exits 0 when it printed them, 2 on a usage error.`;
1297
+ function ulidCommand(args) {
1298
+ const { values } = parse(args, ULID_USAGE, { n: COUNT_OPTION, json: jsonOption('["ulid"]') }, {
1299
+ positionals: [],
1300
+ replaces: "installing a ulid package to mint one",
1301
+ examples: ["dev ulid", ["dev ulid -n 3", "three ULIDs"]]
1302
+ });
1303
+ printIds(Array.from({ length: wholeNumber(values.n, "n", 1) }, () => ulid()), values.json === true);
1304
+ return 0;
1305
+ }
1306
+ function printIds(ids, json) {
1307
+ if (json)
1308
+ printJson(ids);
1309
+ else
1310
+ console.log(ids.join(`
1311
+ `));
1312
+ }
1313
+ var B64_USAGE = `dev b64 [-d] [--url] [text]: base64 of the text, or with -d the text behind a base64 one
1314
+
1315
+ The text is the argument or what is piped on stdin, taken as is (a piped trailing newline is encoded, as base64 does). With --url the output is URL-safe and unpadded. Decoding takes either alphabet, padded or not, and writes the raw bytes.
1316
+ Exits 0 when it printed the result, 1 when -d is given text that is not base64, 2 on a usage error.`;
1317
+ var B64_OPTIONS = {
1318
+ decode: { type: "boolean", short: "d", description: "decode instead of encode" },
1319
+ url: { type: "boolean", description: "URL-safe alphabet without padding, when encoding" },
1320
+ json: jsonOption("{input, output} as text")
1321
+ };
1322
+ async function b64(args) {
1323
+ const { values, positionals } = parse(args, B64_USAGE, B64_OPTIONS, {
1324
+ positionals: ["[text]"],
1325
+ replaces: "base64 and base64 -d, which leave the URL-safe alphabet to tr",
1326
+ examples: ["dev b64 hello", ["echo aGVsbG8 | dev b64 -d", "decoded, padding optional"]]
1327
+ });
1328
+ const input = await bytesInput(positionals[0], "the text");
1329
+ if (values.decode === true) {
1330
+ const output = reading(() => b64Decode(new TextDecoder().decode(input)));
1331
+ if (values.json === true)
1332
+ printJson({ input: new TextDecoder().decode(input), output: new TextDecoder().decode(output) });
1333
+ else
1334
+ await Bun.write(Bun.stdout, output);
1335
+ return 0;
1336
+ }
1337
+ const output = b64Encode(input, values.url === true);
1338
+ if (values.json === true)
1339
+ printJson({ input: new TextDecoder().decode(input), output });
1340
+ else
1341
+ console.log(output);
1342
+ return 0;
1343
+ }
1344
+ var URL_USAGE = `dev url [url]: the parts of a URL and its query decoded, one per line
1345
+
1346
+ The URL is the argument or what is piped on stdin, and has to include its scheme.
1347
+ Exits 0 when it printed the parts, 1 when the text is not a URL, 2 on a usage error.`;
1348
+ async function url(args) {
1349
+ const { values, positionals } = parse(args, URL_USAGE, { json: jsonOption("{href, protocol, username, password, host, hostname, port, pathname, query: [{key, value}], hash}") }, {
1350
+ positionals: ["[url]"],
1351
+ replaces: "reading a long query string by eye or decoding it with python urllib",
1352
+ examples: ['dev url "https://example.com:8443/a%20b?q=x%26y&page=2#top"', ['dev url "https://example.com/?a=1" --json', "for a script"]]
1353
+ });
1354
+ const input = await textInput(positionals[0], "the URL");
1355
+ const parts = reading(() => urlParts(input));
1356
+ if (values.json === true) {
1357
+ printJson(parts);
1358
+ return 0;
1359
+ }
1360
+ const { query, ...fields } = parts;
1361
+ const shown = Object.entries(fields).filter(([, value]) => value !== "");
1362
+ printRows([...shown, ...query.map(({ key, value }) => [`?${key}`, value])]);
1363
+ return 0;
1364
+ }
1365
+ var HASH_USAGE = `dev hash <sha256|sha1|md5|sha512> [file]: the hex digest of a file, or of what is piped on stdin
1366
+
1367
+ Exits 0 when it printed the digest, 1 when the file does not exist, 2 on a usage error.`;
1368
+ async function hash(args) {
1369
+ const { values, positionals } = parse(args, HASH_USAGE, { json: jsonOption("{algorithm, hash, bytes}") }, {
1370
+ positionals: ["<algorithm>", "[file]"],
1371
+ candidates: { "<algorithm>": () => [...ALGORITHMS] },
1372
+ replaces: "sha256sum, sha1sum and md5sum, which print the file name beside the digest",
1373
+ examples: ["dev hash sha256 package.json", ["echo -n abc | dev hash sha1", "the digest of piped text"]]
1374
+ });
1375
+ const algorithm = oneOf(positionals[0] ?? "", "<algorithm>", ALGORITHMS);
1376
+ const file = positionals[1];
1377
+ let bytes;
1378
+ if (file === undefined) {
1379
+ bytes = await bytesInput(undefined, "a file");
1380
+ } else {
1381
+ const source = Bun.file(file);
1382
+ if (!await source.exists())
1383
+ return fail(`no file ${file}`, 1);
1384
+ bytes = new Uint8Array(await source.arrayBuffer());
1385
+ }
1386
+ const digest = hashHex(algorithm, bytes);
1387
+ if (values.json === true)
1388
+ printJson({ algorithm, hash: digest, bytes: bytes.length });
1389
+ else
1390
+ console.log(digest);
1391
+ return 0;
1392
+ }
1393
+ if (import.meta.main) {
1394
+ process7.exitCode = await runCli({
1395
+ name: "dev",
1396
+ version,
1397
+ about: "small developer utilities: passwords and bcrypt hashes, JWTs, timestamps, UUIDs, base64, URLs and file hashes",
1398
+ replaces: "openssl rand, htpasswd, jwt.io, date -d, uuidgen, base64, sha256sum and one-off scripts for each",
1399
+ examples: ["dev password", ["dev jwt <token>", "header, payload and expiry"], ["dev ts 1700000000", "an epoch as dates"]],
1400
+ commands: {
1401
+ password: { summary: "a random password, copied to the clipboard, or its bcrypt hash", run: password },
1402
+ jwt: { summary: "decode a JWT without verifying it, expiry shown as dates", run: jwt },
1403
+ ts: { summary: "convert epochs, ISO dates and durations, local and UTC", run: ts },
1404
+ uuid: { summary: "random UUIDs, v4 or v7", run: async (args) => Promise.resolve(uuid(args)) },
1405
+ ulid: { summary: "random ULIDs", run: async (args) => Promise.resolve(ulidCommand(args)) },
1406
+ b64: { summary: "base64 encode or decode, standard or URL-safe", run: b64 },
1407
+ url: { summary: "the parts of a URL and its decoded query", run: url },
1408
+ hash: { summary: "sha256, sha1, md5 or sha512 of a file or stdin", run: hash }
1409
+ }
1410
+ });
1411
+ }
1412
+ export {
1413
+ b64,
1414
+ hash,
1415
+ jwt,
1416
+ password,
1417
+ ts,
1418
+ ulidCommand,
1419
+ url,
1420
+ uuid
1421
+ };