@kaynooo/cli-env 0.0.0-stage → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/redact.js ADDED
@@ -0,0 +1,1576 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/redact.ts
5
+ import process10 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process6 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/format.ts
12
+ import process3 from "process";
13
+
14
+ // ../kit/src/style.ts
15
+ import process2 from "process";
16
+
17
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
+ function x(s) {
19
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
+ if (!/^[a-f0-9]+$/.test(r))
21
+ return [0, 0, 0];
22
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
23
+ if (t === 3 || t === 4) {
24
+ 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;
25
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
26
+ }
27
+ if (t !== 6 && t !== 8)
28
+ throw Error(`Invalid hex color length: ${t}`);
29
+ 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;
30
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
31
+ throw Error(`Invalid hex color value: ${s}`);
32
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
33
+ }
34
+ function A(s) {
35
+ let [r, t, n, a] = s;
36
+ if (a)
37
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
38
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
39
+ }
40
+ function R(s, r, t) {
41
+ s = (s % 360 + 360) % 360, t /= 100;
42
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
43
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
44
+ return Math.round(255 * y);
45
+ };
46
+ return [a(0), a(8), a(4)];
47
+ }
48
+ function k(s) {
49
+ let [r, t, n] = s;
50
+ r /= 255, t /= 255, n /= 255;
51
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
52
+ if (a !== b) {
53
+ let u = a - b;
54
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
55
+ o = (t - n) / u + (t < n ? 6 : 0);
56
+ else if (a === t)
57
+ o = (n - r) / u + 2;
58
+ else
59
+ o = (r - t) / u + 4;
60
+ o /= 6;
61
+ }
62
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
63
+ }
64
+ function H(s, r, t) {
65
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
66
+ let n = (a) => {
67
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
68
+ return Math.round(255 * o);
69
+ };
70
+ return [n(5), n(3), n(1)];
71
+ }
72
+ function f(s) {
73
+ let [r, t, n] = s;
74
+ r /= 255, t /= 255, n /= 255;
75
+ 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;
76
+ if (o !== 0) {
77
+ if (a === r)
78
+ y = (t - n) / o + (t < n ? 6 : 0);
79
+ else if (a === t)
80
+ y = (n - r) / o + 2;
81
+ else
82
+ y = (r - t) / o + 4;
83
+ y /= 6;
84
+ }
85
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
86
+ }
87
+ function O(s) {
88
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
89
+ if (a === 1)
90
+ return [0, 0, 0, 100];
91
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
92
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
93
+ }
94
+ function v(s, r, t, n) {
95
+ 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))];
96
+ }
97
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
98
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
99
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
100
+ function T(s) {
101
+ 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);
102
+ 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)];
103
+ }
104
+ function M(s, r, t) {
105
+ 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)));
106
+ return [u(o), u(y), u(c)];
107
+ }
108
+ function d(s) {
109
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
110
+ return [i(r, 4), i(a, 4), i(b, 2)];
111
+ }
112
+ function C(s, r, t) {
113
+ let n = t * Math.PI / 180;
114
+ return M(s, r * Math.cos(n), r * Math.sin(n));
115
+ }
116
+ function l(s) {
117
+ let r = s / 255;
118
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
119
+ }
120
+
121
+ class e {
122
+ r;
123
+ g;
124
+ b;
125
+ a;
126
+ constructor(s, r, t, n = 1) {
127
+ this.r = s, this.g = r, this.b = t, this.a = n;
128
+ }
129
+ static from(s, r) {
130
+ if (s === "hex") {
131
+ let [t, n, a, b] = x(r);
132
+ return new e(t, n, a, b);
133
+ }
134
+ if (s === "rgb") {
135
+ if (Array.isArray(r)) {
136
+ let [o, y, c, u] = r;
137
+ return new e(o, y, c, u);
138
+ }
139
+ let { r: t, g: n, b: a, a: b } = r;
140
+ return new e(t, n, a, b);
141
+ }
142
+ if (s === "hsl") {
143
+ let t, n, a, b;
144
+ if (Array.isArray(r))
145
+ [t, n, a, b] = r;
146
+ else
147
+ ({ h: t, s: n, l: a, a: b } = r);
148
+ let [o, y, c] = R(t, n, a);
149
+ return new e(o, y, c, b);
150
+ }
151
+ if (s === "hsv") {
152
+ let t, n, a, b;
153
+ if (Array.isArray(r))
154
+ [t, n, a, b] = r;
155
+ else
156
+ ({ h: t, s: n, v: a, a: b } = r);
157
+ let [o, y, c] = H(t, n, a);
158
+ return new e(o, y, c, b);
159
+ }
160
+ if (s === "cmyk") {
161
+ let t, n, a, b, o;
162
+ if (Array.isArray(r))
163
+ [t, n, a, b, o] = r;
164
+ else
165
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
166
+ let [y, c, u] = v(t, n, a, b);
167
+ return new e(y, c, u, o);
168
+ }
169
+ if (s === "oklch") {
170
+ let t, n, a, b;
171
+ if (Array.isArray(r))
172
+ [t, n, a, b] = r;
173
+ else
174
+ ({ l: t, c: n, h: a, a: b } = r);
175
+ let [o, y, c] = C(t, n, a);
176
+ return new e(o, y, c, b);
177
+ }
178
+ if (s === "oklab") {
179
+ let t, n, a, b;
180
+ if (Array.isArray(r))
181
+ [t, n, a, b] = r;
182
+ else
183
+ ({ l: t, a: n, b: a, alpha: b } = r);
184
+ let [o, y, c] = M(t, n, a);
185
+ return new e(o, y, c, b);
186
+ }
187
+ throw Error("Invalid input");
188
+ }
189
+ to(s) {
190
+ switch (s) {
191
+ case "rgb":
192
+ return [this.r, this.g, this.b];
193
+ case "rgba":
194
+ return [this.r, this.g, this.b, this.a];
195
+ case "hex":
196
+ return A([this.r, this.g, this.b]);
197
+ case "hexa":
198
+ return A([this.r, this.g, this.b, this.a]);
199
+ case "hsl":
200
+ return k([this.r, this.g, this.b]);
201
+ case "hsla":
202
+ return [...k([this.r, this.g, this.b]), this.a];
203
+ case "hsv":
204
+ return f([this.r, this.g, this.b]);
205
+ case "hsva":
206
+ return [...f([this.r, this.g, this.b]), this.a];
207
+ case "cmyk":
208
+ return O([this.r, this.g, this.b]);
209
+ case "cmyka":
210
+ return [...O([this.r, this.g, this.b]), this.a];
211
+ case "oklch":
212
+ return d([this.r, this.g, this.b]);
213
+ case "oklcha":
214
+ return [...d([this.r, this.g, this.b]), this.a];
215
+ case "oklab":
216
+ return T([this.r, this.g, this.b]);
217
+ case "oklaba":
218
+ return [...T([this.r, this.g, this.b]), this.a];
219
+ default:
220
+ return [this.r, this.g, this.b];
221
+ }
222
+ }
223
+ getLuminance() {
224
+ let s = l(this.r), r = l(this.g), t = l(this.b);
225
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
226
+ }
227
+ contrastRatio(s) {
228
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
229
+ return (n + 0.05) / (a + 0.05);
230
+ }
231
+ bestContrastForeground() {
232
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
233
+ return t >= n ? s : r;
234
+ }
235
+ }
236
+
237
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
+ var r = 39;
239
+ var o = 49;
240
+ var f2 = "\x1B[";
241
+ 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") => {
242
+ let [a, l, s] = e.from("hex", i).to("rgb");
243
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
244
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
245
+ var b = new Set(["", "1", "2", "3", "true"]);
246
+ function h(i, n = globalThis.process?.env ?? {}) {
247
+ if (n.FORCE_COLOR !== undefined)
248
+ return b.has(n.FORCE_COLOR);
249
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
250
+ return false;
251
+ return i?.isTTY === true;
252
+ }
253
+ function d2(i, n, a) {
254
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
255
+ return n;
256
+ let l = "", s = "";
257
+ for (let g = 0, y = i.length;g < y; g++) {
258
+ let [c, p] = i[g];
259
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
260
+ }
261
+ return l + n + s;
262
+ }
263
+ function u(i, n = []) {
264
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
265
+ let g = C2[s];
266
+ if (Array.isArray(g))
267
+ return u(i, [...n, g]);
268
+ if (typeof g === "function")
269
+ return (...y) => u(i, [...n, g(...y)]);
270
+ throw Error(`Unknown style: ${String(s)}`);
271
+ } });
272
+ }
273
+ function le(i = {}) {
274
+ return u(i);
275
+ }
276
+ var t = le();
277
+
278
+ // ../kit/src/style.ts
279
+ var MARKS = {
280
+ ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
281
+ warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
282
+ problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
283
+ note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
284
+ };
285
+ function takesControlCodes(stream, env = process2.env) {
286
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
287
+ }
288
+ function paint(stream, env = process2.env) {
289
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
290
+ }
291
+ function marked(mark, text, stream, detail, env = process2.env) {
292
+ const colors = paint(stream, env);
293
+ const { symbol, word, paint: tint } = MARKS[mark];
294
+ const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
295
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
296
+ }
297
+ function ok(text, detail) {
298
+ console.log(marked("ok", text, process2.stdout, detail));
299
+ }
300
+ var STATUSES = {
301
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
302
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
303
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
304
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
305
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
306
+ };
307
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
308
+
309
+ // ../kit/src/format.ts
310
+ function upTo(text, separator) {
311
+ const end = text.indexOf(separator);
312
+ return end === -1 ? text : text.slice(0, end);
313
+ }
314
+ function truncate(text, width) {
315
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
316
+ }
317
+ var LINE_BREAKS = /\s*\n\s*/g;
318
+ var ESCAPE = String.fromCharCode(27);
319
+ function textWidth(text) {
320
+ return Bun.stringWidth(text);
321
+ }
322
+ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
323
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
324
+ const widths = [];
325
+ for (const row of cells) {
326
+ for (const [index, cell] of row.entries())
327
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
328
+ }
329
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
330
+ const colors = paint(process3.stdout);
331
+ const lines = shown.map((row) => row.map((cell, index) => {
332
+ const width = widths[index] ?? 0;
333
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
334
+ if (align[index] === "right")
335
+ return `${gap}${cell}`;
336
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
337
+ }).join(" ").trimEnd());
338
+ return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
339
+ `);
340
+ }
341
+ function narrow(rows, widths, limit) {
342
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
343
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
344
+ const floor = 8;
345
+ while (used() > limit) {
346
+ let widest = -1;
347
+ for (const [index, width] of widths.entries()) {
348
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
349
+ widest = index;
350
+ }
351
+ if (widest === -1)
352
+ break;
353
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
354
+ }
355
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
356
+ }
357
+ function printJson(value) {
358
+ console.log(JSON.stringify(value, undefined, 2));
359
+ }
360
+
361
+ // ../kit/src/help.ts
362
+ import process4 from "process";
363
+ var OPTIONAL = /\[[^\]]+\]/g;
364
+ var USAGE_PREFIX = /^usage:\s*/i;
365
+ var FULL_STOP = /\.$/;
366
+ function usageLine(usage, colors = paint(process4.stdout)) {
367
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
368
+ }
369
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces } = {}) {
370
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
371
+ `);
372
+ }
373
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
374
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
375
+ }
376
+ function wantsHelpJson(env = process4.env) {
377
+ return env.KIT_HELP === "json";
378
+ }
379
+ function description(usage, { examples = [], replaces } = {}) {
380
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
381
+ `);
382
+ const first = lines[0];
383
+ const colon = first.indexOf(": ");
384
+ const prose = lines[lines.indexOf("") + 1] ?? "";
385
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
386
+ return {
387
+ synopsis: colon === -1 ? first : first.slice(0, colon),
388
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
389
+ ...replaces === undefined ? {} : { replaces },
390
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
391
+ };
392
+ }
393
+ function exampleRows(examples, colors = paint(process4.stdout)) {
394
+ if (examples.length === 0)
395
+ return [];
396
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
397
+ }
398
+ function optionRows(options, colors = paint(process4.stdout)) {
399
+ const rows = Object.entries(options).map(([name, option]) => {
400
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
401
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
402
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
403
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
404
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
405
+ });
406
+ const width = Math.max(0, ...rows.map((row) => row.width));
407
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
408
+ }
409
+
410
+ // ../kit/src/text.ts
411
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
412
+ function distance(a, b) {
413
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
414
+ for (const [i, left] of [...a].entries()) {
415
+ const current = [i + 1];
416
+ for (const [j, right] of [...b].entries())
417
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
418
+ previous = current;
419
+ }
420
+ return previous[b.length] ?? 0;
421
+ }
422
+ function closest(name, names) {
423
+ const started = names.find((known) => known.startsWith(name));
424
+ if (started !== undefined)
425
+ return started;
426
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
427
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
428
+ }
429
+ // ../kit/src/input.ts
430
+ import process5 from "process";
431
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
432
+ if (path === "-") {
433
+ if (process5.stdin.isTTY)
434
+ fail(noStdin);
435
+ return Bun.stdin.text();
436
+ }
437
+ const file = Bun.file(path);
438
+ if (!await file.exists())
439
+ fail(`no file ${path}`);
440
+ return file.text();
441
+ }
442
+
443
+ // ../kit/src/args.ts
444
+ var DASHES = /^-+/;
445
+ function jsonOption(holds) {
446
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
447
+ }
448
+
449
+ class Exit extends Error {
450
+ code;
451
+ hint;
452
+ constructor(message, code, hint) {
453
+ super(message);
454
+ this.code = code;
455
+ this.hint = hint;
456
+ }
457
+ }
458
+ function fail(message, code = 2, hint) {
459
+ throw new Exit(message, code, hint);
460
+ }
461
+
462
+ class UsageError extends Exit {
463
+ constructor(message, hint) {
464
+ super(message, 2, hint);
465
+ }
466
+ }
467
+ function badUsage(message) {
468
+ throw new UsageError(message);
469
+ }
470
+
471
+ class HelpShown extends Exit {
472
+ constructor() {
473
+ super("help shown", 0);
474
+ }
475
+ }
476
+
477
+ class Completing {
478
+ options;
479
+ positionals;
480
+ candidates;
481
+ constructor(options, positionals = [], candidates = {}) {
482
+ this.options = options;
483
+ this.positionals = positionals;
484
+ this.candidates = candidates;
485
+ }
486
+ }
487
+ var completion = { active: false };
488
+ var OUTPUT_OPTIONS = {
489
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
490
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
491
+ };
492
+ function applyOutput(color, plain, env = process6.env) {
493
+ const when = plain === true ? "never" : color ?? "auto";
494
+ if (when === "auto")
495
+ return;
496
+ if (when !== "always" && when !== "never")
497
+ badUsage(`--color takes auto, always or never, not ${when}`);
498
+ if (when === "always") {
499
+ env.FORCE_COLOR = "1";
500
+ delete env.NO_COLOR;
501
+ } else {
502
+ env.NO_COLOR = "1";
503
+ delete env.FORCE_COLOR;
504
+ }
505
+ }
506
+ function parse(args, usage, options, settings = {}) {
507
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
508
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
509
+ const listing = listed(all, settings.allowNegative === true);
510
+ if (completion.active)
511
+ throw new Completing(listing, settings.positionals, settings.candidates);
512
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
513
+ let parsed;
514
+ try {
515
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
516
+ } catch (error) {
517
+ const message = parseError(error);
518
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
519
+ }
520
+ const values = parsed.values;
521
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
522
+ if (values.help === true) {
523
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
524
+ throw new HelpShown;
525
+ }
526
+ checkChoices(parsed.values, all);
527
+ checkConflicts(parsed.values, all);
528
+ if (settings.positionals !== undefined)
529
+ checkPositionals(parsed.positionals, settings.positionals);
530
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
531
+ }
532
+ function splitRest(args, passes) {
533
+ const separator = passes ? args.indexOf("--") : -1;
534
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
535
+ }
536
+ function splitTrailing(args, options, count) {
537
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
538
+ let seen = 0;
539
+ if (count === 0)
540
+ return { own: args, rest: undefined };
541
+ for (let at = 0;at < args.length; at++) {
542
+ const word = args[at];
543
+ if (word === "--")
544
+ break;
545
+ if (word.startsWith("-")) {
546
+ if (takesValue(word))
547
+ at++;
548
+ continue;
549
+ }
550
+ seen++;
551
+ if (seen === count)
552
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
553
+ }
554
+ return { own: args, rest: undefined };
555
+ }
556
+ function listed(options, allowNegative) {
557
+ if (!allowNegative)
558
+ return options;
559
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
560
+ if (option.type !== "boolean" || option.negative === undefined)
561
+ return [[name, option]];
562
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
563
+ }));
564
+ }
565
+ function withBare(args, options) {
566
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
567
+ if (bare.size === 0)
568
+ return args;
569
+ const separator = args.indexOf("--");
570
+ const own = separator === -1 ? args : args.slice(0, separator);
571
+ return [...own.flatMap((arg, index) => {
572
+ const optional = bare.get(arg);
573
+ const next = own[index + 1];
574
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
575
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
576
+ }), ...separator === -1 ? [] : args.slice(separator)];
577
+ }
578
+ function checkConflicts(values, options) {
579
+ const given = (name) => values[name] !== undefined && values[name] !== false;
580
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
581
+ const other = given(name) ? conflicts.find(given) : undefined;
582
+ if (other !== undefined)
583
+ badUsage(`--${name} cannot be used with --${other}`);
584
+ }
585
+ }
586
+ function checkChoices(values, options) {
587
+ for (const [name, option] of Object.entries(options)) {
588
+ if (option.choices === undefined)
589
+ continue;
590
+ const given = values[name];
591
+ for (const value of Array.isArray(given) ? given : [given]) {
592
+ if (typeof value === "string")
593
+ oneOf(value, name, option.choices);
594
+ }
595
+ }
596
+ }
597
+ function oneOf(value, name, choices) {
598
+ if (!choices.includes(value))
599
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
600
+ return value;
601
+ }
602
+ function checkPositionals(given, names) {
603
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
604
+ const required = names.filter((name) => !name.startsWith("[")).length;
605
+ if (given.length < required)
606
+ badUsage(`missing ${names[given.length]}`);
607
+ if (!variadic && given.length > names.length)
608
+ badUsage(`unexpected argument ${given[names.length]}`);
609
+ }
610
+ function joinDashValues(args, options) {
611
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
612
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
613
+ const joined = [];
614
+ for (let i = 0;i < args.length; i++) {
615
+ const arg = args[i] ?? "";
616
+ if (arg === "--")
617
+ return [...joined, ...args.slice(i)];
618
+ const name = longOf.get(arg);
619
+ const next = args[i + 1];
620
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
621
+ joined.push(`--${name}=${next}`);
622
+ i++;
623
+ } else {
624
+ joined.push(arg);
625
+ }
626
+ }
627
+ return joined;
628
+ }
629
+ function parseError(error) {
630
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
631
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
632
+ }
633
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
634
+ function nearestOption(message, options, allowNegative) {
635
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
636
+ if (typed === undefined)
637
+ return;
638
+ const word = typed.replace(DASHES, "");
639
+ if (word.length < 2 && !typed.startsWith("--"))
640
+ return;
641
+ const known = Object.entries(options).flatMap(([name, option]) => [
642
+ ...option.short === undefined ? [] : [`-${option.short}`],
643
+ `--${name}`,
644
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
645
+ ]);
646
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
647
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
648
+ }
649
+ // ../kit/src/progress.ts
650
+ var ESC = String.fromCharCode(27);
651
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
652
+ var RESET_STYLE = `${ESC}[0m`;
653
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
654
+ // ../kit/src/cli.ts
655
+ import process8 from "process";
656
+
657
+ // ../kit/src/usage.ts
658
+ import { appendFileSync, mkdirSync } from "fs";
659
+ import { homedir } from "os";
660
+ import { dirname, isAbsolute, join } from "path";
661
+ import process7 from "process";
662
+
663
+ // ../kit/src/logs.ts
664
+ var DAY_MS = 24 * 60 * 60 * 1000;
665
+ var CLI_FOLDER = "kaynooo-cli";
666
+
667
+ // ../kit/src/usage.ts
668
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
669
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
670
+ var LONGEST_NAME = 40;
671
+ var usageError;
672
+ function noteUsageError(message) {
673
+ usageError = message;
674
+ }
675
+ function stateHome(env = process7.env) {
676
+ const dir = env.XDG_STATE_HOME;
677
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
678
+ }
679
+ function usagePath(env = process7.env) {
680
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
681
+ }
682
+ function usageRecorded(env = process7.env) {
683
+ const off = env.KAYNOOO_CLI_NO_USAGE;
684
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
685
+ }
686
+ function flagNames(argv) {
687
+ const end = argv.indexOf("--");
688
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
689
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
690
+ }
691
+ function usageEntry(bin, command, argv, code, now = new Date) {
692
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
693
+ usageError = undefined;
694
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
695
+ }
696
+ function recordUsage(entry, env = process7.env) {
697
+ if (!usageRecorded(env))
698
+ return;
699
+ try {
700
+ const path = usagePath(env);
701
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
702
+ appendFileSync(path, `${JSON.stringify(entry)}
703
+ `, { mode: 384 });
704
+ } catch {}
705
+ }
706
+
707
+ // ../kit/src/cli.ts
708
+ var LEVEL_OPTIONS = {
709
+ ...OUTPUT_OPTIONS,
710
+ help: { type: "boolean", short: "h", description: "show this help" }
711
+ };
712
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
713
+ async function commandRows(all, colors) {
714
+ const commands = shown(all);
715
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
716
+ const groups = new Map([["Commands:", []]]);
717
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
718
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
719
+ const heading = group === undefined ? "Commands:" : `${group}:`;
720
+ const rows = groups.get(heading) ?? [];
721
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
722
+ groups.set(heading, rows);
723
+ }
724
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
725
+ }
726
+ function shown(commands) {
727
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
728
+ }
729
+ function takeOutputFlags(argv) {
730
+ let index = 0;
731
+ for (;index < argv.length; index++) {
732
+ const word = argv[index];
733
+ if (word === "--plain")
734
+ applyOutput(undefined, true);
735
+ else if (word.startsWith("--color="))
736
+ applyOutput(word.slice("--color=".length), undefined);
737
+ else if (word === "--color" && argv[index + 1] !== undefined)
738
+ applyOutput(argv[++index], undefined);
739
+ else
740
+ break;
741
+ }
742
+ return argv.slice(index);
743
+ }
744
+ async function resolveSummary(summary) {
745
+ return typeof summary === "string" ? summary : summary();
746
+ }
747
+ function scopeOf(commands, extra, aliases) {
748
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
749
+ }
750
+ async function expand(scope, words) {
751
+ if (scope.lazy.length === 0)
752
+ return scope;
753
+ const commands = { ...scope.commands };
754
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
755
+ for (const [name, command] of Object.entries(added))
756
+ commands[name] ??= command;
757
+ }
758
+ return { ...scope, commands, lazy: [] };
759
+ }
760
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
761
+ const colors = paint(stream);
762
+ const prefix = path.join(" ");
763
+ const summary = await resolveSummary(lazySummary);
764
+ if (wantsHelpJson())
765
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
766
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
767
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
768
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
769
+ return [
770
+ header(colors, summary),
771
+ "",
772
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
773
+ ...replacesRows(replaces, colors),
774
+ "",
775
+ ...await commandRows(commands, colors),
776
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
777
+ "",
778
+ colors.bold("Options:"),
779
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
780
+ ...exampleRows(examples ?? [], colors),
781
+ "",
782
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
783
+ ].join(`
784
+ `);
785
+ }
786
+ function printError(prefix, message, hint, cause) {
787
+ const colors = paint(process8.stderr);
788
+ const styled = takesControlCodes(process8.stderr);
789
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
790
+ const under = (label, text, tint) => text === undefined ? "" : `
791
+ ${styled ? tint(label) : `${label}:`} ${text}`;
792
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
793
+ }
794
+ function printJsonError(message, hint, cause) {
795
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
796
+ }
797
+ function wantsJson(argv) {
798
+ const end = argv.indexOf("--");
799
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
800
+ }
801
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
802
+ if (error instanceof HelpShown)
803
+ return 0;
804
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
805
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
806
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
807
+ if (error instanceof UsageError)
808
+ noteUsageError(error.message);
809
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
810
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
811
+ return error instanceof Exit ? error.code : 1;
812
+ }
813
+ async function dispatch(level, typed, { version, redact }) {
814
+ const prefix = level.path.join(" ");
815
+ let argv;
816
+ try {
817
+ argv = takeOutputFlags(typed);
818
+ } catch (error) {
819
+ return reportThrown(prefix, error);
820
+ }
821
+ const [name, ...args] = argv;
822
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
823
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
824
+ try {
825
+ return await fallback.run([]);
826
+ } catch (error) {
827
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
828
+ }
829
+ }
830
+ if (name === undefined && level.path.length > 1) {
831
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
832
+ return 2;
833
+ }
834
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
835
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
836
+ return 0;
837
+ }
838
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
839
+ console.log(version);
840
+ return 0;
841
+ }
842
+ let command = level.commands[level.aliases?.[name] ?? name];
843
+ let rest = args;
844
+ let ran = name;
845
+ if (command === undefined && level.lazy.length > 0) {
846
+ level = await expand(level, [...level.path.slice(1), ...argv]);
847
+ command = level.commands[level.aliases?.[name] ?? name];
848
+ }
849
+ if (command === undefined && level.defaultCommand !== undefined) {
850
+ command = level.commands[level.defaultCommand];
851
+ rest = argv;
852
+ ran = level.defaultCommand;
853
+ }
854
+ if (command === undefined) {
855
+ const meant = closest(name, Object.keys(shown(level.commands)));
856
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
857
+ return 2;
858
+ }
859
+ if ("commands" in command) {
860
+ const { summary } = command;
861
+ return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
862
+ }
863
+ try {
864
+ return await command.run(rest);
865
+ } catch (error) {
866
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
867
+ }
868
+ }
869
+ var COMPLETE = "__complete";
870
+ var FILES = "__files__";
871
+ async function completingOf(run) {
872
+ completion.active = true;
873
+ try {
874
+ await run([]);
875
+ } catch (error) {
876
+ if (error instanceof Completing)
877
+ return error;
878
+ } finally {
879
+ completion.active = false;
880
+ }
881
+ return new Completing({});
882
+ }
883
+ async function optionsOf(run) {
884
+ return (await completingOf(run)).options;
885
+ }
886
+ function candidateLine(candidate) {
887
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
888
+ }
889
+ function positionalBeingTyped(before, { options, positionals }) {
890
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
891
+ let index = 0;
892
+ let at = 0;
893
+ while (at < before.length) {
894
+ const word = before[at];
895
+ if (word === "--") {
896
+ index += before.length - at - 1;
897
+ break;
898
+ }
899
+ if (!word.startsWith("-"))
900
+ index++;
901
+ else if (takesValue(word))
902
+ at++;
903
+ at++;
904
+ }
905
+ const last = positionals.at(-1);
906
+ if (index < positionals.length)
907
+ return positionals[index];
908
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
909
+ }
910
+ async function leafCandidates(run, words) {
911
+ const completing = await completingOf(run);
912
+ if ((words.at(-1) ?? "").startsWith("-"))
913
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
914
+ const flag = words.at(-2);
915
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
916
+ if (option?.type === "string") {
917
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
918
+ return values === undefined ? [FILES] : values.map(candidateLine);
919
+ }
920
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
921
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
922
+ return values === undefined ? [FILES] : values.map(candidateLine);
923
+ }
924
+ async function candidates(scope, defaultCommand, words, before = []) {
925
+ const [word = "", ...rest] = words;
926
+ const listing = rest.length === 0 && !word.startsWith("-");
927
+ let { commands, aliases } = scope;
928
+ let command = commands[aliases?.[word] ?? word];
929
+ if (listing || command === undefined) {
930
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
931
+ command = commands[aliases?.[word] ?? word];
932
+ }
933
+ if (listing) {
934
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
935
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
936
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
937
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
938
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
939
+ }
940
+ if (command === undefined) {
941
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
942
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
943
+ }
944
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
945
+ }
946
+ async function printCandidates(found) {
947
+ for (const line of await found)
948
+ console.log(line);
949
+ return 0;
950
+ }
951
+ async function runCli(cli, argv = process8.argv.slice(2)) {
952
+ if (argv[0] === COMPLETE)
953
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
954
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
955
+ if (cli.usage !== false) {
956
+ try {
957
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
958
+ } catch {}
959
+ }
960
+ return code;
961
+ }
962
+ function commandPath(scope, argv) {
963
+ const path = [];
964
+ let level = scope;
965
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
966
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
967
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
968
+ if (command === undefined)
969
+ break;
970
+ path.push(word);
971
+ if (!("commands" in command))
972
+ break;
973
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
974
+ }
975
+ return path.length === 0 ? undefined : path.join(" ");
976
+ }
977
+ async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
978
+ if (argv[0] === COMPLETE)
979
+ return printCandidates(leafCandidates(run, argv.slice(1)));
980
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
981
+ console.log(version);
982
+ return 0;
983
+ }
984
+ let code;
985
+ try {
986
+ code = await run(argv);
987
+ } catch (error) {
988
+ code = reportThrown(name, error, redact, wantsJson(argv));
989
+ }
990
+ if (usage !== false)
991
+ recordUsage(usageEntry(name, undefined, argv, code));
992
+ return code;
993
+ }
994
+ // ../kit/src/secrets.ts
995
+ var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
996
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
997
+ var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
998
+ function isSecretName(name) {
999
+ return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
1000
+ }
1001
+ // ../kit/src/sessions.ts
1002
+ var {Glob } = globalThis.Bun;
1003
+ var SESSION_FILES = new Glob("*.json");
1004
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1005
+ // package.json
1006
+ var version = "0.8.1";
1007
+
1008
+ // src/files.ts
1009
+ import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
1010
+ import { basename, dirname as dirname2, join as join2 } from "path";
1011
+
1012
+ // src/dotenv.ts
1013
+ var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
1014
+ var EXPORTED = /^\s*export\s/;
1015
+ var INLINE_COMMENT = /\s+#.*$/;
1016
+ var CARRIAGE_RETURN = /\r$/;
1017
+ var ESCAPES = { n: `
1018
+ `, r: "\r", t: "\t", '"': '"', "\\": "\\", $: "$" };
1019
+ var LINE_BREAK = /[\r\n]/;
1020
+ var RAW_ONLY = /["\\]/;
1021
+ var NEEDS_QUOTES = /[\s#"'\\$`]/;
1022
+ function closingQuote(text, quote) {
1023
+ for (let index = 0;index < text.length; index++) {
1024
+ if (quote === '"' && text[index] === "\\")
1025
+ index++;
1026
+ else if (text[index] === quote)
1027
+ return index;
1028
+ }
1029
+ return -1;
1030
+ }
1031
+ function unescapeDollar(text) {
1032
+ return text.replaceAll("\\$", "$");
1033
+ }
1034
+ function unescapeDouble(text) {
1035
+ let out = "";
1036
+ for (let index = 0;index < text.length; index++) {
1037
+ const next = text[index + 1];
1038
+ if (text[index] === "\\" && next !== undefined && next in ESCAPES) {
1039
+ out += ESCAPES[next];
1040
+ index++;
1041
+ } else {
1042
+ out += text[index];
1043
+ }
1044
+ }
1045
+ return out;
1046
+ }
1047
+ function parseDotenv(text) {
1048
+ const physical = text.split(`
1049
+ `);
1050
+ const lines = [];
1051
+ for (let index = 0;index < physical.length; index++) {
1052
+ const line = physical[index] ?? "";
1053
+ const match = ASSIGNMENT.exec(line.replace(CARRIAGE_RETURN, ""));
1054
+ if (match === null) {
1055
+ lines.push({ raw: line });
1056
+ continue;
1057
+ }
1058
+ const [, key = "", rest = ""] = match;
1059
+ const start = rest.trimStart();
1060
+ const quote = start[0];
1061
+ if (quote !== '"' && quote !== "'" && quote !== "`") {
1062
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()) });
1063
+ continue;
1064
+ }
1065
+ let body = start.slice(1);
1066
+ let raw = line;
1067
+ let end = closingQuote(body, quote);
1068
+ while (end === -1 && index + 1 < physical.length) {
1069
+ index++;
1070
+ body += `
1071
+ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1072
+ raw += `
1073
+ ${physical[index] ?? ""}`;
1074
+ end = closingQuote(body, quote);
1075
+ }
1076
+ const inner = end === -1 ? body : body.slice(0, end);
1077
+ lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1078
+ }
1079
+ return { lines };
1080
+ }
1081
+ function serializeDotenv(file) {
1082
+ return file.lines.map((line) => line.raw).join(`
1083
+ `);
1084
+ }
1085
+ function entries(file) {
1086
+ const map = new Map;
1087
+ for (const line of file.lines) {
1088
+ if (line.key !== undefined)
1089
+ map.set(line.key, line.value ?? "");
1090
+ }
1091
+ return map;
1092
+ }
1093
+ function formatAssignment(key, value) {
1094
+ if (value === "" || !NEEDS_QUOTES.test(value))
1095
+ return `${key}=${value}`;
1096
+ if (RAW_ONLY.test(value) && !value.includes("'") && !LINE_BREAK.test(value))
1097
+ return `${key}='${value.replaceAll("$", "\\$")}'`;
1098
+ const escaped = value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("\r", "\\r").replaceAll(`
1099
+ `, "\\n").replaceAll("$", "\\$");
1100
+ return `${key}="${escaped}"`;
1101
+ }
1102
+ function setLine(file, key, value, raw) {
1103
+ const index = file.lines.findLastIndex((line) => line.key === key);
1104
+ const existing = file.lines[index];
1105
+ if (existing !== undefined) {
1106
+ const exported = EXPORTED.test(existing.raw) ? "export " : "";
1107
+ file.lines[index] = { raw: raw ?? `${exported}${formatAssignment(key, value)}`, key, value };
1108
+ return;
1109
+ }
1110
+ const line = { raw: raw ?? formatAssignment(key, value), key, value };
1111
+ const last = file.lines.at(-1);
1112
+ if (last === undefined)
1113
+ file.lines.push(line, { raw: "" });
1114
+ else if (last.raw === "")
1115
+ file.lines.splice(-1, 0, line);
1116
+ else
1117
+ file.lines.push(line, { raw: "" });
1118
+ }
1119
+ function removeKey(file, key) {
1120
+ const before = file.lines.length;
1121
+ file.lines = file.lines.filter((line) => line.key !== key);
1122
+ return before - file.lines.length;
1123
+ }
1124
+ function lastLine(file, key) {
1125
+ return file.lines.findLast((line) => line.key === key);
1126
+ }
1127
+
1128
+ // src/mask.ts
1129
+ var MIN_KNOWN_LENGTH = 4;
1130
+ var KEY_MASK = "*** private key redacted ***";
1131
+ var PLAIN_VALUE = /^(?:true|false|null|none|nil|yes|no|on|off|undefined)$/i;
1132
+ var PLACEHOLDER = /^[$%{<(*/]/;
1133
+ var URL_PASSWORD = /(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:([^\s'"]{1,1024})@/dgi;
1134
+ var PORT = /^\d{1,5}$/;
1135
+ var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
1136
+ function isPlaceholder(value) {
1137
+ return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
1138
+ }
1139
+ var TOKEN_FORMATS = [
1140
+ { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
1141
+ { kind: "GitLab token", pattern: /\bglpat-[\w-]{20,}/dg },
1142
+ { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
1143
+ { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
1144
+ { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
1145
+ { kind: "AWS access key", pattern: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/dg },
1146
+ { kind: "npm token", pattern: /\bnpm_[A-Za-z0-9]{30,}/dg },
1147
+ { kind: "Stripe key", pattern: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/dg },
1148
+ { kind: "Google API key", pattern: /\bAIza[\w-]{35}/dg },
1149
+ { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
1150
+ { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
1151
+ { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
1152
+ { kind: "password", pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
1153
+ { kind: "password", pattern: /(?<![\w-])["']?(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?["']?\s*[:=]\s*(["'])((?:\\.|(?!\1)[^\\\n]){4,})\1/dgi, skip: isPlaceholder }
1154
+ ];
1155
+ var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1156
+ var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1157
+ var PEM_BODY = /(?<=-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----)(?:(?!-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----)[\s\S])+/dg;
1158
+ var PEM_BEGIN_ALL = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/g;
1159
+ var URL_PARTS = /(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{0,31}:\/\/([^\s/?#'"<>`]*)([^\s?#'"<>`]*)(?:\?([^\s#'"<>`]*))?/dgi;
1160
+ var PATH_SEGMENT = /[^/]+/g;
1161
+ var SECRET_PARAM = /^(?:token|[a-z]+_token|key|api[_-]?key|access[_-]?key|secret|[a-z]+_secret|password|passwd|pwd|sig|signature|auth|authorization)$/i;
1162
+ var WEBHOOK_FORMATS = [
1163
+ ["Discord webhook", /(?:^|\.)discord(?:app)?\.com\/api\/(?:v\d+\/)?webhooks\/\d+\/([\w-]+)/di],
1164
+ ["Slack webhook", /^hooks\.slack\.com\/(?:services|workflows)\/(?:[\w-]+\/)*([\w-]+)/di],
1165
+ ["Uptime Kuma push URL", /\/api\/push\/([\w-]+)/di],
1166
+ ["healthchecks.io ping URL", /^hc-ping\.com\/([\w-]+)/di]
1167
+ ];
1168
+ var OPAQUE_SEGMENT = /^(?:(?=[\w-]{20,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w-]+|(?=[A-Za-z\d]{32,}$)(?=.*[A-Za-z])(?=.*\d).+)$/;
1169
+ function hint(value) {
1170
+ const shown = Math.min(3, Math.floor(value.length / 4));
1171
+ return `${value.slice(0, shown)}***(${value.length})`;
1172
+ }
1173
+ function forms(value) {
1174
+ return [...new Set([value, encodeURIComponent(value), JSON.stringify(value).slice(1, -1)])];
1175
+ }
1176
+ function knownSecrets(pairs) {
1177
+ const keys = new Map;
1178
+ for (const [key, value] of pairs) {
1179
+ if (value.length < MIN_KNOWN_LENGTH || PLAIN_VALUE.test(value))
1180
+ continue;
1181
+ for (const form of forms(value)) {
1182
+ if (!keys.has(form))
1183
+ keys.set(form, key);
1184
+ }
1185
+ }
1186
+ if (keys.size === 0)
1187
+ return { pattern: undefined, keys };
1188
+ const alternatives = [...keys.keys()].sort((a, b) => b.length - a.length).map((value) => value.replace(ESCAPE2, "\\$&"));
1189
+ return { pattern: new RegExp(`(?<!\\w)(?:${alternatives.join("|")})(?!\\w)`, "g"), keys };
1190
+ }
1191
+ function passwordSpans(text) {
1192
+ const spans = [];
1193
+ for (const url of text.matchAll(URL_PASSWORD)) {
1194
+ const [start, end] = url.indices?.[1] ?? [];
1195
+ const password = url[1] ?? "";
1196
+ const slash = password.indexOf("/");
1197
+ if (start !== undefined && end !== undefined && !(slash !== -1 && PORT.test(password.slice(0, slash))))
1198
+ spans.push([start, end]);
1199
+ }
1200
+ return spans;
1201
+ }
1202
+ function urlPasswords(text) {
1203
+ return passwordSpans(text).map(([start, end]) => text.slice(start, end));
1204
+ }
1205
+ function urlTokens(line) {
1206
+ const found = [];
1207
+ const add = (kind, start, value) => {
1208
+ found.push({ start, end: start + value.length, kind, mask: hint(value) });
1209
+ };
1210
+ for (const url of line.matchAll(URL_PARTS)) {
1211
+ const [authority, path = "", query] = [url[1] ?? "", url[2] ?? "", url[3]];
1212
+ const authorityStart = url.indices?.[1]?.[0];
1213
+ const pathStart = url.indices?.[2]?.[0];
1214
+ const queryStart = url.indices?.[3]?.[0];
1215
+ if (authorityStart === undefined || pathStart === undefined)
1216
+ continue;
1217
+ const hostAt = authority.lastIndexOf("@") + 1;
1218
+ const target = authority.slice(hostAt) + path;
1219
+ for (const [kind, pattern] of WEBHOOK_FORMATS) {
1220
+ const [start, end] = pattern.exec(target)?.indices?.[1] ?? [];
1221
+ if (start !== undefined && end !== undefined)
1222
+ add(kind, authorityStart + hostAt + start, target.slice(start, end));
1223
+ }
1224
+ for (const segment of path.matchAll(PATH_SEGMENT)) {
1225
+ if (OPAQUE_SEGMENT.test(segment[0]))
1226
+ add("URL token", pathStart + segment.index, segment[0]);
1227
+ }
1228
+ if (query === undefined || queryStart === undefined)
1229
+ continue;
1230
+ let offset = 0;
1231
+ for (const param of query.split("&")) {
1232
+ const equals = param.indexOf("=");
1233
+ if (equals > 0 && equals < param.length - 1 && SECRET_PARAM.test(param.slice(0, equals)))
1234
+ add("URL token", queryStart + offset + equals + 1, param.slice(equals + 1));
1235
+ offset += param.length + 1;
1236
+ }
1237
+ }
1238
+ return found.filter((match) => match.end > match.start);
1239
+ }
1240
+ function findSecrets(line, known) {
1241
+ const found = [];
1242
+ for (const [start, end] of passwordSpans(line))
1243
+ found.push({ start, end, kind: "URL password", mask: "***" });
1244
+ for (const body of line.matchAll(PEM_BODY)) {
1245
+ const [start, end] = body.indices?.[0] ?? [];
1246
+ if (start !== undefined && end !== undefined)
1247
+ found.push({ start, end, kind: "private key", mask: KEY_MASK });
1248
+ }
1249
+ for (const { kind, pattern, skip } of TOKEN_FORMATS) {
1250
+ for (const token of line.matchAll(pattern)) {
1251
+ const [start, end] = token.indices?.at(-1) ?? [];
1252
+ if (start === undefined || end === undefined)
1253
+ continue;
1254
+ const value = line.slice(start, end);
1255
+ if (!skip?.(value))
1256
+ found.push({ start, end, kind, mask: hint(value) });
1257
+ }
1258
+ }
1259
+ found.push(...urlTokens(line));
1260
+ if (known?.pattern !== undefined) {
1261
+ for (const value of line.matchAll(known.pattern))
1262
+ found.push({ start: value.index, end: value.index + value[0].length, kind: `value of ${known.keys.get(value[0])}`, mask: hint(value[0]) });
1263
+ }
1264
+ found.sort((a, b) => a.start - b.start || b.end - a.end);
1265
+ const kept = [];
1266
+ for (const match of found) {
1267
+ if (match.start >= (kept.at(-1)?.end ?? 0))
1268
+ kept.push(match);
1269
+ }
1270
+ return kept;
1271
+ }
1272
+ function openKeyBody(line) {
1273
+ const last = [...line.matchAll(PEM_BEGIN_ALL)].at(-1);
1274
+ if (last === undefined)
1275
+ return;
1276
+ const after = line.slice(last.index + last[0].length);
1277
+ return PEM_END.test(after) ? undefined : after.trim();
1278
+ }
1279
+ function maskLine(line, known) {
1280
+ let out = "";
1281
+ let at = 0;
1282
+ for (const match of findSecrets(line, known)) {
1283
+ out += line.slice(at, match.start) + match.mask;
1284
+ at = match.end;
1285
+ }
1286
+ return out + line.slice(at);
1287
+ }
1288
+ function maskValue(key, value, known) {
1289
+ if (value === "")
1290
+ return value;
1291
+ return isSecretName(key) || PEM_BEGIN.test(value) ? hint(value) : maskLine(value, known);
1292
+ }
1293
+
1294
+ // src/files.ts
1295
+ var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
1296
+ var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
1297
+ var KNOWN_DEPTH = 3;
1298
+ var SKIPPED = new Set(["node_modules", ".git", "vendor"]);
1299
+ var LOCK_WAIT_MS = 5000;
1300
+ var LOCK_STALE_MS = 30000;
1301
+ async function isFileEntry(entry, path) {
1302
+ if (entry.isFile())
1303
+ return true;
1304
+ if (!entry.isSymbolicLink())
1305
+ return false;
1306
+ try {
1307
+ return (await stat(path)).isFile();
1308
+ } catch {
1309
+ return false;
1310
+ }
1311
+ }
1312
+ async function envFiles(folder = process.cwd()) {
1313
+ const found = await readdir(folder, { withFileTypes: true });
1314
+ const names = [];
1315
+ for (const entry of found) {
1316
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join2(folder, entry.name)))
1317
+ names.push(entry.name);
1318
+ }
1319
+ return names.sort();
1320
+ }
1321
+ async function readEnv(path) {
1322
+ const file = Bun.file(path);
1323
+ if (!await file.exists())
1324
+ fail(`${path} does not exist`);
1325
+ return parseDotenv(await file.text());
1326
+ }
1327
+ async function writeAtomic(path, text) {
1328
+ let target = path;
1329
+ let mode = 384;
1330
+ let owner;
1331
+ try {
1332
+ target = await realpath(path);
1333
+ const current = await stat(target);
1334
+ mode = current.mode & 511;
1335
+ owner = current;
1336
+ } catch (error) {
1337
+ if (error.code !== "ENOENT")
1338
+ throw error;
1339
+ }
1340
+ const temp = join2(dirname2(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1341
+ try {
1342
+ await writeFile(temp, text, { mode: 384, flag: "wx" });
1343
+ if (owner !== undefined)
1344
+ await keepOwner(temp, owner);
1345
+ await chmod(temp, mode);
1346
+ await rename(temp, target);
1347
+ } finally {
1348
+ await rm(temp, { force: true });
1349
+ }
1350
+ }
1351
+ async function keepOwner(path, owner) {
1352
+ try {
1353
+ await chown(path, owner.uid, owner.gid);
1354
+ } catch (error) {
1355
+ if (error.code !== "EPERM")
1356
+ throw error;
1357
+ }
1358
+ }
1359
+ async function writeEnv(path, file) {
1360
+ await writeAtomic(path, serializeDotenv(file));
1361
+ }
1362
+ async function withLocks(paths, fn) {
1363
+ const held = [];
1364
+ try {
1365
+ for (const path of [...new Set(paths)].sort())
1366
+ held.push(await acquire(path));
1367
+ return await fn();
1368
+ } finally {
1369
+ for (const lock of held)
1370
+ await rm(lock, { force: true });
1371
+ }
1372
+ }
1373
+ async function acquire(path) {
1374
+ let real = path;
1375
+ try {
1376
+ real = await realpath(path);
1377
+ } catch {}
1378
+ const lock = join2(dirname2(real), `.${basename(real)}.lock`);
1379
+ const deadline = Date.now() + LOCK_WAIT_MS;
1380
+ while (true) {
1381
+ try {
1382
+ await writeFile(lock, String(process.pid), { flag: "wx", mode: 384 });
1383
+ return lock;
1384
+ } catch (error) {
1385
+ if (error.code !== "EEXIST")
1386
+ throw error;
1387
+ }
1388
+ try {
1389
+ if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS)
1390
+ await rm(lock, { force: true });
1391
+ } catch {}
1392
+ if (Date.now() > deadline)
1393
+ fail(`${path} is locked by another ev run (${lock})`, 1);
1394
+ await Bun.sleep(25);
1395
+ }
1396
+ }
1397
+ function secretPairs(file) {
1398
+ const pairs = [];
1399
+ for (const [key, value] of entries(file)) {
1400
+ if (isSecretName(key))
1401
+ pairs.push([key, value]);
1402
+ else
1403
+ pairs.push(...urlPasswords(value).map((password) => [key, password]));
1404
+ }
1405
+ return pairs;
1406
+ }
1407
+ async function envFilesBelow(folder, depth = 0) {
1408
+ const found = [];
1409
+ let children;
1410
+ try {
1411
+ children = await readdir(folder, { withFileTypes: true });
1412
+ } catch {
1413
+ return found;
1414
+ }
1415
+ for (const entry of children) {
1416
+ const path = join2(folder, entry.name);
1417
+ if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1418
+ found.push(...await envFilesBelow(path, depth + 1));
1419
+ else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
1420
+ found.push(path);
1421
+ }
1422
+ return found;
1423
+ }
1424
+ async function loadKnown(folder = process.cwd(), extra = []) {
1425
+ const pairs = extra.flatMap(secretPairs);
1426
+ for (const path of await envFilesBelow(folder)) {
1427
+ try {
1428
+ pairs.push(...secretPairs(parseDotenv(await Bun.file(path).text())));
1429
+ } catch {}
1430
+ }
1431
+ return knownSecrets(pairs);
1432
+ }
1433
+
1434
+ // src/redactor.ts
1435
+ var DIFF_START = /^(?:diff --git |@@ )/;
1436
+ var NEW_FILE = /^\+\+\+ (?:b\/)?(.+)$/;
1437
+ var HUNK = /^@@ -\d+(?:,\d+)? \+(\d+)/;
1438
+ var MAX_PENDING = 1 << 18;
1439
+ var OVERLAP = 1 << 13;
1440
+
1441
+ class Redactor {
1442
+ known;
1443
+ pending = "";
1444
+ inKey = false;
1445
+ hidden = false;
1446
+ constructor(known) {
1447
+ this.known = known;
1448
+ }
1449
+ push(chunk) {
1450
+ const end = chunk.lastIndexOf(`
1451
+ `);
1452
+ this.pending += chunk;
1453
+ if (end === -1)
1454
+ return this.pending.length > MAX_PENDING ? this.cut() : "";
1455
+ const split = this.pending.length - chunk.length + end + 1;
1456
+ const complete = this.pending.slice(0, split);
1457
+ this.pending = this.pending.slice(split);
1458
+ return complete.split(`
1459
+ `).slice(0, -1).map((line) => this.line(line)).filter((line) => line !== undefined).map((line) => `${line}
1460
+ `).join("");
1461
+ }
1462
+ cut() {
1463
+ const limit = this.pending.length - OVERLAP;
1464
+ const space = this.pending.lastIndexOf(" ", limit);
1465
+ const at = space > 0 ? space + 1 : limit;
1466
+ const head = this.pending.slice(0, at);
1467
+ this.pending = this.pending.slice(at);
1468
+ return this.line(head) ?? "";
1469
+ }
1470
+ end() {
1471
+ const rest = this.pending;
1472
+ this.pending = "";
1473
+ return rest === "" ? "" : this.line(rest) ?? "";
1474
+ }
1475
+ line(line) {
1476
+ if (this.inKey) {
1477
+ const end = PEM_END.exec(line);
1478
+ if (end === null) {
1479
+ if (this.hidden)
1480
+ return;
1481
+ this.hidden = true;
1482
+ return KEY_MASK;
1483
+ }
1484
+ this.inKey = false;
1485
+ return (end.index > 0 && !this.hidden ? KEY_MASK : "") + this.line(line.slice(end.index));
1486
+ }
1487
+ const body = openKeyBody(line);
1488
+ if (body !== undefined) {
1489
+ this.inKey = true;
1490
+ this.hidden = body !== "";
1491
+ }
1492
+ return maskLine(line, this.known);
1493
+ }
1494
+ }
1495
+ function check(text, known) {
1496
+ const findings = [];
1497
+ const isDiff = text.split(`
1498
+ `).some((line) => DIFF_START.test(line));
1499
+ let file = "stdin";
1500
+ let number = 0;
1501
+ let inKey = false;
1502
+ for (const [index, raw] of text.split(`
1503
+ `).entries()) {
1504
+ let line = raw;
1505
+ if (isDiff) {
1506
+ const hunk = HUNK.exec(raw);
1507
+ if (hunk !== null) {
1508
+ number = Number(hunk[1]) - 1;
1509
+ continue;
1510
+ }
1511
+ const named = NEW_FILE.exec(raw);
1512
+ if (named !== null) {
1513
+ file = named[1] ?? file;
1514
+ continue;
1515
+ }
1516
+ if (raw.startsWith("diff --git ")) {
1517
+ file = "(unnamed)";
1518
+ continue;
1519
+ }
1520
+ if (raw.startsWith("-") || raw.startsWith("\\"))
1521
+ continue;
1522
+ number++;
1523
+ if (!raw.startsWith("+"))
1524
+ continue;
1525
+ line = raw.slice(1);
1526
+ } else {
1527
+ number = index + 1;
1528
+ }
1529
+ if (inKey) {
1530
+ const end = PEM_END.exec(line);
1531
+ inKey = end === null;
1532
+ if (end === null)
1533
+ continue;
1534
+ line = line.slice(end.index);
1535
+ }
1536
+ const found = findSecrets(line, known).map((match) => match.kind);
1537
+ const body = openKeyBody(line);
1538
+ if (body !== undefined) {
1539
+ inKey = true;
1540
+ if (body === "")
1541
+ found.push("private key");
1542
+ }
1543
+ for (const kind of found)
1544
+ findings.push({ file, line: number, kind });
1545
+ }
1546
+ return findings;
1547
+ }
1548
+
1549
+ // src/redact.ts
1550
+ var usage2 = `redact [--check]
1551
+
1552
+ Copies stdin to stdout line by line with secrets masked: known token formats (GitHub, GitLab, Slack, AWS, npm, Stripe, Google and SendGrid keys, sk-, JWTs, Authorization headers, password= and secret= pairs), private key blocks, the password and the tokens of any URL and the values of secret-looking keys in this folder's .env* files.
1553
+ --check prints nothing of the input and lists the file and line of each secret found, exiting 1 when there is any: \`git diff --cached | redact --check\`.
1554
+
1555
+ Exits 0 when it copied the input or found no secret, 1 when --check finds one, 2 on a usage error.`;
1556
+ var options = {
1557
+ check: { type: "boolean", description: "list where secrets are instead of masking them, exit 1 when found" },
1558
+ "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
1559
+ };
1560
+ async function run(args) {
1561
+ const parsed = parse(args, usage2, options, { replaces: "printing a command's secrets into a log or a transcript", examples: [["docker compose config | redact", "the resolved compose file, secrets masked"], ["git diff --cached | redact --check", "refuse a commit carrying a secret"]] });
1562
+ const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
1563
+ if (parsed.values.check === true) {
1564
+ const findings = check(await readInput("-"), known);
1565
+ for (const { file, line, kind } of findings)
1566
+ console.log(`${file}:${line}: ${kind}`);
1567
+ return findings.length === 0 ? 0 : 1;
1568
+ }
1569
+ const redactor = new Redactor(known);
1570
+ const decoder = new TextDecoder;
1571
+ for await (const chunk of Bun.stdin.stream())
1572
+ process10.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1573
+ process10.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1574
+ return 0;
1575
+ }
1576
+ process10.exitCode = await runMain({ name: "redact", version, run });