@kaynooo/cli-proc 0.0.0-stage → 0.2.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,1571 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/ports-cli.ts
5
+ import process12 from "process";
6
+ // ../kit/src/args.ts
7
+ import process5 from "process";
8
+ import { parseArgs } from "util";
9
+
10
+ // ../kit/src/format.ts
11
+ import process3 from "process";
12
+
13
+ // ../kit/src/style.ts
14
+ import process2 from "process";
15
+
16
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
+ function x(s) {
18
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
19
+ if (!/^[a-f0-9]+$/.test(r))
20
+ return [0, 0, 0];
21
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
22
+ if (t === 3 || t === 4) {
23
+ 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;
24
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
25
+ }
26
+ if (t !== 6 && t !== 8)
27
+ throw Error(`Invalid hex color length: ${t}`);
28
+ 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;
29
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
30
+ throw Error(`Invalid hex color value: ${s}`);
31
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
32
+ }
33
+ function A(s) {
34
+ let [r, t, n, a] = s;
35
+ if (a)
36
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
37
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
38
+ }
39
+ function R(s, r, t) {
40
+ s = (s % 360 + 360) % 360, t /= 100;
41
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
42
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
43
+ return Math.round(255 * y);
44
+ };
45
+ return [a(0), a(8), a(4)];
46
+ }
47
+ function k(s) {
48
+ let [r, t, n] = s;
49
+ r /= 255, t /= 255, n /= 255;
50
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
51
+ if (a !== b) {
52
+ let u = a - b;
53
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
54
+ o = (t - n) / u + (t < n ? 6 : 0);
55
+ else if (a === t)
56
+ o = (n - r) / u + 2;
57
+ else
58
+ o = (r - t) / u + 4;
59
+ o /= 6;
60
+ }
61
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
62
+ }
63
+ function H(s, r, t) {
64
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
65
+ let n = (a) => {
66
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
67
+ return Math.round(255 * o);
68
+ };
69
+ return [n(5), n(3), n(1)];
70
+ }
71
+ function f(s) {
72
+ let [r, t, n] = s;
73
+ r /= 255, t /= 255, n /= 255;
74
+ 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;
75
+ if (o !== 0) {
76
+ if (a === r)
77
+ y = (t - n) / o + (t < n ? 6 : 0);
78
+ else if (a === t)
79
+ y = (n - r) / o + 2;
80
+ else
81
+ y = (r - t) / o + 4;
82
+ y /= 6;
83
+ }
84
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
85
+ }
86
+ function O(s) {
87
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
88
+ if (a === 1)
89
+ return [0, 0, 0, 100];
90
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
91
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
92
+ }
93
+ function v(s, r, t, n) {
94
+ 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))];
95
+ }
96
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
97
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
98
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
99
+ function T(s) {
100
+ 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);
101
+ 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)];
102
+ }
103
+ function M(s, r, t) {
104
+ 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)));
105
+ return [u(o), u(y), u(c)];
106
+ }
107
+ function d(s) {
108
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
109
+ return [i(r, 4), i(a, 4), i(b, 2)];
110
+ }
111
+ function C(s, r, t) {
112
+ let n = t * Math.PI / 180;
113
+ return M(s, r * Math.cos(n), r * Math.sin(n));
114
+ }
115
+ function l(s) {
116
+ let r = s / 255;
117
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
118
+ }
119
+
120
+ class e {
121
+ r;
122
+ g;
123
+ b;
124
+ a;
125
+ constructor(s, r, t, n = 1) {
126
+ this.r = s, this.g = r, this.b = t, this.a = n;
127
+ }
128
+ static from(s, r) {
129
+ if (s === "hex") {
130
+ let [t, n, a, b] = x(r);
131
+ return new e(t, n, a, b);
132
+ }
133
+ if (s === "rgb") {
134
+ if (Array.isArray(r)) {
135
+ let [o, y, c, u] = r;
136
+ return new e(o, y, c, u);
137
+ }
138
+ let { r: t, g: n, b: a, a: b } = r;
139
+ return new e(t, n, a, b);
140
+ }
141
+ if (s === "hsl") {
142
+ let t, n, a, b;
143
+ if (Array.isArray(r))
144
+ [t, n, a, b] = r;
145
+ else
146
+ ({ h: t, s: n, l: a, a: b } = r);
147
+ let [o, y, c] = R(t, n, a);
148
+ return new e(o, y, c, b);
149
+ }
150
+ if (s === "hsv") {
151
+ let t, n, a, b;
152
+ if (Array.isArray(r))
153
+ [t, n, a, b] = r;
154
+ else
155
+ ({ h: t, s: n, v: a, a: b } = r);
156
+ let [o, y, c] = H(t, n, a);
157
+ return new e(o, y, c, b);
158
+ }
159
+ if (s === "cmyk") {
160
+ let t, n, a, b, o;
161
+ if (Array.isArray(r))
162
+ [t, n, a, b, o] = r;
163
+ else
164
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
165
+ let [y, c, u] = v(t, n, a, b);
166
+ return new e(y, c, u, o);
167
+ }
168
+ if (s === "oklch") {
169
+ let t, n, a, b;
170
+ if (Array.isArray(r))
171
+ [t, n, a, b] = r;
172
+ else
173
+ ({ l: t, c: n, h: a, a: b } = r);
174
+ let [o, y, c] = C(t, n, a);
175
+ return new e(o, y, c, b);
176
+ }
177
+ if (s === "oklab") {
178
+ let t, n, a, b;
179
+ if (Array.isArray(r))
180
+ [t, n, a, b] = r;
181
+ else
182
+ ({ l: t, a: n, b: a, alpha: b } = r);
183
+ let [o, y, c] = M(t, n, a);
184
+ return new e(o, y, c, b);
185
+ }
186
+ throw Error("Invalid input");
187
+ }
188
+ to(s) {
189
+ switch (s) {
190
+ case "rgb":
191
+ return [this.r, this.g, this.b];
192
+ case "rgba":
193
+ return [this.r, this.g, this.b, this.a];
194
+ case "hex":
195
+ return A([this.r, this.g, this.b]);
196
+ case "hexa":
197
+ return A([this.r, this.g, this.b, this.a]);
198
+ case "hsl":
199
+ return k([this.r, this.g, this.b]);
200
+ case "hsla":
201
+ return [...k([this.r, this.g, this.b]), this.a];
202
+ case "hsv":
203
+ return f([this.r, this.g, this.b]);
204
+ case "hsva":
205
+ return [...f([this.r, this.g, this.b]), this.a];
206
+ case "cmyk":
207
+ return O([this.r, this.g, this.b]);
208
+ case "cmyka":
209
+ return [...O([this.r, this.g, this.b]), this.a];
210
+ case "oklch":
211
+ return d([this.r, this.g, this.b]);
212
+ case "oklcha":
213
+ return [...d([this.r, this.g, this.b]), this.a];
214
+ case "oklab":
215
+ return T([this.r, this.g, this.b]);
216
+ case "oklaba":
217
+ return [...T([this.r, this.g, this.b]), this.a];
218
+ default:
219
+ return [this.r, this.g, this.b];
220
+ }
221
+ }
222
+ getLuminance() {
223
+ let s = l(this.r), r = l(this.g), t = l(this.b);
224
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
225
+ }
226
+ contrastRatio(s) {
227
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
228
+ return (n + 0.05) / (a + 0.05);
229
+ }
230
+ bestContrastForeground() {
231
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
232
+ return t >= n ? s : r;
233
+ }
234
+ }
235
+
236
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
237
+ var r = 39;
238
+ var o = 49;
239
+ var f2 = "\x1B[";
240
+ 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") => {
241
+ let [a, l, s] = e.from("hex", i).to("rgb");
242
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
243
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
244
+ var b = new Set(["", "1", "2", "3", "true"]);
245
+ function h(i, n = globalThis.process?.env ?? {}) {
246
+ if (n.FORCE_COLOR !== undefined)
247
+ return b.has(n.FORCE_COLOR);
248
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
249
+ return false;
250
+ return i?.isTTY === true;
251
+ }
252
+ function d2(i, n, a) {
253
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
254
+ return n;
255
+ let l = "", s = "";
256
+ for (let g = 0, y = i.length;g < y; g++) {
257
+ let [c, p] = i[g];
258
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
259
+ }
260
+ return l + n + s;
261
+ }
262
+ function u(i, n = []) {
263
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
264
+ let g = C2[s];
265
+ if (Array.isArray(g))
266
+ return u(i, [...n, g]);
267
+ if (typeof g === "function")
268
+ return (...y) => u(i, [...n, g(...y)]);
269
+ throw Error(`Unknown style: ${String(s)}`);
270
+ } });
271
+ }
272
+ function le(i = {}) {
273
+ return u(i);
274
+ }
275
+ var t = le();
276
+
277
+ // ../kit/src/style.ts
278
+ function takesControlCodes(stream, env = process2.env) {
279
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
280
+ }
281
+ function paint(stream, env = process2.env) {
282
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
283
+ }
284
+ var STATUSES = {
285
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
286
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
287
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
288
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
289
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
290
+ };
291
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
292
+
293
+ // ../kit/src/format.ts
294
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
295
+ function formatSeconds(total) {
296
+ let rest = Math.max(0, Math.round(total));
297
+ const amounts = UNITS.map(([unit, size]) => {
298
+ const amount = Math.floor(rest / size);
299
+ rest -= amount * size;
300
+ return `${amount}${unit}`;
301
+ });
302
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
303
+ if (first === -1)
304
+ return "0s";
305
+ const next = amounts[first + 1];
306
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
307
+ }
308
+ function upTo(text, separator) {
309
+ const end = text.indexOf(separator);
310
+ return end === -1 ? text : text.slice(0, end);
311
+ }
312
+ function truncate(text, width) {
313
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
314
+ }
315
+ var LINE_BREAKS = /\s*\n\s*/g;
316
+ var ESCAPE = String.fromCharCode(27);
317
+ function textWidth(text) {
318
+ return Bun.stringWidth(text);
319
+ }
320
+ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
321
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
322
+ const widths = [];
323
+ for (const row of cells) {
324
+ for (const [index, cell] of row.entries())
325
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
326
+ }
327
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
328
+ const colors = paint(process3.stdout);
329
+ const lines = shown.map((row) => row.map((cell, index) => {
330
+ const width = widths[index] ?? 0;
331
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
332
+ if (align[index] === "right")
333
+ return `${gap}${cell}`;
334
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
335
+ }).join(" ").trimEnd());
336
+ return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
337
+ `);
338
+ }
339
+ function narrow(rows, widths, limit) {
340
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
341
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
342
+ const floor = 8;
343
+ while (used() > limit) {
344
+ let widest = -1;
345
+ for (const [index, width] of widths.entries()) {
346
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
347
+ widest = index;
348
+ }
349
+ if (widest === -1)
350
+ break;
351
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
352
+ }
353
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
354
+ }
355
+ function printJson(value) {
356
+ console.log(JSON.stringify(value, undefined, 2));
357
+ }
358
+
359
+ // ../kit/src/help.ts
360
+ import process4 from "process";
361
+ var OPTIONAL = /\[[^\]]+\]/g;
362
+ var USAGE_PREFIX = /^usage:\s*/i;
363
+ var FULL_STOP = /\.$/;
364
+ function usageLine(usage, colors = paint(process4.stdout)) {
365
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
366
+ }
367
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
368
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
369
+ `);
370
+ }
371
+ function exitRows(exits, colors = paint(process4.stdout)) {
372
+ if (exits.length === 0)
373
+ return [];
374
+ const width = Math.max(...exits.map(([code]) => String(code).length));
375
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
376
+ }
377
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
378
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
379
+ }
380
+ function wantsHelpJson(env = process4.env) {
381
+ return env.KIT_HELP === "json";
382
+ }
383
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
384
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
385
+ `);
386
+ const first = lines[0];
387
+ const colon = first.indexOf(": ");
388
+ const prose = lines[lines.indexOf("") + 1] ?? "";
389
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
390
+ return {
391
+ synopsis: colon === -1 ? first : first.slice(0, colon),
392
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
393
+ ...replaces === undefined ? {} : { replaces },
394
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
395
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
396
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
397
+ };
398
+ }
399
+ function exampleRows(examples, colors = paint(process4.stdout)) {
400
+ if (examples.length === 0)
401
+ return [];
402
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
403
+ }
404
+ function optionRows(options, colors = paint(process4.stdout)) {
405
+ const rows = Object.entries(options).map(([name, option]) => {
406
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
407
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
408
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
409
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
410
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
411
+ });
412
+ const width = Math.max(0, ...rows.map((row) => row.width));
413
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
414
+ }
415
+
416
+ // ../kit/src/text.ts
417
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
418
+ function distance(a, b) {
419
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
420
+ for (const [i, left] of [...a].entries()) {
421
+ const current = [i + 1];
422
+ for (const [j, right] of [...b].entries())
423
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
424
+ previous = current;
425
+ }
426
+ return previous[b.length] ?? 0;
427
+ }
428
+ function closest(name, names) {
429
+ const started = names.find((known) => known.startsWith(name));
430
+ if (started !== undefined)
431
+ return started;
432
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
433
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
434
+ }
435
+ // ../kit/src/input.ts
436
+ var WHOLE = /^\d+$/;
437
+ function wholeNumber(value, name, fallback, min = 1) {
438
+ if (value === undefined)
439
+ return fallback;
440
+ const number = Number(value);
441
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
442
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
443
+ return number;
444
+ }
445
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
446
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
447
+ function duration(value, name, fallback, unit = "s") {
448
+ if (value === undefined)
449
+ return fallback;
450
+ const match = DURATION.exec(value.trim());
451
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
452
+ if (ms < 1)
453
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
454
+ return ms;
455
+ }
456
+
457
+ // ../kit/src/args.ts
458
+ var DASHES = /^-+/;
459
+ function jsonOption(holds) {
460
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
461
+ }
462
+
463
+ class Exit extends Error {
464
+ code;
465
+ hint;
466
+ constructor(message, code, hint) {
467
+ super(message);
468
+ this.code = code;
469
+ this.hint = hint;
470
+ }
471
+ }
472
+ function fail(message, code = 2, hint) {
473
+ throw new Exit(message, code, hint);
474
+ }
475
+
476
+ class UsageError extends Exit {
477
+ constructor(message, hint) {
478
+ super(message, 2, hint);
479
+ }
480
+ }
481
+ function badUsage(message) {
482
+ throw new UsageError(message);
483
+ }
484
+
485
+ class HelpShown extends Exit {
486
+ constructor() {
487
+ super("help shown", 0);
488
+ }
489
+ }
490
+
491
+ class Completing {
492
+ options;
493
+ positionals;
494
+ candidates;
495
+ constructor(options, positionals = [], candidates = {}) {
496
+ this.options = options;
497
+ this.positionals = positionals;
498
+ this.candidates = candidates;
499
+ }
500
+ }
501
+ var completion = { active: false };
502
+ var OUTPUT_OPTIONS = {
503
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
504
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
505
+ };
506
+ function applyOutput(color, plain, env = process5.env) {
507
+ const when = plain === true ? "never" : color ?? "auto";
508
+ if (when === "auto")
509
+ return;
510
+ if (when !== "always" && when !== "never")
511
+ badUsage(`--color takes auto, always or never, not ${when}`);
512
+ if (when === "always") {
513
+ env.FORCE_COLOR = "1";
514
+ delete env.NO_COLOR;
515
+ } else {
516
+ env.NO_COLOR = "1";
517
+ delete env.FORCE_COLOR;
518
+ }
519
+ }
520
+ function parse(args, usage, options, settings = {}) {
521
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
522
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
523
+ const listing = listed(all, settings.allowNegative === true);
524
+ if (completion.active)
525
+ throw new Completing(listing, settings.positionals, settings.candidates);
526
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
527
+ let parsed;
528
+ try {
529
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
530
+ } catch (error) {
531
+ const message = parseError(error);
532
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
533
+ }
534
+ const values = parsed.values;
535
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
536
+ if (values.help === true) {
537
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
538
+ throw new HelpShown;
539
+ }
540
+ checkChoices(parsed.values, all);
541
+ checkConflicts(parsed.values, all);
542
+ if (settings.positionals !== undefined)
543
+ checkPositionals(parsed.positionals, settings.positionals);
544
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
545
+ }
546
+ function splitRest(args, passes) {
547
+ const separator = passes ? args.indexOf("--") : -1;
548
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
549
+ }
550
+ function splitTrailing(args, options, count) {
551
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
552
+ let seen = 0;
553
+ if (count === 0)
554
+ return { own: args, rest: undefined };
555
+ for (let at = 0;at < args.length; at++) {
556
+ const word = args[at];
557
+ if (word === "--")
558
+ break;
559
+ if (word.startsWith("-")) {
560
+ if (takesValue(word))
561
+ at++;
562
+ continue;
563
+ }
564
+ seen++;
565
+ if (seen === count)
566
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
567
+ }
568
+ return { own: args, rest: undefined };
569
+ }
570
+ function listed(options, allowNegative) {
571
+ if (!allowNegative)
572
+ return options;
573
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
574
+ if (option.type !== "boolean" || option.negative === undefined)
575
+ return [[name, option]];
576
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
577
+ }));
578
+ }
579
+ function withAliases(args, options) {
580
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
581
+ if (named.size === 0)
582
+ return args;
583
+ const separator = args.indexOf("--");
584
+ const own = separator === -1 ? args : args.slice(0, separator);
585
+ return [...own.map((arg) => {
586
+ const at = arg.indexOf("=");
587
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
588
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
589
+ }), ...separator === -1 ? [] : args.slice(separator)];
590
+ }
591
+ function withBare(args, options) {
592
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
593
+ if (bare.size === 0)
594
+ return args;
595
+ const separator = args.indexOf("--");
596
+ const own = separator === -1 ? args : args.slice(0, separator);
597
+ return [...own.flatMap((arg, index) => {
598
+ const optional = bare.get(arg);
599
+ const next = own[index + 1];
600
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
601
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
602
+ }), ...separator === -1 ? [] : args.slice(separator)];
603
+ }
604
+ function checkConflicts(values, options) {
605
+ const given = (name) => values[name] !== undefined && values[name] !== false;
606
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
607
+ const other = given(name) ? conflicts.find(given) : undefined;
608
+ if (other !== undefined)
609
+ badUsage(`--${name} cannot be used with --${other}`);
610
+ }
611
+ }
612
+ function checkChoices(values, options) {
613
+ for (const [name, option] of Object.entries(options)) {
614
+ if (option.choices === undefined)
615
+ continue;
616
+ const given = values[name];
617
+ for (const value of Array.isArray(given) ? given : [given]) {
618
+ if (typeof value === "string")
619
+ oneOf(value, name, option.choices);
620
+ }
621
+ }
622
+ }
623
+ function oneOf(value, name, choices) {
624
+ if (!choices.includes(value))
625
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
626
+ return value;
627
+ }
628
+ function checkPositionals(given, names) {
629
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
630
+ const required = names.filter((name) => !name.startsWith("[")).length;
631
+ if (given.length < required)
632
+ badUsage(`missing ${names[given.length]}`);
633
+ if (!variadic && given.length > names.length)
634
+ badUsage(`unexpected argument ${given[names.length]}`);
635
+ }
636
+ function joinDashValues(args, options) {
637
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
638
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
639
+ const joined = [];
640
+ for (let i = 0;i < args.length; i++) {
641
+ const arg = args[i] ?? "";
642
+ if (arg === "--")
643
+ return [...joined, ...args.slice(i)];
644
+ const name = longOf.get(arg);
645
+ const next = args[i + 1];
646
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
647
+ joined.push(`--${name}=${next}`);
648
+ i++;
649
+ } else {
650
+ joined.push(arg);
651
+ }
652
+ }
653
+ return joined;
654
+ }
655
+ function parseError(error) {
656
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
657
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
658
+ }
659
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
660
+ function nearestOption(message, options, allowNegative) {
661
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
662
+ if (typed === undefined)
663
+ return;
664
+ const word = typed.replace(DASHES, "");
665
+ if (word.length < 2 && !typed.startsWith("--"))
666
+ return;
667
+ const known = Object.entries(options).flatMap(([name, option]) => [
668
+ ...option.short === undefined ? [] : [`-${option.short}`],
669
+ `--${name}`,
670
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
671
+ ]);
672
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
673
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
674
+ }
675
+ // ../kit/src/process.ts
676
+ import { constants } from "os";
677
+ import process6 from "process";
678
+ var KILL_GRACE_MS = 2000;
679
+ function exitCodeOf(code, signal) {
680
+ if (code !== null)
681
+ return code;
682
+ if (typeof signal === "number")
683
+ return 128 + signal;
684
+ return signal === null ? 129 : 128 + constants.signals[signal];
685
+ }
686
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
687
+ const chunks = [];
688
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
689
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
690
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
691
+ const timers = [];
692
+ const killGroup = (killing) => {
693
+ if (state.done)
694
+ return;
695
+ try {
696
+ if (grouped)
697
+ process6.kill(-proc.pid, killing);
698
+ else
699
+ proc.kill(killing);
700
+ } catch {}
701
+ };
702
+ const stop = () => {
703
+ killGroup("SIGTERM");
704
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
705
+ };
706
+ const onAbort = () => stop();
707
+ if (timeoutMs !== undefined) {
708
+ timers.push(setTimeout(() => {
709
+ state.timedOut = true;
710
+ stop();
711
+ }, timeoutMs));
712
+ }
713
+ if (signal?.aborted === true)
714
+ onAbort();
715
+ else
716
+ signal?.addEventListener("abort", onAbort, { once: true });
717
+ onStart?.({ kill: (killing) => killGroup(killing) });
718
+ const drain = async (stream, name) => {
719
+ for await (const data of stream) {
720
+ if (state.failure !== undefined)
721
+ continue;
722
+ try {
723
+ onChunk?.({ stream: name, data });
724
+ } catch (error) {
725
+ state.failure = error;
726
+ stop();
727
+ continue;
728
+ }
729
+ if (state.kept + data.length > maxBytes) {
730
+ state.truncated = true;
731
+ continue;
732
+ }
733
+ state.kept += data.length;
734
+ chunks.push({ stream: name, data });
735
+ }
736
+ };
737
+ try {
738
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
739
+ await proc.exited;
740
+ } finally {
741
+ state.done = true;
742
+ for (const timer of timers)
743
+ clearTimeout(timer);
744
+ signal?.removeEventListener("abort", onAbort);
745
+ }
746
+ if (state.failure !== undefined)
747
+ throw state.failure;
748
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
749
+ let output;
750
+ let text;
751
+ return {
752
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
753
+ chunks,
754
+ timedOut: state.timedOut,
755
+ truncated: state.truncated,
756
+ get output() {
757
+ return output ??= joined();
758
+ },
759
+ get text() {
760
+ return text ??= (output ??= joined()).toString();
761
+ }
762
+ };
763
+ }
764
+
765
+ // ../kit/src/progress.ts
766
+ var ESC = String.fromCharCode(27);
767
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
768
+ var RESET_STYLE = `${ESC}[0m`;
769
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
770
+ // ../kit/src/cli.ts
771
+ import { readFileSync, realpathSync } from "fs";
772
+ import { dirname as dirname2, join as join2 } from "path";
773
+ import process8 from "process";
774
+
775
+ // ../kit/src/usage.ts
776
+ import { appendFileSync, mkdirSync } from "fs";
777
+ import { homedir } from "os";
778
+ import { dirname, isAbsolute, join } from "path";
779
+ import process7 from "process";
780
+
781
+ // ../kit/src/logs.ts
782
+ var DAY_MS = 24 * 60 * 60 * 1000;
783
+ var CLI_FOLDER = "kaynooo-cli";
784
+
785
+ // ../kit/src/usage.ts
786
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
787
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
788
+ var LONGEST_NAME = 40;
789
+ var usageError;
790
+ function noteUsageError(message) {
791
+ usageError = message;
792
+ }
793
+ function stateHome(env = process7.env) {
794
+ const dir = env.XDG_STATE_HOME;
795
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
796
+ }
797
+ function usagePath(env = process7.env) {
798
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
799
+ }
800
+ function usageRecorded(env = process7.env) {
801
+ const off = env.KAYNOOO_CLI_NO_USAGE;
802
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
803
+ }
804
+ function flagNames(argv) {
805
+ const end = argv.indexOf("--");
806
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
807
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
808
+ }
809
+ function usageEntry(bin, command, argv, code, now = new Date) {
810
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
811
+ usageError = undefined;
812
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
813
+ }
814
+ function recordUsage(entry, env = process7.env) {
815
+ if (!usageRecorded(env))
816
+ return;
817
+ try {
818
+ const path = usagePath(env);
819
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
820
+ appendFileSync(path, `${JSON.stringify(entry)}
821
+ `, { mode: 384 });
822
+ } catch {}
823
+ }
824
+
825
+ // ../kit/src/cli.ts
826
+ var LEVEL_OPTIONS = {
827
+ ...OUTPUT_OPTIONS,
828
+ help: { type: "boolean", short: "h", description: "show this help" }
829
+ };
830
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
831
+ function printError(prefix, message, hint, cause) {
832
+ const colors = paint(process8.stderr);
833
+ const styled = takesControlCodes(process8.stderr);
834
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
835
+ const under = (label, text, tint) => text === undefined ? "" : `
836
+ ${styled ? tint(label) : `${label}:`} ${text}`;
837
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
838
+ }
839
+ function printJsonError(message, hint, cause) {
840
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
841
+ }
842
+ function wantsJson(argv) {
843
+ const end = argv.indexOf("--");
844
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
845
+ }
846
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
847
+ if (error instanceof HelpShown)
848
+ return 0;
849
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
850
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
851
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
852
+ if (error instanceof UsageError)
853
+ noteUsageError(error.message);
854
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
855
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
856
+ return error instanceof Exit ? error.code : 1;
857
+ }
858
+ var COMPLETE = "__complete";
859
+ var FILES = "__files__";
860
+ async function completingOf(run) {
861
+ completion.active = true;
862
+ try {
863
+ await run([]);
864
+ } catch (error) {
865
+ if (error instanceof Completing)
866
+ return error;
867
+ } finally {
868
+ completion.active = false;
869
+ }
870
+ return new Completing({});
871
+ }
872
+ function candidateLine(candidate) {
873
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
874
+ }
875
+ function positionalBeingTyped(before, { options, positionals }) {
876
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
877
+ let index = 0;
878
+ let at = 0;
879
+ while (at < before.length) {
880
+ const word = before[at];
881
+ if (word === "--") {
882
+ index += before.length - at - 1;
883
+ break;
884
+ }
885
+ if (!word.startsWith("-"))
886
+ index++;
887
+ else if (takesValue(word))
888
+ at++;
889
+ at++;
890
+ }
891
+ const last = positionals.at(-1);
892
+ if (index < positionals.length)
893
+ return positionals[index];
894
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
895
+ }
896
+ async function leafCandidates(run, words) {
897
+ const completing = await completingOf(run);
898
+ if ((words.at(-1) ?? "").startsWith("-"))
899
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
900
+ const flag = words.at(-2);
901
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
902
+ if (option?.type === "string") {
903
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
904
+ return values === undefined ? [FILES] : values.map(candidateLine);
905
+ }
906
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
907
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
908
+ return values === undefined ? [FILES] : values.map(candidateLine);
909
+ }
910
+ async function printCandidates(found) {
911
+ for (const line of await found)
912
+ console.log(line);
913
+ return 0;
914
+ }
915
+ function packageVersion(entry = Bun.main) {
916
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
917
+ try {
918
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
919
+ if (typeof version === "string")
920
+ return version;
921
+ } catch {}
922
+ if (dirname2(dir) === dir)
923
+ return "0.0.0";
924
+ }
925
+ }
926
+ async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
927
+ if (argv[0] === COMPLETE)
928
+ return printCandidates(leafCandidates(run, argv.slice(1)));
929
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
930
+ console.log(version ?? packageVersion());
931
+ return 0;
932
+ }
933
+ let code;
934
+ try {
935
+ code = await run(argv);
936
+ } catch (error) {
937
+ code = reportThrown(name, error, redact, wantsJson(argv));
938
+ }
939
+ if (usage !== false) {
940
+ try {
941
+ recordUsage(usageEntry(name, undefined, argv, code));
942
+ } catch {}
943
+ }
944
+ return code;
945
+ }
946
+ // ../kit/src/secrets.ts
947
+ var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
948
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
949
+ var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
950
+ function isSecretName(name) {
951
+ return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
952
+ }
953
+ // ../kit/src/sessions.ts
954
+ var {Glob } = globalThis.Bun;
955
+ var SESSION_FILES = new Glob("*.json");
956
+ var ACCOUNT_DIRS = new Glob("*/sessions");
957
+ // ../kit/src/size.ts
958
+ var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
959
+ var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
960
+ function parseSize(text, bareUnit = 1) {
961
+ const match = SIZE.exec(text.trim());
962
+ if (match === null)
963
+ return;
964
+ const suffix = match[2].toLowerCase();
965
+ return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
966
+ }
967
+ // src/ports.ts
968
+ import { basename as basename2 } from "path";
969
+ import process11 from "process";
970
+
971
+ // ../kit/src/prompt.ts
972
+ import process10 from "process";
973
+ var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|[\s\S]/giu;
974
+ var CONTROL = /^[\x00-\x1F\x7F]/;
975
+ var KEYS = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
976
+ function readKeys(input) {
977
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => KEYS[sequence] ?? (CONTROL.test(sequence) ? [] : [{ text: sequence }]));
978
+ }
979
+ async function confirm(question, { default: fallback, ...settings } = {}) {
980
+ let answered = fallback;
981
+ const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
982
+ const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
983
+ if (key === "cancel")
984
+ return "cancel";
985
+ if (key === "enter")
986
+ return answered === undefined ? undefined : "enter";
987
+ const letter = typeof key === "object" ? key.text.toLowerCase() : "";
988
+ if (letter !== "y" && letter !== "n")
989
+ return;
990
+ answered = letter === "y";
991
+ return "enter";
992
+ });
993
+ return accepted ? answered : undefined;
994
+ }
995
+ function asking(colors, question, typed, keys) {
996
+ return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
997
+ }
998
+ function answer(colors, question, state, picked) {
999
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1000
+ }
1001
+ async function ask(question, { hint, terminal = process10 }, render, press) {
1002
+ const { stdin, stderr } = terminal;
1003
+ if (stdin.isTTY !== true || stderr.isTTY !== true)
1004
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1005
+ const colors = paint(stderr);
1006
+ let drawn = 0;
1007
+ let outcome;
1008
+ const draw = (state) => {
1009
+ const frame = render(colors, state, { columns: stderr.columns || 80, rows: stderr.rows || 24 });
1010
+ stderr.write(`${drawn > 1 ? `\x1B[${drawn - 1}A` : ""}\r\x1B[0J${frame.join(`
1011
+ `)}`);
1012
+ drawn = frame.length;
1013
+ };
1014
+ try {
1015
+ stdin.setRawMode(true);
1016
+ stdin.resume();
1017
+ stderr.write("\x1B[?25l");
1018
+ draw("asking");
1019
+ return await new Promise((resolve) => {
1020
+ function onData(data) {
1021
+ for (const key of readKeys(data.toString())) {
1022
+ const pressed = press(key);
1023
+ if (pressed !== undefined) {
1024
+ settle(pressed);
1025
+ return;
1026
+ }
1027
+ }
1028
+ draw("asking");
1029
+ }
1030
+ function onEnd() {
1031
+ settle("cancel");
1032
+ }
1033
+ function settle(settled) {
1034
+ outcome = settled;
1035
+ stdin.off("data", onData);
1036
+ stdin.off("end", onEnd);
1037
+ resolve(settled === "enter");
1038
+ }
1039
+ stdin.on("data", onData);
1040
+ stdin.on("end", onEnd);
1041
+ });
1042
+ } finally {
1043
+ draw(outcome ?? "cancel");
1044
+ stderr.write(`
1045
+ \x1B[?25h`);
1046
+ stdin.setRawMode(false);
1047
+ stdin.pause();
1048
+ }
1049
+ }
1050
+
1051
+ // src/parse.ts
1052
+ var LISTENING = { tcp: "0A", udp: "07" };
1053
+ var WHITESPACE = /\s+/;
1054
+ var HEX_PAIR = /../g;
1055
+ var SOCKET_LINK = /^socket:\[(\d+)\]$/;
1056
+ var UNIT_SCOPE = /\.(?:service|scope)$/;
1057
+ var CONTAINER_ID = /(?:docker-|libpod-|\/docker\/)([0-9a-f]{64})/;
1058
+ var DOCKER_PORT = /:(\d+)(?:-(\d+))?->[\d-]+\/(tcp|udp)/;
1059
+ function word(hex) {
1060
+ const bytes = (hex.match(HEX_PAIR) ?? []).reverse().map((byte) => Number.parseInt(byte, 16));
1061
+ return [bytes[0] << 8 | bytes[1], bytes[2] << 8 | bytes[3]];
1062
+ }
1063
+ function parseAddress(hex) {
1064
+ if (hex.length === 8) {
1065
+ const [high, low] = word(hex);
1066
+ return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
1067
+ }
1068
+ const hextets = (hex.match(/.{8}/g) ?? []).flatMap(word);
1069
+ if (hextets.length !== 8)
1070
+ return hex;
1071
+ if (hextets.slice(0, 5).every((part) => part === 0) && hextets[5] === 65535)
1072
+ return `::ffff:${hextets[6] >> 8}.${hextets[6] & 255}.${hextets[7] >> 8}.${hextets[7] & 255}`;
1073
+ return compress(hextets);
1074
+ }
1075
+ function compress(hextets) {
1076
+ let best = { start: -1, length: 0 };
1077
+ let run = { start: 0, length: 0 };
1078
+ for (const [at, part] of hextets.entries()) {
1079
+ run = part === 0 ? { start: run.length === 0 ? at : run.start, length: run.length + 1 } : { start: 0, length: 0 };
1080
+ if (run.length > best.length)
1081
+ best = run;
1082
+ }
1083
+ const text = (parts) => parts.map((part) => part.toString(16)).join(":");
1084
+ if (best.length < 2)
1085
+ return text(hextets);
1086
+ return `${text(hextets.slice(0, best.start))}::${text(hextets.slice(best.start + best.length))}`;
1087
+ }
1088
+ function parseNetTable(text, protocol, family) {
1089
+ const sockets = [];
1090
+ for (const line of text.split(`
1091
+ `).slice(1)) {
1092
+ const columns = line.trim().split(WHITESPACE);
1093
+ const [address = "", port = ""] = (columns[1] ?? "").split(":");
1094
+ if (columns.length < 10 || columns[3] !== LISTENING[protocol])
1095
+ continue;
1096
+ const number = Number.parseInt(port, 16);
1097
+ if (number === 0 || Number.isNaN(number))
1098
+ continue;
1099
+ sockets.push({ protocol, family, address: parseAddress(address), port: number, uid: Number(columns[7]), inode: Number(columns[9]) });
1100
+ }
1101
+ return sockets;
1102
+ }
1103
+ function socketInode(link) {
1104
+ const match = SOCKET_LINK.exec(link);
1105
+ return match === null ? undefined : Number(match[1]);
1106
+ }
1107
+ function parseStat(text) {
1108
+ const open = text.indexOf("(");
1109
+ const close = text.lastIndexOf(")");
1110
+ if (open === -1 || close < open)
1111
+ return;
1112
+ const rest = text.slice(close + 2).trim().split(WHITESPACE);
1113
+ const field = (number) => Number(rest[number - 3]);
1114
+ if (rest.length < 20)
1115
+ return;
1116
+ 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) };
1117
+ }
1118
+ function parseStatus(text) {
1119
+ const fields = new Map;
1120
+ for (const line of text.split(`
1121
+ `)) {
1122
+ const colon = line.indexOf(":");
1123
+ if (colon > 0)
1124
+ fields.set(line.slice(0, colon), line.slice(colon + 1).trim());
1125
+ }
1126
+ return fields;
1127
+ }
1128
+ function statusBytes(fields, key) {
1129
+ const value = Number.parseInt(fields.get(key) ?? "", 10);
1130
+ return Number.isNaN(value) ? undefined : value * 1024;
1131
+ }
1132
+ function statusUid(fields) {
1133
+ const value = Number.parseInt(fields.get("Uid") ?? "", 10);
1134
+ return Number.isNaN(value) ? undefined : value;
1135
+ }
1136
+ var LIMIT_LINE = /^(\S+(?: \S+)*)\s{2,}(\S+)\s+(\S+)(?:\s+(\S+))?\s*$/;
1137
+ function parseLimits(text) {
1138
+ const limits = [];
1139
+ for (const line of text.split(`
1140
+ `).slice(1)) {
1141
+ const match = LIMIT_LINE.exec(line);
1142
+ if (match !== null)
1143
+ limits.push({ name: match[1], soft: match[2], hard: match[3], units: match[4] ?? "" });
1144
+ }
1145
+ return limits;
1146
+ }
1147
+ function parseCmdline(text) {
1148
+ return text.split("\x00").filter((_, at, parts) => at < parts.length - 1 || parts[at] !== "");
1149
+ }
1150
+ function parseEnviron(text) {
1151
+ return parseCmdline(text).map((entry) => {
1152
+ const equals = entry.indexOf("=");
1153
+ return equals === -1 ? [entry, ""] : [entry.slice(0, equals), entry.slice(equals + 1)];
1154
+ });
1155
+ }
1156
+ function parseCgroup(text) {
1157
+ return text.split(`
1158
+ `).filter((line) => line !== "").map((line) => {
1159
+ const [hierarchy = "", controllers = "", ...path] = line.split(":");
1160
+ return { hierarchy, controllers, path: path.join(":") };
1161
+ });
1162
+ }
1163
+ function cgroupUnit(entries) {
1164
+ const path = (entries.find((entry) => entry.hierarchy === "0") ?? entries[0])?.path ?? "";
1165
+ return path.split("/").reverse().find((part) => UNIT_SCOPE.test(part));
1166
+ }
1167
+ function cgroupContainer(entries) {
1168
+ for (const { path } of entries) {
1169
+ const match = CONTAINER_ID.exec(path);
1170
+ if (match !== null)
1171
+ return match[1];
1172
+ }
1173
+ return;
1174
+ }
1175
+ function userNameOf(passwd, uid) {
1176
+ for (const line of passwd.split(`
1177
+ `)) {
1178
+ const [name, , id] = line.split(":");
1179
+ if (id === String(uid) && name !== undefined && name !== "")
1180
+ return name;
1181
+ }
1182
+ return;
1183
+ }
1184
+ function parseDockerPs(text) {
1185
+ const containers = [];
1186
+ for (const line of text.split(`
1187
+ `)) {
1188
+ const [name = "", ports = "", project = "", service = ""] = line.split("\t");
1189
+ if (name === "")
1190
+ continue;
1191
+ const published = [];
1192
+ for (const entry of ports.split(",")) {
1193
+ const match = DOCKER_PORT.exec(entry);
1194
+ if (match === null)
1195
+ continue;
1196
+ const first = Number(match[1]);
1197
+ for (let host = first;host <= Number(match[2] ?? first); host++)
1198
+ published.push({ host, protocol: match[3] });
1199
+ }
1200
+ containers.push({ name, project: project === "" ? undefined : project, service: service === "" ? undefined : service, published });
1201
+ }
1202
+ return containers;
1203
+ }
1204
+
1205
+ // src/docker.ts
1206
+ var FORMAT = '{{.Names}}\t{{.Ports}}\t{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.service"}}';
1207
+ async function dockerContainers() {
1208
+ if (Bun.which("docker") === null)
1209
+ return [];
1210
+ try {
1211
+ const ran = await runCommand(["docker", "ps", "--format", FORMAT], { timeoutMs: 4000 });
1212
+ return ran.code === 0 ? parseDockerPs(ran.text) : [];
1213
+ } catch {
1214
+ return [];
1215
+ }
1216
+ }
1217
+
1218
+ // src/read.ts
1219
+ import { readdir, readFile, readlink } from "fs/promises";
1220
+ var CLOCK_TICKS = 100;
1221
+ async function text2(path) {
1222
+ try {
1223
+ return await readFile(path, "utf8");
1224
+ } catch {
1225
+ return;
1226
+ }
1227
+ }
1228
+ async function link(path) {
1229
+ try {
1230
+ return await readlink(path);
1231
+ } catch {
1232
+ return;
1233
+ }
1234
+ }
1235
+ var DIGITS = /^\d+$/;
1236
+ var BOOT_TIME = /^btime\s+(\d+)/m;
1237
+ async function listPids(root = "/proc") {
1238
+ return (await readdir(root)).filter((name) => DIGITS.test(name)).map(Number);
1239
+ }
1240
+ async function bootMs(root = "/proc") {
1241
+ const match = BOOT_TIME.exec(await text2(`${root}/stat`) ?? "");
1242
+ return match === null ? Date.now() : Number(match[1]) * 1000;
1243
+ }
1244
+ async function readProc(pid, boot, { root = "/proc", detail = true } = {}) {
1245
+ const dir = `${root}/${pid}`;
1246
+ const [statText, statusText, cmdline] = await Promise.all([text2(`${dir}/stat`), text2(`${dir}/status`), text2(`${dir}/cmdline`)]);
1247
+ const stat = statText === undefined ? undefined : parseStat(statText);
1248
+ if (stat === undefined || statusText === undefined)
1249
+ return;
1250
+ const status = parseStatus(statusText);
1251
+ const info = {
1252
+ pid,
1253
+ ppid: stat.ppid,
1254
+ comm: stat.comm,
1255
+ args: parseCmdline(cmdline ?? ""),
1256
+ uid: statusUid(status) ?? -1,
1257
+ state: stat.state,
1258
+ session: stat.session,
1259
+ rss: statusBytes(status, "VmRSS") ?? 0,
1260
+ startMs: boot + stat.startTicks / CLOCK_TICKS * 1000
1261
+ };
1262
+ if (!detail)
1263
+ return info;
1264
+ const [cwd, exe, cgroup] = await Promise.all([link(`${dir}/cwd`), link(`${dir}/exe`), text2(`${dir}/cgroup`)]);
1265
+ const groups = parseCgroup(cgroup ?? "");
1266
+ return { ...info, cwd, exe, unit: cgroupUnit(groups), container: cgroupContainer(groups) };
1267
+ }
1268
+ async function snapshot(root = "/proc", detailed = () => true) {
1269
+ const boot = await bootMs(root);
1270
+ const found = [];
1271
+ for (const pid of await listPids(root)) {
1272
+ const light = await readProc(pid, boot, { root, detail: false });
1273
+ if (light === undefined)
1274
+ continue;
1275
+ found.push(detailed(light.uid) ? await readProc(pid, boot, { root }) ?? light : light);
1276
+ }
1277
+ return found;
1278
+ }
1279
+ function ancestry(pid, byPid) {
1280
+ const chain = [];
1281
+ let at = pid;
1282
+ while (at !== undefined && at > 0 && !chain.includes(at)) {
1283
+ chain.push(at);
1284
+ at = byPid.get(at)?.ppid;
1285
+ }
1286
+ return chain;
1287
+ }
1288
+ async function readSockets(root = "/proc") {
1289
+ const tables = [["tcp", "tcp", 4], ["tcp6", "tcp", 6], ["udp", "udp", 4], ["udp6", "udp", 6]];
1290
+ const sockets = [];
1291
+ for (const [file, protocol, family] of tables)
1292
+ sockets.push(...parseNetTable(await text2(`${root}/net/${file}`) ?? "", protocol, family));
1293
+ return sockets;
1294
+ }
1295
+ async function socketsOf(pid, root = "/proc") {
1296
+ const inodes = new Set;
1297
+ try {
1298
+ for (const fd of await readdir(`${root}/${pid}/fd`)) {
1299
+ const inode = socketInode(await link(`${root}/${pid}/fd/${fd}`) ?? "");
1300
+ if (inode !== undefined)
1301
+ inodes.add(inode);
1302
+ }
1303
+ } catch {}
1304
+ return inodes;
1305
+ }
1306
+ async function socketOwners(root = "/proc") {
1307
+ const owners = new Map;
1308
+ for (const pid of await listPids(root)) {
1309
+ for (const inode of await socketsOf(pid, root))
1310
+ owners.set(inode, pid);
1311
+ }
1312
+ return owners;
1313
+ }
1314
+ async function fdCount(pid, root = "/proc") {
1315
+ try {
1316
+ return (await readdir(`${root}/${pid}/fd`)).length;
1317
+ } catch {
1318
+ return;
1319
+ }
1320
+ }
1321
+ var passwd;
1322
+ async function userName(uid) {
1323
+ passwd ??= await text2("/etc/passwd") ?? "";
1324
+ return userNameOf(passwd, uid);
1325
+ }
1326
+
1327
+ // src/kill.ts
1328
+ var SHELLS = new Set(["sh", "bash", "zsh", "fish", "dash", "ash", "nu", "tcsh", "ksh", "elvish", "xonsh"]);
1329
+ var TERMINALS = new Set(["kitty", "alacritty", "konsole", "wezterm-gui", "foot", "footclient", "xterm", "gnome-terminal-", "ghostty", "tmux: server", "tmux", "screen", "terminator", "tilix", "urxvt", "st", "yakuake", "ptyxis"]);
1330
+ function protectionOf(proc, { uid, mine }) {
1331
+ if (proc.pid === 1)
1332
+ return "pid 1";
1333
+ if (proc.uid !== uid)
1334
+ return "another user's process";
1335
+ if (mine.has(proc.pid))
1336
+ return "this command or one of its ancestors";
1337
+ if (SHELLS.has(proc.comm))
1338
+ return "a shell";
1339
+ return TERMINALS.has(proc.comm) ? "a terminal" : undefined;
1340
+ }
1341
+ var realSignaller = {
1342
+ send(pid, signal) {
1343
+ try {
1344
+ process.kill(pid, signal);
1345
+ return true;
1346
+ } catch {
1347
+ return false;
1348
+ }
1349
+ },
1350
+ async alive(pid) {
1351
+ const stat = await text2(`/proc/${pid}/stat`);
1352
+ return stat !== undefined && !stat.slice(stat.lastIndexOf(")") + 2).startsWith("Z");
1353
+ },
1354
+ sleep: async (ms) => Bun.sleep(ms)
1355
+ };
1356
+ var POLL_MS = 100;
1357
+ async function waitGone(pids, graceMs, signaller) {
1358
+ let alive = pids;
1359
+ let waited = 0;
1360
+ while (alive.length > 0 && waited < graceMs) {
1361
+ await signaller.sleep(POLL_MS);
1362
+ waited += POLL_MS;
1363
+ alive = await filterAlive(alive, signaller);
1364
+ }
1365
+ return alive;
1366
+ }
1367
+ async function filterAlive(pids, signaller) {
1368
+ const alive = [];
1369
+ for (const pid of pids) {
1370
+ if (await signaller.alive(pid))
1371
+ alive.push(pid);
1372
+ }
1373
+ return alive;
1374
+ }
1375
+ async function terminate(pids, { escalate, graceMs, signaller = realSignaller }) {
1376
+ const failed = pids.filter((pid) => !signaller.send(pid, "SIGTERM"));
1377
+ const refused = await filterAlive(failed, signaller);
1378
+ const sent = pids.filter((pid) => !failed.includes(pid));
1379
+ const remaining = await waitGone(sent, graceMs, signaller);
1380
+ const terminated = pids.filter((pid) => failed.includes(pid) ? !refused.includes(pid) : !remaining.includes(pid));
1381
+ if (!escalate || remaining.length === 0)
1382
+ return { terminated, killed: [], survived: [...refused, ...remaining] };
1383
+ for (const pid of remaining)
1384
+ signaller.send(pid, "SIGKILL");
1385
+ const stuck = await waitGone(remaining, 2000, signaller);
1386
+ return { terminated, killed: remaining.filter((pid) => !stuck.includes(pid)), survived: [...refused, ...stuck] };
1387
+ }
1388
+
1389
+ // src/mask.ts
1390
+ import { basename } from "path";
1391
+ var MASK = "***";
1392
+ var URL_PASSWORD = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi;
1393
+ 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;
1394
+ var OPAQUE = /(?<![\w-])(?=[\w-]{32,}(?![\w-]))(?=[\w-]*[A-Z])(?=[\w-]*\d)[\w-]+/gi;
1395
+ var PEM = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*/;
1396
+ function maskText(value) {
1397
+ return value.replace(PEM, MASK).replace(URL_PASSWORD, `$1${MASK}@`).replace(TOKEN, MASK).replace(OPAQUE, MASK);
1398
+ }
1399
+ function maskValue(name, value) {
1400
+ if (value === "")
1401
+ return value;
1402
+ return isSecretName(name) ? MASK : maskText(value);
1403
+ }
1404
+ function maskEnviron(entries) {
1405
+ return entries.map(([name, value]) => [name, maskValue(name, value)]);
1406
+ }
1407
+ var FLAG = /^-{1,2}([\w.-]+)(=|$)/;
1408
+ var ASSIGNMENT_NAME = /^[\w.-]+$/;
1409
+ var PASSWORD_SPLIT = new Set(["sshpass"]);
1410
+ var PASSWORD_JOINED = new Set(["mysql", "mysqldump", "mysqladmin", "mariadb", "mariadb-dump"]);
1411
+ function maskArgs(args) {
1412
+ const command = basename(args[0] ?? "");
1413
+ let hidden = false;
1414
+ return args.map((arg, index) => {
1415
+ if (hidden) {
1416
+ hidden = false;
1417
+ return arg.startsWith("-") ? maskText(arg) : MASK;
1418
+ }
1419
+ if (index > 0 && arg === "-p" && PASSWORD_SPLIT.has(command)) {
1420
+ hidden = true;
1421
+ return arg;
1422
+ }
1423
+ if (index > 0 && arg.length > 2 && arg.startsWith("-p") && PASSWORD_JOINED.has(command))
1424
+ return `-p${MASK}`;
1425
+ const flag = FLAG.exec(arg);
1426
+ if (flag !== null) {
1427
+ if (flag[2] === "=")
1428
+ return isSecretName(flag[1]) ? `${arg.slice(0, flag[0].length)}${MASK}` : maskText(arg);
1429
+ hidden = isSecretName(flag[1]);
1430
+ return arg;
1431
+ }
1432
+ const equals = arg.indexOf("=");
1433
+ 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);
1434
+ });
1435
+ }
1436
+
1437
+ // src/ports.ts
1438
+ var usage2 = `ports [port]
1439
+
1440
+ Lists what listens on this machine, TCP and UDP over IPv4 and IPv6, one row per port with its bound address, the owning process, its command and its working directory. A port Docker publishes is held by docker-proxy, and shows as its compose project and service when docker is installed; the owner of a socket of another user cannot be read and shows as -.
1441
+ \`ports <port>\` keeps that port alone and exits 1 when nothing listens on it.
1442
+ \`ports <port> --kill\` stops its owner with SIGTERM, and with --force SIGKILL once --grace has passed, after asking on a terminal unless --yes is given. It refuses processes of other users, pid 1, this command and its ancestors, and docker-proxy, for which it names the container to stop instead.
1443
+
1444
+ Exits 0 when it listed or stopped, 1 when nothing listens on the given port or the owner could not be stopped, 2 on a usage error.`;
1445
+ var options = {
1446
+ json: jsonOption("[{ port, protocol, addresses, pid, command, cwd, container }]"),
1447
+ kill: { type: "boolean", description: "stop the owner of the given port" },
1448
+ force: { type: "boolean", description: "with --kill, SIGKILL what SIGTERM did not stop within --grace" },
1449
+ yes: { type: "boolean", short: "y", description: "with --kill, do not ask first" },
1450
+ grace: { type: "string", description: "with --force, how long SIGTERM gets before SIGKILL (5s)" }
1451
+ };
1452
+ function buildRows(sockets, owners, procs, containers) {
1453
+ const rows = new Map;
1454
+ for (const socket of sockets) {
1455
+ const pid = owners.get(socket.inode);
1456
+ const proc = pid === undefined ? undefined : procs.get(pid);
1457
+ const key = `${socket.protocol}/${socket.port}/${pid ?? "unknown"}`;
1458
+ const row = rows.get(key);
1459
+ if (row !== undefined) {
1460
+ if (!row.addresses.includes(socket.address))
1461
+ row.addresses.push(socket.address);
1462
+ continue;
1463
+ }
1464
+ const held = proc === undefined || proc.comm === "docker-proxy";
1465
+ const container = held ? containers.find((candidate) => candidate.published.some((port) => port.host === socket.port && port.protocol === socket.protocol)) : undefined;
1466
+ rows.set(key, {
1467
+ port: socket.port,
1468
+ protocol: socket.protocol,
1469
+ addresses: [socket.address],
1470
+ pid,
1471
+ command: proc === undefined ? undefined : maskArgs([basename2(proc.args[0] ?? proc.comm), ...proc.args.slice(1)]).join(" "),
1472
+ cwd: proc?.cwd,
1473
+ uid: proc?.uid ?? socket.uid,
1474
+ container: container === undefined ? undefined : { name: container.name, project: container.project, service: container.service }
1475
+ });
1476
+ }
1477
+ return [...rows.values()].sort((a, b) => a.port - b.port || a.protocol.localeCompare(b.protocol) || (a.pid ?? 0) - (b.pid ?? 0));
1478
+ }
1479
+ function containerLabel(container) {
1480
+ return container.project === undefined ? container.name : `${container.project}/${container.service ?? container.name}`;
1481
+ }
1482
+ function refusal(row, proc, guard) {
1483
+ if (row.container !== undefined && (proc === undefined || proc.comm === "docker-proxy"))
1484
+ return `published by the container ${row.container.name} (${containerLabel(row.container)}): stop it with \`docker stop ${row.container.name}\``;
1485
+ if (proc === undefined || row.pid === undefined)
1486
+ return "its owner is not readable (another user's process): rerun as that user";
1487
+ const reason = protectionOf(proc, guard);
1488
+ return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`;
1489
+ }
1490
+ function render(rows) {
1491
+ const colors = paint(process11.stdout);
1492
+ const cells = rows.map((row) => [
1493
+ colors.cyan(String(row.port)),
1494
+ row.protocol,
1495
+ row.addresses.join(", "),
1496
+ row.pid === undefined ? "-" : String(row.pid),
1497
+ row.container === undefined ? truncate(row.command ?? "-", 60) : colors.yellow(`docker ${containerLabel(row.container)}`),
1498
+ colors.dim(row.cwd ?? "-")
1499
+ ]);
1500
+ return table([["PORT", "PROTO", "ADDRESS", "PID", "COMMAND", "CWD"], ...cells], { header: true });
1501
+ }
1502
+ async function stop(port, rows, procs, values) {
1503
+ const guard = { uid: process11.getuid?.() ?? -1, mine: new Set(ancestry(process11.pid, procs)) };
1504
+ const targets = new Map;
1505
+ for (const row of rows) {
1506
+ const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard);
1507
+ if (reason !== undefined)
1508
+ console.error(`port ${port}: ${reason}`);
1509
+ else if (row.pid !== undefined)
1510
+ targets.set(row.pid, row);
1511
+ }
1512
+ if (targets.size === 0)
1513
+ return 1;
1514
+ const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? "", 40)})`).join(", ");
1515
+ if (values.yes !== true) {
1516
+ if (!process11.stdin.isTTY)
1517
+ fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2);
1518
+ if (await confirm(`Stop ${names}?`, { default: false }) !== true)
1519
+ return 1;
1520
+ }
1521
+ const outcome = await terminate([...targets.keys()], { escalate: values.force === true, graceMs: duration(values.grace, "grace", 5000) });
1522
+ for (const pid of [...outcome.terminated, ...outcome.killed])
1523
+ console.log(`stopped ${pid}${outcome.killed.includes(pid) ? " (SIGKILL)" : ""}`);
1524
+ for (const pid of outcome.survived)
1525
+ console.error(`${pid} is still running${values.force === true ? "" : ", pass --force to SIGKILL it"}`);
1526
+ return outcome.survived.length === 0 ? 0 : 1;
1527
+ }
1528
+ async function ports(args) {
1529
+ const { values, positionals } = parse(args, usage2, options, {
1530
+ positionals: ["[port]"],
1531
+ replaces: "ss -ltnp | grep, lsof -i, fuser -k and lookups of docker-proxy by hand",
1532
+ examples: [
1533
+ ["ports", "every listening port with its owner"],
1534
+ ["ports 3000", "who holds 3000, exit 1 when nobody does"],
1535
+ ["ports 3000 --kill --yes", "stop it"],
1536
+ "ports --json"
1537
+ ]
1538
+ });
1539
+ const [given] = positionals;
1540
+ const port = given === undefined ? undefined : wholeNumber(given, "<port>", 0);
1541
+ if (port !== undefined && port > 65535)
1542
+ badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
1543
+ if (values.kill === true && port === undefined)
1544
+ badUsage("--kill takes the port to free: ports <port> --kill");
1545
+ const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process11.getuid?.())]);
1546
+ const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
1547
+ const wanted = sockets.filter((socket) => port === undefined || socket.port === port);
1548
+ const needsDocker = wanted.some((socket) => {
1549
+ const pid = owners.get(socket.inode);
1550
+ return pid === undefined || byPid.get(pid)?.comm === "docker-proxy";
1551
+ });
1552
+ const rows = buildRows(wanted, owners, byPid, needsDocker ? await dockerContainers() : []);
1553
+ if (port !== undefined && rows.length === 0) {
1554
+ console.error(`nothing listens on port ${port}`);
1555
+ return 1;
1556
+ }
1557
+ if (values.kill === true && port !== undefined)
1558
+ return stop(port, rows, byPid, values);
1559
+ if (values.json === true) {
1560
+ printJson(rows);
1561
+ return 0;
1562
+ }
1563
+ console.log(render(rows));
1564
+ const unknown = rows.filter((row) => row.pid === undefined && row.container === undefined).length;
1565
+ if (unknown > 0)
1566
+ console.error(paint(process11.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
1567
+ return 0;
1568
+ }
1569
+
1570
+ // src/ports-cli.ts
1571
+ process12.exitCode = await runMain({ name: "ports", run: ports });