@kaynooo/cli-proc 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1367 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/pid-cli.ts
5
+ import process10 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 process2 from "process";
13
+
14
+ // ../kit/src/style.ts
15
+ import process 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
+ function takesControlCodes(stream, env = process.env) {
280
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
281
+ }
282
+ function paint(stream, env = process.env) {
283
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
284
+ }
285
+ var STATUSES = {
286
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
287
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
288
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
289
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
290
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
291
+ };
292
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
293
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-hrsswv1w.js
294
+ function $e(t, e = false, i = 1) {
295
+ let n = typeof e === "object" ? e : { units: e ? "si" : "iec", dp: i }, { units: s = "iec", dp: u = 1 } = n, r = s === "si" ? 1000 : 1024;
296
+ if (Math.abs(t) < r)
297
+ return `${t} B`;
298
+ let c = s === "iec" ? ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] : ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], o = -1, l = 10 ** u;
299
+ do
300
+ t /= r, ++o;
301
+ while (Math.round(Math.abs(t) * l) / l >= r && o < c.length - 1);
302
+ return `${t.toFixed(u)} ${c[o]}`;
303
+ }
304
+
305
+ // ../kit/src/format.ts
306
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
307
+ function formatSeconds(total) {
308
+ let rest = Math.max(0, Math.round(total));
309
+ const amounts = UNITS.map(([unit, size]) => {
310
+ const amount = Math.floor(rest / size);
311
+ rest -= amount * size;
312
+ return `${amount}${unit}`;
313
+ });
314
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
315
+ if (first === -1)
316
+ return "0s";
317
+ const next = amounts[first + 1];
318
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
319
+ }
320
+ function upTo(text, separator) {
321
+ const end = text.indexOf(separator);
322
+ return end === -1 ? text : text.slice(0, end);
323
+ }
324
+ function truncate(text, width) {
325
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
326
+ }
327
+ var LINE_BREAKS = /\s*\n\s*/g;
328
+ var ESCAPE = String.fromCharCode(27);
329
+ function textWidth(text) {
330
+ return Bun.stringWidth(text);
331
+ }
332
+ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
333
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
334
+ const widths = [];
335
+ for (const row of cells) {
336
+ for (const [index, cell] of row.entries())
337
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
338
+ }
339
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
340
+ const colors = paint(process2.stdout);
341
+ const lines = shown.map((row) => row.map((cell, index) => {
342
+ const width = widths[index] ?? 0;
343
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
344
+ if (align[index] === "right")
345
+ return `${gap}${cell}`;
346
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
347
+ }).join(" ").trimEnd());
348
+ return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
349
+ `);
350
+ }
351
+ function narrow(rows, widths, limit) {
352
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
353
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
354
+ const floor = 8;
355
+ while (used() > limit) {
356
+ let widest = -1;
357
+ for (const [index, width] of widths.entries()) {
358
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
359
+ widest = index;
360
+ }
361
+ if (widest === -1)
362
+ break;
363
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
364
+ }
365
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
366
+ }
367
+ function printJson(value) {
368
+ console.log(JSON.stringify(value, undefined, 2));
369
+ }
370
+
371
+ // ../kit/src/help.ts
372
+ import process3 from "process";
373
+ var OPTIONAL = /\[[^\]]+\]/g;
374
+ var USAGE_PREFIX = /^usage:\s*/i;
375
+ var FULL_STOP = /\.$/;
376
+ function usageLine(usage, colors = paint(process3.stdout)) {
377
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
378
+ }
379
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
380
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
381
+ `);
382
+ }
383
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
384
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
385
+ }
386
+ function wantsHelpJson(env = process3.env) {
387
+ return env.KIT_HELP === "json";
388
+ }
389
+ function description(usage, { examples = [], replaces } = {}) {
390
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
391
+ `);
392
+ const first = lines[0];
393
+ const colon = first.indexOf(": ");
394
+ const prose = lines[lines.indexOf("") + 1] ?? "";
395
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
396
+ return {
397
+ synopsis: colon === -1 ? first : first.slice(0, colon),
398
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
399
+ ...replaces === undefined ? {} : { replaces },
400
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
401
+ };
402
+ }
403
+ function exampleRows(examples, colors = paint(process3.stdout)) {
404
+ if (examples.length === 0)
405
+ return [];
406
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
407
+ }
408
+ function optionRows(options, colors = paint(process3.stdout)) {
409
+ const rows = Object.entries(options).map(([name, option]) => {
410
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
411
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
412
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
413
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
414
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
415
+ });
416
+ const width = Math.max(0, ...rows.map((row) => row.width));
417
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
418
+ }
419
+
420
+ // ../kit/src/text.ts
421
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
422
+ function distance(a, b) {
423
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
424
+ for (const [i, left] of [...a].entries()) {
425
+ const current = [i + 1];
426
+ for (const [j, right] of [...b].entries())
427
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
428
+ previous = current;
429
+ }
430
+ return previous[b.length] ?? 0;
431
+ }
432
+ function closest(name, names) {
433
+ const started = names.find((known) => known.startsWith(name));
434
+ if (started !== undefined)
435
+ return started;
436
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
437
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
438
+ }
439
+ // ../kit/src/input.ts
440
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
441
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
442
+ function duration(value, name, fallback, unit = "s") {
443
+ if (value === undefined)
444
+ return fallback;
445
+ const match = DURATION.exec(value.trim());
446
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
447
+ if (ms < 1)
448
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
449
+ return ms;
450
+ }
451
+
452
+ // ../kit/src/args.ts
453
+ var DASHES = /^-+/;
454
+ function jsonOption(holds) {
455
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
456
+ }
457
+
458
+ class Exit extends Error {
459
+ code;
460
+ hint;
461
+ constructor(message, code, hint) {
462
+ super(message);
463
+ this.code = code;
464
+ this.hint = hint;
465
+ }
466
+ }
467
+ function fail(message, code = 2, hint) {
468
+ throw new Exit(message, code, hint);
469
+ }
470
+
471
+ class UsageError extends Exit {
472
+ constructor(message, hint) {
473
+ super(message, 2, hint);
474
+ }
475
+ }
476
+ function badUsage(message) {
477
+ throw new UsageError(message);
478
+ }
479
+
480
+ class HelpShown extends Exit {
481
+ constructor() {
482
+ super("help shown", 0);
483
+ }
484
+ }
485
+
486
+ class Completing {
487
+ options;
488
+ positionals;
489
+ candidates;
490
+ constructor(options, positionals = [], candidates = {}) {
491
+ this.options = options;
492
+ this.positionals = positionals;
493
+ this.candidates = candidates;
494
+ }
495
+ }
496
+ var completion = { active: false };
497
+ var OUTPUT_OPTIONS = {
498
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
499
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
500
+ };
501
+ function applyOutput(color, plain, env = process4.env) {
502
+ const when = plain === true ? "never" : color ?? "auto";
503
+ if (when === "auto")
504
+ return;
505
+ if (when !== "always" && when !== "never")
506
+ badUsage(`--color takes auto, always or never, not ${when}`);
507
+ if (when === "always") {
508
+ env.FORCE_COLOR = "1";
509
+ delete env.NO_COLOR;
510
+ } else {
511
+ env.NO_COLOR = "1";
512
+ delete env.FORCE_COLOR;
513
+ }
514
+ }
515
+ function parse(args, usage, options, settings = {}) {
516
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
517
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
518
+ const listing = listed(all, settings.allowNegative === true);
519
+ if (completion.active)
520
+ throw new Completing(listing, settings.positionals, settings.candidates);
521
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
522
+ let parsed;
523
+ try {
524
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
525
+ } catch (error) {
526
+ const message = parseError(error);
527
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
528
+ }
529
+ const values = parsed.values;
530
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
531
+ if (values.help === true) {
532
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
533
+ throw new HelpShown;
534
+ }
535
+ checkChoices(parsed.values, all);
536
+ checkConflicts(parsed.values, all);
537
+ if (settings.positionals !== undefined)
538
+ checkPositionals(parsed.positionals, settings.positionals);
539
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
540
+ }
541
+ function splitRest(args, passes) {
542
+ const separator = passes ? args.indexOf("--") : -1;
543
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
544
+ }
545
+ function splitTrailing(args, options, count) {
546
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
547
+ let seen = 0;
548
+ if (count === 0)
549
+ return { own: args, rest: undefined };
550
+ for (let at = 0;at < args.length; at++) {
551
+ const word = args[at];
552
+ if (word === "--")
553
+ break;
554
+ if (word.startsWith("-")) {
555
+ if (takesValue(word))
556
+ at++;
557
+ continue;
558
+ }
559
+ seen++;
560
+ if (seen === count)
561
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
562
+ }
563
+ return { own: args, rest: undefined };
564
+ }
565
+ function listed(options, allowNegative) {
566
+ if (!allowNegative)
567
+ return options;
568
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
569
+ if (option.type !== "boolean" || option.negative === undefined)
570
+ return [[name, option]];
571
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
572
+ }));
573
+ }
574
+ function withBare(args, options) {
575
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
576
+ if (bare.size === 0)
577
+ return args;
578
+ const separator = args.indexOf("--");
579
+ const own = separator === -1 ? args : args.slice(0, separator);
580
+ return [...own.flatMap((arg, index) => {
581
+ const optional = bare.get(arg);
582
+ const next = own[index + 1];
583
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
584
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
585
+ }), ...separator === -1 ? [] : args.slice(separator)];
586
+ }
587
+ function checkConflicts(values, options) {
588
+ const given = (name) => values[name] !== undefined && values[name] !== false;
589
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
590
+ const other = given(name) ? conflicts.find(given) : undefined;
591
+ if (other !== undefined)
592
+ badUsage(`--${name} cannot be used with --${other}`);
593
+ }
594
+ }
595
+ function checkChoices(values, options) {
596
+ for (const [name, option] of Object.entries(options)) {
597
+ if (option.choices === undefined)
598
+ continue;
599
+ const given = values[name];
600
+ for (const value of Array.isArray(given) ? given : [given]) {
601
+ if (typeof value === "string")
602
+ oneOf(value, name, option.choices);
603
+ }
604
+ }
605
+ }
606
+ function oneOf(value, name, choices) {
607
+ if (!choices.includes(value))
608
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
609
+ return value;
610
+ }
611
+ function checkPositionals(given, names) {
612
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
613
+ const required = names.filter((name) => !name.startsWith("[")).length;
614
+ if (given.length < required)
615
+ badUsage(`missing ${names[given.length]}`);
616
+ if (!variadic && given.length > names.length)
617
+ badUsage(`unexpected argument ${given[names.length]}`);
618
+ }
619
+ function joinDashValues(args, options) {
620
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
621
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
622
+ const joined = [];
623
+ for (let i = 0;i < args.length; i++) {
624
+ const arg = args[i] ?? "";
625
+ if (arg === "--")
626
+ return [...joined, ...args.slice(i)];
627
+ const name = longOf.get(arg);
628
+ const next = args[i + 1];
629
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
630
+ joined.push(`--${name}=${next}`);
631
+ i++;
632
+ } else {
633
+ joined.push(arg);
634
+ }
635
+ }
636
+ return joined;
637
+ }
638
+ function parseError(error) {
639
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
640
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
641
+ }
642
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
643
+ function nearestOption(message, options, allowNegative) {
644
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
645
+ if (typed === undefined)
646
+ return;
647
+ const word = typed.replace(DASHES, "");
648
+ if (word.length < 2 && !typed.startsWith("--"))
649
+ return;
650
+ const known = Object.entries(options).flatMap(([name, option]) => [
651
+ ...option.short === undefined ? [] : [`-${option.short}`],
652
+ `--${name}`,
653
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
654
+ ]);
655
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
656
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
657
+ }
658
+ // ../kit/src/process.ts
659
+ import { constants } from "os";
660
+ import process5 from "process";
661
+ var KILL_GRACE_MS = 2000;
662
+ function exitCodeOf(code, signal) {
663
+ if (code !== null)
664
+ return code;
665
+ if (typeof signal === "number")
666
+ return 128 + signal;
667
+ return signal === null ? 129 : 128 + constants.signals[signal];
668
+ }
669
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
670
+ const chunks = [];
671
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
672
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
673
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
674
+ const timers = [];
675
+ const killGroup = (killing) => {
676
+ if (state.done)
677
+ return;
678
+ try {
679
+ if (grouped)
680
+ process5.kill(-proc.pid, killing);
681
+ else
682
+ proc.kill(killing);
683
+ } catch {}
684
+ };
685
+ const stop = () => {
686
+ killGroup("SIGTERM");
687
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
688
+ };
689
+ const onAbort = () => stop();
690
+ if (timeoutMs !== undefined) {
691
+ timers.push(setTimeout(() => {
692
+ state.timedOut = true;
693
+ stop();
694
+ }, timeoutMs));
695
+ }
696
+ if (signal?.aborted === true)
697
+ onAbort();
698
+ else
699
+ signal?.addEventListener("abort", onAbort, { once: true });
700
+ onStart?.({ kill: (killing) => killGroup(killing) });
701
+ const drain = async (stream, name) => {
702
+ for await (const data of stream) {
703
+ if (state.failure !== undefined)
704
+ continue;
705
+ try {
706
+ onChunk?.({ stream: name, data });
707
+ } catch (error) {
708
+ state.failure = error;
709
+ stop();
710
+ continue;
711
+ }
712
+ if (state.kept + data.length > maxBytes) {
713
+ state.truncated = true;
714
+ continue;
715
+ }
716
+ state.kept += data.length;
717
+ chunks.push({ stream: name, data });
718
+ }
719
+ };
720
+ try {
721
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
722
+ await proc.exited;
723
+ } finally {
724
+ state.done = true;
725
+ for (const timer of timers)
726
+ clearTimeout(timer);
727
+ signal?.removeEventListener("abort", onAbort);
728
+ }
729
+ if (state.failure !== undefined)
730
+ throw state.failure;
731
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
732
+ let output;
733
+ let text;
734
+ return {
735
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
736
+ chunks,
737
+ timedOut: state.timedOut,
738
+ truncated: state.truncated,
739
+ get output() {
740
+ return output ??= joined();
741
+ },
742
+ get text() {
743
+ return text ??= (output ??= joined()).toString();
744
+ }
745
+ };
746
+ }
747
+
748
+ // ../kit/src/progress.ts
749
+ var ESC = String.fromCharCode(27);
750
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
751
+ var RESET_STYLE = `${ESC}[0m`;
752
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
753
+ // ../kit/src/cli.ts
754
+ import process7 from "process";
755
+
756
+ // ../kit/src/usage.ts
757
+ import { appendFileSync, mkdirSync } from "fs";
758
+ import { homedir } from "os";
759
+ import { dirname, isAbsolute, join } from "path";
760
+ import process6 from "process";
761
+
762
+ // ../kit/src/logs.ts
763
+ var DAY_MS = 24 * 60 * 60 * 1000;
764
+ var CLI_FOLDER = "kaynooo-cli";
765
+
766
+ // ../kit/src/usage.ts
767
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
768
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
769
+ var LONGEST_NAME = 40;
770
+ var usageError;
771
+ function noteUsageError(message) {
772
+ usageError = message;
773
+ }
774
+ function stateHome(env = process6.env) {
775
+ const dir = env.XDG_STATE_HOME;
776
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
777
+ }
778
+ function usagePath(env = process6.env) {
779
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
780
+ }
781
+ function usageRecorded(env = process6.env) {
782
+ const off = env.KAYNOOO_CLI_NO_USAGE;
783
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
784
+ }
785
+ function flagNames(argv) {
786
+ const end = argv.indexOf("--");
787
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
788
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
789
+ }
790
+ function usageEntry(bin, command, argv, code, now = new Date) {
791
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
792
+ usageError = undefined;
793
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
794
+ }
795
+ function recordUsage(entry, env = process6.env) {
796
+ if (!usageRecorded(env))
797
+ return;
798
+ try {
799
+ const path = usagePath(env);
800
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
801
+ appendFileSync(path, `${JSON.stringify(entry)}
802
+ `, { mode: 384 });
803
+ } catch {}
804
+ }
805
+
806
+ // ../kit/src/cli.ts
807
+ var LEVEL_OPTIONS = {
808
+ ...OUTPUT_OPTIONS,
809
+ help: { type: "boolean", short: "h", description: "show this help" }
810
+ };
811
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
812
+ function printError(prefix, message, hint, cause) {
813
+ const colors = paint(process7.stderr);
814
+ const styled = takesControlCodes(process7.stderr);
815
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
816
+ const under = (label, text, tint) => text === undefined ? "" : `
817
+ ${styled ? tint(label) : `${label}:`} ${text}`;
818
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
819
+ }
820
+ function printJsonError(message, hint, cause) {
821
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
822
+ }
823
+ function wantsJson(argv) {
824
+ const end = argv.indexOf("--");
825
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
826
+ }
827
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
828
+ if (error instanceof HelpShown)
829
+ return 0;
830
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
831
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
832
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
833
+ if (error instanceof UsageError)
834
+ noteUsageError(error.message);
835
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
836
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
837
+ return error instanceof Exit ? error.code : 1;
838
+ }
839
+ var COMPLETE = "__complete";
840
+ var FILES = "__files__";
841
+ async function completingOf(run) {
842
+ completion.active = true;
843
+ try {
844
+ await run([]);
845
+ } catch (error) {
846
+ if (error instanceof Completing)
847
+ return error;
848
+ } finally {
849
+ completion.active = false;
850
+ }
851
+ return new Completing({});
852
+ }
853
+ function candidateLine(candidate) {
854
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
855
+ }
856
+ function positionalBeingTyped(before, { options, positionals }) {
857
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
858
+ let index = 0;
859
+ let at = 0;
860
+ while (at < before.length) {
861
+ const word = before[at];
862
+ if (word === "--") {
863
+ index += before.length - at - 1;
864
+ break;
865
+ }
866
+ if (!word.startsWith("-"))
867
+ index++;
868
+ else if (takesValue(word))
869
+ at++;
870
+ at++;
871
+ }
872
+ const last = positionals.at(-1);
873
+ if (index < positionals.length)
874
+ return positionals[index];
875
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
876
+ }
877
+ async function leafCandidates(run, words) {
878
+ const completing = await completingOf(run);
879
+ if ((words.at(-1) ?? "").startsWith("-"))
880
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
881
+ const flag = words.at(-2);
882
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
883
+ if (option?.type === "string") {
884
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
885
+ return values === undefined ? [FILES] : values.map(candidateLine);
886
+ }
887
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
888
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
889
+ return values === undefined ? [FILES] : values.map(candidateLine);
890
+ }
891
+ async function printCandidates(found) {
892
+ for (const line of await found)
893
+ console.log(line);
894
+ return 0;
895
+ }
896
+ async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
897
+ if (argv[0] === COMPLETE)
898
+ return printCandidates(leafCandidates(run, argv.slice(1)));
899
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
900
+ console.log(version);
901
+ return 0;
902
+ }
903
+ let code;
904
+ try {
905
+ code = await run(argv);
906
+ } catch (error) {
907
+ code = reportThrown(name, error, redact, wantsJson(argv));
908
+ }
909
+ if (usage !== false)
910
+ recordUsage(usageEntry(name, undefined, argv, code));
911
+ return code;
912
+ }
913
+ // ../kit/src/secrets.ts
914
+ var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
915
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
916
+ var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
917
+ function isSecretName(name) {
918
+ return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
919
+ }
920
+ // ../kit/src/sessions.ts
921
+ var {Glob } = globalThis.Bun;
922
+ var SESSION_FILES = new Glob("*.json");
923
+ var ACCOUNT_DIRS = new Glob("*/sessions");
924
+ // package.json
925
+ var version = "0.1.0";
926
+
927
+ // src/pid.ts
928
+ import process9 from "process";
929
+
930
+ // src/mask.ts
931
+ var MASK = "***";
932
+ var URL_PASSWORD = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi;
933
+ var TOKEN = /\b(?:gh[pousr]_|github_pat_|glpat-|sk-|xox[abprs]-|npm_|[sr]k_(?:live|test)_)[\w-]{10,}|\beyJ[\w-]+\.[\w-]+\.[\w-]+|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bBearer\s+[\w.~+/=-]{16,}/g;
934
+ var OPAQUE = /(?<![\w-])(?=[\w-]{32,}(?![\w-]))(?=[\w-]*[A-Z])(?=[\w-]*\d)[\w-]+/gi;
935
+ var PEM = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*/;
936
+ function maskText(value) {
937
+ return value.replace(PEM, MASK).replace(URL_PASSWORD, `$1${MASK}@`).replace(TOKEN, MASK).replace(OPAQUE, MASK);
938
+ }
939
+ function maskValue(name, value) {
940
+ if (value === "")
941
+ return value;
942
+ return isSecretName(name) ? MASK : maskText(value);
943
+ }
944
+ function maskEnviron(entries) {
945
+ return entries.map(([name, value]) => [name, maskValue(name, value)]);
946
+ }
947
+ var FLAG = /^-{1,2}([\w.-]+)(=|$)/;
948
+ var ASSIGNMENT_NAME = /^[\w.-]+$/;
949
+ function maskArgs(args) {
950
+ let hidden = false;
951
+ return args.map((arg) => {
952
+ if (hidden) {
953
+ hidden = false;
954
+ return arg.startsWith("-") ? maskText(arg) : MASK;
955
+ }
956
+ const flag = FLAG.exec(arg);
957
+ if (flag !== null) {
958
+ if (flag[2] === "=")
959
+ return isSecretName(flag[1]) ? `${arg.slice(0, flag[0].length)}${MASK}` : maskText(arg);
960
+ hidden = isSecretName(flag[1]);
961
+ return arg;
962
+ }
963
+ const equals = arg.indexOf("=");
964
+ return equals > 0 && ASSIGNMENT_NAME.test(arg.slice(0, equals)) ? `${arg.slice(0, equals + 1)}${maskValue(arg.slice(0, equals), arg.slice(equals + 1))}` : maskText(arg);
965
+ });
966
+ }
967
+
968
+ // src/parse.ts
969
+ var LISTENING = { tcp: "0A", udp: "07" };
970
+ var WHITESPACE = /\s+/;
971
+ var HEX_PAIR = /../g;
972
+ var SOCKET_LINK = /^socket:\[(\d+)\]$/;
973
+ var UNIT_SCOPE = /\.(?:service|scope)$/;
974
+ var CONTAINER_ID = /(?:docker-|libpod-|\/docker\/)([0-9a-f]{64})/;
975
+ var DOCKER_PORT = /:(\d+)(?:-(\d+))?->[\d-]+\/(tcp|udp)/;
976
+ function word(hex) {
977
+ const bytes = (hex.match(HEX_PAIR) ?? []).reverse().map((byte) => Number.parseInt(byte, 16));
978
+ return [bytes[0] << 8 | bytes[1], bytes[2] << 8 | bytes[3]];
979
+ }
980
+ function parseAddress(hex) {
981
+ if (hex.length === 8) {
982
+ const [high, low] = word(hex);
983
+ return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
984
+ }
985
+ const hextets = (hex.match(/.{8}/g) ?? []).flatMap(word);
986
+ if (hextets.length !== 8)
987
+ return hex;
988
+ if (hextets.slice(0, 5).every((part) => part === 0) && hextets[5] === 65535)
989
+ return `::ffff:${hextets[6] >> 8}.${hextets[6] & 255}.${hextets[7] >> 8}.${hextets[7] & 255}`;
990
+ return compress(hextets);
991
+ }
992
+ function compress(hextets) {
993
+ let best = { start: -1, length: 0 };
994
+ let run = { start: 0, length: 0 };
995
+ for (const [at, part] of hextets.entries()) {
996
+ run = part === 0 ? { start: run.length === 0 ? at : run.start, length: run.length + 1 } : { start: 0, length: 0 };
997
+ if (run.length > best.length)
998
+ best = run;
999
+ }
1000
+ const text = (parts) => parts.map((part) => part.toString(16)).join(":");
1001
+ if (best.length < 2)
1002
+ return text(hextets);
1003
+ return `${text(hextets.slice(0, best.start))}::${text(hextets.slice(best.start + best.length))}`;
1004
+ }
1005
+ function parseNetTable(text, protocol, family) {
1006
+ const sockets = [];
1007
+ for (const line of text.split(`
1008
+ `).slice(1)) {
1009
+ const columns = line.trim().split(WHITESPACE);
1010
+ const [address = "", port = ""] = (columns[1] ?? "").split(":");
1011
+ if (columns.length < 10 || columns[3] !== LISTENING[protocol])
1012
+ continue;
1013
+ const number = Number.parseInt(port, 16);
1014
+ if (number === 0 || Number.isNaN(number))
1015
+ continue;
1016
+ sockets.push({ protocol, family, address: parseAddress(address), port: number, uid: Number(columns[7]), inode: Number(columns[9]) });
1017
+ }
1018
+ return sockets;
1019
+ }
1020
+ function socketInode(link) {
1021
+ const match = SOCKET_LINK.exec(link);
1022
+ return match === null ? undefined : Number(match[1]);
1023
+ }
1024
+ function parseStat(text) {
1025
+ const open = text.indexOf("(");
1026
+ const close = text.lastIndexOf(")");
1027
+ if (open === -1 || close < open)
1028
+ return;
1029
+ const rest = text.slice(close + 2).trim().split(WHITESPACE);
1030
+ const field = (number) => Number(rest[number - 3]);
1031
+ if (rest.length < 20)
1032
+ return;
1033
+ return { comm: text.slice(open + 1, close), state: rest[0], ppid: field(4), pgrp: field(5), session: field(6), tty: field(7), threads: field(20), startTicks: field(22) };
1034
+ }
1035
+ function parseStatus(text) {
1036
+ const fields = new Map;
1037
+ for (const line of text.split(`
1038
+ `)) {
1039
+ const colon = line.indexOf(":");
1040
+ if (colon > 0)
1041
+ fields.set(line.slice(0, colon), line.slice(colon + 1).trim());
1042
+ }
1043
+ return fields;
1044
+ }
1045
+ function statusBytes(fields, key) {
1046
+ const value = Number.parseInt(fields.get(key) ?? "", 10);
1047
+ return Number.isNaN(value) ? undefined : value * 1024;
1048
+ }
1049
+ function statusUid(fields) {
1050
+ const value = Number.parseInt(fields.get("Uid") ?? "", 10);
1051
+ return Number.isNaN(value) ? undefined : value;
1052
+ }
1053
+ var LIMIT_LINE = /^(\S+(?: \S+)*)\s{2,}(\S+)\s+(\S+)(?:\s+(\S+))?\s*$/;
1054
+ function parseLimits(text) {
1055
+ const limits = [];
1056
+ for (const line of text.split(`
1057
+ `).slice(1)) {
1058
+ const match = LIMIT_LINE.exec(line);
1059
+ if (match !== null)
1060
+ limits.push({ name: match[1], soft: match[2], hard: match[3], units: match[4] ?? "" });
1061
+ }
1062
+ return limits;
1063
+ }
1064
+ function parseCmdline(text) {
1065
+ return text.split("\x00").filter((_, at, parts) => at < parts.length - 1 || parts[at] !== "");
1066
+ }
1067
+ function parseEnviron(text) {
1068
+ return parseCmdline(text).map((entry) => {
1069
+ const equals = entry.indexOf("=");
1070
+ return equals === -1 ? [entry, ""] : [entry.slice(0, equals), entry.slice(equals + 1)];
1071
+ });
1072
+ }
1073
+ function parseCgroup(text) {
1074
+ return text.split(`
1075
+ `).filter((line) => line !== "").map((line) => {
1076
+ const [hierarchy = "", controllers = "", ...path] = line.split(":");
1077
+ return { hierarchy, controllers, path: path.join(":") };
1078
+ });
1079
+ }
1080
+ function cgroupUnit(entries) {
1081
+ const path = (entries.find((entry) => entry.hierarchy === "0") ?? entries[0])?.path ?? "";
1082
+ return path.split("/").reverse().find((part) => UNIT_SCOPE.test(part));
1083
+ }
1084
+ function cgroupContainer(entries) {
1085
+ for (const { path } of entries) {
1086
+ const match = CONTAINER_ID.exec(path);
1087
+ if (match !== null)
1088
+ return match[1];
1089
+ }
1090
+ return;
1091
+ }
1092
+ var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
1093
+ var SIZE_UNITS = { "": 1024 ** 2, k: 1024, m: 1024 ** 2, g: 1024 ** 3, t: 1024 ** 4 };
1094
+ function parseSize(text) {
1095
+ const match = SIZE.exec(text.trim());
1096
+ return match === null ? undefined : Math.round(Number(match[1]) * SIZE_UNITS[match[2].toLowerCase()]);
1097
+ }
1098
+ function userNameOf(passwd, uid) {
1099
+ for (const line of passwd.split(`
1100
+ `)) {
1101
+ const [name, , id] = line.split(":");
1102
+ if (id === String(uid) && name !== undefined && name !== "")
1103
+ return name;
1104
+ }
1105
+ return;
1106
+ }
1107
+ function parseDockerPs(text) {
1108
+ const containers = [];
1109
+ for (const line of text.split(`
1110
+ `)) {
1111
+ const [name = "", ports = "", project = "", service = ""] = line.split("\t");
1112
+ if (name === "")
1113
+ continue;
1114
+ const published = [];
1115
+ for (const entry of ports.split(",")) {
1116
+ const match = DOCKER_PORT.exec(entry);
1117
+ if (match === null)
1118
+ continue;
1119
+ const first = Number(match[1]);
1120
+ for (let host = first;host <= Number(match[2] ?? first); host++)
1121
+ published.push({ host, protocol: match[3] });
1122
+ }
1123
+ containers.push({ name, project: project === "" ? undefined : project, service: service === "" ? undefined : service, published });
1124
+ }
1125
+ return containers;
1126
+ }
1127
+
1128
+ // src/read.ts
1129
+ import { readdir, readFile, readlink } from "fs/promises";
1130
+ var CLOCK_TICKS = 100;
1131
+ async function text2(path) {
1132
+ try {
1133
+ return await readFile(path, "utf8");
1134
+ } catch {
1135
+ return;
1136
+ }
1137
+ }
1138
+ async function link(path) {
1139
+ try {
1140
+ return await readlink(path);
1141
+ } catch {
1142
+ return;
1143
+ }
1144
+ }
1145
+ var DIGITS = /^\d+$/;
1146
+ var BOOT_TIME = /^btime\s+(\d+)/m;
1147
+ async function listPids(root = "/proc") {
1148
+ return (await readdir(root)).filter((name) => DIGITS.test(name)).map(Number);
1149
+ }
1150
+ async function bootMs(root = "/proc") {
1151
+ const match = BOOT_TIME.exec(await text2(`${root}/stat`) ?? "");
1152
+ return match === null ? Date.now() : Number(match[1]) * 1000;
1153
+ }
1154
+ async function readProc(pid, boot, { root = "/proc", detail = true } = {}) {
1155
+ const dir = `${root}/${pid}`;
1156
+ const [statText, statusText, cmdline] = await Promise.all([text2(`${dir}/stat`), text2(`${dir}/status`), text2(`${dir}/cmdline`)]);
1157
+ const stat = statText === undefined ? undefined : parseStat(statText);
1158
+ if (stat === undefined || statusText === undefined)
1159
+ return;
1160
+ const status = parseStatus(statusText);
1161
+ const info = {
1162
+ pid,
1163
+ ppid: stat.ppid,
1164
+ comm: stat.comm,
1165
+ args: parseCmdline(cmdline ?? ""),
1166
+ uid: statusUid(status) ?? -1,
1167
+ state: stat.state,
1168
+ session: stat.session,
1169
+ rss: statusBytes(status, "VmRSS") ?? 0,
1170
+ startMs: boot + stat.startTicks / CLOCK_TICKS * 1000
1171
+ };
1172
+ if (!detail)
1173
+ return info;
1174
+ const [cwd, exe, cgroup] = await Promise.all([link(`${dir}/cwd`), link(`${dir}/exe`), text2(`${dir}/cgroup`)]);
1175
+ const groups = parseCgroup(cgroup ?? "");
1176
+ return { ...info, cwd, exe, unit: cgroupUnit(groups), container: cgroupContainer(groups) };
1177
+ }
1178
+ async function snapshot(root = "/proc", detailed = () => true) {
1179
+ const boot = await bootMs(root);
1180
+ const found = [];
1181
+ for (const pid of await listPids(root)) {
1182
+ const light = await readProc(pid, boot, { root, detail: false });
1183
+ if (light === undefined)
1184
+ continue;
1185
+ found.push(detailed(light.uid) ? await readProc(pid, boot, { root }) ?? light : light);
1186
+ }
1187
+ return found;
1188
+ }
1189
+ function ancestry(pid, byPid) {
1190
+ const chain = [];
1191
+ let at = pid;
1192
+ while (at !== undefined && at > 0 && !chain.includes(at)) {
1193
+ chain.push(at);
1194
+ at = byPid.get(at)?.ppid;
1195
+ }
1196
+ return chain;
1197
+ }
1198
+ async function readSockets(root = "/proc") {
1199
+ const tables = [["tcp", "tcp", 4], ["tcp6", "tcp", 6], ["udp", "udp", 4], ["udp6", "udp", 6]];
1200
+ const sockets = [];
1201
+ for (const [file, protocol, family] of tables)
1202
+ sockets.push(...parseNetTable(await text2(`${root}/net/${file}`) ?? "", protocol, family));
1203
+ return sockets;
1204
+ }
1205
+ async function socketsOf(pid, root = "/proc") {
1206
+ const inodes = new Set;
1207
+ try {
1208
+ for (const fd of await readdir(`${root}/${pid}/fd`)) {
1209
+ const inode = socketInode(await link(`${root}/${pid}/fd/${fd}`) ?? "");
1210
+ if (inode !== undefined)
1211
+ inodes.add(inode);
1212
+ }
1213
+ } catch {}
1214
+ return inodes;
1215
+ }
1216
+ async function socketOwners(root = "/proc") {
1217
+ const owners = new Map;
1218
+ for (const pid of await listPids(root)) {
1219
+ for (const inode of await socketsOf(pid, root))
1220
+ owners.set(inode, pid);
1221
+ }
1222
+ return owners;
1223
+ }
1224
+ async function fdCount(pid, root = "/proc") {
1225
+ try {
1226
+ return (await readdir(`${root}/${pid}/fd`)).length;
1227
+ } catch {
1228
+ return;
1229
+ }
1230
+ }
1231
+ var passwd;
1232
+ async function userName(uid) {
1233
+ passwd ??= await text2("/etc/passwd") ?? "";
1234
+ return userNameOf(passwd, uid);
1235
+ }
1236
+
1237
+ // src/pid.ts
1238
+ var usage2 = `pid <pid>
1239
+
1240
+ Shows what a process is: its executable, working directory, command line, parent chain up to init, user, start time and age, memory, open files and limits, the TCP and UDP ports it listens on and its cgroup. Everything is read from /proc; what the calling user cannot read of another user's process is left out and named at the end.
1241
+ The environment is not shown unless --env is given, with every value that looks like a secret masked.
1242
+
1243
+ Exits 0 when it showed the process, 1 when no process has this pid, 2 on a usage error.`;
1244
+ var DIGITS2 = /^\d+$/;
1245
+ var options = {
1246
+ env: { type: "boolean", description: "show the environment, secrets masked" },
1247
+ json: jsonOption("everything, with the environment under env when --env is given")
1248
+ };
1249
+ async function parentsOf(proc, boot) {
1250
+ const parents = [];
1251
+ const seen = new Set([proc.pid]);
1252
+ let at = proc.ppid;
1253
+ while (at > 0 && !seen.has(at)) {
1254
+ seen.add(at);
1255
+ const parent = await readProc(at, boot, { detail: false });
1256
+ if (parent === undefined)
1257
+ break;
1258
+ parents.push({ pid: parent.pid, comm: parent.comm, command: maskArgs(parent.args).join(" ") });
1259
+ at = parent.ppid;
1260
+ }
1261
+ return parents;
1262
+ }
1263
+ async function report(pid, showEnv) {
1264
+ const boot = await bootMs();
1265
+ const proc = await readProc(pid, boot);
1266
+ if (proc === undefined)
1267
+ return;
1268
+ const unreadable = [];
1269
+ const status = parseStatus(await text2(`/proc/${pid}/status`) ?? "");
1270
+ const limitsText = await text2(`/proc/${pid}/limits`);
1271
+ const sockets = await socketsOf(pid);
1272
+ const listening = sockets.size === 0 ? [] : (await readSockets()).filter((socket) => sockets.has(socket.inode));
1273
+ const environText = showEnv ? await text2(`/proc/${pid}/environ`) : undefined;
1274
+ const cgroup = parseCgroup(await text2(`/proc/${pid}/cgroup`) ?? "")[0]?.path;
1275
+ const files = await fdCount(pid);
1276
+ const stat = parseStat(await text2(`/proc/${pid}/stat`) ?? "");
1277
+ const uid = proc.uid;
1278
+ if (proc.exe === undefined)
1279
+ unreadable.push("executable");
1280
+ if (proc.cwd === undefined)
1281
+ unreadable.push("working directory");
1282
+ if (files === undefined)
1283
+ unreadable.push("open files");
1284
+ if (limitsText === undefined)
1285
+ unreadable.push("limits");
1286
+ if (showEnv && environText === undefined)
1287
+ unreadable.push("environment");
1288
+ return {
1289
+ pid,
1290
+ comm: proc.comm,
1291
+ state: proc.state,
1292
+ exe: proc.exe,
1293
+ cwd: proc.cwd,
1294
+ command: maskArgs(proc.args),
1295
+ parents: await parentsOf(proc, boot),
1296
+ user: { uid, name: await userName(uid) },
1297
+ startedAt: new Date(proc.startMs).toISOString(),
1298
+ ageSeconds: Math.max(0, (Date.now() - proc.startMs) / 1000),
1299
+ threads: stat?.threads,
1300
+ memory: { rss: statusBytes(status, "VmRSS"), peak: statusBytes(status, "VmHWM"), virtual: statusBytes(status, "VmSize"), swap: statusBytes(status, "VmSwap") },
1301
+ openFiles: files,
1302
+ limits: parseLimits(limitsText ?? ""),
1303
+ listening: listening.map(({ protocol, address, port }) => ({ protocol, address, port })),
1304
+ cgroup: cgroup === "" ? undefined : cgroup,
1305
+ container: proc.container,
1306
+ env: environText === undefined ? undefined : maskEnviron(parseEnviron(environText)).map(([name, value]) => ({ name, value })),
1307
+ unreadable
1308
+ };
1309
+ }
1310
+ function limitLine(limits, name) {
1311
+ const limit = limits.find((candidate) => candidate.name === name);
1312
+ return limit === undefined ? "-" : `soft ${limit.soft}, hard ${limit.hard}`;
1313
+ }
1314
+ function render(info, showEnv) {
1315
+ const colors = paint(process9.stdout);
1316
+ const memory = info.memory;
1317
+ const size = (bytes) => bytes === undefined ? "-" : $e(bytes);
1318
+ const rows = [
1319
+ ["Executable", info.exe ?? "-"],
1320
+ ["Directory", info.cwd ?? "-"],
1321
+ ["Command", info.command.join(" ") || `[${info.comm}]`],
1322
+ ["Parents", info.parents.length === 0 ? "none (init)" : info.parents.map((parent) => `${parent.pid} ${parent.comm}`).join(" < ")],
1323
+ ["User", `${info.user.name ?? "?"} (${info.user.uid})`],
1324
+ ["State", info.state],
1325
+ ["Started", `${info.startedAt} (${formatSeconds(info.ageSeconds)} ago)`],
1326
+ ["Memory", `rss ${size(memory.rss)}, peak ${size(memory.peak)}, virtual ${size(memory.virtual)}, swap ${size(memory.swap)}`],
1327
+ ["Open files", `${info.openFiles ?? "-"} (limit ${limitLine(info.limits, "Max open files")})`],
1328
+ ["Processes", `${info.threads ?? "-"} threads (limit ${limitLine(info.limits, "Max processes")})`],
1329
+ ["Listening", info.listening.length === 0 ? "nothing" : info.listening.map(({ protocol, address, port }) => `${protocol} ${address.includes(":") ? `[${address}]` : address}:${port}`).join(", ")]
1330
+ ];
1331
+ if (info.cgroup !== undefined)
1332
+ rows.push(["Cgroup", info.cgroup]);
1333
+ const lines = [colors.bold(`pid ${info.pid} ${info.comm}`), ...rows.map(([label, value]) => `${colors.dim(label.padEnd(11))} ${value}`)];
1334
+ if (showEnv && info.env !== undefined)
1335
+ lines.push("", colors.bold("Environment"), ...info.env.map(({ name, value }) => `${name}=${value}`));
1336
+ else if (!showEnv)
1337
+ lines.push("", colors.dim("Environment hidden, pass --env to show it with secrets masked"));
1338
+ if (info.unreadable.length > 0)
1339
+ lines.push("", colors.yellow(`Could not read: ${info.unreadable.join(", ")} (a process of another user: rerun as that user)`));
1340
+ return lines.join(`
1341
+ `);
1342
+ }
1343
+ async function pid(args) {
1344
+ const { values, positionals } = parse(args, usage2, options, {
1345
+ positionals: ["<pid>"],
1346
+ replaces: "cat /proc/<pid>/{cmdline,environ,limits}, readlink /proc/<pid>/{exe,cwd}, the fish pid function",
1347
+ examples: [
1348
+ ["pid 4242", "executable, directory, command, parents, memory, limits and ports"],
1349
+ ["pid 4242 --env", "with the environment, secrets masked"],
1350
+ "pid 4242 --json"
1351
+ ]
1352
+ });
1353
+ const [given] = positionals;
1354
+ if (!DIGITS2.test(given))
1355
+ fail(`the pid takes a number, not ${given}`, 2);
1356
+ const info = await report(Number(given), values.env === true);
1357
+ if (info === undefined)
1358
+ return fail(`no process with pid ${given}`, 1);
1359
+ if (values.json === true)
1360
+ printJson(info);
1361
+ else
1362
+ console.log(render(info, values.env === true));
1363
+ return 0;
1364
+ }
1365
+
1366
+ // src/pid-cli.ts
1367
+ process10.exitCode = await runMain({ name: "pid", version, run: pid });