@kaynooo/cli-wait 0.12.6 → 0.12.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/chunk-p9bag6re.js +74 -0
- package/dist/cli.js +12 -2245
- package/dist/slot-cli.js +4 -1962
- package/package.json +3 -6
package/dist/slot-cli.js
CHANGED
|
@@ -1,1970 +1,12 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
var
|
|
4
|
-
if (fn)
|
|
5
|
-
try {
|
|
6
|
-
res = fn(fn = 0);
|
|
7
|
-
} catch (e) {
|
|
8
|
-
err = [e];
|
|
9
|
-
}
|
|
10
|
-
if (err)
|
|
11
|
-
throw err[0];
|
|
12
|
-
return res;
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
|
|
16
|
-
function Ao(t, e, r = "...") {
|
|
17
|
-
let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
|
|
18
|
-
if (t.length <= e)
|
|
19
|
-
return t;
|
|
20
|
-
let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
|
|
21
|
-
if (o && !Y.test(t[c.length] ?? " "))
|
|
22
|
-
c = c.replace(Nt, "") || c;
|
|
23
|
-
if (o)
|
|
24
|
-
c = c.trimEnd();
|
|
25
|
-
return s ? (c + n).slice(0, l) : c + n;
|
|
26
|
-
}
|
|
27
|
-
var N, Nt, Y, be, W;
|
|
28
|
-
var init_chunk_rkhsft4a = __esm(() => {
|
|
29
|
-
N = new Map;
|
|
30
|
-
Nt = /\s+\S*$/;
|
|
31
|
-
Y = /\s/;
|
|
32
|
-
be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
|
|
33
|
-
W = new Map;
|
|
34
|
-
});
|
|
35
|
-
|
|
36
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
|
|
37
|
-
var init_text = __esm(() => {
|
|
38
|
-
init_chunk_rkhsft4a();
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
// ../kit/src/mode.ts
|
|
42
|
-
import process2 from "process";
|
|
43
|
-
function isSet(value) {
|
|
44
|
-
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
45
|
-
}
|
|
46
|
-
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
47
|
-
const chosen = env.KIT_MODE;
|
|
48
|
-
if (chosen !== undefined && MODES.has(chosen))
|
|
49
|
-
return chosen;
|
|
50
|
-
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
51
|
-
return "agent";
|
|
52
|
-
if (stream.isTTY === true)
|
|
53
|
-
return "terminal";
|
|
54
|
-
return isSet(env.CI) ? "ci" : "pipe";
|
|
55
|
-
}
|
|
56
|
-
var MODES, AGENT_VARIABLES;
|
|
57
|
-
var init_mode = __esm(() => {
|
|
58
|
-
MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
59
|
-
AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
63
|
-
function b(r) {
|
|
64
|
-
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
65
|
-
if (!G2.test(e))
|
|
66
|
-
return [0, 0, 0];
|
|
67
|
-
if (e.length === 3 || e.length === 4)
|
|
68
|
-
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
69
|
-
if (e.length !== 6 && e.length !== 8)
|
|
70
|
-
throw Error(`Invalid hex color length: ${e.length}`);
|
|
71
|
-
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
72
|
-
}
|
|
73
|
-
function C(r, e = globalThis.process?.env ?? {}) {
|
|
74
|
-
if (e.FORCE_COLOR !== undefined)
|
|
75
|
-
return h.has(e.FORCE_COLOR);
|
|
76
|
-
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
77
|
-
return false;
|
|
78
|
-
return r?.isTTY === true;
|
|
79
|
-
}
|
|
80
|
-
function f(r, e = []) {
|
|
81
|
-
let l = "", n = "";
|
|
82
|
-
for (let t = 0, i = e.length;t < i; t++)
|
|
83
|
-
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
84
|
-
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
85
|
-
return new Proxy(c, { get(t, i) {
|
|
86
|
-
let a = B[i];
|
|
87
|
-
if (Array.isArray(a)) {
|
|
88
|
-
let s = g.get(i);
|
|
89
|
-
if (s === undefined)
|
|
90
|
-
s = f(r, [...e, a]), g.set(i, s);
|
|
91
|
-
return s;
|
|
92
|
-
}
|
|
93
|
-
if (typeof a === "function")
|
|
94
|
-
return (...s) => {
|
|
95
|
-
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
96
|
-
if (u === undefined) {
|
|
97
|
-
if (g.size >= 64)
|
|
98
|
-
g.clear();
|
|
99
|
-
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
100
|
-
}
|
|
101
|
-
return u;
|
|
102
|
-
};
|
|
103
|
-
throw Error(`Unknown style: ${String(i)}`);
|
|
104
|
-
} });
|
|
105
|
-
}
|
|
106
|
-
function Fe(r = {}) {
|
|
107
|
-
return f(r);
|
|
108
|
-
}
|
|
109
|
-
var G2, B, h, o;
|
|
110
|
-
var init_chunk_x450vn3m = __esm(() => {
|
|
111
|
-
G2 = /^[a-f0-9]+$/i;
|
|
112
|
-
B = { 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, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
|
|
113
|
-
let [l, n, c] = b(r);
|
|
114
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
115
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
116
|
-
h = new Set(["", "1", "2", "3", "true"]);
|
|
117
|
-
o = Fe();
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
|
|
121
|
-
var init_colors = __esm(() => {
|
|
122
|
-
init_chunk_x450vn3m();
|
|
123
|
-
});
|
|
124
|
-
|
|
125
|
-
// ../kit/src/config.ts
|
|
126
|
-
import { existsSync } from "fs";
|
|
127
|
-
import { dirname, join, resolve } from "path";
|
|
128
|
-
import process3 from "process";
|
|
129
|
-
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
130
|
-
const wanted = typeof names === "string" ? [names] : names;
|
|
131
|
-
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
132
|
-
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
133
|
-
if (found !== undefined)
|
|
134
|
-
return found;
|
|
135
|
-
if (stop(dir) || dirname(dir) === dir)
|
|
136
|
-
return;
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
var init_config = __esm(() => {
|
|
140
|
-
init_args();
|
|
141
|
-
});
|
|
142
|
-
|
|
143
|
-
// ../kit/src/user-config.ts
|
|
144
|
-
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
145
|
-
import { homedir } from "os";
|
|
146
|
-
import { isAbsolute, join as join2 } from "path";
|
|
147
|
-
import process4 from "process";
|
|
148
|
-
function xdgFolder(value, fallback) {
|
|
149
|
-
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
150
|
-
}
|
|
151
|
-
function configBase(where = {}) {
|
|
152
|
-
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
153
|
-
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
154
|
-
}
|
|
155
|
-
function userConfigPath(bin, where = {}) {
|
|
156
|
-
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
157
|
-
}
|
|
158
|
-
function userConfigReadPath(bin, legacy = [], where = {}) {
|
|
159
|
-
const current = userConfigPath(bin, where);
|
|
160
|
-
if (existsSync2(current))
|
|
161
|
-
return current;
|
|
162
|
-
const base = configBase(where);
|
|
163
|
-
return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
|
|
164
|
-
}
|
|
165
|
-
function readUserConfig(bin, where = {}, legacy = []) {
|
|
166
|
-
const path = userConfigReadPath(bin, legacy, where);
|
|
167
|
-
if (!existsSync2(path))
|
|
168
|
-
return {};
|
|
169
|
-
try {
|
|
170
|
-
const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
|
|
171
|
-
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
|
|
172
|
-
} catch {
|
|
173
|
-
return {};
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
|
|
177
|
-
const value = readUserConfig(bin, where, legacy)[key];
|
|
178
|
-
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
|
|
179
|
-
}
|
|
180
|
-
var init_user_config = () => {};
|
|
181
|
-
|
|
182
|
-
// ../kit/src/theme.ts
|
|
183
|
-
import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
|
|
184
|
-
import { homedir as homedir2 } from "os";
|
|
185
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
186
|
-
import process5 from "process";
|
|
187
|
-
function isColorSpec(spec) {
|
|
188
|
-
if (typeof spec === "number")
|
|
189
|
-
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
190
|
-
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
191
|
-
}
|
|
192
|
-
function cubeLevel(channel) {
|
|
193
|
-
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
194
|
-
}
|
|
195
|
-
function nearest256(hex) {
|
|
196
|
-
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
197
|
-
const levels = rgb.map(cubeLevel);
|
|
198
|
-
const cube = levels.map((level) => CUBE[level]);
|
|
199
|
-
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
200
|
-
const greyValue = 8 + grey * 10;
|
|
201
|
-
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
202
|
-
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
203
|
-
}
|
|
204
|
-
function hasTrueColor(env) {
|
|
205
|
-
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
206
|
-
}
|
|
207
|
-
function tinted(colors, spec, env = process5.env) {
|
|
208
|
-
if (typeof spec === "number")
|
|
209
|
-
return colors.ansi256(spec);
|
|
210
|
-
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
211
|
-
if (HEX.test(token))
|
|
212
|
-
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
213
|
-
return chain[token] ?? chain;
|
|
214
|
-
}, colors);
|
|
215
|
-
}
|
|
216
|
-
function isRecord(value) {
|
|
217
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
218
|
-
}
|
|
219
|
-
function readThemeFile(path, warn) {
|
|
220
|
-
try {
|
|
221
|
-
const stat = statSync(path, { throwIfNoEntry: false });
|
|
222
|
-
if (stat === undefined)
|
|
223
|
-
return;
|
|
224
|
-
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
225
|
-
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
226
|
-
return;
|
|
227
|
-
}
|
|
228
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
229
|
-
if (isRecord(parsed))
|
|
230
|
-
return parsed;
|
|
231
|
-
warn(`${path} is not a JSON object, theme ignored`);
|
|
232
|
-
} catch (error) {
|
|
233
|
-
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
234
|
-
}
|
|
235
|
-
return;
|
|
236
|
-
}
|
|
237
|
-
function applyPreset(theme, name, warn, where) {
|
|
238
|
-
if (name === undefined)
|
|
239
|
-
return;
|
|
240
|
-
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
241
|
-
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
242
|
-
return;
|
|
243
|
-
}
|
|
244
|
-
const preset = PRESETS[name];
|
|
245
|
-
Object.assign(theme.colors, preset.colors);
|
|
246
|
-
Object.assign(theme.glyphs, preset.glyphs);
|
|
247
|
-
if (preset.accents !== undefined)
|
|
248
|
-
theme.accents = [...preset.accents];
|
|
249
|
-
if (Object.hasOwn(preset, "gradient"))
|
|
250
|
-
theme.gradient = preset.gradient;
|
|
251
|
-
return name;
|
|
252
|
-
}
|
|
253
|
-
function applyFile(theme, file, where, warn) {
|
|
254
|
-
if (isRecord(file.colors)) {
|
|
255
|
-
for (const [key, value] of Object.entries(file.colors)) {
|
|
256
|
-
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
257
|
-
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
258
|
-
else if (!isColorSpec(value))
|
|
259
|
-
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
260
|
-
else
|
|
261
|
-
theme.colors[key] = value;
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
if (isRecord(file.glyphs)) {
|
|
265
|
-
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
266
|
-
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
267
|
-
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
268
|
-
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
269
|
-
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
270
|
-
else
|
|
271
|
-
theme.glyphs[key] = value;
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
275
|
-
theme.accents = [...file.accents];
|
|
276
|
-
else if (file.accents !== undefined)
|
|
277
|
-
warn(`${where}: accents must be a non-empty list of colours`);
|
|
278
|
-
if (file.gradient === null)
|
|
279
|
-
theme.gradient = undefined;
|
|
280
|
-
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
281
|
-
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
282
|
-
else if (file.gradient !== undefined)
|
|
283
|
-
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
284
|
-
if (isRecord(file.bins)) {
|
|
285
|
-
for (const [bin, value] of Object.entries(file.bins)) {
|
|
286
|
-
if (isColorSpec(value))
|
|
287
|
-
theme.bins[bin] = value;
|
|
288
|
-
else
|
|
289
|
-
warn(`${where}: bin ${bin} has no valid colour`);
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
function endsWalk(home) {
|
|
294
|
-
return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
|
|
295
|
-
}
|
|
296
|
-
function warnOnce(message) {
|
|
297
|
-
if (warned.has(message))
|
|
298
|
-
return;
|
|
299
|
-
warned.add(message);
|
|
300
|
-
console.error(`warning: theme ${message}`);
|
|
301
|
-
}
|
|
302
|
-
function isPath(chosen) {
|
|
303
|
-
return chosen.includes("/") || chosen.endsWith(".json");
|
|
304
|
-
}
|
|
305
|
-
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
306
|
-
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
307
|
-
const sources = [];
|
|
308
|
-
const chosen = env.KIT_THEME ?? "";
|
|
309
|
-
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
310
|
-
if (isPath(chosen))
|
|
311
|
-
wanted.push(resolve2(from, chosen));
|
|
312
|
-
const files = [];
|
|
313
|
-
for (const path of wanted) {
|
|
314
|
-
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
315
|
-
if (path !== undefined && file !== undefined)
|
|
316
|
-
files.push({ path, file });
|
|
317
|
-
}
|
|
318
|
-
let preset = "default";
|
|
319
|
-
if (chosen !== "" && !isPath(chosen)) {
|
|
320
|
-
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
321
|
-
} else {
|
|
322
|
-
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
323
|
-
if (named !== undefined)
|
|
324
|
-
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
325
|
-
}
|
|
326
|
-
for (const { path, file } of files) {
|
|
327
|
-
applyFile(theme, file, path, warn);
|
|
328
|
-
sources.push(path);
|
|
329
|
-
}
|
|
330
|
-
return { theme, sources, preset };
|
|
331
|
-
}
|
|
332
|
-
function activeTheme() {
|
|
333
|
-
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
334
|
-
if (current === undefined || key !== currentKey) {
|
|
335
|
-
current = loadTheme();
|
|
336
|
-
currentKey = key;
|
|
337
|
-
}
|
|
338
|
-
return current;
|
|
339
|
-
}
|
|
340
|
-
var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
|
|
341
|
-
var init_theme = __esm(() => {
|
|
342
|
-
init_config();
|
|
343
|
-
init_user_config();
|
|
344
|
-
ENDS = new Map;
|
|
345
|
-
DEFAULT = {
|
|
346
|
-
colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
|
|
347
|
-
glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
|
|
348
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
349
|
-
bins: {},
|
|
350
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
351
|
-
};
|
|
352
|
-
BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
|
|
353
|
-
MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
|
|
354
|
-
ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
355
|
-
PRESETS = {
|
|
356
|
-
default: {},
|
|
357
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
358
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
359
|
-
ascii: { glyphs: ASCII }
|
|
360
|
-
};
|
|
361
|
-
STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
|
|
362
|
-
HEX = /^#[0-9a-f]{6}$/i;
|
|
363
|
-
CONTROL = /\p{Cc}/u;
|
|
364
|
-
MAX_FILE_BYTES = 64 * 1024;
|
|
365
|
-
SPACES = /\s+/;
|
|
366
|
-
CUBE = [0, 95, 135, 175, 215, 255];
|
|
367
|
-
warned = new Set;
|
|
368
|
-
});
|
|
369
|
-
|
|
370
|
-
// ../kit/src/style.ts
|
|
371
|
-
import process6 from "process";
|
|
372
|
-
function takesControlCodes(stream, env = process6.env) {
|
|
373
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
374
|
-
}
|
|
375
|
-
function paint(stream, env = process6.env) {
|
|
376
|
-
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
377
|
-
}
|
|
378
|
-
function marked(mark, text, stream, detail, env = process6.env) {
|
|
379
|
-
const colors = paint(stream, env);
|
|
380
|
-
let head = MARK_WORDS[mark];
|
|
381
|
-
if (takesControlCodes(stream, env)) {
|
|
382
|
-
const { theme } = activeTheme();
|
|
383
|
-
head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
|
|
384
|
-
}
|
|
385
|
-
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
386
|
-
}
|
|
387
|
-
function problem(text, detail) {
|
|
388
|
-
console.error(marked("problem", text, process6.stderr, detail));
|
|
389
|
-
}
|
|
390
|
-
function statusOf(word) {
|
|
391
|
-
return STATUS_OF.get(word.toLowerCase());
|
|
392
|
-
}
|
|
393
|
-
function badge(word, stream, env = process6.env) {
|
|
394
|
-
const status = statusOf(word);
|
|
395
|
-
if (status === undefined || !takesControlCodes(stream, env))
|
|
396
|
-
return word;
|
|
397
|
-
const { theme } = activeTheme();
|
|
398
|
-
return tinted(paint(stream, env), theme.colors[status], env)(`${theme.glyphs[status]} ${word}`);
|
|
399
|
-
}
|
|
400
|
-
var MARK_WORDS, STATUS_WORDS, STATUS_OF;
|
|
401
|
-
var init_style = __esm(() => {
|
|
402
|
-
init_colors();
|
|
403
|
-
init_mode();
|
|
404
|
-
init_theme();
|
|
405
|
-
MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
|
|
406
|
-
STATUS_WORDS = {
|
|
407
|
-
passed: ["passed", "success", "succeeded", "ok"],
|
|
408
|
-
failed: ["failed", "failure", "error", "errored"],
|
|
409
|
-
running: ["running", "in_progress", "started", "holding"],
|
|
410
|
-
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
411
|
-
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
412
|
-
};
|
|
413
|
-
STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
414
|
-
});
|
|
415
|
-
|
|
416
|
-
// ../kit/src/format.ts
|
|
417
|
-
import process7 from "process";
|
|
418
|
-
function formatSeconds(total) {
|
|
419
|
-
let rest = Math.max(0, Math.round(total));
|
|
420
|
-
const amounts = UNITS.map(([unit, size]) => {
|
|
421
|
-
const amount = Math.floor(rest / size);
|
|
422
|
-
rest -= amount * size;
|
|
423
|
-
return `${amount}${unit}`;
|
|
424
|
-
});
|
|
425
|
-
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
426
|
-
if (first === -1)
|
|
427
|
-
return "0s";
|
|
428
|
-
const next = amounts[first + 1];
|
|
429
|
-
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
430
|
-
}
|
|
431
|
-
function formatDuration(ms) {
|
|
432
|
-
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
433
|
-
}
|
|
434
|
-
function formatElapsed(ms) {
|
|
435
|
-
return formatSeconds(Math.floor(Math.max(0, ms) / 1000));
|
|
436
|
-
}
|
|
437
|
-
function upTo(text, separator) {
|
|
438
|
-
const end = text.indexOf(separator);
|
|
439
|
-
return end === -1 ? text : text.slice(0, end);
|
|
440
|
-
}
|
|
441
|
-
function formatAge(date, now = Date.now()) {
|
|
442
|
-
const at = typeof date === "number" ? date : Date.parse(date);
|
|
443
|
-
if (Number.isNaN(at))
|
|
444
|
-
return "-";
|
|
445
|
-
const seconds = (now - at) / 1000;
|
|
446
|
-
return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
|
|
447
|
-
}
|
|
448
|
-
function truncate(text, width) {
|
|
449
|
-
return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
|
|
450
|
-
}
|
|
451
|
-
function textWidth(text) {
|
|
452
|
-
return Bun.stringWidth(text);
|
|
453
|
-
}
|
|
454
|
-
function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
|
|
455
|
-
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
456
|
-
if (outputMode(stream, env) === "agent")
|
|
457
|
-
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
458
|
-
`);
|
|
459
|
-
const widths = [];
|
|
460
|
-
for (const row of cells) {
|
|
461
|
-
for (const [index, cell] of row.entries())
|
|
462
|
-
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
463
|
-
}
|
|
464
|
-
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
465
|
-
const colors = paint(stream);
|
|
466
|
-
const lines = shown.map((row) => row.map((cell, index) => {
|
|
467
|
-
const width = widths[index] ?? 0;
|
|
468
|
-
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
469
|
-
if (align[index] === "right")
|
|
470
|
-
return `${gap}${cell}`;
|
|
471
|
-
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
472
|
-
}).join(" ").trimEnd());
|
|
473
|
-
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
474
|
-
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
475
|
-
`);
|
|
476
|
-
}
|
|
477
|
-
function narrow(rows, widths, limit) {
|
|
478
|
-
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
479
|
-
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
480
|
-
const floor = 8;
|
|
481
|
-
while (used() > limit) {
|
|
482
|
-
let widest = -1;
|
|
483
|
-
for (const [index, width] of widths.entries()) {
|
|
484
|
-
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
485
|
-
widest = index;
|
|
486
|
-
}
|
|
487
|
-
if (widest === -1)
|
|
488
|
-
break;
|
|
489
|
-
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
490
|
-
}
|
|
491
|
-
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
492
|
-
}
|
|
493
|
-
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
494
|
-
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
495
|
-
}
|
|
496
|
-
function printJson(value) {
|
|
497
|
-
console.log(jsonText(value));
|
|
498
|
-
}
|
|
499
|
-
var UNITS, LINE_BREAKS, ESCAPE;
|
|
500
|
-
var init_format = __esm(() => {
|
|
501
|
-
init_text();
|
|
502
|
-
init_mode();
|
|
503
|
-
init_style();
|
|
504
|
-
UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
505
|
-
LINE_BREAKS = /\s*\n\s*/g;
|
|
506
|
-
ESCAPE = String.fromCharCode(27);
|
|
507
|
-
});
|
|
508
|
-
|
|
509
|
-
// ../kit/src/help.ts
|
|
510
|
-
import process8 from "process";
|
|
511
|
-
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
512
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
513
|
-
`);
|
|
514
|
-
const blank = lines.indexOf("");
|
|
515
|
-
const synopses = blank === -1 ? lines : lines.slice(0, blank);
|
|
516
|
-
const details = blank === -1 ? [] : lines.slice(blank + 1);
|
|
517
|
-
const colon = synopses[0].indexOf(": ");
|
|
518
|
-
const inline = synopses[0].slice(colon + 2);
|
|
519
|
-
const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
|
|
520
|
-
if (colon !== -1)
|
|
521
|
-
synopses[0] = synopses[0].slice(0, colon);
|
|
522
|
-
const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
|
|
523
|
-
`)}`;
|
|
524
|
-
const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
|
|
525
|
-
const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
|
|
526
|
-
return [head, ...lead, ...rest].join(`
|
|
527
|
-
`);
|
|
528
|
-
}
|
|
529
|
-
function prose(line, colors) {
|
|
530
|
-
if (colors.cyan("x") === "x")
|
|
531
|
-
return line;
|
|
532
|
-
return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
|
|
533
|
-
}
|
|
534
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
535
|
-
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
536
|
-
`);
|
|
537
|
-
}
|
|
538
|
-
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
539
|
-
if (exits.length === 0)
|
|
540
|
-
return [];
|
|
541
|
-
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
542
|
-
}
|
|
543
|
-
function wantsHelpJson(env = process8.env) {
|
|
544
|
-
return env.KIT_HELP === "json";
|
|
545
|
-
}
|
|
546
|
-
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
547
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
548
|
-
`);
|
|
549
|
-
const first = lines[0];
|
|
550
|
-
const colon = first.indexOf(": ");
|
|
551
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
552
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
553
|
-
return {
|
|
554
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
555
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
556
|
-
...replaces === undefined ? {} : { replaces },
|
|
557
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
558
|
-
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
559
|
-
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
560
|
-
};
|
|
561
|
-
}
|
|
562
|
-
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
563
|
-
if (examples.length === 0 || outputMode() === "agent")
|
|
564
|
-
return [];
|
|
565
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
566
|
-
}
|
|
567
|
-
function optionRows(options, colors = paint(process8.stdout)) {
|
|
568
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
569
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
570
|
-
const choices = option.choices?.join("|");
|
|
571
|
-
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
572
|
-
const named = inline ? `<${choices}>` : "<value>";
|
|
573
|
-
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
574
|
-
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
575
|
-
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
576
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
577
|
-
});
|
|
578
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
579
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
580
|
-
}
|
|
581
|
-
var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
|
|
582
|
-
var init_help = __esm(() => {
|
|
583
|
-
init_mode();
|
|
584
|
-
init_style();
|
|
585
|
-
OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
586
|
-
USAGE_PREFIX = /^usage:\s*/i;
|
|
587
|
-
FULL_STOP = /\.$/;
|
|
588
|
-
PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
|
|
589
|
-
});
|
|
590
|
-
|
|
591
|
-
// ../kit/src/text.ts
|
|
592
|
-
function distance(a, b) {
|
|
593
|
-
const left = [...a];
|
|
594
|
-
const right = [...b];
|
|
595
|
-
let before = [];
|
|
596
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
597
|
-
for (const [i, x] of left.entries()) {
|
|
598
|
-
const current = [i + 1];
|
|
599
|
-
for (const [j, y] of right.entries()) {
|
|
600
|
-
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
601
|
-
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
602
|
-
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
603
|
-
current.push(cost);
|
|
604
|
-
}
|
|
605
|
-
before = previous;
|
|
606
|
-
previous = current;
|
|
607
|
-
}
|
|
608
|
-
return previous[right.length] ?? 0;
|
|
609
|
-
}
|
|
610
|
-
function closest(name, names) {
|
|
611
|
-
const started = names.find((known) => known.startsWith(name));
|
|
612
|
-
if (started !== undefined)
|
|
613
|
-
return started;
|
|
614
|
-
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
615
|
-
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
616
|
-
}
|
|
617
|
-
var init_text2 = () => {};
|
|
618
|
-
|
|
619
|
-
// ../kit/src/input.ts
|
|
620
|
-
function wholeNumber(value, name, fallback, min = 1) {
|
|
621
|
-
if (value === undefined)
|
|
622
|
-
return fallback;
|
|
623
|
-
const number = Number(value);
|
|
624
|
-
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
625
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
626
|
-
return number;
|
|
627
|
-
}
|
|
628
|
-
function durationMs(text, unit) {
|
|
629
|
-
if (BARE_DURATION.test(text))
|
|
630
|
-
return Number(text) * UNIT_MS[unit];
|
|
631
|
-
if (!DURATION.test(text))
|
|
632
|
-
return 0;
|
|
633
|
-
let ms = 0;
|
|
634
|
-
for (const [, amount, part] of text.matchAll(DURATION_PART))
|
|
635
|
-
ms += Number(amount) * UNIT_MS[part];
|
|
636
|
-
return ms;
|
|
637
|
-
}
|
|
638
|
-
function duration(value, name, fallback, unit = "s") {
|
|
639
|
-
if (value === undefined)
|
|
640
|
-
return fallback;
|
|
641
|
-
const ms = durationMs(value.trim(), unit);
|
|
642
|
-
if (ms < 1)
|
|
643
|
-
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
644
|
-
return ms;
|
|
645
|
-
}
|
|
646
|
-
var WHOLE, BARE_DURATION, DURATION, DURATION_PART, UNIT_MS;
|
|
647
|
-
var init_input = __esm(() => {
|
|
648
|
-
init_args();
|
|
649
|
-
WHOLE = /^\d+$/;
|
|
650
|
-
BARE_DURATION = /^\d+(?:\.\d+)?$/;
|
|
651
|
-
DURATION = /^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/;
|
|
652
|
-
DURATION_PART = /(\d+(?:\.\d+)?)(ms|min|[smhd])/g;
|
|
653
|
-
UNIT_MS = { ms: 1, s: 1000, m: 60000, min: 60000, h: 3600000, d: 86400000 };
|
|
654
|
-
});
|
|
655
|
-
|
|
656
|
-
// ../kit/src/args.ts
|
|
657
|
-
import process9 from "process";
|
|
658
|
-
import { parseArgs } from "util";
|
|
659
|
-
function jsonOption(holds) {
|
|
660
|
-
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
661
|
-
}
|
|
662
|
-
function fail(message, code = 2, hint) {
|
|
663
|
-
throw new Exit(message, code, hint);
|
|
664
|
-
}
|
|
665
|
-
function badUsage(message) {
|
|
666
|
-
throw new UsageError(message);
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
class Completing {
|
|
670
|
-
options;
|
|
671
|
-
positionals;
|
|
672
|
-
candidates;
|
|
673
|
-
constructor(options, positionals = [], candidates = {}) {
|
|
674
|
-
this.options = options;
|
|
675
|
-
this.positionals = positionals;
|
|
676
|
-
this.candidates = candidates;
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
function applyOutput(color, plain, env = process9.env) {
|
|
680
|
-
const when = plain === true ? "never" : color ?? "auto";
|
|
681
|
-
if (when === "auto")
|
|
682
|
-
return;
|
|
683
|
-
if (when !== "always" && when !== "never")
|
|
684
|
-
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
685
|
-
if (when === "always") {
|
|
686
|
-
env.FORCE_COLOR = "1";
|
|
687
|
-
delete env.NO_COLOR;
|
|
688
|
-
} else {
|
|
689
|
-
env.NO_COLOR = "1";
|
|
690
|
-
delete env.FORCE_COLOR;
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
function parse(args, usage, options, settings = {}) {
|
|
694
|
-
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
695
|
-
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
696
|
-
const listing = listed(all, settings.allowNegative === true);
|
|
697
|
-
if (completion.active)
|
|
698
|
-
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
699
|
-
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
700
|
-
let parsed;
|
|
701
|
-
try {
|
|
702
|
-
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
703
|
-
} catch (error) {
|
|
704
|
-
const message = parseError(error);
|
|
705
|
-
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
706
|
-
}
|
|
707
|
-
const values = parsed.values;
|
|
708
|
-
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
709
|
-
if (values.help === true) {
|
|
710
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
711
|
-
throw new HelpShown;
|
|
712
|
-
}
|
|
713
|
-
checkChoices(parsed.values, all);
|
|
714
|
-
checkConflicts(parsed.values, all);
|
|
715
|
-
if (settings.positionals !== undefined)
|
|
716
|
-
checkPositionals(parsed.positionals, settings.positionals);
|
|
717
|
-
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
718
|
-
}
|
|
719
|
-
function splitRest(args, passes) {
|
|
720
|
-
const separator = passes ? args.indexOf("--") : -1;
|
|
721
|
-
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
722
|
-
}
|
|
723
|
-
function splitTrailing(args, options, count) {
|
|
724
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
725
|
-
let seen = 0;
|
|
726
|
-
if (count === 0)
|
|
727
|
-
return { own: args, rest: undefined };
|
|
728
|
-
for (let at = 0;at < args.length; at++) {
|
|
729
|
-
const word = args[at];
|
|
730
|
-
if (word === "--")
|
|
731
|
-
break;
|
|
732
|
-
if (word.startsWith("-")) {
|
|
733
|
-
if (takesValue(word))
|
|
734
|
-
at++;
|
|
735
|
-
continue;
|
|
736
|
-
}
|
|
737
|
-
seen++;
|
|
738
|
-
if (seen === count)
|
|
739
|
-
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
740
|
-
}
|
|
741
|
-
return { own: args, rest: undefined };
|
|
742
|
-
}
|
|
743
|
-
function listed(options, allowNegative) {
|
|
744
|
-
if (!allowNegative)
|
|
745
|
-
return options;
|
|
746
|
-
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
747
|
-
if (option.type !== "boolean" || option.negative === undefined)
|
|
748
|
-
return [[name, option]];
|
|
749
|
-
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
750
|
-
}));
|
|
751
|
-
}
|
|
752
|
-
function withAliases(args, options) {
|
|
753
|
-
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
754
|
-
if (named.size === 0)
|
|
755
|
-
return args;
|
|
756
|
-
const separator = args.indexOf("--");
|
|
757
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
758
|
-
return [...own.map((arg) => {
|
|
759
|
-
const at = arg.indexOf("=");
|
|
760
|
-
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
761
|
-
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
762
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
763
|
-
}
|
|
764
|
-
function withBare(args, options) {
|
|
765
|
-
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
766
|
-
if (bare.size === 0)
|
|
767
|
-
return args;
|
|
768
|
-
const separator = args.indexOf("--");
|
|
769
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
770
|
-
return [...own.flatMap((arg, index) => {
|
|
771
|
-
const optional = bare.get(arg);
|
|
772
|
-
const next = own[index + 1];
|
|
773
|
-
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
774
|
-
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
775
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
776
|
-
}
|
|
777
|
-
function checkConflicts(values, options) {
|
|
778
|
-
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
779
|
-
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
780
|
-
const other = given(name) ? conflicts.find(given) : undefined;
|
|
781
|
-
if (other !== undefined)
|
|
782
|
-
badUsage(`--${name} cannot be used with --${other}`);
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
function checkChoices(values, options) {
|
|
786
|
-
for (const [name, option] of Object.entries(options)) {
|
|
787
|
-
if (option.choices === undefined)
|
|
788
|
-
continue;
|
|
789
|
-
const given = values[name];
|
|
790
|
-
for (const value of Array.isArray(given) ? given : [given]) {
|
|
791
|
-
if (typeof value === "string")
|
|
792
|
-
oneOf(value, name, option.choices);
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
function oneOf(value, name, choices) {
|
|
797
|
-
if (!choices.includes(value))
|
|
798
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
799
|
-
return value;
|
|
800
|
-
}
|
|
801
|
-
function checkPositionals(given, names) {
|
|
802
|
-
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
803
|
-
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
804
|
-
if (given.length < required)
|
|
805
|
-
badUsage(`missing ${names[given.length]}`);
|
|
806
|
-
if (!variadic && given.length > names.length)
|
|
807
|
-
badUsage(`unexpected argument ${given[names.length]}`);
|
|
808
|
-
}
|
|
809
|
-
function joinDashValues(args, options) {
|
|
810
|
-
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
811
|
-
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
812
|
-
const joined = [];
|
|
813
|
-
for (let i = 0;i < args.length; i++) {
|
|
814
|
-
const arg = args[i] ?? "";
|
|
815
|
-
if (arg === "--")
|
|
816
|
-
return [...joined, ...args.slice(i)];
|
|
817
|
-
const name = longOf.get(arg);
|
|
818
|
-
const next = args[i + 1];
|
|
819
|
-
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
820
|
-
joined.push(`--${name}=${next}`);
|
|
821
|
-
i++;
|
|
822
|
-
} else {
|
|
823
|
-
joined.push(arg);
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
return joined;
|
|
827
|
-
}
|
|
828
|
-
function parseError(error) {
|
|
829
|
-
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
830
|
-
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
831
|
-
}
|
|
832
|
-
function nearestOption(message, options, allowNegative) {
|
|
833
|
-
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
834
|
-
if (typed === undefined)
|
|
835
|
-
return;
|
|
836
|
-
const word = typed.replace(DASHES, "");
|
|
837
|
-
if (word.length < 2 && !typed.startsWith("--"))
|
|
838
|
-
return;
|
|
839
|
-
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
840
|
-
...option.short === undefined ? [] : [`-${option.short}`],
|
|
841
|
-
`--${name}`,
|
|
842
|
-
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
843
|
-
]);
|
|
844
|
-
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
845
|
-
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
846
|
-
}
|
|
847
|
-
var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
|
|
848
|
-
var init_args = __esm(() => {
|
|
849
|
-
init_format();
|
|
850
|
-
init_help();
|
|
851
|
-
init_text2();
|
|
852
|
-
init_help();
|
|
853
|
-
init_input();
|
|
854
|
-
DASHES = /^-+/;
|
|
855
|
-
EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
|
|
856
|
-
Exit = class Exit extends Error {
|
|
857
|
-
code;
|
|
858
|
-
hint;
|
|
859
|
-
[EXIT] = true;
|
|
860
|
-
constructor(message, code, hint) {
|
|
861
|
-
super(message);
|
|
862
|
-
this.code = code;
|
|
863
|
-
this.hint = hint;
|
|
864
|
-
}
|
|
865
|
-
static [Symbol.hasInstance](value) {
|
|
866
|
-
if (this !== Exit)
|
|
867
|
-
return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
868
|
-
return typeof value === "object" && value !== null && value[EXIT] === true;
|
|
869
|
-
}
|
|
870
|
-
};
|
|
871
|
-
UsageError = class UsageError extends Exit {
|
|
872
|
-
constructor(message, hint) {
|
|
873
|
-
super(message, 2, hint);
|
|
874
|
-
}
|
|
875
|
-
};
|
|
876
|
-
HelpShown = class HelpShown extends Exit {
|
|
877
|
-
constructor() {
|
|
878
|
-
super("help shown", 0);
|
|
879
|
-
}
|
|
880
|
-
};
|
|
881
|
-
completion = { active: false };
|
|
882
|
-
OUTPUT_OPTIONS = {
|
|
883
|
-
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
884
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
885
|
-
};
|
|
886
|
-
UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
887
|
-
});
|
|
888
|
-
|
|
889
|
-
// ../kit/src/folders.ts
|
|
890
|
-
var SKIPPED_FOLDERS;
|
|
891
|
-
var init_folders = __esm(() => {
|
|
892
|
-
init_user_config();
|
|
893
|
-
SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
894
|
-
});
|
|
895
|
-
|
|
896
|
-
// src/slot-cli.ts
|
|
897
|
-
import process22 from "process";
|
|
898
|
-
|
|
899
|
-
// ../kit/src/index.ts
|
|
900
|
-
init_args();
|
|
901
|
-
|
|
902
|
-
// ../kit/src/argv.ts
|
|
903
|
-
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
904
|
-
import { resolve as resolve3 } from "path";
|
|
905
|
-
import process10 from "process";
|
|
906
|
-
function commandLine() {
|
|
907
|
-
try {
|
|
908
|
-
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
909
|
-
} catch {
|
|
910
|
-
return;
|
|
911
|
-
}
|
|
912
|
-
}
|
|
913
|
-
function realPath(word) {
|
|
914
|
-
try {
|
|
915
|
-
return realpathSync(resolve3(word));
|
|
916
|
-
} catch {
|
|
917
|
-
return;
|
|
918
|
-
}
|
|
919
|
-
}
|
|
920
|
-
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
921
|
-
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
922
|
-
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
923
|
-
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
924
|
-
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
925
|
-
}
|
|
926
|
-
// ../kit/src/chart.ts
|
|
927
|
-
init_format();
|
|
928
|
-
init_mode();
|
|
929
|
-
init_style();
|
|
930
|
-
init_theme();
|
|
931
|
-
// ../kit/src/ci.ts
|
|
932
|
-
init_args();
|
|
933
|
-
init_format();
|
|
934
|
-
|
|
935
|
-
// ../kit/src/progress.ts
|
|
936
|
-
init_format();
|
|
937
|
-
import process12 from "process";
|
|
938
|
-
|
|
939
|
-
// ../kit/src/process.ts
|
|
940
|
-
import { readFileSync as readFileSync4 } from "fs";
|
|
941
|
-
import { constants } from "os";
|
|
942
|
-
import process11 from "process";
|
|
943
|
-
var KILL_GRACE_MS = 2000;
|
|
944
|
-
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
945
|
-
var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
946
|
-
function exitCodeOf(code, signal) {
|
|
947
|
-
if (code !== null)
|
|
948
|
-
return code;
|
|
949
|
-
if (typeof signal === "number")
|
|
950
|
-
return 128 + signal;
|
|
951
|
-
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
952
|
-
}
|
|
953
|
-
function groupsOf(pid) {
|
|
954
|
-
try {
|
|
955
|
-
const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
|
|
956
|
-
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
957
|
-
return { group: Number(fields[2]), foreground: Number(fields[5]) };
|
|
958
|
-
} catch {
|
|
959
|
-
return;
|
|
960
|
-
}
|
|
961
|
-
}
|
|
962
|
-
function heardTheTerminal(child) {
|
|
963
|
-
if (child.pid === undefined)
|
|
964
|
-
return false;
|
|
965
|
-
const own = groupsOf("self");
|
|
966
|
-
return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
|
|
967
|
-
}
|
|
968
|
-
function holdSignals(cleanup) {
|
|
969
|
-
let received;
|
|
970
|
-
let child;
|
|
971
|
-
const held = {
|
|
972
|
-
get signal() {
|
|
973
|
-
return received;
|
|
974
|
-
},
|
|
975
|
-
forward: (to) => {
|
|
976
|
-
child = to;
|
|
977
|
-
},
|
|
978
|
-
release: () => {
|
|
979
|
-
for (const signal of SIGNALS)
|
|
980
|
-
process11.off(signal, onSignal);
|
|
981
|
-
}
|
|
982
|
-
};
|
|
983
|
-
function onSignal(signal) {
|
|
984
|
-
received = signal;
|
|
985
|
-
if (child !== undefined) {
|
|
986
|
-
if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
|
|
987
|
-
child.kill(signal);
|
|
988
|
-
return;
|
|
989
|
-
}
|
|
990
|
-
if (cleanup === undefined)
|
|
991
|
-
return;
|
|
992
|
-
held.release();
|
|
993
|
-
cleanup(signal);
|
|
994
|
-
process11.kill(process11.pid, signal);
|
|
995
|
-
}
|
|
996
|
-
for (const signal of SIGNALS)
|
|
997
|
-
process11.on(signal, onSignal);
|
|
998
|
-
return held;
|
|
999
|
-
}
|
|
1000
|
-
async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
1001
|
-
const chunks = [];
|
|
1002
|
-
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
1003
|
-
const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin: input === undefined ? stdin : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
|
|
1004
|
-
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
1005
|
-
const timers = [];
|
|
1006
|
-
const killGroup = (killing) => {
|
|
1007
|
-
if (state.done)
|
|
1008
|
-
return;
|
|
1009
|
-
try {
|
|
1010
|
-
if (grouped)
|
|
1011
|
-
process11.kill(-proc.pid, killing);
|
|
1012
|
-
else
|
|
1013
|
-
proc.kill(killing);
|
|
1014
|
-
} catch {}
|
|
1015
|
-
};
|
|
1016
|
-
const stop = () => {
|
|
1017
|
-
killGroup("SIGTERM");
|
|
1018
|
-
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
1019
|
-
};
|
|
1020
|
-
const onAbort = () => stop();
|
|
1021
|
-
if (timeoutMs !== undefined) {
|
|
1022
|
-
timers.push(setTimeout(() => {
|
|
1023
|
-
state.timedOut = true;
|
|
1024
|
-
stop();
|
|
1025
|
-
}, timeoutMs));
|
|
1026
|
-
}
|
|
1027
|
-
if (signal?.aborted === true)
|
|
1028
|
-
onAbort();
|
|
1029
|
-
else
|
|
1030
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1031
|
-
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
1032
|
-
const drain = async (stream, name) => {
|
|
1033
|
-
for await (const data of stream) {
|
|
1034
|
-
if (state.failure !== undefined)
|
|
1035
|
-
continue;
|
|
1036
|
-
try {
|
|
1037
|
-
onChunk?.({ stream: name, data });
|
|
1038
|
-
} catch (error) {
|
|
1039
|
-
state.failure = error;
|
|
1040
|
-
stop();
|
|
1041
|
-
continue;
|
|
1042
|
-
}
|
|
1043
|
-
if (state.truncated)
|
|
1044
|
-
continue;
|
|
1045
|
-
let kept = data;
|
|
1046
|
-
if (state.kept + data.length > maxBytes) {
|
|
1047
|
-
let cut = maxBytes - state.kept;
|
|
1048
|
-
while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
|
|
1049
|
-
cut--;
|
|
1050
|
-
kept = data.subarray(0, cut);
|
|
1051
|
-
state.truncated = true;
|
|
1052
|
-
}
|
|
1053
|
-
state.kept += kept.length;
|
|
1054
|
-
if (kept.length > 0)
|
|
1055
|
-
chunks.push({ stream: name, data: kept });
|
|
1056
|
-
}
|
|
1057
|
-
};
|
|
1058
|
-
try {
|
|
1059
|
-
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
1060
|
-
await proc.exited;
|
|
1061
|
-
} finally {
|
|
1062
|
-
state.done = true;
|
|
1063
|
-
for (const timer of timers)
|
|
1064
|
-
clearTimeout(timer);
|
|
1065
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1066
|
-
}
|
|
1067
|
-
if (state.failure !== undefined)
|
|
1068
|
-
throw state.failure;
|
|
1069
|
-
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
1070
|
-
let output;
|
|
1071
|
-
let text;
|
|
1072
|
-
let stdout;
|
|
1073
|
-
return {
|
|
1074
|
-
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
1075
|
-
chunks,
|
|
1076
|
-
timedOut: state.timedOut,
|
|
1077
|
-
truncated: state.truncated,
|
|
1078
|
-
get output() {
|
|
1079
|
-
return output ??= joined();
|
|
1080
|
-
},
|
|
1081
|
-
get text() {
|
|
1082
|
-
return text ??= (output ??= joined()).toString();
|
|
1083
|
-
},
|
|
1084
|
-
get stdout() {
|
|
1085
|
-
return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
|
|
1086
|
-
}
|
|
1087
|
-
};
|
|
1088
|
-
}
|
|
1089
|
-
|
|
1090
|
-
// ../kit/src/progress.ts
|
|
1091
|
-
init_style();
|
|
1092
|
-
init_theme();
|
|
1093
|
-
var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
1094
|
-
var FRAME_MS = 200;
|
|
1095
|
-
var CLEAR_BELOW = "\r\x1B[J";
|
|
1096
|
-
var ESC = String.fromCharCode(27);
|
|
1097
|
-
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
1098
|
-
var RESET_STYLE = `${ESC}[0m`;
|
|
1099
|
-
var CTRL_C = 3;
|
|
1100
|
-
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
1101
|
-
var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
|
|
1102
|
-
function liveRegion(render, stream = process12.stderr, env = process12.env) {
|
|
1103
|
-
if (!takesControlCodes(stream, env))
|
|
1104
|
-
return { redraw: () => {
|
|
1105
|
-
return;
|
|
1106
|
-
}, print: (text) => void stream.write(`${text}
|
|
1107
|
-
`), stop: () => {
|
|
1108
|
-
return;
|
|
1109
|
-
}, pause: () => () => {
|
|
1110
|
-
return;
|
|
1111
|
-
} };
|
|
1112
|
-
const write = stream.write.bind(stream);
|
|
1113
|
-
let frame = 0;
|
|
1114
|
-
let drawn = false;
|
|
1115
|
-
let paused = false;
|
|
1116
|
-
let stopped = false;
|
|
1117
|
-
const columns = () => {
|
|
1118
|
-
const now = stream.getWindowSize?.()[0] ?? stream.columns;
|
|
1119
|
-
return now === undefined || now === 0 ? 80 : now;
|
|
1120
|
-
};
|
|
1121
|
-
const clear = () => {
|
|
1122
|
-
if (drawn)
|
|
1123
|
-
write(CLEAR_BELOW);
|
|
1124
|
-
drawn = false;
|
|
1125
|
-
};
|
|
1126
|
-
const draw = () => {
|
|
1127
|
-
if (paused)
|
|
1128
|
-
return;
|
|
1129
|
-
const width = columns() - 1;
|
|
1130
|
-
const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
|
|
1131
|
-
const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
|
|
1132
|
-
if (lines.length === 0) {
|
|
1133
|
-
clear();
|
|
1134
|
-
return;
|
|
1135
|
-
}
|
|
1136
|
-
write(`${CLEAR_BELOW}${lines.join(`
|
|
1137
|
-
`)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
|
|
1138
|
-
drawn = true;
|
|
1139
|
-
};
|
|
1140
|
-
let timer = setInterval(draw, FRAME_MS);
|
|
1141
|
-
stream.on?.("resize", draw);
|
|
1142
|
-
let restore = interceptOutput(clear);
|
|
1143
|
-
let release = swallowInput();
|
|
1144
|
-
const onExit = () => {
|
|
1145
|
-
clear();
|
|
1146
|
-
release();
|
|
1147
|
-
};
|
|
1148
|
-
const signals = holdSignals(stop);
|
|
1149
|
-
function stop() {
|
|
1150
|
-
stopped = true;
|
|
1151
|
-
clearInterval(timer);
|
|
1152
|
-
stream.off?.("resize", draw);
|
|
1153
|
-
clear();
|
|
1154
|
-
restore();
|
|
1155
|
-
release();
|
|
1156
|
-
process12.off("exit", onExit);
|
|
1157
|
-
signals.release();
|
|
1158
|
-
}
|
|
1159
|
-
function pause() {
|
|
1160
|
-
if (paused || stopped)
|
|
1161
|
-
return () => {
|
|
1162
|
-
return;
|
|
1163
|
-
};
|
|
1164
|
-
paused = true;
|
|
1165
|
-
clearInterval(timer);
|
|
1166
|
-
stream.off?.("resize", draw);
|
|
1167
|
-
clear();
|
|
1168
|
-
restore();
|
|
1169
|
-
release();
|
|
1170
|
-
return () => {
|
|
1171
|
-
if (!paused || stopped)
|
|
1172
|
-
return;
|
|
1173
|
-
paused = false;
|
|
1174
|
-
timer = setInterval(draw, FRAME_MS);
|
|
1175
|
-
timer.unref();
|
|
1176
|
-
stream.on?.("resize", draw);
|
|
1177
|
-
restore = interceptOutput(clear);
|
|
1178
|
-
release = swallowInput();
|
|
1179
|
-
draw();
|
|
1180
|
-
};
|
|
1181
|
-
}
|
|
1182
|
-
timer.unref();
|
|
1183
|
-
process12.on("exit", onExit);
|
|
1184
|
-
return {
|
|
1185
|
-
redraw: draw,
|
|
1186
|
-
print: (text) => {
|
|
1187
|
-
clear();
|
|
1188
|
-
write(`${text}
|
|
1189
|
-
`);
|
|
1190
|
-
draw();
|
|
1191
|
-
},
|
|
1192
|
-
stop,
|
|
1193
|
-
pause
|
|
1194
|
-
};
|
|
1195
|
-
}
|
|
1196
|
-
function cutToWidth(line, width) {
|
|
1197
|
-
if (Bun.stringWidth(line) <= width)
|
|
1198
|
-
return line;
|
|
1199
|
-
let room = width;
|
|
1200
|
-
let kept = "";
|
|
1201
|
-
let index = 0;
|
|
1202
|
-
let linked = false;
|
|
1203
|
-
while (index < line.length) {
|
|
1204
|
-
ESCAPE_CODE.lastIndex = index;
|
|
1205
|
-
const escape = ESCAPE_CODE.exec(line);
|
|
1206
|
-
if (escape !== null) {
|
|
1207
|
-
kept += escape[0];
|
|
1208
|
-
linked ||= escape[0].startsWith(`${ESC}]`);
|
|
1209
|
-
index = ESCAPE_CODE.lastIndex;
|
|
1210
|
-
continue;
|
|
1211
|
-
}
|
|
1212
|
-
const char = String.fromCodePoint(line.codePointAt(index));
|
|
1213
|
-
const columns = Bun.stringWidth(char);
|
|
1214
|
-
if (columns > room)
|
|
1215
|
-
break;
|
|
1216
|
-
kept += char;
|
|
1217
|
-
room -= columns;
|
|
1218
|
-
index += char.length;
|
|
1219
|
-
}
|
|
1220
|
-
return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
|
|
1221
|
-
}
|
|
1222
|
-
function swallowInput() {
|
|
1223
|
-
const input = process12.stdin;
|
|
1224
|
-
if (!input.isTTY)
|
|
1225
|
-
return () => {
|
|
1226
|
-
return;
|
|
1227
|
-
};
|
|
1228
|
-
const onData = (data) => {
|
|
1229
|
-
if (data.includes(CTRL_C))
|
|
1230
|
-
process12.kill(process12.pid, "SIGINT");
|
|
1231
|
-
};
|
|
1232
|
-
input.setRawMode(true);
|
|
1233
|
-
input.on("data", onData);
|
|
1234
|
-
input.resume();
|
|
1235
|
-
let released = false;
|
|
1236
|
-
return () => {
|
|
1237
|
-
if (released)
|
|
1238
|
-
return;
|
|
1239
|
-
released = true;
|
|
1240
|
-
input.off("data", onData);
|
|
1241
|
-
input.pause();
|
|
1242
|
-
input.setRawMode(false);
|
|
1243
|
-
};
|
|
1244
|
-
}
|
|
1245
|
-
function interceptOutput(clear) {
|
|
1246
|
-
const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
|
|
1247
|
-
const wrapped = targets.map(([target, name]) => {
|
|
1248
|
-
const original = Reflect.get(target, name);
|
|
1249
|
-
const wrapper = (...args) => {
|
|
1250
|
-
clear();
|
|
1251
|
-
return original.apply(target, args);
|
|
1252
|
-
};
|
|
1253
|
-
Reflect.set(target, name, wrapper);
|
|
1254
|
-
return { target, name, original, wrapper };
|
|
1255
|
-
});
|
|
1256
|
-
return () => {
|
|
1257
|
-
for (const { target, name, original, wrapper } of wrapped) {
|
|
1258
|
-
if (Reflect.get(target, name) === wrapper)
|
|
1259
|
-
Reflect.set(target, name, original);
|
|
1260
|
-
}
|
|
1261
|
-
};
|
|
1262
|
-
}
|
|
1263
|
-
|
|
1264
|
-
// ../kit/src/ci.ts
|
|
1265
|
-
init_style();
|
|
1266
|
-
|
|
1267
|
-
// ../kit/src/tool.ts
|
|
1268
|
-
init_format();
|
|
1269
|
-
// ../kit/src/cli.ts
|
|
1270
|
-
init_args();
|
|
1271
|
-
import { readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
|
|
1272
|
-
import { dirname as dirname3, join as join6 } from "path";
|
|
1273
|
-
import process17 from "process";
|
|
1274
|
-
|
|
1275
|
-
// ../kit/src/askpass.ts
|
|
1276
|
-
import process13 from "process";
|
|
1277
|
-
var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
|
|
1278
|
-
async function askpassClient(argv) {
|
|
1279
|
-
const socketPath = process13.env[SOCKET_VARIABLE];
|
|
1280
|
-
if (socketPath === undefined)
|
|
1281
|
-
return;
|
|
1282
|
-
const request = { prompt: argv[0] ?? "", ...process13.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
1283
|
-
const { promise, resolve } = Promise.withResolvers();
|
|
1284
|
-
let received = "";
|
|
1285
|
-
try {
|
|
1286
|
-
await Bun.connect({
|
|
1287
|
-
unix: socketPath,
|
|
1288
|
-
socket: {
|
|
1289
|
-
open: (socket) => void socket.write(`${JSON.stringify(request)}
|
|
1290
|
-
`),
|
|
1291
|
-
data: (_, chunk) => {
|
|
1292
|
-
received += chunk.toString();
|
|
1293
|
-
},
|
|
1294
|
-
close: () => resolve(received),
|
|
1295
|
-
error: () => resolve("")
|
|
1296
|
-
}
|
|
1297
|
-
});
|
|
1298
|
-
} catch {
|
|
1299
|
-
return 1;
|
|
1300
|
-
}
|
|
1301
|
-
const reply = await promise;
|
|
1302
|
-
if (reply === "")
|
|
1303
|
-
return 1;
|
|
1304
|
-
const { answer } = JSON.parse(reply);
|
|
1305
|
-
if (request.notice === true)
|
|
1306
|
-
return 0;
|
|
1307
|
-
if (answer === undefined)
|
|
1308
|
-
return 1;
|
|
1309
|
-
process13.stdout.write(`${answer}
|
|
1310
|
-
`);
|
|
1311
|
-
return 0;
|
|
1312
|
-
}
|
|
1313
|
-
|
|
1314
|
-
// ../kit/src/completions.ts
|
|
1315
|
-
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
1316
|
-
var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
|
|
1317
|
-
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
1318
|
-
set -l current (commandline -ct)
|
|
1319
|
-
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
1320
|
-
if test "$line" = __files__
|
|
1321
|
-
__fish_complete_path $current
|
|
1322
|
-
else
|
|
1323
|
-
echo $line
|
|
1324
|
-
end
|
|
1325
|
-
end
|
|
1326
|
-
end`;
|
|
1327
|
-
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1328
|
-
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
1329
|
-
local -a lines
|
|
1330
|
-
COMPREPLY=()
|
|
1331
|
-
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
1332
|
-
for line in "\${lines[@]}"; do
|
|
1333
|
-
if [[ $line == __files__ ]]; then
|
|
1334
|
-
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
1335
|
-
else
|
|
1336
|
-
words+="\${line%%$'\\t'*}"$'\\n'
|
|
1337
|
-
fi
|
|
1338
|
-
done
|
|
1339
|
-
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1340
|
-
}`;
|
|
1341
|
-
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1342
|
-
local line
|
|
1343
|
-
local -a described plain
|
|
1344
|
-
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
1345
|
-
if [[ $line == __files__ ]]; then
|
|
1346
|
-
_files
|
|
1347
|
-
elif [[ $line == *$'\\t'* ]]; then
|
|
1348
|
-
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
1349
|
-
else
|
|
1350
|
-
plain+=("$line")
|
|
1351
|
-
fi
|
|
1352
|
-
done
|
|
1353
|
-
(( \${#described} )) && _describe -V value described
|
|
1354
|
-
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
1355
|
-
return 0
|
|
1356
|
-
}`;
|
|
1357
|
-
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1358
|
-
if (shell === "fish")
|
|
1359
|
-
return `${header}
|
|
1360
|
-
${FISH_FUNCTION}
|
|
1361
|
-
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1362
|
-
`).join("")}`;
|
|
1363
|
-
if (shell === "bash")
|
|
1364
|
-
return `${header}
|
|
1365
|
-
${BASH_FUNCTION}
|
|
1366
|
-
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1367
|
-
`;
|
|
1368
|
-
return `${header}
|
|
1369
|
-
${ZSH_FUNCTION}
|
|
1370
|
-
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
1371
|
-
`;
|
|
1372
|
-
}
|
|
1373
|
-
|
|
1374
|
-
// ../kit/src/notify.ts
|
|
1375
|
-
init_format();
|
|
1376
|
-
init_mode();
|
|
1377
|
-
import process14 from "process";
|
|
1378
|
-
var NOTIFY_AFTER_MS = 1e4;
|
|
1379
|
-
var CANCELLED = 130;
|
|
1380
|
-
function base64(text) {
|
|
1381
|
-
return Buffer.from(text).toString("base64");
|
|
1382
|
-
}
|
|
1383
|
-
function notification(title, body, env = process14.env) {
|
|
1384
|
-
const id = `kit${process14.pid}`;
|
|
1385
|
-
const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
|
|
1386
|
-
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1387
|
-
}
|
|
1388
|
-
function notifyEnd(command, code, ms, { stream = process14.stderr, env = process14.env } = {}) {
|
|
1389
|
-
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1390
|
-
return;
|
|
1391
|
-
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1392
|
-
}
|
|
1393
|
-
|
|
1394
|
-
// ../kit/src/cli.ts
|
|
1395
|
-
init_style();
|
|
1396
|
-
init_text2();
|
|
1397
|
-
|
|
1398
|
-
// ../kit/src/usage.ts
|
|
1399
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
1400
|
-
import { homedir as homedir4 } from "os";
|
|
1401
|
-
import { dirname as dirname2, join as join5 } from "path";
|
|
1402
|
-
import process16 from "process";
|
|
1403
|
-
|
|
1404
|
-
// ../kit/src/logs.ts
|
|
1405
|
-
init_user_config();
|
|
1406
|
-
import { lstatSync, openSync } from "fs";
|
|
1407
|
-
import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
|
|
1408
|
-
import { homedir as homedir3, tmpdir } from "os";
|
|
1409
|
-
import { join as join4 } from "path";
|
|
1410
|
-
import process15 from "process";
|
|
1411
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1412
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
1413
|
-
function isPrivateDirectory(path) {
|
|
1414
|
-
try {
|
|
1415
|
-
const info = lstatSync(path, { throwIfNoEntry: false });
|
|
1416
|
-
return info !== undefined && info.isDirectory() && info.uid === (process15.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
|
|
1417
|
-
} catch {
|
|
1418
|
-
return false;
|
|
1419
|
-
}
|
|
1420
|
-
}
|
|
1421
|
-
async function privateLogDirectory(name, env = process15.env) {
|
|
1422
|
-
const path = join4(xdgFolder(env.XDG_RUNTIME_DIR, join4(homedir3(), ".cache")), CLI_FOLDER, name);
|
|
1423
|
-
try {
|
|
1424
|
-
await mkdir(path, { recursive: true, mode: 448 });
|
|
1425
|
-
if (isPrivateDirectory(path))
|
|
1426
|
-
return path;
|
|
1427
|
-
} catch {}
|
|
1428
|
-
return mkdtemp(join4(tmpdir(), `${name.replaceAll("/", "-")}-`));
|
|
1429
|
-
}
|
|
1430
|
-
|
|
1431
|
-
// ../kit/src/usage.ts
|
|
1432
|
-
init_user_config();
|
|
1433
|
-
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1434
|
-
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1435
|
-
var LONGEST_NAME = 40;
|
|
1436
|
-
var usageError;
|
|
1437
|
-
function noteUsageError(message) {
|
|
1438
|
-
usageError = message;
|
|
1439
|
-
}
|
|
1440
|
-
function stateHome(env = process16.env) {
|
|
1441
|
-
return xdgFolder(env.XDG_STATE_HOME, join5(homedir4(), ".local", "state"));
|
|
1442
|
-
}
|
|
1443
|
-
function usagePath(env = process16.env) {
|
|
1444
|
-
return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1445
|
-
}
|
|
1446
|
-
function usageRecorded(env = process16.env) {
|
|
1447
|
-
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1448
|
-
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1449
|
-
}
|
|
1450
|
-
function flagNames(argv) {
|
|
1451
|
-
const end = argv.indexOf("--");
|
|
1452
|
-
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1453
|
-
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1454
|
-
}
|
|
1455
|
-
function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
1456
|
-
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1457
|
-
usageError = undefined;
|
|
1458
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
1459
|
-
}
|
|
1460
|
-
function recordUsage(entry, env = process16.env) {
|
|
1461
|
-
if (!usageRecorded(env))
|
|
1462
|
-
return;
|
|
1463
|
-
try {
|
|
1464
|
-
const path = usagePath(env);
|
|
1465
|
-
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1466
|
-
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1467
|
-
`, { mode: 384 });
|
|
1468
|
-
} catch {}
|
|
1469
|
-
}
|
|
1470
|
-
|
|
1471
|
-
// ../kit/src/cli.ts
|
|
1472
|
-
var LEVEL_OPTIONS = {
|
|
1473
|
-
...OUTPUT_OPTIONS,
|
|
1474
|
-
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1475
|
-
};
|
|
1476
|
-
var TOP_OPTIONS = {
|
|
1477
|
-
...LEVEL_OPTIONS,
|
|
1478
|
-
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1479
|
-
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1480
|
-
};
|
|
1481
|
-
function printError(prefix, message, hint, cause) {
|
|
1482
|
-
const colors = paint(process17.stderr);
|
|
1483
|
-
const styled = takesControlCodes(process17.stderr);
|
|
1484
|
-
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1485
|
-
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1486
|
-
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1487
|
-
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1488
|
-
}
|
|
1489
|
-
function printJsonError(message, hint, cause) {
|
|
1490
|
-
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1491
|
-
}
|
|
1492
|
-
function wantsJson(argv) {
|
|
1493
|
-
const end = argv.indexOf("--");
|
|
1494
|
-
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1495
|
-
}
|
|
1496
|
-
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1497
|
-
if (error instanceof HelpShown)
|
|
1498
|
-
return 0;
|
|
1499
|
-
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1500
|
-
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1501
|
-
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1502
|
-
if (error instanceof Exit && error.code === 2)
|
|
1503
|
-
noteUsageError(error.message);
|
|
1504
|
-
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1505
|
-
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1506
|
-
return error instanceof Exit ? error.code : 1;
|
|
1507
|
-
}
|
|
1508
|
-
var COMPLETE = "__complete";
|
|
1509
|
-
var FILES = "__files__";
|
|
1510
|
-
async function completingOf(run) {
|
|
1511
|
-
completion.active = true;
|
|
1512
|
-
try {
|
|
1513
|
-
await run([]);
|
|
1514
|
-
} catch (error) {
|
|
1515
|
-
if (error instanceof Completing)
|
|
1516
|
-
return error;
|
|
1517
|
-
} finally {
|
|
1518
|
-
completion.active = false;
|
|
1519
|
-
}
|
|
1520
|
-
return new Completing({});
|
|
1521
|
-
}
|
|
1522
|
-
function candidateLine(candidate) {
|
|
1523
|
-
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1524
|
-
}
|
|
1525
|
-
function positionalBeingTyped(before, { options, positionals }) {
|
|
1526
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1527
|
-
const typed = [];
|
|
1528
|
-
let at = 0;
|
|
1529
|
-
while (at < before.length) {
|
|
1530
|
-
const word = before[at];
|
|
1531
|
-
if (word === "--") {
|
|
1532
|
-
typed.push(...before.slice(at + 1));
|
|
1533
|
-
break;
|
|
1534
|
-
}
|
|
1535
|
-
if (!word.startsWith("-"))
|
|
1536
|
-
typed.push(word);
|
|
1537
|
-
else if (takesValue(word))
|
|
1538
|
-
at++;
|
|
1539
|
-
at++;
|
|
1540
|
-
}
|
|
1541
|
-
const last = positionals.at(-1);
|
|
1542
|
-
if (typed.length < positionals.length)
|
|
1543
|
-
return { name: positionals[typed.length], typed };
|
|
1544
|
-
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1545
|
-
}
|
|
1546
|
-
async function leafCandidates(run, words) {
|
|
1547
|
-
const completing = await completingOf(run);
|
|
1548
|
-
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1549
|
-
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1550
|
-
const flag = words.at(-2);
|
|
1551
|
-
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1552
|
-
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1553
|
-
if (option?.type === "string") {
|
|
1554
|
-
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1555
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1556
|
-
}
|
|
1557
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1558
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1559
|
-
}
|
|
1560
|
-
var COMPLETIONS = "--completions";
|
|
1561
|
-
function flagValue([flag = "", ...rest]) {
|
|
1562
|
-
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1563
|
-
}
|
|
1564
|
-
function printCompletionScript(name, args) {
|
|
1565
|
-
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1566
|
-
if (shell === undefined || args.length !== 1) {
|
|
1567
|
-
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1568
|
-
return 2;
|
|
1569
|
-
}
|
|
1570
|
-
console.log(completionScript(shell, [name]).trimEnd());
|
|
1571
|
-
return 0;
|
|
1572
|
-
}
|
|
1573
|
-
async function printCandidates(found) {
|
|
1574
|
-
for (const line of await found)
|
|
1575
|
-
console.log(line);
|
|
1576
|
-
return 0;
|
|
1577
|
-
}
|
|
1578
|
-
function packageVersion(entry = Bun.main) {
|
|
1579
|
-
let resolved = entry;
|
|
1580
|
-
try {
|
|
1581
|
-
resolved = realpathSync2(entry);
|
|
1582
|
-
} catch {}
|
|
1583
|
-
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1584
|
-
try {
|
|
1585
|
-
const { version } = JSON.parse(readFileSync5(join6(dir, "package.json"), "utf8"));
|
|
1586
|
-
if (typeof version === "string")
|
|
1587
|
-
return version;
|
|
1588
|
-
} catch {}
|
|
1589
|
-
if (dirname3(dir) === dir)
|
|
1590
|
-
return "0.0.0";
|
|
1591
|
-
}
|
|
1592
|
-
}
|
|
1593
|
-
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1594
|
-
const answered = await askpassClient(argv);
|
|
1595
|
-
if (answered !== undefined)
|
|
1596
|
-
return answered;
|
|
1597
|
-
if (argv[0] === COMPLETE)
|
|
1598
|
-
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1599
|
-
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1600
|
-
return printCompletionScript(name, flagValue(argv));
|
|
1601
|
-
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1602
|
-
console.log(version ?? packageVersion());
|
|
1603
|
-
return 0;
|
|
1604
|
-
}
|
|
1605
|
-
let code;
|
|
1606
|
-
const started = performance.now();
|
|
1607
|
-
try {
|
|
1608
|
-
code = await run(argv);
|
|
1609
|
-
} catch (error) {
|
|
1610
|
-
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1611
|
-
}
|
|
1612
|
-
notifyEnd(name, code, performance.now() - started);
|
|
1613
|
-
if (usage !== false) {
|
|
1614
|
-
try {
|
|
1615
|
-
recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
|
|
1616
|
-
} catch {}
|
|
1617
|
-
}
|
|
1618
|
-
return code;
|
|
1619
|
-
}
|
|
1620
|
-
|
|
1621
|
-
// ../kit/src/index.ts
|
|
1622
|
-
init_config();
|
|
1623
|
-
|
|
1624
|
-
// ../kit/src/excerpt.ts
|
|
1625
|
-
init_text2();
|
|
1626
|
-
|
|
1627
|
-
// ../kit/src/index.ts
|
|
1628
|
-
init_folders();
|
|
1629
|
-
init_format();
|
|
1630
|
-
|
|
1631
|
-
// ../kit/src/git.ts
|
|
1632
|
-
init_args();
|
|
1633
|
-
// ../kit/src/limit.ts
|
|
1634
|
-
init_args();
|
|
1635
|
-
|
|
1636
|
-
// ../kit/src/index.ts
|
|
1637
|
-
init_mode();
|
|
1638
|
-
|
|
1639
|
-
// ../kit/src/report.ts
|
|
1640
|
-
init_style();
|
|
1641
|
-
init_text2();
|
|
1642
|
-
// ../kit/src/secrets.ts
|
|
1643
|
-
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1644
|
-
var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
|
|
1645
|
-
// ../kit/src/sessions.ts
|
|
1646
|
-
import { homedir as homedir5 } from "os";
|
|
1647
|
-
import { join as join7 } from "path";
|
|
1648
|
-
import process18 from "process";
|
|
1649
|
-
var {Glob } = globalThis.Bun;
|
|
1650
|
-
var SESSION_FILES = new Glob("*.json");
|
|
1651
|
-
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1652
|
-
async function sessionDirs() {
|
|
1653
|
-
const home = homedir5();
|
|
1654
|
-
const dirs = new Set([join7(home, ".claude", "sessions")]);
|
|
1655
|
-
if (process18.env.CLAUDE_CONFIG_DIR !== undefined)
|
|
1656
|
-
dirs.add(join7(process18.env.CLAUDE_CONFIG_DIR, "sessions"));
|
|
1657
|
-
try {
|
|
1658
|
-
for await (const dir of ACCOUNT_DIRS.scan({ cwd: join7(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
|
|
1659
|
-
dirs.add(dir);
|
|
1660
|
-
} catch {}
|
|
1661
|
-
return [...dirs];
|
|
1662
|
-
}
|
|
1663
|
-
async function procStat(pid) {
|
|
1664
|
-
try {
|
|
1665
|
-
const stat = await Bun.file(`/proc/${pid}/stat`).text();
|
|
1666
|
-
return stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
1667
|
-
} catch {
|
|
1668
|
-
return;
|
|
1669
|
-
}
|
|
1670
|
-
}
|
|
1671
|
-
async function isAlive(pid, procStart) {
|
|
1672
|
-
const stat = await procStat(pid);
|
|
1673
|
-
if (stat === undefined)
|
|
1674
|
-
return false;
|
|
1675
|
-
return procStart === undefined || stat[19] === procStart;
|
|
1676
|
-
}
|
|
1677
|
-
async function liveSessions() {
|
|
1678
|
-
const sessions = new Map;
|
|
1679
|
-
for (const dir of await sessionDirs()) {
|
|
1680
|
-
let files;
|
|
1681
|
-
try {
|
|
1682
|
-
files = await Array.fromAsync(SESSION_FILES.scan({ cwd: dir, absolute: true }));
|
|
1683
|
-
} catch {
|
|
1684
|
-
continue;
|
|
1685
|
-
}
|
|
1686
|
-
for (const file of files) {
|
|
1687
|
-
let entry;
|
|
1688
|
-
try {
|
|
1689
|
-
entry = await Bun.file(file).json();
|
|
1690
|
-
} catch {
|
|
1691
|
-
continue;
|
|
1692
|
-
}
|
|
1693
|
-
if (entry.name === undefined || entry.pid === undefined || sessions.has(entry.pid) || !await isAlive(entry.pid, entry.procStart))
|
|
1694
|
-
continue;
|
|
1695
|
-
sessions.set(entry.pid, { name: entry.name, pid: entry.pid, status: entry.status ?? "unknown", cwd: entry.cwd ?? "" });
|
|
1696
|
-
}
|
|
1697
|
-
}
|
|
1698
|
-
return [...sessions.values()];
|
|
1699
|
-
}
|
|
1700
|
-
async function currentSession(sessions) {
|
|
1701
|
-
const byPid = new Map(sessions.map((session) => [session.pid, session]));
|
|
1702
|
-
let pid = process18.ppid;
|
|
1703
|
-
for (let depth = 0;depth < 32 && pid > 1; depth++) {
|
|
1704
|
-
const session = byPid.get(pid);
|
|
1705
|
-
if (session !== undefined)
|
|
1706
|
-
return session;
|
|
1707
|
-
const parent = Number((await procStat(pid))?.[1]);
|
|
1708
|
-
if (!Number.isInteger(parent))
|
|
1709
|
-
return;
|
|
1710
|
-
pid = parent;
|
|
1711
|
-
}
|
|
1712
|
-
return;
|
|
1713
|
-
}
|
|
1714
|
-
|
|
1715
|
-
// ../kit/src/index.ts
|
|
1716
|
-
init_style();
|
|
1717
|
-
init_text2();
|
|
1718
|
-
init_theme();
|
|
1719
|
-
init_user_config();
|
|
1720
|
-
|
|
1721
|
-
// ../kit/src/watch.ts
|
|
1722
|
-
init_args();
|
|
1723
|
-
init_input();
|
|
1724
|
-
init_style();
|
|
1725
|
-
// ../kit/src/workspace-root.ts
|
|
1726
|
-
init_user_config();
|
|
1727
|
-
// src/slot.ts
|
|
1728
|
-
import { existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync6, rmSync } from "fs";
|
|
1729
|
-
import { availableParallelism } from "os";
|
|
1730
|
-
import { join as join8 } from "path";
|
|
1731
|
-
import process21 from "process";
|
|
1732
|
-
|
|
1733
|
-
// src/flock.ts
|
|
1734
|
-
import { closeSync, constants as constants2, ftruncateSync, openSync as openSync2, writeSync } from "fs";
|
|
1735
|
-
import process20 from "process";
|
|
1736
|
-
import { dlopen, FFIType } from "bun:ffi";
|
|
1737
|
-
var LOCK_EX = 2;
|
|
1738
|
-
var LOCK_NB = 4;
|
|
1739
|
-
var flock;
|
|
1740
|
-
function native() {
|
|
1741
|
-
flock ??= dlopen(process20.platform === "darwin" ? "libSystem.B.dylib" : "libc.so.6", { flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } }).symbols.flock;
|
|
1742
|
-
return flock;
|
|
1743
|
-
}
|
|
1744
|
-
function tryLock(path) {
|
|
1745
|
-
const fd = openSync2(path, constants2.O_RDWR | constants2.O_CREAT, 384);
|
|
1746
|
-
if (native()(fd, LOCK_EX | LOCK_NB) !== 0) {
|
|
1747
|
-
closeSync(fd);
|
|
1748
|
-
return;
|
|
1749
|
-
}
|
|
1750
|
-
return { fd, release: () => closeSync(fd) };
|
|
1751
|
-
}
|
|
1752
|
-
function writeHeld(held, text) {
|
|
1753
|
-
ftruncateSync(held.fd);
|
|
1754
|
-
writeSync(held.fd, text, 0);
|
|
1755
|
-
}
|
|
1756
|
-
|
|
1757
|
-
// src/slot.ts
|
|
1758
|
-
var RUN_USAGE = `slot [options] -- <cmd>...: waits for a free machine-wide slot, then runs the command and exits with its code
|
|
3
|
+
import{paint,badge,formatDuration,formatAge,truncate,table,printJson,wholeNumber,duration,jsonOption,fail,parse,exitCodeOf,holdSignals,privateLogDirectory,runMain,liveSessions,currentSession}from"./chunk-p9bag6re.js";import process3 from"process";import{existsSync,mkdirSync,readdirSync,readFileSync,rmSync}from"fs";import{availableParallelism}from"os";import{join}from"path";import process2 from"process";import{closeSync,constants,ftruncateSync,openSync,writeSync}from"fs";import process from"process";import{dlopen,FFIType}from"bun:ffi";var LOCK_EX=2,LOCK_NB=4,flock;function native(){return flock??=dlopen(process.platform==="darwin"?"libSystem.B.dylib":"libc.so.6",{flock:{args:[FFIType.i32,FFIType.i32],returns:FFIType.i32}}).symbols.flock,flock}function tryLock(path){let fd=openSync(path,constants.O_RDWR|constants.O_CREAT,384);if(native()(fd,LOCK_EX|LOCK_NB)!==0){closeSync(fd);return}return{fd,release:()=>closeSync(fd)}}function writeHeld(held,text){ftruncateSync(held.fd),writeSync(held.fd,text,0)}var RUN_USAGE=`slot [options] -- <cmd>...: waits for a free machine-wide slot, then runs the command and exits with its code
|
|
1759
4
|
slot ls [--json]: lists who holds a slot or a lock and who waits for one (slot ls --help)
|
|
1760
5
|
|
|
1761
6
|
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; one is freed the moment its holder ends, SIGKILL included.
|
|
1762
7
|
A slotted command that runs slot again does not wait for a second slot, so wrapping a script and the commands inside it cannot deadlock.
|
|
1763
|
-
A first word \`ls\` always means the listing: run the ls command as \`slot -n 4 -- ls
|
|
1764
|
-
var RUN_EXITS = [[0, "the command did"], ["its own", "the code of a command that failed"], [2, "it timed out waiting for the slot or a usage error"], [127, "the command cannot be started"]];
|
|
1765
|
-
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
|
|
1766
|
-
|
|
1767
|
-
--json prints {slots, busy, entries}, each entry as {state, resource, pid, session, command, cwd, since}.`;
|
|
1768
|
-
var SLOTS = { type: "string", short: "n", description: "how many commands may hold a slot at once (half the CPU count)" };
|
|
1769
|
-
var RUN_OPTIONS = {
|
|
1770
|
-
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)" },
|
|
1771
|
-
"no-slot": { type: "boolean", description: "take the --lock alone, without a slot" },
|
|
1772
|
-
slots: SLOTS,
|
|
1773
|
-
timeout: { type: "string", short: "t", description: "how long to wait before giving up (30s, 5m, 1h, a bare number in seconds), forever by default" }
|
|
1774
|
-
};
|
|
1775
|
-
var LS_OPTIONS = { slots: SLOTS, json: jsonOption() };
|
|
1776
|
-
var POLL = 250;
|
|
1777
|
-
var COMMAND_WIDTH = 60;
|
|
1778
|
-
var LOCK_NAME = /^\w[\w.-]*$/;
|
|
1779
|
-
var HOLDING = "SLOT_HOLDING";
|
|
1780
|
-
function defaultSlots() {
|
|
1781
|
-
return Math.max(1, Math.floor(availableParallelism() / 2));
|
|
1782
|
-
}
|
|
1783
|
-
async function stateDir() {
|
|
1784
|
-
const dir = process21.env.SLOT_DIR ?? await privateLogDirectory("slot");
|
|
1785
|
-
for (const sub of ["slots", "locks", "waiters"])
|
|
1786
|
-
mkdirSync2(join8(dir, sub), { recursive: true, mode: 448 });
|
|
1787
|
-
return dir;
|
|
1788
|
-
}
|
|
1789
|
-
function readHolder(path) {
|
|
1790
|
-
try {
|
|
1791
|
-
const holder = JSON.parse(readFileSync6(path, "utf8"));
|
|
1792
|
-
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;
|
|
1793
|
-
} catch {
|
|
1794
|
-
return;
|
|
1795
|
-
}
|
|
1796
|
-
}
|
|
1797
|
-
function pathOf(dir, kind, name) {
|
|
1798
|
-
return join8(dir, kind === "slot" ? "slots" : "locks", name);
|
|
1799
|
-
}
|
|
1800
|
-
function candidates(dir, { kind, name, count }) {
|
|
1801
|
-
if (kind === "lock")
|
|
1802
|
-
return [{ path: pathOf(dir, "lock", name), resource: `lock ${name}` }];
|
|
1803
|
-
return Array.from({ length: count }, (_, index) => ({ path: pathOf(dir, "slot", String(index)), resource: `slot ${index + 1}` }));
|
|
1804
|
-
}
|
|
1805
|
-
function attempt(dir, wanted) {
|
|
1806
|
-
for (const { path, resource } of candidates(dir, wanted)) {
|
|
1807
|
-
const held = tryLock(path);
|
|
1808
|
-
if (held !== undefined)
|
|
1809
|
-
return { held, resource };
|
|
1810
|
-
}
|
|
1811
|
-
return;
|
|
1812
|
-
}
|
|
1813
|
-
function who(holder) {
|
|
1814
|
-
return `${holder.session ?? `pid ${holder.pid}`} running ${truncate(holder.command, COMMAND_WIDTH)} for ${formatDuration(Date.now() - holder.since)}`;
|
|
1815
|
-
}
|
|
1816
|
-
function waitingLine(dir, wanted) {
|
|
1817
|
-
const holders = candidates(dir, wanted).map(({ path }) => readHolder(path)).filter((holder) => holder !== undefined).sort((a, b) => a.since - b.since);
|
|
1818
|
-
const oldest = holders[0];
|
|
1819
|
-
const by = oldest === undefined ? "another process" : who(oldest);
|
|
1820
|
-
if (wanted.kind === "lock")
|
|
1821
|
-
return `slot: waiting for lock ${wanted.name}, held by ${by}`;
|
|
1822
|
-
return `slot: waiting for a slot (${holders.length} of ${wanted.count} busy), the oldest held by ${by}`;
|
|
1823
|
-
}
|
|
1824
|
-
async function holderOf(command) {
|
|
1825
|
-
const session = await currentSession(await liveSessions());
|
|
1826
|
-
return { pid: process21.pid, command: command.join(" "), cwd: process21.cwd(), since: Date.now(), ...session === undefined ? {} : { session: session.name } };
|
|
1827
|
-
}
|
|
1828
|
-
var waiterCount = 0;
|
|
1829
|
-
async function acquire(dir, resources, holder, deadline, timeoutMs) {
|
|
1830
|
-
let waiter;
|
|
1831
|
-
try {
|
|
1832
|
-
for (;; ) {
|
|
1833
|
-
const taken = [];
|
|
1834
|
-
let busy;
|
|
1835
|
-
for (const wanted of resources) {
|
|
1836
|
-
const got = attempt(dir, wanted);
|
|
1837
|
-
if (got === undefined) {
|
|
1838
|
-
busy = wanted;
|
|
1839
|
-
break;
|
|
1840
|
-
}
|
|
1841
|
-
taken.push(got);
|
|
1842
|
-
}
|
|
1843
|
-
if (busy === undefined) {
|
|
1844
|
-
for (const { held } of taken)
|
|
1845
|
-
writeHeld(held, JSON.stringify(holder));
|
|
1846
|
-
return taken;
|
|
1847
|
-
}
|
|
1848
|
-
for (const { held } of taken)
|
|
1849
|
-
held.release();
|
|
1850
|
-
const resource = busy.kind === "lock" ? `lock ${busy.name}` : "slot";
|
|
1851
|
-
if (waiter === undefined) {
|
|
1852
|
-
const path = join8(dir, "waiters", `${process21.pid}-${waiterCount++}`);
|
|
1853
|
-
const held = tryLock(path);
|
|
1854
|
-
if (held !== undefined) {
|
|
1855
|
-
writeHeld(held, JSON.stringify({ ...holder, resource }));
|
|
1856
|
-
waiter = { held, path, resource };
|
|
1857
|
-
}
|
|
1858
|
-
console.error(waitingLine(dir, busy));
|
|
1859
|
-
} else if (waiter.resource !== resource) {
|
|
1860
|
-
writeHeld(waiter.held, JSON.stringify({ ...holder, resource }));
|
|
1861
|
-
waiter.resource = resource;
|
|
1862
|
-
}
|
|
1863
|
-
if (Date.now() >= deadline)
|
|
1864
|
-
fail(`gave up after ${formatDuration(timeoutMs)} waiting for ${busy.kind === "lock" ? `lock ${busy.name}` : "a slot"}`);
|
|
1865
|
-
await Bun.sleep(POLL);
|
|
1866
|
-
}
|
|
1867
|
-
} finally {
|
|
1868
|
-
if (waiter !== undefined) {
|
|
1869
|
-
rmSync(waiter.path, { force: true });
|
|
1870
|
-
waiter.held.release();
|
|
1871
|
-
}
|
|
1872
|
-
}
|
|
1873
|
-
}
|
|
1874
|
-
function withSeparator(args) {
|
|
1875
|
-
const takesValue = (word) => Object.entries(RUN_OPTIONS).some(([name, option]) => option.type === "string" && (word === `--${name}` || ("short" in option) && word === `-${option.short}`));
|
|
1876
|
-
for (let at = 0;at < args.length; at++) {
|
|
1877
|
-
const word = args[at];
|
|
1878
|
-
if (word === "--")
|
|
1879
|
-
return args;
|
|
1880
|
-
if (!word.startsWith("-"))
|
|
1881
|
-
return [...args.slice(0, at), "--", ...args.slice(at)];
|
|
1882
|
-
if (takesValue(word))
|
|
1883
|
-
at++;
|
|
1884
|
-
}
|
|
1885
|
-
return args;
|
|
1886
|
-
}
|
|
1887
|
-
async function runSlotted(given) {
|
|
1888
|
-
const args = withSeparator(given);
|
|
1889
|
-
const parsed = parse(args, RUN_USAGE, RUN_OPTIONS, { rest: true, exits: RUN_EXITS, 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"] });
|
|
1890
|
-
const { values, rest } = parsed;
|
|
1891
|
-
if (rest === undefined || rest.length === 0)
|
|
1892
|
-
fail(`give the command after --
|
|
8
|
+
A first word \`ls\` always means the listing: run the ls command as \`slot -n 4 -- ls\`.`,RUN_EXITS=[[0,"the command did"],["its own","the code of a command that failed"],[2,"it timed out waiting for the slot or a usage error"],[127,"the command cannot be started"]],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
|
|
1893
9
|
|
|
1894
|
-
${
|
|
1895
|
-
const locks = [...new Set(values.lock ?? [])].sort();
|
|
1896
|
-
for (const name of locks) {
|
|
1897
|
-
if (!LOCK_NAME.test(name))
|
|
1898
|
-
fail(`--lock ${name} is no lock name: letters, digits, dots, dashes and underscores`);
|
|
1899
|
-
}
|
|
1900
|
-
if (values["no-slot"] === true && locks.length === 0)
|
|
1901
|
-
fail("--no-slot takes the --lock alone, and none is given");
|
|
1902
|
-
const count = wholeNumber(values.slots, "slots", defaultSlots());
|
|
1903
|
-
const timeoutMs = duration(values.timeout, "timeout", Number.POSITIVE_INFINITY);
|
|
1904
|
-
const deadline = Date.now() + timeoutMs;
|
|
1905
|
-
const holding = new Set((process21.env[HOLDING] ?? "").split(",").filter((token) => token !== ""));
|
|
1906
|
-
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 }]];
|
|
1907
|
-
const signals = holdSignals(() => {
|
|
1908
|
-
return;
|
|
1909
|
-
});
|
|
1910
|
-
const taken = [];
|
|
1911
|
-
try {
|
|
1912
|
-
if (wanted.length > 0) {
|
|
1913
|
-
const dir = await stateDir();
|
|
1914
|
-
const holder = await holderOf(rest);
|
|
1915
|
-
taken.push(...await acquire(dir, wanted, holder, deadline, timeoutMs));
|
|
1916
|
-
}
|
|
1917
|
-
const tokens = new Set([...holding, ...locks.map((name) => `lock:${name}`), ...wanted.some((resource) => resource.kind === "slot") ? ["slot"] : []]);
|
|
1918
|
-
let child;
|
|
1919
|
-
try {
|
|
1920
|
-
child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...process21.env, [HOLDING]: [...tokens].join(",") } });
|
|
1921
|
-
} catch (error) {
|
|
1922
|
-
fail(`cannot run ${rest[0]}: ${error instanceof Error ? error.message : String(error)}`, 127);
|
|
1923
|
-
}
|
|
1924
|
-
signals.forward(child);
|
|
1925
|
-
await child.exited;
|
|
1926
|
-
return exitCodeOf(child.exitCode, child.signalCode);
|
|
1927
|
-
} finally {
|
|
1928
|
-
signals.release();
|
|
1929
|
-
for (const { held } of taken)
|
|
1930
|
-
held.release();
|
|
1931
|
-
}
|
|
1932
|
-
}
|
|
1933
|
-
function scan(dir, state, kind) {
|
|
1934
|
-
const folder = join8(dir, kind);
|
|
1935
|
-
const entries = [];
|
|
1936
|
-
for (const name of existsSync4(folder) ? readdirSync(folder) : []) {
|
|
1937
|
-
const path = join8(folder, name);
|
|
1938
|
-
const probe = tryLock(path);
|
|
1939
|
-
if (probe !== undefined) {
|
|
1940
|
-
if (kind === "waiters")
|
|
1941
|
-
rmSync(path, { force: true });
|
|
1942
|
-
probe.release();
|
|
1943
|
-
continue;
|
|
1944
|
-
}
|
|
1945
|
-
const holder = readHolder(path);
|
|
1946
|
-
const resource = kind === "waiters" ? holder?.resource ?? "slot" : `${kind === "slots" ? "slot" : "lock"} ${kind === "slots" ? Number(name) + 1 : name}`;
|
|
1947
|
-
entries.push({ state, resource, pid: holder?.pid ?? 0, command: holder?.command ?? "?", cwd: holder?.cwd ?? "", since: holder?.since ?? 0, ...holder?.session === undefined ? {} : { session: holder.session } });
|
|
1948
|
-
}
|
|
1949
|
-
return entries;
|
|
1950
|
-
}
|
|
1951
|
-
async function listSlots(args) {
|
|
1952
|
-
const { values } = parse(args, LS_USAGE, LS_OPTIONS, { exits: [[0, "it listed them"], [2, "a usage error"]], examples: ["slot ls", "slot ls --json"] });
|
|
1953
|
-
const count = wholeNumber(values.slots, "slots", defaultSlots());
|
|
1954
|
-
const dir = await stateDir();
|
|
1955
|
-
const holding = [...scan(dir, "holding", "slots"), ...scan(dir, "holding", "locks")].sort((a, b) => a.since - b.since);
|
|
1956
|
-
const waiting = scan(dir, "waiting", "waiters").sort((a, b) => a.since - b.since);
|
|
1957
|
-
const entries = [...holding, ...waiting];
|
|
1958
|
-
const busy = holding.filter((entry) => entry.resource.startsWith("slot ")).length;
|
|
1959
|
-
if (values.json === true) {
|
|
1960
|
-
printJson({ slots: count, busy, entries });
|
|
1961
|
-
return 0;
|
|
1962
|
-
}
|
|
1963
|
-
console.log(paint(process21.stdout).bold(`slots: ${busy} of ${count} busy`));
|
|
1964
|
-
if (entries.length > 0)
|
|
1965
|
-
console.log(table(entries.map((entry) => [badge(entry.state, process21.stdout), entry.resource, entry.session ?? `pid ${entry.pid}`, truncate(entry.command, COMMAND_WIDTH), entry.since === 0 ? "?" : formatAge(entry.since)])));
|
|
1966
|
-
return 0;
|
|
1967
|
-
}
|
|
10
|
+
--json prints {slots, busy, entries}, each entry as {state, resource, pid, session, command, cwd, since}.`,SLOTS={type:"string",short:"n",description:"how many commands may hold a slot at once (half the CPU count)"},RUN_OPTIONS={lock:{type:"string",short:"l",multiple:!0,description:"a named lock to hold as well, for what must not run twice at once (shop-test-db)"},"no-slot":{type:"boolean",description:"take the --lock alone, without a slot"},slots:SLOTS,timeout:{type:"string",short:"t",description:"how long to wait before giving up (30s, 5m, 1h, a bare number in seconds), forever by default"}},LS_OPTIONS={slots:SLOTS,json:jsonOption()},POLL=250,COMMAND_WIDTH=60,LOCK_NAME=/^\w[\w.-]*$/,HOLDING="SLOT_HOLDING";function defaultSlots(){return Math.max(1,Math.floor(availableParallelism()/2))}async function stateDir(){let dir=process2.env.SLOT_DIR??await privateLogDirectory("slot");for(let sub of["slots","locks","waiters"])mkdirSync(join(dir,sub),{recursive:!0,mode:448});return dir}function readHolder(path){try{let holder=JSON.parse(readFileSync(path,"utf8"));return typeof holder.pid==="number"&&typeof holder.command==="string"?{pid:holder.pid,command:holder.command,cwd:holder.cwd??"",since:holder.since??0,...holder.session===void 0?{}:{session:holder.session},...holder.resource===void 0?{}:{resource:holder.resource}}:void 0}catch{return}}function pathOf(dir,kind,name){return join(dir,kind==="slot"?"slots":"locks",name)}function candidates(dir,{kind,name,count}){if(kind==="lock")return[{path:pathOf(dir,"lock",name),resource:`lock ${name}`}];return Array.from({length:count},(_,index)=>({path:pathOf(dir,"slot",String(index)),resource:`slot ${index+1}`}))}function attempt(dir,wanted){for(let{path,resource}of candidates(dir,wanted)){let held=tryLock(path);if(held!==void 0)return{held,resource}}return}function who(holder){return`${holder.session??`pid ${holder.pid}`} running ${truncate(holder.command,COMMAND_WIDTH)} for ${formatDuration(Date.now()-holder.since)}`}function waitingLine(dir,wanted){let holders=candidates(dir,wanted).map(({path})=>readHolder(path)).filter((holder)=>holder!==void 0).sort((a,b)=>a.since-b.since),oldest=holders[0],by=oldest===void 0?"another process":who(oldest);if(wanted.kind==="lock")return`slot: waiting for lock ${wanted.name}, held by ${by}`;return`slot: waiting for a slot (${holders.length} of ${wanted.count} busy), the oldest held by ${by}`}async function holderOf(command){let session=await currentSession(await liveSessions());return{pid:process2.pid,command:command.join(" "),cwd:process2.cwd(),since:Date.now(),...session===void 0?{}:{session:session.name}}}var waiterCount=0;async function acquire(dir,resources,holder,deadline,timeoutMs){let waiter;try{for(;;){let taken=[],busy;for(let wanted of resources){let got=attempt(dir,wanted);if(got===void 0){busy=wanted;break}taken.push(got)}if(busy===void 0){for(let{held}of taken)writeHeld(held,JSON.stringify(holder));return taken}for(let{held}of taken)held.release();let resource=busy.kind==="lock"?`lock ${busy.name}`:"slot";if(waiter===void 0){let path=join(dir,"waiters",`${process2.pid}-${waiterCount++}`),held=tryLock(path);if(held!==void 0)writeHeld(held,JSON.stringify({...holder,resource})),waiter={held,path,resource};console.error(waitingLine(dir,busy))}else if(waiter.resource!==resource)writeHeld(waiter.held,JSON.stringify({...holder,resource})),waiter.resource=resource;if(Date.now()>=deadline)fail(`gave up after ${formatDuration(timeoutMs)} waiting for ${busy.kind==="lock"?`lock ${busy.name}`:"a slot"}`);await Bun.sleep(POLL)}}finally{if(waiter!==void 0)rmSync(waiter.path,{force:!0}),waiter.held.release()}}function withSeparator(args){let takesValue=(word)=>Object.entries(RUN_OPTIONS).some(([name,option])=>option.type==="string"&&(word===`--${name}`||("short"in option)&&word===`-${option.short}`));for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")return args;if(!word.startsWith("-"))return[...args.slice(0,at),"--",...args.slice(at)];if(takesValue(word))at++}return args}async function runSlotted(given){let args=withSeparator(given),parsed=parse(args,RUN_USAGE,RUN_OPTIONS,{rest:!0,exits:RUN_EXITS,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 shop-test-db -- vendor/bin/phpunit","one phpunit at a time on the shared test database"],"slot ls"]}),{values,rest}=parsed;if(rest===void 0||rest.length===0)fail(`give the command after --
|
|
1968
11
|
|
|
1969
|
-
|
|
1970
|
-
process22.exitCode = await runMain({ name: "slot", run: async (args) => args[0] === "ls" ? listSlots(args.slice(1)) : runSlotted(args) });
|
|
12
|
+
${RUN_USAGE}`);let locks=[...new Set(values.lock??[])].sort();for(let name of locks)if(!LOCK_NAME.test(name))fail(`--lock ${name} is no lock name: letters, digits, dots, dashes and underscores`);if(values["no-slot"]===!0&&locks.length===0)fail("--no-slot takes the --lock alone, and none is given");let count=wholeNumber(values.slots,"slots",defaultSlots()),timeoutMs=duration(values.timeout,"timeout",Number.POSITIVE_INFINITY),deadline=Date.now()+timeoutMs,holding=new Set((process2.env[HOLDING]??"").split(",").filter((token)=>token!=="")),wanted=[...locks.filter((name)=>!holding.has(`lock:${name}`)).map((name)=>({kind:"lock",name,count})),...values["no-slot"]===!0||holding.has("slot")?[]:[{kind:"slot",name:"",count}]],signals=holdSignals(()=>{return}),taken=[];try{if(wanted.length>0){let dir=await stateDir(),holder=await holderOf(rest);taken.push(...await acquire(dir,wanted,holder,deadline,timeoutMs))}let tokens=new Set([...holding,...locks.map((name)=>`lock:${name}`),...wanted.some((resource)=>resource.kind==="slot")?["slot"]:[]]),child;try{child=Bun.spawn(rest,{stdio:["inherit","inherit","inherit"],env:{...process2.env,[HOLDING]:[...tokens].join(",")}})}catch(error){fail(`cannot run ${rest[0]}: ${error instanceof Error?error.message:String(error)}`,127)}return signals.forward(child),await child.exited,exitCodeOf(child.exitCode,child.signalCode)}finally{signals.release();for(let{held}of taken)held.release()}}function scan(dir,state,kind){let folder=join(dir,kind),entries=[];for(let name of existsSync(folder)?readdirSync(folder):[]){let path=join(folder,name),probe=tryLock(path);if(probe!==void 0){if(kind==="waiters")rmSync(path,{force:!0});probe.release();continue}let holder=readHolder(path),resource=kind==="waiters"?holder?.resource??"slot":`${kind==="slots"?"slot":"lock"} ${kind==="slots"?Number(name)+1:name}`;entries.push({state,resource,pid:holder?.pid??0,command:holder?.command??"?",cwd:holder?.cwd??"",since:holder?.since??0,...holder?.session===void 0?{}:{session:holder.session}})}return entries}async function listSlots(args){let{values}=parse(args,LS_USAGE,LS_OPTIONS,{exits:[[0,"it listed them"],[2,"a usage error"]],examples:["slot ls","slot ls --json"]}),count=wholeNumber(values.slots,"slots",defaultSlots()),dir=await stateDir(),holding=[...scan(dir,"holding","slots"),...scan(dir,"holding","locks")].sort((a,b)=>a.since-b.since),waiting=scan(dir,"waiting","waiters").sort((a,b)=>a.since-b.since),entries=[...holding,...waiting],busy=holding.filter((entry)=>entry.resource.startsWith("slot ")).length;if(values.json===!0)return printJson({slots:count,busy,entries}),0;if(console.log(paint(process2.stdout).bold(`slots: ${busy} of ${count} busy`)),entries.length>0)console.log(table(entries.map((entry)=>[badge(entry.state,process2.stdout),entry.resource,entry.session??`pid ${entry.pid}`,truncate(entry.command,COMMAND_WIDTH),entry.since===0?"?":formatAge(entry.since)])));return 0}process3.exitCode=await runMain({name:"slot",run:async(args)=>args[0]==="ls"?listSlots(args.slice(1)):runSlotted(args)});
|