@kaynooo/cli-wait 0.0.0-stage → 0.5.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,1171 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/slot-cli.ts
5
+ import process12 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process3 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.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
+ function x(s) {
19
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
+ if (!/^[a-f0-9]+$/.test(r))
21
+ return [0, 0, 0];
22
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
23
+ if (t === 3 || t === 4) {
24
+ let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
25
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
26
+ }
27
+ if (t !== 6 && t !== 8)
28
+ throw Error(`Invalid hex color length: ${t}`);
29
+ let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
30
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
31
+ throw Error(`Invalid hex color value: ${s}`);
32
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
33
+ }
34
+ function A(s) {
35
+ let [r, t, n, a] = s;
36
+ if (a)
37
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
38
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
39
+ }
40
+ function R(s, r, t) {
41
+ s = (s % 360 + 360) % 360, t /= 100;
42
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
43
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
44
+ return Math.round(255 * y);
45
+ };
46
+ return [a(0), a(8), a(4)];
47
+ }
48
+ function k(s) {
49
+ let [r, t, n] = s;
50
+ r /= 255, t /= 255, n /= 255;
51
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
52
+ if (a !== b) {
53
+ let u = a - b;
54
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
55
+ o = (t - n) / u + (t < n ? 6 : 0);
56
+ else if (a === t)
57
+ o = (n - r) / u + 2;
58
+ else
59
+ o = (r - t) / u + 4;
60
+ o /= 6;
61
+ }
62
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
63
+ }
64
+ function H(s, r, t) {
65
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
66
+ let n = (a) => {
67
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
68
+ return Math.round(255 * o);
69
+ };
70
+ return [n(5), n(3), n(1)];
71
+ }
72
+ function f(s) {
73
+ let [r, t, n] = s;
74
+ r /= 255, t /= 255, n /= 255;
75
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
76
+ if (o !== 0) {
77
+ if (a === r)
78
+ y = (t - n) / o + (t < n ? 6 : 0);
79
+ else if (a === t)
80
+ y = (n - r) / o + 2;
81
+ else
82
+ y = (r - t) / o + 4;
83
+ y /= 6;
84
+ }
85
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
86
+ }
87
+ function O(s) {
88
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
89
+ if (a === 1)
90
+ return [0, 0, 0, 100];
91
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
92
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
93
+ }
94
+ function v(s, r, t, n) {
95
+ return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
96
+ }
97
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
98
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
99
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
100
+ function T(s) {
101
+ let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
102
+ return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
103
+ }
104
+ function M(s, r, t) {
105
+ let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
106
+ return [u(o), u(y), u(c)];
107
+ }
108
+ function d(s) {
109
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
110
+ return [i(r, 4), i(a, 4), i(b, 2)];
111
+ }
112
+ function C(s, r, t) {
113
+ let n = t * Math.PI / 180;
114
+ return M(s, r * Math.cos(n), r * Math.sin(n));
115
+ }
116
+ function l(s) {
117
+ let r = s / 255;
118
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
119
+ }
120
+
121
+ class e {
122
+ r;
123
+ g;
124
+ b;
125
+ a;
126
+ constructor(s, r, t, n = 1) {
127
+ this.r = s, this.g = r, this.b = t, this.a = n;
128
+ }
129
+ static from(s, r) {
130
+ if (s === "hex") {
131
+ let [t, n, a, b] = x(r);
132
+ return new e(t, n, a, b);
133
+ }
134
+ if (s === "rgb") {
135
+ if (Array.isArray(r)) {
136
+ let [o, y, c, u] = r;
137
+ return new e(o, y, c, u);
138
+ }
139
+ let { r: t, g: n, b: a, a: b } = r;
140
+ return new e(t, n, a, b);
141
+ }
142
+ if (s === "hsl") {
143
+ let t, n, a, b;
144
+ if (Array.isArray(r))
145
+ [t, n, a, b] = r;
146
+ else
147
+ ({ h: t, s: n, l: a, a: b } = r);
148
+ let [o, y, c] = R(t, n, a);
149
+ return new e(o, y, c, b);
150
+ }
151
+ if (s === "hsv") {
152
+ let t, n, a, b;
153
+ if (Array.isArray(r))
154
+ [t, n, a, b] = r;
155
+ else
156
+ ({ h: t, s: n, v: a, a: b } = r);
157
+ let [o, y, c] = H(t, n, a);
158
+ return new e(o, y, c, b);
159
+ }
160
+ if (s === "cmyk") {
161
+ let t, n, a, b, o;
162
+ if (Array.isArray(r))
163
+ [t, n, a, b, o] = r;
164
+ else
165
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
166
+ let [y, c, u] = v(t, n, a, b);
167
+ return new e(y, c, u, o);
168
+ }
169
+ if (s === "oklch") {
170
+ let t, n, a, b;
171
+ if (Array.isArray(r))
172
+ [t, n, a, b] = r;
173
+ else
174
+ ({ l: t, c: n, h: a, a: b } = r);
175
+ let [o, y, c] = C(t, n, a);
176
+ return new e(o, y, c, b);
177
+ }
178
+ if (s === "oklab") {
179
+ let t, n, a, b;
180
+ if (Array.isArray(r))
181
+ [t, n, a, b] = r;
182
+ else
183
+ ({ l: t, a: n, b: a, alpha: b } = r);
184
+ let [o, y, c] = M(t, n, a);
185
+ return new e(o, y, c, b);
186
+ }
187
+ throw Error("Invalid input");
188
+ }
189
+ to(s) {
190
+ switch (s) {
191
+ case "rgb":
192
+ return [this.r, this.g, this.b];
193
+ case "rgba":
194
+ return [this.r, this.g, this.b, this.a];
195
+ case "hex":
196
+ return A([this.r, this.g, this.b]);
197
+ case "hexa":
198
+ return A([this.r, this.g, this.b, this.a]);
199
+ case "hsl":
200
+ return k([this.r, this.g, this.b]);
201
+ case "hsla":
202
+ return [...k([this.r, this.g, this.b]), this.a];
203
+ case "hsv":
204
+ return f([this.r, this.g, this.b]);
205
+ case "hsva":
206
+ return [...f([this.r, this.g, this.b]), this.a];
207
+ case "cmyk":
208
+ return O([this.r, this.g, this.b]);
209
+ case "cmyka":
210
+ return [...O([this.r, this.g, this.b]), this.a];
211
+ case "oklch":
212
+ return d([this.r, this.g, this.b]);
213
+ case "oklcha":
214
+ return [...d([this.r, this.g, this.b]), this.a];
215
+ case "oklab":
216
+ return T([this.r, this.g, this.b]);
217
+ case "oklaba":
218
+ return [...T([this.r, this.g, this.b]), this.a];
219
+ default:
220
+ return [this.r, this.g, this.b];
221
+ }
222
+ }
223
+ getLuminance() {
224
+ let s = l(this.r), r = l(this.g), t = l(this.b);
225
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
226
+ }
227
+ contrastRatio(s) {
228
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
229
+ return (n + 0.05) / (a + 0.05);
230
+ }
231
+ bestContrastForeground() {
232
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
233
+ return t >= n ? s : r;
234
+ }
235
+ }
236
+
237
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
+ var r = 39;
239
+ var o = 49;
240
+ var f2 = "\x1B[";
241
+ var C2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
242
+ let [a, l, s] = e.from("hex", i).to("rgb");
243
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
244
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
245
+ var b = new Set(["", "1", "2", "3", "true"]);
246
+ function h(i, n = globalThis.process?.env ?? {}) {
247
+ if (n.FORCE_COLOR !== undefined)
248
+ return b.has(n.FORCE_COLOR);
249
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
250
+ return false;
251
+ return i?.isTTY === true;
252
+ }
253
+ function d2(i, n, a) {
254
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
255
+ return n;
256
+ let l = "", s = "";
257
+ for (let g = 0, y = i.length;g < y; g++) {
258
+ let [c, p] = i[g];
259
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
260
+ }
261
+ return l + n + s;
262
+ }
263
+ function u(i, n = []) {
264
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
265
+ let g = C2[s];
266
+ if (Array.isArray(g))
267
+ return u(i, [...n, g]);
268
+ if (typeof g === "function")
269
+ return (...y) => u(i, [...n, g(...y)]);
270
+ throw Error(`Unknown style: ${String(s)}`);
271
+ } });
272
+ }
273
+ function le(i = {}) {
274
+ return u(i);
275
+ }
276
+ var t = le();
277
+
278
+ // ../kit/src/style.ts
279
+ 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
+
294
+ // ../kit/src/format.ts
295
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
296
+ function formatSeconds(total) {
297
+ let rest = Math.max(0, Math.round(total));
298
+ const amounts = UNITS.map(([unit, size]) => {
299
+ const amount = Math.floor(rest / size);
300
+ rest -= amount * size;
301
+ return `${amount}${unit}`;
302
+ });
303
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
304
+ if (first === -1)
305
+ return "0s";
306
+ const next = amounts[first + 1];
307
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
308
+ }
309
+ function formatDuration(ms) {
310
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
311
+ }
312
+ function formatElapsed(ms) {
313
+ return formatSeconds(Math.floor(Math.max(0, ms) / 1000));
314
+ }
315
+ function upTo(text, separator) {
316
+ const end = text.indexOf(separator);
317
+ return end === -1 ? text : text.slice(0, end);
318
+ }
319
+ function formatAge(date, now = Date.now()) {
320
+ const at = typeof date === "number" ? date : Date.parse(date);
321
+ if (Number.isNaN(at))
322
+ return "-";
323
+ const seconds = (now - at) / 1000;
324
+ return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
325
+ }
326
+ function truncate(text, width) {
327
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
328
+ }
329
+ var LINE_BREAKS = /\s*\n\s*/g;
330
+ var ESCAPE = String.fromCharCode(27);
331
+ function textWidth(text) {
332
+ return Bun.stringWidth(text);
333
+ }
334
+ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
335
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
336
+ const widths = [];
337
+ for (const row of cells) {
338
+ for (const [index, cell] of row.entries())
339
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
340
+ }
341
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
342
+ const colors = paint(process2.stdout);
343
+ const lines = shown.map((row) => row.map((cell, index) => {
344
+ const width = widths[index] ?? 0;
345
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
346
+ if (align[index] === "right")
347
+ return `${gap}${cell}`;
348
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
349
+ }).join(" ").trimEnd());
350
+ return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
351
+ `);
352
+ }
353
+ function narrow(rows, widths, limit) {
354
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
355
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
356
+ const floor = 8;
357
+ while (used() > limit) {
358
+ let widest = -1;
359
+ for (const [index, width] of widths.entries()) {
360
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
361
+ widest = index;
362
+ }
363
+ if (widest === -1)
364
+ break;
365
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
366
+ }
367
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
368
+ }
369
+ function printJson(value) {
370
+ console.log(JSON.stringify(value, undefined, 2));
371
+ }
372
+
373
+ // ../kit/src/text.ts
374
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
375
+ function distance(a, b) {
376
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
377
+ for (const [i, left] of [...a].entries()) {
378
+ const current = [i + 1];
379
+ for (const [j, right] of [...b].entries())
380
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
381
+ previous = current;
382
+ }
383
+ return previous[b.length] ?? 0;
384
+ }
385
+ function closest(name, names) {
386
+ const started = names.find((known) => known.startsWith(name));
387
+ if (started !== undefined)
388
+ return started;
389
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
390
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
391
+ }
392
+
393
+ // ../kit/src/args.ts
394
+ function jsonOption(holds) {
395
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
396
+ }
397
+
398
+ class Exit extends Error {
399
+ code;
400
+ hint;
401
+ constructor(message, code, hint) {
402
+ super(message);
403
+ this.code = code;
404
+ this.hint = hint;
405
+ }
406
+ }
407
+ function fail(message, code = 2, hint) {
408
+ throw new Exit(message, code, hint);
409
+ }
410
+
411
+ class UsageError extends Exit {
412
+ constructor(message, hint) {
413
+ super(message, 2, hint);
414
+ }
415
+ }
416
+ function badUsage(message) {
417
+ throw new UsageError(message);
418
+ }
419
+
420
+ class HelpShown extends Exit {
421
+ constructor() {
422
+ super("help shown", 0);
423
+ }
424
+ }
425
+
426
+ class Completing {
427
+ options;
428
+ constructor(options) {
429
+ this.options = options;
430
+ }
431
+ }
432
+ var completion = { active: false };
433
+ var OPTIONAL = /\[[^\]]+\]/g;
434
+ var USAGE_PREFIX = /^usage:\s*/i;
435
+ var FULL_STOP = /\.$/;
436
+ var DASHES = /^-+/;
437
+ function usageLine(usage, colors = paint(process3.stdout)) {
438
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
439
+ }
440
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
441
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
442
+ `);
443
+ }
444
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
445
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
446
+ }
447
+ function wantsHelpJson(env = process3.env) {
448
+ return env.KIT_HELP === "json";
449
+ }
450
+ function description(usage, { examples = [], replaces } = {}) {
451
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
452
+ `);
453
+ const first = lines[0];
454
+ const colon = first.indexOf(": ");
455
+ const prose = lines[lines.indexOf("") + 1] ?? "";
456
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
457
+ return {
458
+ synopsis: colon === -1 ? first : first.slice(0, colon),
459
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
460
+ ...replaces === undefined ? {} : { replaces },
461
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
462
+ };
463
+ }
464
+ function exampleRows(examples, colors = paint(process3.stdout)) {
465
+ if (examples.length === 0)
466
+ return [];
467
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
468
+ }
469
+ function optionRows(options, colors = paint(process3.stdout)) {
470
+ const rows = Object.entries(options).map(([name, option]) => {
471
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
472
+ const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
473
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
474
+ });
475
+ const width = Math.max(0, ...rows.map((row) => row.width));
476
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
477
+ }
478
+ var OUTPUT_OPTIONS = {
479
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
480
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
481
+ };
482
+ function applyOutput(color, plain, env = process3.env) {
483
+ const when = plain === true ? "never" : color ?? "auto";
484
+ if (when === "auto")
485
+ return;
486
+ if (when !== "always" && when !== "never")
487
+ badUsage(`--color takes auto, always or never, not ${when}`);
488
+ if (when === "always") {
489
+ env.FORCE_COLOR = "1";
490
+ delete env.NO_COLOR;
491
+ } else {
492
+ env.NO_COLOR = "1";
493
+ delete env.FORCE_COLOR;
494
+ }
495
+ }
496
+ function parse(args, usage, options, settings = {}) {
497
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
498
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
499
+ if (completion.active)
500
+ throw new Completing(all);
501
+ const separator = settings.rest === true ? args.indexOf("--") : -1;
502
+ const own = separator === -1 ? args : args.slice(0, separator);
503
+ const rest = separator === -1 ? undefined : args.slice(separator + 1);
504
+ let parsed;
505
+ try {
506
+ parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
507
+ } catch (error) {
508
+ const message = parseError(error);
509
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
510
+ }
511
+ const values = parsed.values;
512
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
513
+ if (values.help === true) {
514
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
515
+ throw new HelpShown;
516
+ }
517
+ if (settings.positionals !== undefined)
518
+ checkPositionals(parsed.positionals, settings.positionals);
519
+ return { ...parsed, positionals: parsed.positionals, rest };
520
+ }
521
+ function checkPositionals(given, names) {
522
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
523
+ const required = names.filter((name) => !name.startsWith("[")).length;
524
+ if (given.length < required)
525
+ badUsage(`missing ${names[given.length]}`);
526
+ if (!variadic && given.length > names.length)
527
+ badUsage(`unexpected argument ${given[names.length]}`);
528
+ }
529
+ function joinDashValues(args, options) {
530
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
531
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
532
+ const joined = [];
533
+ for (let i = 0;i < args.length; i++) {
534
+ const arg = args[i] ?? "";
535
+ if (arg === "--")
536
+ return [...joined, ...args.slice(i)];
537
+ const name = longOf.get(arg);
538
+ const next = args[i + 1];
539
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
540
+ joined.push(`--${name}=${next}`);
541
+ i++;
542
+ } else {
543
+ joined.push(arg);
544
+ }
545
+ }
546
+ return joined;
547
+ }
548
+ function parseError(error) {
549
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
550
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
551
+ }
552
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
553
+ function nearestOption(message, options, allowNegative) {
554
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
555
+ if (typed === undefined)
556
+ return;
557
+ const word = typed.replace(DASHES, "");
558
+ if (word.length < 2 && !typed.startsWith("--"))
559
+ return;
560
+ const known = Object.entries(options).flatMap(([name, option]) => [
561
+ ...option.short === undefined ? [] : [`-${option.short}`],
562
+ `--${name}`,
563
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
564
+ ]);
565
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
566
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
567
+ }
568
+ var WHOLE = /^\d+$/;
569
+ function wholeNumber(value, name, fallback, min = 1) {
570
+ if (value === undefined)
571
+ return fallback;
572
+ const number = Number(value);
573
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
574
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
575
+ return number;
576
+ }
577
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
578
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
579
+ function duration(value, name, fallback, unit = "s") {
580
+ if (value === undefined)
581
+ return fallback;
582
+ const match = DURATION.exec(value.trim());
583
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
584
+ if (ms < 1)
585
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
586
+ return ms;
587
+ }
588
+ // ../kit/src/progress.ts
589
+ import process5 from "process";
590
+
591
+ // ../kit/src/process.ts
592
+ import { constants } from "os";
593
+ import process4 from "process";
594
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
595
+ function exitCodeOf(code, signal) {
596
+ if (code !== null)
597
+ return code;
598
+ if (typeof signal === "number")
599
+ return 128 + signal;
600
+ return signal === null ? 129 : 128 + constants.signals[signal];
601
+ }
602
+ function holdSignals(cleanup) {
603
+ let received;
604
+ let child;
605
+ const held = {
606
+ get signal() {
607
+ return received;
608
+ },
609
+ forward: (to) => {
610
+ child = to;
611
+ },
612
+ release: () => {
613
+ for (const signal of SIGNALS)
614
+ process4.off(signal, onSignal);
615
+ }
616
+ };
617
+ function onSignal(signal) {
618
+ received = signal;
619
+ if (child !== undefined) {
620
+ child.kill(signal);
621
+ return;
622
+ }
623
+ if (cleanup === undefined)
624
+ return;
625
+ held.release();
626
+ cleanup(signal);
627
+ process4.kill(process4.pid, signal);
628
+ }
629
+ for (const signal of SIGNALS)
630
+ process4.on(signal, onSignal);
631
+ return held;
632
+ }
633
+
634
+ // ../kit/src/progress.ts
635
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
636
+ var FRAME_MS = 200;
637
+ var CLEAR_LINE = "\r\x1B[2K";
638
+ var LINE_UP = "\x1B[1A\x1B[2K";
639
+ var ESC = String.fromCharCode(27);
640
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
641
+ var RESET_STYLE = `${ESC}[0m`;
642
+ var CTRL_C = 3;
643
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
644
+ var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
645
+ function liveRegion(render, stream = process5.stderr, env = process5.env) {
646
+ if (!takesControlCodes(stream, env))
647
+ return { redraw: () => {
648
+ return;
649
+ }, print: (text) => void stream.write(`${text}
650
+ `), stop: () => {
651
+ return;
652
+ } };
653
+ const write = stream.write.bind(stream);
654
+ let frame = 0;
655
+ let drawn = 0;
656
+ const clear = () => {
657
+ if (drawn > 0)
658
+ write(`${CLEAR_LINE}${LINE_UP.repeat(drawn - 1)}`);
659
+ drawn = 0;
660
+ };
661
+ const draw = () => {
662
+ const width = (stream.columns === undefined || stream.columns === 0 ? 80 : stream.columns) - 1;
663
+ const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
664
+ const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
665
+ if (lines.length === 0) {
666
+ clear();
667
+ return;
668
+ }
669
+ write(`${drawn > 0 ? `${CLEAR_LINE}${LINE_UP.repeat(drawn - 1)}` : CLEAR_LINE}${lines.join(`
670
+ `)}`);
671
+ drawn = lines.length;
672
+ };
673
+ const timer = setInterval(draw, FRAME_MS);
674
+ const restore = interceptOutput(clear);
675
+ const release = swallowInput();
676
+ const onExit = () => {
677
+ clear();
678
+ release();
679
+ };
680
+ const signals = holdSignals(stop);
681
+ function stop() {
682
+ clearInterval(timer);
683
+ clear();
684
+ restore();
685
+ release();
686
+ process5.off("exit", onExit);
687
+ signals.release();
688
+ }
689
+ timer.unref();
690
+ process5.on("exit", onExit);
691
+ return {
692
+ redraw: draw,
693
+ print: (text) => {
694
+ clear();
695
+ write(`${text}
696
+ `);
697
+ draw();
698
+ },
699
+ stop
700
+ };
701
+ }
702
+ function cutToWidth(line, width) {
703
+ if (Bun.stringWidth(line) <= width)
704
+ return line;
705
+ let room = width;
706
+ let kept = "";
707
+ let index = 0;
708
+ let linked = false;
709
+ while (index < line.length) {
710
+ ESCAPE_CODE.lastIndex = index;
711
+ const escape = ESCAPE_CODE.exec(line);
712
+ if (escape !== null) {
713
+ kept += escape[0];
714
+ linked ||= escape[0].startsWith(`${ESC}]`);
715
+ index = ESCAPE_CODE.lastIndex;
716
+ continue;
717
+ }
718
+ const char = String.fromCodePoint(line.codePointAt(index));
719
+ const columns = Bun.stringWidth(char);
720
+ if (columns > room)
721
+ break;
722
+ kept += char;
723
+ room -= columns;
724
+ index += char.length;
725
+ }
726
+ return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
727
+ }
728
+ function swallowInput() {
729
+ const input = process5.stdin;
730
+ if (!input.isTTY)
731
+ return () => {
732
+ return;
733
+ };
734
+ const onData = (data) => {
735
+ if (data.includes(CTRL_C))
736
+ process5.kill(process5.pid, "SIGINT");
737
+ };
738
+ input.setRawMode(true);
739
+ input.on("data", onData);
740
+ input.resume();
741
+ let released = false;
742
+ return () => {
743
+ if (released)
744
+ return;
745
+ released = true;
746
+ input.off("data", onData);
747
+ input.pause();
748
+ input.setRawMode(false);
749
+ };
750
+ }
751
+ function interceptOutput(clear) {
752
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process5.stdout, "write"], [process5.stderr, "write"]];
753
+ const wrapped = targets.map(([target, name]) => {
754
+ const original = Reflect.get(target, name);
755
+ const wrapper = (...args) => {
756
+ clear();
757
+ return original.apply(target, args);
758
+ };
759
+ Reflect.set(target, name, wrapper);
760
+ return { target, name, original, wrapper };
761
+ });
762
+ return () => {
763
+ for (const { target, name, original, wrapper } of wrapped) {
764
+ if (Reflect.get(target, name) === wrapper)
765
+ Reflect.set(target, name, original);
766
+ }
767
+ };
768
+ }
769
+ // ../kit/src/cli.ts
770
+ import process6 from "process";
771
+ var LEVEL_OPTIONS = {
772
+ ...OUTPUT_OPTIONS,
773
+ help: { type: "boolean", short: "h", description: "show this help" }
774
+ };
775
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
776
+ function printError(prefix, message, hint, cause) {
777
+ const colors = paint(process6.stderr);
778
+ const styled = takesControlCodes(process6.stderr);
779
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
780
+ const under = (label, text, tint) => text === undefined ? "" : `
781
+ ${styled ? tint(label) : `${label}:`} ${text}`;
782
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
783
+ }
784
+ function printJsonError(message, hint, cause) {
785
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
786
+ }
787
+ function wantsJson(argv) {
788
+ const end = argv.indexOf("--");
789
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
790
+ }
791
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
792
+ if (error instanceof HelpShown)
793
+ return 0;
794
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
795
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
796
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
797
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
798
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
799
+ return error instanceof Exit ? error.code : 1;
800
+ }
801
+ var COMPLETE = "__complete";
802
+ var FILES = "__files__";
803
+ async function optionsOf(run) {
804
+ completion.active = true;
805
+ try {
806
+ await run([]);
807
+ } catch (error) {
808
+ if (error instanceof Completing)
809
+ return error.options;
810
+ } finally {
811
+ completion.active = false;
812
+ }
813
+ return {};
814
+ }
815
+ async function leafCandidates(run, words) {
816
+ if (!(words.at(-1) ?? "").startsWith("-"))
817
+ return [FILES];
818
+ return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
819
+ }
820
+ async function printCandidates(found) {
821
+ for (const line of await found)
822
+ console.log(line);
823
+ return 0;
824
+ }
825
+ async function runMain({ name, version, run, redact }, argv = process6.argv.slice(2)) {
826
+ if (argv[0] === COMPLETE)
827
+ return printCandidates(leafCandidates(run, argv.slice(1)));
828
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
829
+ console.log(version);
830
+ return 0;
831
+ }
832
+ try {
833
+ return await run(argv);
834
+ } catch (error) {
835
+ return reportThrown(name, error, redact, wantsJson(argv));
836
+ }
837
+ }
838
+ // ../kit/src/logs.ts
839
+ import { lstatSync, openSync } from "fs";
840
+ import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
841
+ import { homedir, tmpdir } from "os";
842
+ import { join } from "path";
843
+ import process7 from "process";
844
+ var DAY_MS = 24 * 60 * 60 * 1000;
845
+ var CLI_FOLDER = "kaynooo-cli";
846
+ function isPrivateDirectory(path) {
847
+ try {
848
+ const info = lstatSync(path, { throwIfNoEntry: false });
849
+ return info !== undefined && info.isDirectory() && info.uid === (process7.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
850
+ } catch {
851
+ return false;
852
+ }
853
+ }
854
+ async function privateLogDirectory(name, env = process7.env) {
855
+ const runtime = env.XDG_RUNTIME_DIR;
856
+ const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
857
+ const path = join(base, name);
858
+ try {
859
+ await mkdir(path, { recursive: true, mode: 448 });
860
+ if (isPrivateDirectory(path))
861
+ return path;
862
+ } catch {}
863
+ return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
864
+ }
865
+ // ../kit/src/secrets.ts
866
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
867
+ // ../kit/src/sessions.ts
868
+ import { homedir as homedir2 } from "os";
869
+ import { join as join2 } from "path";
870
+ import process8 from "process";
871
+ var {Glob } = globalThis.Bun;
872
+ var SESSION_FILES = new Glob("*.json");
873
+ var ACCOUNT_DIRS = new Glob("*/sessions");
874
+ async function sessionDirs() {
875
+ const home = homedir2();
876
+ const dirs = new Set([join2(home, ".claude", "sessions")]);
877
+ if (process8.env.CLAUDE_CONFIG_DIR !== undefined)
878
+ dirs.add(join2(process8.env.CLAUDE_CONFIG_DIR, "sessions"));
879
+ try {
880
+ for await (const dir of ACCOUNT_DIRS.scan({ cwd: join2(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
881
+ dirs.add(dir);
882
+ } catch {}
883
+ return [...dirs];
884
+ }
885
+ async function procStat(pid) {
886
+ try {
887
+ const stat = await Bun.file(`/proc/${pid}/stat`).text();
888
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ");
889
+ } catch {
890
+ return;
891
+ }
892
+ }
893
+ async function isAlive(pid, procStart) {
894
+ const stat = await procStat(pid);
895
+ if (stat === undefined)
896
+ return false;
897
+ return procStart === undefined || stat[19] === procStart;
898
+ }
899
+ async function liveSessions() {
900
+ const sessions = new Map;
901
+ for (const dir of await sessionDirs()) {
902
+ let files;
903
+ try {
904
+ files = await Array.fromAsync(SESSION_FILES.scan({ cwd: dir, absolute: true }));
905
+ } catch {
906
+ continue;
907
+ }
908
+ for (const file of files) {
909
+ let entry;
910
+ try {
911
+ entry = await Bun.file(file).json();
912
+ } catch {
913
+ continue;
914
+ }
915
+ if (entry.name === undefined || entry.pid === undefined || sessions.has(entry.pid) || !await isAlive(entry.pid, entry.procStart))
916
+ continue;
917
+ sessions.set(entry.pid, { name: entry.name, pid: entry.pid, status: entry.status ?? "unknown", cwd: entry.cwd ?? "" });
918
+ }
919
+ }
920
+ return [...sessions.values()];
921
+ }
922
+ async function currentSession(sessions) {
923
+ const byPid = new Map(sessions.map((session) => [session.pid, session]));
924
+ let pid = process8.ppid;
925
+ for (let depth = 0;depth < 32 && pid > 1; depth++) {
926
+ const session = byPid.get(pid);
927
+ if (session !== undefined)
928
+ return session;
929
+ const parent = Number((await procStat(pid))?.[1]);
930
+ if (!Number.isInteger(parent))
931
+ return;
932
+ pid = parent;
933
+ }
934
+ return;
935
+ }
936
+ // package.json
937
+ var version = "0.5.0";
938
+
939
+ // src/slot.ts
940
+ import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync } from "fs";
941
+ import { availableParallelism } from "os";
942
+ import { join as join3 } from "path";
943
+ import process11 from "process";
944
+
945
+ // src/flock.ts
946
+ import { closeSync, constants as constants2, ftruncateSync, openSync as openSync2, writeSync } from "fs";
947
+ import process10 from "process";
948
+ import { dlopen, FFIType } from "bun:ffi";
949
+ var LOCK_EX = 2;
950
+ var LOCK_NB = 4;
951
+ var flock;
952
+ function native() {
953
+ flock ??= dlopen(process10.platform === "darwin" ? "libSystem.B.dylib" : "libc.so.6", { flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } }).symbols.flock;
954
+ return flock;
955
+ }
956
+ function tryLock(path) {
957
+ const fd = openSync2(path, constants2.O_RDWR | constants2.O_CREAT, 384);
958
+ if (native()(fd, LOCK_EX | LOCK_NB) !== 0) {
959
+ closeSync(fd);
960
+ return;
961
+ }
962
+ return { fd, release: () => closeSync(fd) };
963
+ }
964
+ function writeHeld(held, text) {
965
+ ftruncateSync(held.fd);
966
+ writeSync(held.fd, text, 0);
967
+ }
968
+
969
+ // src/slot.ts
970
+ var RUN_USAGE = `slot [options] -- <cmd>...: waits for a free machine-wide slot, then runs the command and exits with its code
971
+ slot ls [--json]: lists who holds a slot or a lock and who waits for one (slot ls --help)
972
+
973
+ The slots and locks are shared by every session, worktree and shell of this user, so heavy jobs (phpunit, playwright, vue-tsc, eslint) queue instead of overloading the machine.
974
+ A slot or lock is freed the moment its holder ends, SIGKILL included, since the kernel drops it with the process.
975
+ A slotted command that runs slot again does not wait for a second slot, so wrapping both a script and the commands inside it cannot deadlock.
976
+ A first word \`ls\` always means the listing, so run the ls command as \`slot -n 4 -- ls\` or by its path.
977
+ Exits with the command's code, 2 on a timeout or a usage error.`;
978
+ var LS_USAGE = `slot ls [options]: lists the slots and locks held, with the session, the command and how long ago it started, then who waits for one
979
+
980
+ --json prints {slots, busy, entries}, each entry as {state, resource, pid, session, command, cwd, since}.`;
981
+ var SLOTS = { type: "string", short: "n", description: "how many commands may hold a slot at once (half the CPU count)" };
982
+ var RUN_OPTIONS = {
983
+ lock: { type: "string", short: "l", multiple: true, description: "a named lock to hold as well, for what must not run twice at once (booki-test-db)" },
984
+ "no-slot": { type: "boolean", description: "take the --lock alone, without a slot" },
985
+ slots: SLOTS,
986
+ timeout: { type: "string", short: "t", description: "how long to wait before giving up (30s, 5m, 1h, a bare number in seconds), forever by default" }
987
+ };
988
+ var LS_OPTIONS = { slots: SLOTS, json: jsonOption() };
989
+ var POLL = 250;
990
+ var COMMAND_WIDTH = 60;
991
+ var LOCK_NAME = /^\w[\w.-]*$/;
992
+ var HOLDING = "SLOT_HOLDING";
993
+ function defaultSlots() {
994
+ return Math.max(1, Math.floor(availableParallelism() / 2));
995
+ }
996
+ async function stateDir() {
997
+ const dir = process11.env.SLOT_DIR ?? await privateLogDirectory("slot");
998
+ for (const sub of ["slots", "locks", "waiters"])
999
+ mkdirSync(join3(dir, sub), { recursive: true, mode: 448 });
1000
+ return dir;
1001
+ }
1002
+ function readHolder(path) {
1003
+ try {
1004
+ const holder = JSON.parse(readFileSync(path, "utf8"));
1005
+ return typeof holder.pid === "number" && typeof holder.command === "string" ? { pid: holder.pid, command: holder.command, cwd: holder.cwd ?? "", since: holder.since ?? 0, ...holder.session === undefined ? {} : { session: holder.session }, ...holder.resource === undefined ? {} : { resource: holder.resource } } : undefined;
1006
+ } catch {
1007
+ return;
1008
+ }
1009
+ }
1010
+ function pathOf(dir, kind, name) {
1011
+ return join3(dir, kind === "slot" ? "slots" : "locks", name);
1012
+ }
1013
+ function candidates(dir, { kind, name, count }) {
1014
+ if (kind === "lock")
1015
+ return [{ path: pathOf(dir, "lock", name), resource: `lock ${name}` }];
1016
+ return Array.from({ length: count }, (_, index) => ({ path: pathOf(dir, "slot", String(index)), resource: `slot ${index + 1}` }));
1017
+ }
1018
+ function attempt(dir, wanted) {
1019
+ for (const { path, resource } of candidates(dir, wanted)) {
1020
+ const held = tryLock(path);
1021
+ if (held !== undefined)
1022
+ return { held, resource };
1023
+ }
1024
+ return;
1025
+ }
1026
+ function who(holder) {
1027
+ return `${holder.session ?? `pid ${holder.pid}`} running ${truncate(holder.command, COMMAND_WIDTH)} for ${formatDuration(Date.now() - holder.since)}`;
1028
+ }
1029
+ function waitingLine(dir, wanted) {
1030
+ const holders = candidates(dir, wanted).map(({ path }) => readHolder(path)).filter((holder) => holder !== undefined).sort((a, b) => a.since - b.since);
1031
+ const oldest = holders[0];
1032
+ const by = oldest === undefined ? "another process" : who(oldest);
1033
+ if (wanted.kind === "lock")
1034
+ return `slot: waiting for lock ${wanted.name}, held by ${by}`;
1035
+ return `slot: waiting for a slot (${holders.length} of ${wanted.count} busy), the oldest held by ${by}`;
1036
+ }
1037
+ async function holderOf(command) {
1038
+ const session = await currentSession(await liveSessions());
1039
+ return { pid: process11.pid, command: command.join(" "), cwd: process11.cwd(), since: Date.now(), ...session === undefined ? {} : { session: session.name } };
1040
+ }
1041
+ var waiterCount = 0;
1042
+ async function acquire(dir, resources, holder, deadline, timeoutMs) {
1043
+ let waiter;
1044
+ try {
1045
+ for (;; ) {
1046
+ const taken = [];
1047
+ let busy;
1048
+ for (const wanted of resources) {
1049
+ const got = attempt(dir, wanted);
1050
+ if (got === undefined) {
1051
+ busy = wanted;
1052
+ break;
1053
+ }
1054
+ taken.push(got);
1055
+ }
1056
+ if (busy === undefined) {
1057
+ for (const { held } of taken)
1058
+ writeHeld(held, JSON.stringify(holder));
1059
+ return taken;
1060
+ }
1061
+ for (const { held } of taken)
1062
+ held.release();
1063
+ const resource = busy.kind === "lock" ? `lock ${busy.name}` : "slot";
1064
+ if (waiter === undefined) {
1065
+ const path = join3(dir, "waiters", `${process11.pid}-${waiterCount++}`);
1066
+ const held = tryLock(path);
1067
+ if (held !== undefined) {
1068
+ writeHeld(held, JSON.stringify({ ...holder, resource }));
1069
+ waiter = { held, path, resource };
1070
+ }
1071
+ console.error(waitingLine(dir, busy));
1072
+ } else if (waiter.resource !== resource) {
1073
+ writeHeld(waiter.held, JSON.stringify({ ...holder, resource }));
1074
+ waiter.resource = resource;
1075
+ }
1076
+ if (Date.now() >= deadline)
1077
+ fail(`gave up after ${formatDuration(timeoutMs)} waiting for ${busy.kind === "lock" ? `lock ${busy.name}` : "a slot"}`);
1078
+ await Bun.sleep(POLL);
1079
+ }
1080
+ } finally {
1081
+ if (waiter !== undefined) {
1082
+ unlinkSync(waiter.path);
1083
+ waiter.held.release();
1084
+ }
1085
+ }
1086
+ }
1087
+ async function runSlotted(args) {
1088
+ const bare = args[0] !== undefined && !args[0].startsWith("-");
1089
+ const parsed = parse(bare ? [] : args, RUN_USAGE, RUN_OPTIONS, { rest: true, replaces: "flock wrappers, hand-written heavy.sh queues and parallel runs fighting over one test database", examples: [["slot -- bunx vue-tsc", "wait for a free slot, then type-check"], ["slot --lock booki-test-db -- vendor/bin/phpunit", "one phpunit at a time on the shared test database"], "slot ls"] });
1090
+ const { values } = parsed;
1091
+ const rest = bare ? args : parsed.rest;
1092
+ if (rest === undefined || rest.length === 0)
1093
+ fail(`give the command after --
1094
+
1095
+ ${RUN_USAGE}`);
1096
+ const locks = [...new Set(values.lock ?? [])].sort();
1097
+ for (const name of locks) {
1098
+ if (!LOCK_NAME.test(name))
1099
+ fail(`--lock ${name} is no lock name: letters, digits, dots, dashes and underscores`);
1100
+ }
1101
+ if (values["no-slot"] === true && locks.length === 0)
1102
+ fail("--no-slot takes the --lock alone, and none is given");
1103
+ const count = wholeNumber(values.slots, "slots", defaultSlots());
1104
+ const timeoutMs = duration(values.timeout, "timeout", Number.POSITIVE_INFINITY);
1105
+ const deadline = Date.now() + timeoutMs;
1106
+ const holding = new Set((process11.env[HOLDING] ?? "").split(",").filter((token) => token !== ""));
1107
+ const wanted = [...locks.filter((name) => !holding.has(`lock:${name}`)).map((name) => ({ kind: "lock", name, count })), ...values["no-slot"] === true || holding.has("slot") ? [] : [{ kind: "slot", name: "", count }]];
1108
+ const signals = holdSignals(() => {
1109
+ return;
1110
+ });
1111
+ const taken = [];
1112
+ try {
1113
+ if (wanted.length > 0) {
1114
+ const dir = await stateDir();
1115
+ const holder = await holderOf(rest);
1116
+ taken.push(...await acquire(dir, wanted, holder, deadline, timeoutMs));
1117
+ }
1118
+ const tokens = new Set([...holding, ...locks.map((name) => `lock:${name}`), ...wanted.some((resource) => resource.kind === "slot") ? ["slot"] : []]);
1119
+ let child;
1120
+ try {
1121
+ child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...process11.env, [HOLDING]: [...tokens].join(",") } });
1122
+ } catch (error) {
1123
+ fail(`cannot run ${rest[0]}: ${error instanceof Error ? error.message : String(error)}`, 127);
1124
+ }
1125
+ signals.forward(child);
1126
+ await child.exited;
1127
+ return exitCodeOf(child.exitCode, child.signalCode);
1128
+ } finally {
1129
+ signals.release();
1130
+ for (const { held } of taken)
1131
+ held.release();
1132
+ }
1133
+ }
1134
+ function scan(dir, state, kind) {
1135
+ const folder = join3(dir, kind);
1136
+ const entries = [];
1137
+ for (const name of existsSync(folder) ? readdirSync(folder) : []) {
1138
+ const path = join3(folder, name);
1139
+ const probe = tryLock(path);
1140
+ if (probe !== undefined) {
1141
+ if (kind === "waiters")
1142
+ unlinkSync(path);
1143
+ probe.release();
1144
+ continue;
1145
+ }
1146
+ const holder = readHolder(path);
1147
+ const resource = kind === "waiters" ? holder?.resource ?? "slot" : `${kind === "slots" ? "slot" : "lock"} ${kind === "slots" ? Number(name) + 1 : name}`;
1148
+ entries.push({ state, resource, pid: holder?.pid ?? 0, command: holder?.command ?? "?", cwd: holder?.cwd ?? "", since: holder?.since ?? 0, ...holder?.session === undefined ? {} : { session: holder.session } });
1149
+ }
1150
+ return entries;
1151
+ }
1152
+ async function listSlots(args) {
1153
+ const { values } = parse(args, LS_USAGE, LS_OPTIONS, { examples: ["slot ls", "slot ls --json"] });
1154
+ const count = wholeNumber(values.slots, "slots", defaultSlots());
1155
+ const dir = await stateDir();
1156
+ const holding = [...scan(dir, "holding", "slots"), ...scan(dir, "holding", "locks")].sort((a, b) => a.since - b.since);
1157
+ const waiting = scan(dir, "waiting", "waiters").sort((a, b) => a.since - b.since);
1158
+ const entries = [...holding, ...waiting];
1159
+ const busy = holding.filter((entry) => entry.resource.startsWith("slot ")).length;
1160
+ if (values.json === true) {
1161
+ printJson({ slots: count, busy, entries });
1162
+ return 0;
1163
+ }
1164
+ console.log(`slots: ${busy} of ${count} busy`);
1165
+ if (entries.length > 0)
1166
+ console.log(table(entries.map((entry) => [entry.state, entry.resource, entry.session ?? `pid ${entry.pid}`, truncate(entry.command, COMMAND_WIDTH), entry.since === 0 ? "?" : formatAge(entry.since)])));
1167
+ return 0;
1168
+ }
1169
+
1170
+ // src/slot-cli.ts
1171
+ process12.exitCode = await runMain({ name: "slot", version, run: async (args) => args[0] === "ls" ? listSlots(args.slice(1)) : runSlotted(args) });