@kaynooo/cli-env 0.0.0-stage → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/redact.js ADDED
@@ -0,0 +1,1362 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/redact.ts
5
+ import process7 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process4 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.0+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.0+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/text.ts
362
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
363
+ function distance(a, b) {
364
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
365
+ for (const [i, left] of [...a].entries()) {
366
+ const current = [i + 1];
367
+ for (const [j, right] of [...b].entries())
368
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
369
+ previous = current;
370
+ }
371
+ return previous[b.length] ?? 0;
372
+ }
373
+ function closest(name, names) {
374
+ const started = names.find((known) => known.startsWith(name));
375
+ if (started !== undefined)
376
+ return started;
377
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
378
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
379
+ }
380
+
381
+ // ../kit/src/args.ts
382
+ function jsonOption(holds) {
383
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
384
+ }
385
+
386
+ class Exit extends Error {
387
+ code;
388
+ hint;
389
+ constructor(message, code, hint) {
390
+ super(message);
391
+ this.code = code;
392
+ this.hint = hint;
393
+ }
394
+ }
395
+ function fail(message, code = 2, hint) {
396
+ throw new Exit(message, code, hint);
397
+ }
398
+
399
+ class UsageError extends Exit {
400
+ constructor(message, hint) {
401
+ super(message, 2, hint);
402
+ }
403
+ }
404
+ function badUsage(message) {
405
+ throw new UsageError(message);
406
+ }
407
+
408
+ class HelpShown extends Exit {
409
+ constructor() {
410
+ super("help shown", 0);
411
+ }
412
+ }
413
+
414
+ class Completing {
415
+ options;
416
+ constructor(options) {
417
+ this.options = options;
418
+ }
419
+ }
420
+ var completion = { active: false };
421
+ var OPTIONAL = /\[[^\]]+\]/g;
422
+ var USAGE_PREFIX = /^usage:\s*/i;
423
+ var FULL_STOP = /\.$/;
424
+ var DASHES = /^-+/;
425
+ function usageLine(usage, colors = paint(process4.stdout)) {
426
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
427
+ }
428
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces } = {}) {
429
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
430
+ `);
431
+ }
432
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
433
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
434
+ }
435
+ function wantsHelpJson(env = process4.env) {
436
+ return env.KIT_HELP === "json";
437
+ }
438
+ function description(usage, { examples = [], replaces } = {}) {
439
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
440
+ `);
441
+ const first = lines[0];
442
+ const colon = first.indexOf(": ");
443
+ const prose = lines[lines.indexOf("") + 1] ?? "";
444
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
445
+ return {
446
+ synopsis: colon === -1 ? first : first.slice(0, colon),
447
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
448
+ ...replaces === undefined ? {} : { replaces },
449
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
450
+ };
451
+ }
452
+ function exampleRows(examples, colors = paint(process4.stdout)) {
453
+ if (examples.length === 0)
454
+ return [];
455
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
456
+ }
457
+ function optionRows(options, colors = paint(process4.stdout)) {
458
+ const rows = Object.entries(options).map(([name, option]) => {
459
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
460
+ const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
461
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
462
+ });
463
+ const width = Math.max(0, ...rows.map((row) => row.width));
464
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
465
+ }
466
+ var OUTPUT_OPTIONS = {
467
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
468
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
469
+ };
470
+ function applyOutput(color, plain, env = process4.env) {
471
+ const when = plain === true ? "never" : color ?? "auto";
472
+ if (when === "auto")
473
+ return;
474
+ if (when !== "always" && when !== "never")
475
+ badUsage(`--color takes auto, always or never, not ${when}`);
476
+ if (when === "always") {
477
+ env.FORCE_COLOR = "1";
478
+ delete env.NO_COLOR;
479
+ } else {
480
+ env.NO_COLOR = "1";
481
+ delete env.FORCE_COLOR;
482
+ }
483
+ }
484
+ function parse(args, usage, options, settings = {}) {
485
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
486
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
487
+ if (completion.active)
488
+ throw new Completing(all);
489
+ const separator = settings.rest === true ? args.indexOf("--") : -1;
490
+ const own = separator === -1 ? args : args.slice(0, separator);
491
+ const rest = separator === -1 ? undefined : args.slice(separator + 1);
492
+ let parsed;
493
+ try {
494
+ parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
495
+ } catch (error) {
496
+ const message = parseError(error);
497
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
498
+ }
499
+ const values = parsed.values;
500
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
501
+ if (values.help === true) {
502
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
503
+ throw new HelpShown;
504
+ }
505
+ if (settings.positionals !== undefined)
506
+ checkPositionals(parsed.positionals, settings.positionals);
507
+ return { ...parsed, positionals: parsed.positionals, rest };
508
+ }
509
+ function checkPositionals(given, names) {
510
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
511
+ const required = names.filter((name) => !name.startsWith("[")).length;
512
+ if (given.length < required)
513
+ badUsage(`missing ${names[given.length]}`);
514
+ if (!variadic && given.length > names.length)
515
+ badUsage(`unexpected argument ${given[names.length]}`);
516
+ }
517
+ function joinDashValues(args, options) {
518
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
519
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
520
+ const joined = [];
521
+ for (let i = 0;i < args.length; i++) {
522
+ const arg = args[i] ?? "";
523
+ if (arg === "--")
524
+ return [...joined, ...args.slice(i)];
525
+ const name = longOf.get(arg);
526
+ const next = args[i + 1];
527
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
528
+ joined.push(`--${name}=${next}`);
529
+ i++;
530
+ } else {
531
+ joined.push(arg);
532
+ }
533
+ }
534
+ return joined;
535
+ }
536
+ function parseError(error) {
537
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
538
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
539
+ }
540
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
541
+ function nearestOption(message, options, allowNegative) {
542
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
543
+ if (typed === undefined)
544
+ return;
545
+ const word = typed.replace(DASHES, "");
546
+ if (word.length < 2 && !typed.startsWith("--"))
547
+ return;
548
+ const known = Object.entries(options).flatMap(([name, option]) => [
549
+ ...option.short === undefined ? [] : [`-${option.short}`],
550
+ `--${name}`,
551
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
552
+ ]);
553
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
554
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
555
+ }
556
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
557
+ if (path === "-") {
558
+ if (process4.stdin.isTTY)
559
+ fail(noStdin);
560
+ return Bun.stdin.text();
561
+ }
562
+ const file = Bun.file(path);
563
+ if (!await file.exists())
564
+ fail(`no file ${path}`);
565
+ return file.text();
566
+ }
567
+ // ../kit/src/progress.ts
568
+ var ESC = String.fromCharCode(27);
569
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
570
+ var RESET_STYLE = `${ESC}[0m`;
571
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
572
+ // ../kit/src/cli.ts
573
+ import process5 from "process";
574
+ var LEVEL_OPTIONS = {
575
+ ...OUTPUT_OPTIONS,
576
+ help: { type: "boolean", short: "h", description: "show this help" }
577
+ };
578
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
579
+ async function commandRows(commands, colors) {
580
+ const width = Math.max(...Object.keys(commands).map((name) => name.length));
581
+ const groups = new Map([["Commands:", []]]);
582
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
583
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
584
+ const heading = group === undefined ? "Commands:" : `${group}:`;
585
+ const rows = groups.get(heading) ?? [];
586
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
587
+ groups.set(heading, rows);
588
+ }
589
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
590
+ }
591
+ function takeOutputFlags(argv) {
592
+ let index = 0;
593
+ for (;index < argv.length; index++) {
594
+ const word = argv[index];
595
+ if (word === "--plain")
596
+ applyOutput(undefined, true);
597
+ else if (word.startsWith("--color="))
598
+ applyOutput(word.slice("--color=".length), undefined);
599
+ else if (word === "--color" && argv[index + 1] !== undefined)
600
+ applyOutput(argv[++index], undefined);
601
+ else
602
+ break;
603
+ }
604
+ return argv.slice(index);
605
+ }
606
+ async function resolveSummary(summary) {
607
+ return typeof summary === "string" ? summary : summary();
608
+ }
609
+ function scopeOf(commands, extra, aliases) {
610
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
611
+ }
612
+ async function expand(scope, words) {
613
+ if (scope.lazy.length === 0)
614
+ return scope;
615
+ const commands = { ...scope.commands };
616
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
617
+ for (const [name, command] of Object.entries(added))
618
+ commands[name] ??= command;
619
+ }
620
+ return { ...scope, commands, lazy: [] };
621
+ }
622
+ async function help({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
623
+ const colors = paint(stream);
624
+ const prefix = path.join(" ");
625
+ const summary = await resolveSummary(lazySummary);
626
+ if (wantsHelpJson())
627
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
628
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
629
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
630
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
631
+ return [
632
+ header(colors, summary),
633
+ "",
634
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
635
+ ...replacesRows(replaces, colors),
636
+ "",
637
+ ...await commandRows(commands, colors),
638
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
639
+ "",
640
+ colors.bold("Options:"),
641
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
642
+ ...exampleRows(examples ?? [], colors),
643
+ "",
644
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
645
+ ].join(`
646
+ `);
647
+ }
648
+ function printError(prefix, message, hint, cause) {
649
+ const colors = paint(process5.stderr);
650
+ const styled = takesControlCodes(process5.stderr);
651
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
652
+ const under = (label, text, tint) => text === undefined ? "" : `
653
+ ${styled ? tint(label) : `${label}:`} ${text}`;
654
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
655
+ }
656
+ function printJsonError(message, hint, cause) {
657
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
658
+ }
659
+ function wantsJson(argv) {
660
+ const end = argv.indexOf("--");
661
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
662
+ }
663
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
664
+ if (error instanceof HelpShown)
665
+ return 0;
666
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
667
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
668
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
669
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
670
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
671
+ return error instanceof Exit ? error.code : 1;
672
+ }
673
+ async function dispatch(level, typed, { version, redact }) {
674
+ const prefix = level.path.join(" ");
675
+ let argv;
676
+ try {
677
+ argv = takeOutputFlags(typed);
678
+ } catch (error) {
679
+ return reportThrown(prefix, error);
680
+ }
681
+ const [name, ...args] = argv;
682
+ if (name === undefined && level.path.length > 1) {
683
+ console.error(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
684
+ return 2;
685
+ }
686
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
687
+ console.log(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
688
+ return 0;
689
+ }
690
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
691
+ console.log(version);
692
+ return 0;
693
+ }
694
+ let command = level.commands[level.aliases?.[name] ?? name];
695
+ let rest = args;
696
+ if (command === undefined && level.lazy.length > 0) {
697
+ level = await expand(level, [...level.path.slice(1), ...argv]);
698
+ command = level.commands[level.aliases?.[name] ?? name];
699
+ }
700
+ if (command === undefined && level.defaultCommand !== undefined) {
701
+ command = level.commands[level.defaultCommand];
702
+ rest = argv;
703
+ }
704
+ if (command === undefined) {
705
+ const meant = closest(name, Object.keys(level.commands));
706
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
707
+ return 2;
708
+ }
709
+ if ("commands" in command) {
710
+ const { summary } = command;
711
+ return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, examples: command.examples, replaces: undefined }, rest, { version, redact });
712
+ }
713
+ try {
714
+ return await command.run(rest);
715
+ } catch (error) {
716
+ return reportThrown(`${prefix} ${name}`, error, redact, wantsJson(rest));
717
+ }
718
+ }
719
+ var COMPLETE = "__complete";
720
+ var FILES = "__files__";
721
+ async function optionsOf(run) {
722
+ completion.active = true;
723
+ try {
724
+ await run([]);
725
+ } catch (error) {
726
+ if (error instanceof Completing)
727
+ return error.options;
728
+ } finally {
729
+ completion.active = false;
730
+ }
731
+ return {};
732
+ }
733
+ async function leafCandidates(run, words) {
734
+ if (!(words.at(-1) ?? "").startsWith("-"))
735
+ return [FILES];
736
+ return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
737
+ }
738
+ async function candidates(scope, defaultCommand, words, before = []) {
739
+ const [word = "", ...rest] = words;
740
+ const listing = rest.length === 0 && !word.startsWith("-");
741
+ let { commands, aliases } = scope;
742
+ let command = commands[aliases?.[word] ?? word];
743
+ if (listing || command === undefined) {
744
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
745
+ command = commands[aliases?.[word] ?? word];
746
+ }
747
+ if (listing)
748
+ return Promise.all(Object.entries(commands).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
749
+ if (command === undefined) {
750
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
751
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
752
+ }
753
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
754
+ }
755
+ async function printCandidates(found) {
756
+ for (const line of await found)
757
+ console.log(line);
758
+ return 0;
759
+ }
760
+ async function runCli(cli, argv = process5.argv.slice(2)) {
761
+ if (argv[0] === COMPLETE)
762
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
763
+ return 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, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
764
+ }
765
+ async function runMain({ name, version, run, redact }, argv = process5.argv.slice(2)) {
766
+ if (argv[0] === COMPLETE)
767
+ return printCandidates(leafCandidates(run, argv.slice(1)));
768
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
769
+ console.log(version);
770
+ return 0;
771
+ }
772
+ try {
773
+ return await run(argv);
774
+ } catch (error) {
775
+ return reportThrown(name, error, redact, wantsJson(argv));
776
+ }
777
+ }
778
+ // ../kit/src/logs.ts
779
+ var DAY_MS = 24 * 60 * 60 * 1000;
780
+ // ../kit/src/secrets.ts
781
+ var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
782
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
783
+ var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
784
+ function isSecretName(name) {
785
+ return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
786
+ }
787
+ // ../kit/src/sessions.ts
788
+ var {Glob } = globalThis.Bun;
789
+ var SESSION_FILES = new Glob("*.json");
790
+ var ACCOUNT_DIRS = new Glob("*/sessions");
791
+ // package.json
792
+ var version = "0.8.0";
793
+
794
+ // src/files.ts
795
+ import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
796
+ import { basename, dirname, join } from "path";
797
+
798
+ // src/dotenv.ts
799
+ var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
800
+ var EXPORTED = /^\s*export\s/;
801
+ var INLINE_COMMENT = /\s+#.*$/;
802
+ var CARRIAGE_RETURN = /\r$/;
803
+ var ESCAPES = { n: `
804
+ `, r: "\r", t: "\t", '"': '"', "\\": "\\", $: "$" };
805
+ var LINE_BREAK = /[\r\n]/;
806
+ var RAW_ONLY = /["\\]/;
807
+ var NEEDS_QUOTES = /[\s#"'\\$`]/;
808
+ function closingQuote(text, quote) {
809
+ for (let index = 0;index < text.length; index++) {
810
+ if (quote === '"' && text[index] === "\\")
811
+ index++;
812
+ else if (text[index] === quote)
813
+ return index;
814
+ }
815
+ return -1;
816
+ }
817
+ function unescapeDollar(text) {
818
+ return text.replaceAll("\\$", "$");
819
+ }
820
+ function unescapeDouble(text) {
821
+ let out = "";
822
+ for (let index = 0;index < text.length; index++) {
823
+ const next = text[index + 1];
824
+ if (text[index] === "\\" && next !== undefined && next in ESCAPES) {
825
+ out += ESCAPES[next];
826
+ index++;
827
+ } else {
828
+ out += text[index];
829
+ }
830
+ }
831
+ return out;
832
+ }
833
+ function parseDotenv(text) {
834
+ const physical = text.split(`
835
+ `);
836
+ const lines = [];
837
+ for (let index = 0;index < physical.length; index++) {
838
+ const line = physical[index] ?? "";
839
+ const match = ASSIGNMENT.exec(line.replace(CARRIAGE_RETURN, ""));
840
+ if (match === null) {
841
+ lines.push({ raw: line });
842
+ continue;
843
+ }
844
+ const [, key = "", rest = ""] = match;
845
+ const start = rest.trimStart();
846
+ const quote = start[0];
847
+ if (quote !== '"' && quote !== "'" && quote !== "`") {
848
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()) });
849
+ continue;
850
+ }
851
+ let body = start.slice(1);
852
+ let raw = line;
853
+ let end = closingQuote(body, quote);
854
+ while (end === -1 && index + 1 < physical.length) {
855
+ index++;
856
+ body += `
857
+ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
858
+ raw += `
859
+ ${physical[index] ?? ""}`;
860
+ end = closingQuote(body, quote);
861
+ }
862
+ const inner = end === -1 ? body : body.slice(0, end);
863
+ lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
864
+ }
865
+ return { lines };
866
+ }
867
+ function serializeDotenv(file) {
868
+ return file.lines.map((line) => line.raw).join(`
869
+ `);
870
+ }
871
+ function entries(file) {
872
+ const map = new Map;
873
+ for (const line of file.lines) {
874
+ if (line.key !== undefined)
875
+ map.set(line.key, line.value ?? "");
876
+ }
877
+ return map;
878
+ }
879
+ function formatAssignment(key, value) {
880
+ if (value === "" || !NEEDS_QUOTES.test(value))
881
+ return `${key}=${value}`;
882
+ if (RAW_ONLY.test(value) && !value.includes("'") && !LINE_BREAK.test(value))
883
+ return `${key}='${value.replaceAll("$", "\\$")}'`;
884
+ const escaped = value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("\r", "\\r").replaceAll(`
885
+ `, "\\n").replaceAll("$", "\\$");
886
+ return `${key}="${escaped}"`;
887
+ }
888
+ function setLine(file, key, value, raw) {
889
+ const index = file.lines.findLastIndex((line) => line.key === key);
890
+ const existing = file.lines[index];
891
+ if (existing !== undefined) {
892
+ const exported = EXPORTED.test(existing.raw) ? "export " : "";
893
+ file.lines[index] = { raw: raw ?? `${exported}${formatAssignment(key, value)}`, key, value };
894
+ return;
895
+ }
896
+ const line = { raw: raw ?? formatAssignment(key, value), key, value };
897
+ const last = file.lines.at(-1);
898
+ if (last === undefined)
899
+ file.lines.push(line, { raw: "" });
900
+ else if (last.raw === "")
901
+ file.lines.splice(-1, 0, line);
902
+ else
903
+ file.lines.push(line, { raw: "" });
904
+ }
905
+ function removeKey(file, key) {
906
+ const before = file.lines.length;
907
+ file.lines = file.lines.filter((line) => line.key !== key);
908
+ return before - file.lines.length;
909
+ }
910
+ function lastLine(file, key) {
911
+ return file.lines.findLast((line) => line.key === key);
912
+ }
913
+
914
+ // src/mask.ts
915
+ var MIN_KNOWN_LENGTH = 4;
916
+ var KEY_MASK = "*** private key redacted ***";
917
+ var PLAIN_VALUE = /^(?:true|false|null|none|nil|yes|no|on|off|undefined)$/i;
918
+ var PLACEHOLDER = /^[$%{<(*/]/;
919
+ var URL_PASSWORD = /(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:([^\s'"]{1,1024})@/dgi;
920
+ var PORT = /^\d{1,5}$/;
921
+ var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
922
+ function isPlaceholder(value) {
923
+ return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
924
+ }
925
+ var TOKEN_FORMATS = [
926
+ { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
927
+ { kind: "GitLab token", pattern: /\bglpat-[\w-]{20,}/dg },
928
+ { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
929
+ { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
930
+ { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
931
+ { kind: "AWS access key", pattern: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/dg },
932
+ { kind: "npm token", pattern: /\bnpm_[A-Za-z0-9]{30,}/dg },
933
+ { kind: "Stripe key", pattern: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/dg },
934
+ { kind: "Google API key", pattern: /\bAIza[\w-]{35}/dg },
935
+ { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
936
+ { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
937
+ { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
938
+ { kind: "password", pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
939
+ { kind: "password", pattern: /(?<![\w-])["']?(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?["']?\s*[:=]\s*(["'])((?:\\.|(?!\1)[^\\\n]){4,})\1/dgi, skip: isPlaceholder }
940
+ ];
941
+ var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
942
+ var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
943
+ var PEM_BODY = /(?<=-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----)(?:(?!-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----)[\s\S])+/dg;
944
+ var PEM_BEGIN_ALL = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/g;
945
+ var URL_PARTS = /(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{0,31}:\/\/([^\s/?#'"<>`]*)([^\s?#'"<>`]*)(?:\?([^\s#'"<>`]*))?/dgi;
946
+ var PATH_SEGMENT = /[^/]+/g;
947
+ var SECRET_PARAM = /^(?:token|[a-z]+_token|key|api[_-]?key|access[_-]?key|secret|[a-z]+_secret|password|passwd|pwd|sig|signature|auth|authorization)$/i;
948
+ var WEBHOOK_FORMATS = [
949
+ ["Discord webhook", /(?:^|\.)discord(?:app)?\.com\/api\/(?:v\d+\/)?webhooks\/\d+\/([\w-]+)/di],
950
+ ["Slack webhook", /^hooks\.slack\.com\/(?:services|workflows)\/(?:[\w-]+\/)*([\w-]+)/di],
951
+ ["Uptime Kuma push URL", /\/api\/push\/([\w-]+)/di],
952
+ ["healthchecks.io ping URL", /^hc-ping\.com\/([\w-]+)/di]
953
+ ];
954
+ var OPAQUE_SEGMENT = /^(?:(?=[\w-]{20,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w-]+|(?=[A-Za-z\d]{32,}$)(?=.*[A-Za-z])(?=.*\d).+)$/;
955
+ function hint(value) {
956
+ const shown = Math.min(3, Math.floor(value.length / 4));
957
+ return `${value.slice(0, shown)}***(${value.length})`;
958
+ }
959
+ function forms(value) {
960
+ return [...new Set([value, encodeURIComponent(value), JSON.stringify(value).slice(1, -1)])];
961
+ }
962
+ function knownSecrets(pairs) {
963
+ const keys = new Map;
964
+ for (const [key, value] of pairs) {
965
+ if (value.length < MIN_KNOWN_LENGTH || PLAIN_VALUE.test(value))
966
+ continue;
967
+ for (const form of forms(value)) {
968
+ if (!keys.has(form))
969
+ keys.set(form, key);
970
+ }
971
+ }
972
+ if (keys.size === 0)
973
+ return { pattern: undefined, keys };
974
+ const alternatives = [...keys.keys()].sort((a, b) => b.length - a.length).map((value) => value.replace(ESCAPE2, "\\$&"));
975
+ return { pattern: new RegExp(`(?<!\\w)(?:${alternatives.join("|")})(?!\\w)`, "g"), keys };
976
+ }
977
+ function passwordSpans(text) {
978
+ const spans = [];
979
+ for (const url of text.matchAll(URL_PASSWORD)) {
980
+ const [start, end] = url.indices?.[1] ?? [];
981
+ const password = url[1] ?? "";
982
+ const slash = password.indexOf("/");
983
+ if (start !== undefined && end !== undefined && !(slash !== -1 && PORT.test(password.slice(0, slash))))
984
+ spans.push([start, end]);
985
+ }
986
+ return spans;
987
+ }
988
+ function urlPasswords(text) {
989
+ return passwordSpans(text).map(([start, end]) => text.slice(start, end));
990
+ }
991
+ function urlTokens(line) {
992
+ const found = [];
993
+ const add = (kind, start, value) => {
994
+ found.push({ start, end: start + value.length, kind, mask: hint(value) });
995
+ };
996
+ for (const url of line.matchAll(URL_PARTS)) {
997
+ const [authority, path = "", query] = [url[1] ?? "", url[2] ?? "", url[3]];
998
+ const authorityStart = url.indices?.[1]?.[0];
999
+ const pathStart = url.indices?.[2]?.[0];
1000
+ const queryStart = url.indices?.[3]?.[0];
1001
+ if (authorityStart === undefined || pathStart === undefined)
1002
+ continue;
1003
+ const hostAt = authority.lastIndexOf("@") + 1;
1004
+ const target = authority.slice(hostAt) + path;
1005
+ for (const [kind, pattern] of WEBHOOK_FORMATS) {
1006
+ const [start, end] = pattern.exec(target)?.indices?.[1] ?? [];
1007
+ if (start !== undefined && end !== undefined)
1008
+ add(kind, authorityStart + hostAt + start, target.slice(start, end));
1009
+ }
1010
+ for (const segment of path.matchAll(PATH_SEGMENT)) {
1011
+ if (OPAQUE_SEGMENT.test(segment[0]))
1012
+ add("URL token", pathStart + segment.index, segment[0]);
1013
+ }
1014
+ if (query === undefined || queryStart === undefined)
1015
+ continue;
1016
+ let offset = 0;
1017
+ for (const param of query.split("&")) {
1018
+ const equals = param.indexOf("=");
1019
+ if (equals > 0 && equals < param.length - 1 && SECRET_PARAM.test(param.slice(0, equals)))
1020
+ add("URL token", queryStart + offset + equals + 1, param.slice(equals + 1));
1021
+ offset += param.length + 1;
1022
+ }
1023
+ }
1024
+ return found.filter((match) => match.end > match.start);
1025
+ }
1026
+ function findSecrets(line, known) {
1027
+ const found = [];
1028
+ for (const [start, end] of passwordSpans(line))
1029
+ found.push({ start, end, kind: "URL password", mask: "***" });
1030
+ for (const body of line.matchAll(PEM_BODY)) {
1031
+ const [start, end] = body.indices?.[0] ?? [];
1032
+ if (start !== undefined && end !== undefined)
1033
+ found.push({ start, end, kind: "private key", mask: KEY_MASK });
1034
+ }
1035
+ for (const { kind, pattern, skip } of TOKEN_FORMATS) {
1036
+ for (const token of line.matchAll(pattern)) {
1037
+ const [start, end] = token.indices?.at(-1) ?? [];
1038
+ if (start === undefined || end === undefined)
1039
+ continue;
1040
+ const value = line.slice(start, end);
1041
+ if (!skip?.(value))
1042
+ found.push({ start, end, kind, mask: hint(value) });
1043
+ }
1044
+ }
1045
+ found.push(...urlTokens(line));
1046
+ if (known?.pattern !== undefined) {
1047
+ for (const value of line.matchAll(known.pattern))
1048
+ found.push({ start: value.index, end: value.index + value[0].length, kind: `value of ${known.keys.get(value[0])}`, mask: hint(value[0]) });
1049
+ }
1050
+ found.sort((a, b) => a.start - b.start || b.end - a.end);
1051
+ const kept = [];
1052
+ for (const match of found) {
1053
+ if (match.start >= (kept.at(-1)?.end ?? 0))
1054
+ kept.push(match);
1055
+ }
1056
+ return kept;
1057
+ }
1058
+ function openKeyBody(line) {
1059
+ const last = [...line.matchAll(PEM_BEGIN_ALL)].at(-1);
1060
+ if (last === undefined)
1061
+ return;
1062
+ const after = line.slice(last.index + last[0].length);
1063
+ return PEM_END.test(after) ? undefined : after.trim();
1064
+ }
1065
+ function maskLine(line, known) {
1066
+ let out = "";
1067
+ let at = 0;
1068
+ for (const match of findSecrets(line, known)) {
1069
+ out += line.slice(at, match.start) + match.mask;
1070
+ at = match.end;
1071
+ }
1072
+ return out + line.slice(at);
1073
+ }
1074
+ function maskValue(key, value, known) {
1075
+ if (value === "")
1076
+ return value;
1077
+ return isSecretName(key) || PEM_BEGIN.test(value) ? hint(value) : maskLine(value, known);
1078
+ }
1079
+
1080
+ // src/files.ts
1081
+ var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
1082
+ var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
1083
+ var KNOWN_DEPTH = 3;
1084
+ var SKIPPED = new Set(["node_modules", ".git", "vendor"]);
1085
+ var LOCK_WAIT_MS = 5000;
1086
+ var LOCK_STALE_MS = 30000;
1087
+ async function isFileEntry(entry, path) {
1088
+ if (entry.isFile())
1089
+ return true;
1090
+ if (!entry.isSymbolicLink())
1091
+ return false;
1092
+ try {
1093
+ return (await stat(path)).isFile();
1094
+ } catch {
1095
+ return false;
1096
+ }
1097
+ }
1098
+ async function envFiles(folder = process.cwd()) {
1099
+ const found = await readdir(folder, { withFileTypes: true });
1100
+ const names = [];
1101
+ for (const entry of found) {
1102
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join(folder, entry.name)))
1103
+ names.push(entry.name);
1104
+ }
1105
+ return names.sort();
1106
+ }
1107
+ async function readEnv(path) {
1108
+ const file = Bun.file(path);
1109
+ if (!await file.exists())
1110
+ fail(`${path} does not exist`);
1111
+ return parseDotenv(await file.text());
1112
+ }
1113
+ async function writeAtomic(path, text) {
1114
+ let target = path;
1115
+ let mode = 384;
1116
+ let owner;
1117
+ try {
1118
+ target = await realpath(path);
1119
+ const current = await stat(target);
1120
+ mode = current.mode & 511;
1121
+ owner = current;
1122
+ } catch (error) {
1123
+ if (error.code !== "ENOENT")
1124
+ throw error;
1125
+ }
1126
+ const temp = join(dirname(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1127
+ try {
1128
+ await writeFile(temp, text, { mode: 384, flag: "wx" });
1129
+ if (owner !== undefined)
1130
+ await keepOwner(temp, owner);
1131
+ await chmod(temp, mode);
1132
+ await rename(temp, target);
1133
+ } finally {
1134
+ await rm(temp, { force: true });
1135
+ }
1136
+ }
1137
+ async function keepOwner(path, owner) {
1138
+ try {
1139
+ await chown(path, owner.uid, owner.gid);
1140
+ } catch (error) {
1141
+ if (error.code !== "EPERM")
1142
+ throw error;
1143
+ }
1144
+ }
1145
+ async function writeEnv(path, file) {
1146
+ await writeAtomic(path, serializeDotenv(file));
1147
+ }
1148
+ async function withLocks(paths, fn) {
1149
+ const held = [];
1150
+ try {
1151
+ for (const path of [...new Set(paths)].sort())
1152
+ held.push(await acquire(path));
1153
+ return await fn();
1154
+ } finally {
1155
+ for (const lock of held)
1156
+ await rm(lock, { force: true });
1157
+ }
1158
+ }
1159
+ async function acquire(path) {
1160
+ let real = path;
1161
+ try {
1162
+ real = await realpath(path);
1163
+ } catch {}
1164
+ const lock = join(dirname(real), `.${basename(real)}.lock`);
1165
+ const deadline = Date.now() + LOCK_WAIT_MS;
1166
+ while (true) {
1167
+ try {
1168
+ await writeFile(lock, String(process.pid), { flag: "wx", mode: 384 });
1169
+ return lock;
1170
+ } catch (error) {
1171
+ if (error.code !== "EEXIST")
1172
+ throw error;
1173
+ }
1174
+ try {
1175
+ if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS)
1176
+ await rm(lock, { force: true });
1177
+ } catch {}
1178
+ if (Date.now() > deadline)
1179
+ fail(`${path} is locked by another ev run (${lock})`, 1);
1180
+ await Bun.sleep(25);
1181
+ }
1182
+ }
1183
+ function secretPairs(file) {
1184
+ const pairs = [];
1185
+ for (const [key, value] of entries(file)) {
1186
+ if (isSecretName(key))
1187
+ pairs.push([key, value]);
1188
+ else
1189
+ pairs.push(...urlPasswords(value).map((password) => [key, password]));
1190
+ }
1191
+ return pairs;
1192
+ }
1193
+ async function envFilesBelow(folder, depth = 0) {
1194
+ const found = [];
1195
+ let children;
1196
+ try {
1197
+ children = await readdir(folder, { withFileTypes: true });
1198
+ } catch {
1199
+ return found;
1200
+ }
1201
+ for (const entry of children) {
1202
+ const path = join(folder, entry.name);
1203
+ if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1204
+ found.push(...await envFilesBelow(path, depth + 1));
1205
+ else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
1206
+ found.push(path);
1207
+ }
1208
+ return found;
1209
+ }
1210
+ async function loadKnown(folder = process.cwd(), extra = []) {
1211
+ const pairs = extra.flatMap(secretPairs);
1212
+ for (const path of await envFilesBelow(folder)) {
1213
+ try {
1214
+ pairs.push(...secretPairs(parseDotenv(await Bun.file(path).text())));
1215
+ } catch {}
1216
+ }
1217
+ return knownSecrets(pairs);
1218
+ }
1219
+
1220
+ // src/redactor.ts
1221
+ var DIFF_START = /^(?:diff --git |@@ )/;
1222
+ var NEW_FILE = /^\+\+\+ (?:b\/)?(.+)$/;
1223
+ var HUNK = /^@@ -\d+(?:,\d+)? \+(\d+)/;
1224
+ var MAX_PENDING = 1 << 18;
1225
+ var OVERLAP = 1 << 13;
1226
+
1227
+ class Redactor {
1228
+ known;
1229
+ pending = "";
1230
+ inKey = false;
1231
+ hidden = false;
1232
+ constructor(known) {
1233
+ this.known = known;
1234
+ }
1235
+ push(chunk) {
1236
+ const end = chunk.lastIndexOf(`
1237
+ `);
1238
+ this.pending += chunk;
1239
+ if (end === -1)
1240
+ return this.pending.length > MAX_PENDING ? this.cut() : "";
1241
+ const split = this.pending.length - chunk.length + end + 1;
1242
+ const complete = this.pending.slice(0, split);
1243
+ this.pending = this.pending.slice(split);
1244
+ return complete.split(`
1245
+ `).slice(0, -1).map((line) => this.line(line)).filter((line) => line !== undefined).map((line) => `${line}
1246
+ `).join("");
1247
+ }
1248
+ cut() {
1249
+ const limit = this.pending.length - OVERLAP;
1250
+ const space = this.pending.lastIndexOf(" ", limit);
1251
+ const at = space > 0 ? space + 1 : limit;
1252
+ const head = this.pending.slice(0, at);
1253
+ this.pending = this.pending.slice(at);
1254
+ return this.line(head) ?? "";
1255
+ }
1256
+ end() {
1257
+ const rest = this.pending;
1258
+ this.pending = "";
1259
+ return rest === "" ? "" : this.line(rest) ?? "";
1260
+ }
1261
+ line(line) {
1262
+ if (this.inKey) {
1263
+ const end = PEM_END.exec(line);
1264
+ if (end === null) {
1265
+ if (this.hidden)
1266
+ return;
1267
+ this.hidden = true;
1268
+ return KEY_MASK;
1269
+ }
1270
+ this.inKey = false;
1271
+ return (end.index > 0 && !this.hidden ? KEY_MASK : "") + this.line(line.slice(end.index));
1272
+ }
1273
+ const body = openKeyBody(line);
1274
+ if (body !== undefined) {
1275
+ this.inKey = true;
1276
+ this.hidden = body !== "";
1277
+ }
1278
+ return maskLine(line, this.known);
1279
+ }
1280
+ }
1281
+ function check(text, known) {
1282
+ const findings = [];
1283
+ const isDiff = text.split(`
1284
+ `).some((line) => DIFF_START.test(line));
1285
+ let file = "stdin";
1286
+ let number = 0;
1287
+ let inKey = false;
1288
+ for (const [index, raw] of text.split(`
1289
+ `).entries()) {
1290
+ let line = raw;
1291
+ if (isDiff) {
1292
+ const hunk = HUNK.exec(raw);
1293
+ if (hunk !== null) {
1294
+ number = Number(hunk[1]) - 1;
1295
+ continue;
1296
+ }
1297
+ const named = NEW_FILE.exec(raw);
1298
+ if (named !== null) {
1299
+ file = named[1] ?? file;
1300
+ continue;
1301
+ }
1302
+ if (raw.startsWith("diff --git ")) {
1303
+ file = "(unnamed)";
1304
+ continue;
1305
+ }
1306
+ if (raw.startsWith("-") || raw.startsWith("\\"))
1307
+ continue;
1308
+ number++;
1309
+ if (!raw.startsWith("+"))
1310
+ continue;
1311
+ line = raw.slice(1);
1312
+ } else {
1313
+ number = index + 1;
1314
+ }
1315
+ if (inKey) {
1316
+ const end = PEM_END.exec(line);
1317
+ inKey = end === null;
1318
+ if (end === null)
1319
+ continue;
1320
+ line = line.slice(end.index);
1321
+ }
1322
+ const found = findSecrets(line, known).map((match) => match.kind);
1323
+ const body = openKeyBody(line);
1324
+ if (body !== undefined) {
1325
+ inKey = true;
1326
+ if (body === "")
1327
+ found.push("private key");
1328
+ }
1329
+ for (const kind of found)
1330
+ findings.push({ file, line: number, kind });
1331
+ }
1332
+ return findings;
1333
+ }
1334
+
1335
+ // src/redact.ts
1336
+ var usage = `redact [--check]
1337
+
1338
+ 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.
1339
+ --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\`.
1340
+
1341
+ Exits 0 when it copied the input or found no secret, 1 when --check finds one, 2 on a usage error.`;
1342
+ var options = {
1343
+ check: { type: "boolean", description: "list where secrets are instead of masking them, exit 1 when found" },
1344
+ "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
1345
+ };
1346
+ async function run(args) {
1347
+ const parsed = parse(args, usage, 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"]] });
1348
+ const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
1349
+ if (parsed.values.check === true) {
1350
+ const findings = check(await readInput("-"), known);
1351
+ for (const { file, line, kind } of findings)
1352
+ console.log(`${file}:${line}: ${kind}`);
1353
+ return findings.length === 0 ? 0 : 1;
1354
+ }
1355
+ const redactor = new Redactor(known);
1356
+ const decoder = new TextDecoder;
1357
+ for await (const chunk of Bun.stdin.stream())
1358
+ process7.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1359
+ process7.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1360
+ return 0;
1361
+ }
1362
+ process7.exitCode = await runMain({ name: "redact", version, run });