@kaynooo/cli-proc 0.8.2 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/proc-cli.js +48 -2744
- package/package.json +18 -9
- package/src/manage.ts +333 -0
- package/src/pid.ts +14 -2
- package/src/ports.ts +47 -12
- package/src/proc-cli.ts +13 -7
- package/src/procs.ts +33 -9
- package/src/read.ts +41 -19
package/dist/proc-cli.js
CHANGED
|
@@ -1,1334 +1,19 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
var __esm = (fn, res, err) => () => {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
if (err)
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
function a
|
|
17
|
-
return JSON.stringify([e ?? null, t ?? null, o]);
|
|
18
|
-
}
|
|
19
|
-
function y(e, t) {
|
|
20
|
-
let o = a(e, t), n = i.get(o);
|
|
21
|
-
if (!n)
|
|
22
|
-
n = new Intl.NumberFormat(e, t), i.set(o, n);
|
|
23
|
-
return n;
|
|
24
|
-
}
|
|
25
|
-
var r, i, l;
|
|
26
|
-
var init_chunk_n6z2kk96 = __esm(() => {
|
|
27
|
-
r = new Map;
|
|
28
|
-
i = new Map;
|
|
29
|
-
l = new Map;
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
|
|
33
|
-
function Ao(t, e, r = "...") {
|
|
34
|
-
let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
|
|
35
|
-
if (t.length <= e)
|
|
36
|
-
return t;
|
|
37
|
-
let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
|
|
38
|
-
if (o && !Y.test(t[c.length] ?? " "))
|
|
39
|
-
c = c.replace(Nt, "") || c;
|
|
40
|
-
if (o)
|
|
41
|
-
c = c.trimEnd();
|
|
42
|
-
return s ? (c + n).slice(0, l) : c + n;
|
|
43
|
-
}
|
|
44
|
-
var N, Nt, Y, be, W;
|
|
45
|
-
var init_chunk_rkhsft4a = __esm(() => {
|
|
46
|
-
N = new Map;
|
|
47
|
-
Nt = /\s+\S*$/;
|
|
48
|
-
Y = /\s/;
|
|
49
|
-
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));
|
|
50
|
-
W = new Map;
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
|
|
54
|
-
var init_text = __esm(() => {
|
|
55
|
-
init_chunk_rkhsft4a();
|
|
56
|
-
});
|
|
57
|
-
|
|
58
|
-
// ../kit/src/mode.ts
|
|
59
|
-
import process2 from "process";
|
|
60
|
-
function isSet(value) {
|
|
61
|
-
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
62
|
-
}
|
|
63
|
-
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
64
|
-
const chosen = env.KIT_MODE;
|
|
65
|
-
if (chosen !== undefined && MODES.has(chosen))
|
|
66
|
-
return chosen;
|
|
67
|
-
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
68
|
-
return "agent";
|
|
69
|
-
if (stream.isTTY === true)
|
|
70
|
-
return "terminal";
|
|
71
|
-
return isSet(env.CI) ? "ci" : "pipe";
|
|
72
|
-
}
|
|
73
|
-
function isInteractive(streams = process2) {
|
|
74
|
-
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
75
|
-
}
|
|
76
|
-
var MODES, AGENT_VARIABLES;
|
|
77
|
-
var init_mode = __esm(() => {
|
|
78
|
-
MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
79
|
-
AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
83
|
-
function b(r) {
|
|
84
|
-
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
85
|
-
if (!G2.test(e))
|
|
86
|
-
return [0, 0, 0];
|
|
87
|
-
if (e.length === 3 || e.length === 4)
|
|
88
|
-
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
89
|
-
if (e.length !== 6 && e.length !== 8)
|
|
90
|
-
throw Error(`Invalid hex color length: ${e.length}`);
|
|
91
|
-
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
92
|
-
}
|
|
93
|
-
function C(r, e = globalThis.process?.env ?? {}) {
|
|
94
|
-
if (e.FORCE_COLOR !== undefined)
|
|
95
|
-
return h.has(e.FORCE_COLOR);
|
|
96
|
-
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
97
|
-
return false;
|
|
98
|
-
return r?.isTTY === true;
|
|
99
|
-
}
|
|
100
|
-
function f(r, e = []) {
|
|
101
|
-
let l = "", n = "";
|
|
102
|
-
for (let t = 0, i = e.length;t < i; t++)
|
|
103
|
-
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
104
|
-
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
105
|
-
return new Proxy(c, { get(t, i) {
|
|
106
|
-
let a = B[i];
|
|
107
|
-
if (Array.isArray(a)) {
|
|
108
|
-
let s = g.get(i);
|
|
109
|
-
if (s === undefined)
|
|
110
|
-
s = f(r, [...e, a]), g.set(i, s);
|
|
111
|
-
return s;
|
|
112
|
-
}
|
|
113
|
-
if (typeof a === "function")
|
|
114
|
-
return (...s) => {
|
|
115
|
-
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
116
|
-
if (u === undefined) {
|
|
117
|
-
if (g.size >= 64)
|
|
118
|
-
g.clear();
|
|
119
|
-
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
120
|
-
}
|
|
121
|
-
return u;
|
|
122
|
-
};
|
|
123
|
-
throw Error(`Unknown style: ${String(i)}`);
|
|
124
|
-
} });
|
|
125
|
-
}
|
|
126
|
-
function Fe(r = {}) {
|
|
127
|
-
return f(r);
|
|
128
|
-
}
|
|
129
|
-
var G2, B, h, o;
|
|
130
|
-
var init_chunk_x450vn3m = __esm(() => {
|
|
131
|
-
G2 = /^[a-f0-9]+$/i;
|
|
132
|
-
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") => {
|
|
133
|
-
let [l, n, c] = b(r);
|
|
134
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
135
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
136
|
-
h = new Set(["", "1", "2", "3", "true"]);
|
|
137
|
-
o = Fe();
|
|
138
|
-
});
|
|
139
|
-
|
|
140
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
|
|
141
|
-
var init_colors = __esm(() => {
|
|
142
|
-
init_chunk_x450vn3m();
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
// ../kit/src/config.ts
|
|
146
|
-
import { existsSync } from "fs";
|
|
147
|
-
import { dirname, join, resolve } from "path";
|
|
148
|
-
import process3 from "process";
|
|
149
|
-
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
150
|
-
const wanted = typeof names === "string" ? [names] : names;
|
|
151
|
-
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
152
|
-
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
153
|
-
if (found !== undefined)
|
|
154
|
-
return found;
|
|
155
|
-
if (stop(dir) || dirname(dir) === dir)
|
|
156
|
-
return;
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
var init_config = __esm(() => {
|
|
160
|
-
init_args();
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
// ../kit/src/user-config.ts
|
|
164
|
-
import { homedir } from "os";
|
|
165
|
-
import { isAbsolute, join as join2 } from "path";
|
|
166
|
-
import process4 from "process";
|
|
167
|
-
function xdgFolder(value, fallback) {
|
|
168
|
-
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
169
|
-
}
|
|
170
|
-
function configBase(where = {}) {
|
|
171
|
-
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
172
|
-
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
173
|
-
}
|
|
174
|
-
function userConfigPath(bin, where = {}) {
|
|
175
|
-
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
176
|
-
}
|
|
177
|
-
var init_user_config = () => {};
|
|
178
|
-
|
|
179
|
-
// ../kit/src/theme.ts
|
|
180
|
-
import { existsSync as existsSync2, readFileSync, statSync } from "fs";
|
|
181
|
-
import { homedir as homedir2 } from "os";
|
|
182
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
183
|
-
import process5 from "process";
|
|
184
|
-
function isColorSpec(spec) {
|
|
185
|
-
if (typeof spec === "number")
|
|
186
|
-
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
187
|
-
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
188
|
-
}
|
|
189
|
-
function cubeLevel(channel) {
|
|
190
|
-
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
191
|
-
}
|
|
192
|
-
function nearest256(hex) {
|
|
193
|
-
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
194
|
-
const levels = rgb.map(cubeLevel);
|
|
195
|
-
const cube = levels.map((level) => CUBE[level]);
|
|
196
|
-
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
197
|
-
const greyValue = 8 + grey * 10;
|
|
198
|
-
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
199
|
-
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
200
|
-
}
|
|
201
|
-
function hasTrueColor(env) {
|
|
202
|
-
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
203
|
-
}
|
|
204
|
-
function tinted(colors, spec, env = process5.env) {
|
|
205
|
-
if (typeof spec === "number")
|
|
206
|
-
return colors.ansi256(spec);
|
|
207
|
-
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
208
|
-
if (HEX.test(token))
|
|
209
|
-
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
210
|
-
return chain[token] ?? chain;
|
|
211
|
-
}, colors);
|
|
212
|
-
}
|
|
213
|
-
function isRecord(value) {
|
|
214
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
215
|
-
}
|
|
216
|
-
function readThemeFile(path, warn) {
|
|
217
|
-
try {
|
|
218
|
-
const stat = statSync(path, { throwIfNoEntry: false });
|
|
219
|
-
if (stat === undefined)
|
|
220
|
-
return;
|
|
221
|
-
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
222
|
-
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
223
|
-
return;
|
|
224
|
-
}
|
|
225
|
-
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
226
|
-
if (isRecord(parsed))
|
|
227
|
-
return parsed;
|
|
228
|
-
warn(`${path} is not a JSON object, theme ignored`);
|
|
229
|
-
} catch (error) {
|
|
230
|
-
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
231
|
-
}
|
|
232
|
-
return;
|
|
233
|
-
}
|
|
234
|
-
function applyPreset(theme, name, warn, where) {
|
|
235
|
-
if (name === undefined)
|
|
236
|
-
return;
|
|
237
|
-
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
238
|
-
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
239
|
-
return;
|
|
240
|
-
}
|
|
241
|
-
const preset = PRESETS[name];
|
|
242
|
-
Object.assign(theme.colors, preset.colors);
|
|
243
|
-
Object.assign(theme.glyphs, preset.glyphs);
|
|
244
|
-
if (preset.accents !== undefined)
|
|
245
|
-
theme.accents = [...preset.accents];
|
|
246
|
-
if (Object.hasOwn(preset, "gradient"))
|
|
247
|
-
theme.gradient = preset.gradient;
|
|
248
|
-
return name;
|
|
249
|
-
}
|
|
250
|
-
function applyFile(theme, file, where, warn) {
|
|
251
|
-
if (isRecord(file.colors)) {
|
|
252
|
-
for (const [key, value] of Object.entries(file.colors)) {
|
|
253
|
-
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
254
|
-
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
255
|
-
else if (!isColorSpec(value))
|
|
256
|
-
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
257
|
-
else
|
|
258
|
-
theme.colors[key] = value;
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
if (isRecord(file.glyphs)) {
|
|
262
|
-
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
263
|
-
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
264
|
-
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
265
|
-
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
266
|
-
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
267
|
-
else
|
|
268
|
-
theme.glyphs[key] = value;
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
272
|
-
theme.accents = [...file.accents];
|
|
273
|
-
else if (file.accents !== undefined)
|
|
274
|
-
warn(`${where}: accents must be a non-empty list of colours`);
|
|
275
|
-
if (file.gradient === null)
|
|
276
|
-
theme.gradient = undefined;
|
|
277
|
-
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
278
|
-
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
279
|
-
else if (file.gradient !== undefined)
|
|
280
|
-
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
281
|
-
if (isRecord(file.bins)) {
|
|
282
|
-
for (const [bin, value] of Object.entries(file.bins)) {
|
|
283
|
-
if (isColorSpec(value))
|
|
284
|
-
theme.bins[bin] = value;
|
|
285
|
-
else
|
|
286
|
-
warn(`${where}: bin ${bin} has no valid colour`);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
function endsWalk(home) {
|
|
291
|
-
return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
|
|
292
|
-
}
|
|
293
|
-
function warnOnce(message) {
|
|
294
|
-
if (warned.has(message))
|
|
295
|
-
return;
|
|
296
|
-
warned.add(message);
|
|
297
|
-
console.error(`warning: theme ${message}`);
|
|
298
|
-
}
|
|
299
|
-
function isPath(chosen) {
|
|
300
|
-
return chosen.includes("/") || chosen.endsWith(".json");
|
|
301
|
-
}
|
|
302
|
-
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
303
|
-
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
304
|
-
const sources = [];
|
|
305
|
-
const chosen = env.KIT_THEME ?? "";
|
|
306
|
-
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
307
|
-
if (isPath(chosen))
|
|
308
|
-
wanted.push(resolve2(from, chosen));
|
|
309
|
-
const files = [];
|
|
310
|
-
for (const path of wanted) {
|
|
311
|
-
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
312
|
-
if (path !== undefined && file !== undefined)
|
|
313
|
-
files.push({ path, file });
|
|
314
|
-
}
|
|
315
|
-
let preset = "default";
|
|
316
|
-
if (chosen !== "" && !isPath(chosen)) {
|
|
317
|
-
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
318
|
-
} else {
|
|
319
|
-
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
320
|
-
if (named !== undefined)
|
|
321
|
-
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
322
|
-
}
|
|
323
|
-
for (const { path, file } of files) {
|
|
324
|
-
applyFile(theme, file, path, warn);
|
|
325
|
-
sources.push(path);
|
|
326
|
-
}
|
|
327
|
-
return { theme, sources, preset };
|
|
328
|
-
}
|
|
329
|
-
function activeTheme() {
|
|
330
|
-
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
331
|
-
if (current === undefined || key !== currentKey) {
|
|
332
|
-
current = loadTheme();
|
|
333
|
-
currentKey = key;
|
|
334
|
-
}
|
|
335
|
-
return current;
|
|
336
|
-
}
|
|
337
|
-
var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
|
|
338
|
-
var init_theme = __esm(() => {
|
|
339
|
-
init_config();
|
|
340
|
-
init_user_config();
|
|
341
|
-
ENDS = new Map;
|
|
342
|
-
DEFAULT = {
|
|
343
|
-
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" },
|
|
344
|
-
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" },
|
|
345
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
346
|
-
bins: {},
|
|
347
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
348
|
-
};
|
|
349
|
-
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" };
|
|
350
|
-
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" };
|
|
351
|
-
ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
352
|
-
PRESETS = {
|
|
353
|
-
default: {},
|
|
354
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
355
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
356
|
-
ascii: { glyphs: ASCII }
|
|
357
|
-
};
|
|
358
|
-
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"]);
|
|
359
|
-
HEX = /^#[0-9a-f]{6}$/i;
|
|
360
|
-
CONTROL = /\p{Cc}/u;
|
|
361
|
-
MAX_FILE_BYTES = 64 * 1024;
|
|
362
|
-
SPACES = /\s+/;
|
|
363
|
-
CUBE = [0, 95, 135, 175, 215, 255];
|
|
364
|
-
warned = new Set;
|
|
365
|
-
});
|
|
366
|
-
|
|
367
|
-
// ../kit/src/style.ts
|
|
368
|
-
import process6 from "process";
|
|
369
|
-
function takesControlCodes(stream, env = process6.env) {
|
|
370
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
371
|
-
}
|
|
372
|
-
function paint(stream, env = process6.env) {
|
|
373
|
-
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
374
|
-
}
|
|
375
|
-
function marked(mark, text, stream, detail, env = process6.env) {
|
|
376
|
-
const colors = paint(stream, env);
|
|
377
|
-
let head = MARK_WORDS[mark];
|
|
378
|
-
if (takesControlCodes(stream, env)) {
|
|
379
|
-
const { theme } = activeTheme();
|
|
380
|
-
head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
|
|
381
|
-
}
|
|
382
|
-
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
383
|
-
}
|
|
384
|
-
function problem(text, detail) {
|
|
385
|
-
console.error(marked("problem", text, process6.stderr, detail));
|
|
386
|
-
}
|
|
387
|
-
var MARK_WORDS, STATUS_WORDS, STATUS_OF;
|
|
388
|
-
var init_style = __esm(() => {
|
|
389
|
-
init_colors();
|
|
390
|
-
init_mode();
|
|
391
|
-
init_theme();
|
|
392
|
-
MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
|
|
393
|
-
STATUS_WORDS = {
|
|
394
|
-
passed: ["passed", "success", "succeeded", "ok"],
|
|
395
|
-
failed: ["failed", "failure", "error", "errored"],
|
|
396
|
-
running: ["running", "in_progress", "started", "holding"],
|
|
397
|
-
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
398
|
-
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
399
|
-
};
|
|
400
|
-
STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
401
|
-
});
|
|
402
|
-
|
|
403
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-knqbxp56.js
|
|
404
|
-
function tt(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
|
|
405
|
-
let e = r === "si" ? 1000 : 1024;
|
|
406
|
-
if (Math.abs(i) < e)
|
|
407
|
-
return `${i} B`;
|
|
408
|
-
let s = r === "iec" ? ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] : ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], o = -1, a = 10 ** t;
|
|
409
|
-
do
|
|
410
|
-
i /= e, ++o;
|
|
411
|
-
while (Math.round(Math.abs(i) * a) / a >= e && o < s.length - 1);
|
|
412
|
-
return `${n ? y(n, { minimumFractionDigits: t, maximumFractionDigits: t }).format(i) : i.toFixed(t)} ${s[o]}`;
|
|
413
|
-
}
|
|
414
|
-
var init_chunk_knqbxp56 = __esm(() => {
|
|
415
|
-
init_chunk_n6z2kk96();
|
|
416
|
-
});
|
|
417
|
-
|
|
418
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/format/index.js
|
|
419
|
-
var init_format = __esm(() => {
|
|
420
|
-
init_chunk_knqbxp56();
|
|
421
|
-
});
|
|
422
|
-
|
|
423
|
-
// ../kit/src/format.ts
|
|
424
|
-
import process7 from "process";
|
|
425
|
-
function formatSeconds(total) {
|
|
426
|
-
let rest = Math.max(0, Math.round(total));
|
|
427
|
-
const amounts = UNITS.map(([unit, size]) => {
|
|
428
|
-
const amount = Math.floor(rest / size);
|
|
429
|
-
rest -= amount * size;
|
|
430
|
-
return `${amount}${unit}`;
|
|
431
|
-
});
|
|
432
|
-
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
433
|
-
if (first === -1)
|
|
434
|
-
return "0s";
|
|
435
|
-
const next = amounts[first + 1];
|
|
436
|
-
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
437
|
-
}
|
|
438
|
-
function formatDuration(ms) {
|
|
439
|
-
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
440
|
-
}
|
|
441
|
-
function upTo(text, separator) {
|
|
442
|
-
const end = text.indexOf(separator);
|
|
443
|
-
return end === -1 ? text : text.slice(0, end);
|
|
444
|
-
}
|
|
445
|
-
function truncate(text, width) {
|
|
446
|
-
return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
|
|
447
|
-
}
|
|
448
|
-
function textWidth(text) {
|
|
449
|
-
return Bun.stringWidth(text);
|
|
450
|
-
}
|
|
451
|
-
function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
|
|
452
|
-
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
453
|
-
if (outputMode(stream, env) === "agent")
|
|
454
|
-
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
455
|
-
`);
|
|
456
|
-
const widths = [];
|
|
457
|
-
for (const row of cells) {
|
|
458
|
-
for (const [index, cell] of row.entries())
|
|
459
|
-
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
460
|
-
}
|
|
461
|
-
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
462
|
-
const colors = paint(stream);
|
|
463
|
-
const lines = shown.map((row) => row.map((cell, index) => {
|
|
464
|
-
const width = widths[index] ?? 0;
|
|
465
|
-
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
466
|
-
if (align[index] === "right")
|
|
467
|
-
return `${gap}${cell}`;
|
|
468
|
-
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
469
|
-
}).join(" ").trimEnd());
|
|
470
|
-
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
471
|
-
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
472
|
-
`);
|
|
473
|
-
}
|
|
474
|
-
function narrow(rows, widths, limit) {
|
|
475
|
-
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
476
|
-
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
477
|
-
const floor = 8;
|
|
478
|
-
while (used() > limit) {
|
|
479
|
-
let widest = -1;
|
|
480
|
-
for (const [index, width] of widths.entries()) {
|
|
481
|
-
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
482
|
-
widest = index;
|
|
483
|
-
}
|
|
484
|
-
if (widest === -1)
|
|
485
|
-
break;
|
|
486
|
-
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
487
|
-
}
|
|
488
|
-
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
489
|
-
}
|
|
490
|
-
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
491
|
-
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
492
|
-
}
|
|
493
|
-
function printJson(value) {
|
|
494
|
-
console.log(jsonText(value));
|
|
495
|
-
}
|
|
496
|
-
var UNITS, LINE_BREAKS, ESCAPE;
|
|
497
|
-
var init_format2 = __esm(() => {
|
|
498
|
-
init_text();
|
|
499
|
-
init_mode();
|
|
500
|
-
init_style();
|
|
501
|
-
init_format();
|
|
502
|
-
UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
503
|
-
LINE_BREAKS = /\s*\n\s*/g;
|
|
504
|
-
ESCAPE = String.fromCharCode(27);
|
|
505
|
-
});
|
|
506
|
-
|
|
507
|
-
// ../kit/src/help.ts
|
|
508
|
-
import process8 from "process";
|
|
509
|
-
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
510
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
511
|
-
`);
|
|
512
|
-
const blank = lines.indexOf("");
|
|
513
|
-
const synopses = blank === -1 ? lines : lines.slice(0, blank);
|
|
514
|
-
const details = blank === -1 ? [] : lines.slice(blank + 1);
|
|
515
|
-
const colon = synopses[0].indexOf(": ");
|
|
516
|
-
const inline = synopses[0].slice(colon + 2);
|
|
517
|
-
const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
|
|
518
|
-
if (colon !== -1)
|
|
519
|
-
synopses[0] = synopses[0].slice(0, colon);
|
|
520
|
-
const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
|
|
521
|
-
`)}`;
|
|
522
|
-
const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
|
|
523
|
-
const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
|
|
524
|
-
return [head, ...lead, ...rest].join(`
|
|
525
|
-
`);
|
|
526
|
-
}
|
|
527
|
-
function prose(line, colors) {
|
|
528
|
-
if (colors.cyan("x") === "x")
|
|
529
|
-
return line;
|
|
530
|
-
return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
|
|
531
|
-
}
|
|
532
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
533
|
-
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
534
|
-
`);
|
|
535
|
-
}
|
|
536
|
-
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
537
|
-
if (exits.length === 0)
|
|
538
|
-
return [];
|
|
539
|
-
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
540
|
-
}
|
|
541
|
-
function wantsHelpJson(env = process8.env) {
|
|
542
|
-
return env.KIT_HELP === "json";
|
|
543
|
-
}
|
|
544
|
-
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
545
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
546
|
-
`);
|
|
547
|
-
const first = lines[0];
|
|
548
|
-
const colon = first.indexOf(": ");
|
|
549
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
550
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
551
|
-
return {
|
|
552
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
553
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
554
|
-
...replaces === undefined ? {} : { replaces },
|
|
555
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
556
|
-
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
557
|
-
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
558
|
-
};
|
|
559
|
-
}
|
|
560
|
-
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
561
|
-
if (examples.length === 0 || outputMode() === "agent")
|
|
562
|
-
return [];
|
|
563
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
564
|
-
}
|
|
565
|
-
function optionRows(options, colors = paint(process8.stdout)) {
|
|
566
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
567
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
568
|
-
const choices = option.choices?.join("|");
|
|
569
|
-
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
570
|
-
const named = inline ? `<${choices}>` : "<value>";
|
|
571
|
-
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
572
|
-
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
573
|
-
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
574
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
575
|
-
});
|
|
576
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
577
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
578
|
-
}
|
|
579
|
-
var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
|
|
580
|
-
var init_help = __esm(() => {
|
|
581
|
-
init_mode();
|
|
582
|
-
init_style();
|
|
583
|
-
OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
584
|
-
USAGE_PREFIX = /^usage:\s*/i;
|
|
585
|
-
FULL_STOP = /\.$/;
|
|
586
|
-
PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
|
|
587
|
-
});
|
|
588
|
-
|
|
589
|
-
// ../kit/src/text.ts
|
|
590
|
-
function distance(a, b) {
|
|
591
|
-
const left = [...a];
|
|
592
|
-
const right = [...b];
|
|
593
|
-
let before = [];
|
|
594
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
595
|
-
for (const [i, x] of left.entries()) {
|
|
596
|
-
const current = [i + 1];
|
|
597
|
-
for (const [j, y] of right.entries()) {
|
|
598
|
-
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
599
|
-
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
600
|
-
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
601
|
-
current.push(cost);
|
|
602
|
-
}
|
|
603
|
-
before = previous;
|
|
604
|
-
previous = current;
|
|
605
|
-
}
|
|
606
|
-
return previous[right.length] ?? 0;
|
|
607
|
-
}
|
|
608
|
-
function closest(name, names) {
|
|
609
|
-
const started = names.find((known) => known.startsWith(name));
|
|
610
|
-
if (started !== undefined)
|
|
611
|
-
return started;
|
|
612
|
-
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
613
|
-
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
614
|
-
}
|
|
615
|
-
var init_text2 = () => {};
|
|
616
|
-
|
|
617
|
-
// ../kit/src/input.ts
|
|
618
|
-
function wholeNumber(value, name, fallback, min = 1) {
|
|
619
|
-
if (value === undefined)
|
|
620
|
-
return fallback;
|
|
621
|
-
const number = Number(value);
|
|
622
|
-
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
623
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
624
|
-
return number;
|
|
625
|
-
}
|
|
626
|
-
function durationMs(text, unit) {
|
|
627
|
-
if (BARE_DURATION.test(text))
|
|
628
|
-
return Number(text) * UNIT_MS[unit];
|
|
629
|
-
if (!DURATION.test(text))
|
|
630
|
-
return 0;
|
|
631
|
-
let ms = 0;
|
|
632
|
-
for (const [, amount, part] of text.matchAll(DURATION_PART))
|
|
633
|
-
ms += Number(amount) * UNIT_MS[part];
|
|
634
|
-
return ms;
|
|
635
|
-
}
|
|
636
|
-
function duration(value, name, fallback, unit = "s") {
|
|
637
|
-
if (value === undefined)
|
|
638
|
-
return fallback;
|
|
639
|
-
const ms = durationMs(value.trim(), unit);
|
|
640
|
-
if (ms < 1)
|
|
641
|
-
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
642
|
-
return ms;
|
|
643
|
-
}
|
|
644
|
-
var WHOLE, BARE_DURATION, DURATION, DURATION_PART, UNIT_MS;
|
|
645
|
-
var init_input = __esm(() => {
|
|
646
|
-
init_args();
|
|
647
|
-
WHOLE = /^\d+$/;
|
|
648
|
-
BARE_DURATION = /^\d+(?:\.\d+)?$/;
|
|
649
|
-
DURATION = /^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/;
|
|
650
|
-
DURATION_PART = /(\d+(?:\.\d+)?)(ms|min|[smhd])/g;
|
|
651
|
-
UNIT_MS = { ms: 1, s: 1000, m: 60000, min: 60000, h: 3600000, d: 86400000 };
|
|
652
|
-
});
|
|
653
|
-
|
|
654
|
-
// ../kit/src/args.ts
|
|
655
|
-
import process9 from "process";
|
|
656
|
-
import { parseArgs } from "util";
|
|
657
|
-
function jsonOption(holds) {
|
|
658
|
-
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
659
|
-
}
|
|
660
|
-
function fail(message, code = 2, hint) {
|
|
661
|
-
throw new Exit(message, code, hint);
|
|
662
|
-
}
|
|
663
|
-
function badUsage(message) {
|
|
664
|
-
throw new UsageError(message);
|
|
665
|
-
}
|
|
666
|
-
|
|
667
|
-
class Completing {
|
|
668
|
-
options;
|
|
669
|
-
positionals;
|
|
670
|
-
candidates;
|
|
671
|
-
constructor(options, positionals = [], candidates = {}) {
|
|
672
|
-
this.options = options;
|
|
673
|
-
this.positionals = positionals;
|
|
674
|
-
this.candidates = candidates;
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
function applyOutput(color, plain, env = process9.env) {
|
|
678
|
-
const when = plain === true ? "never" : color ?? "auto";
|
|
679
|
-
if (when === "auto")
|
|
680
|
-
return;
|
|
681
|
-
if (when !== "always" && when !== "never")
|
|
682
|
-
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
683
|
-
if (when === "always") {
|
|
684
|
-
env.FORCE_COLOR = "1";
|
|
685
|
-
delete env.NO_COLOR;
|
|
686
|
-
} else {
|
|
687
|
-
env.NO_COLOR = "1";
|
|
688
|
-
delete env.FORCE_COLOR;
|
|
689
|
-
}
|
|
690
|
-
}
|
|
691
|
-
function parse(args, usage, options, settings = {}) {
|
|
692
|
-
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
693
|
-
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
694
|
-
const listing = listed(all, settings.allowNegative === true);
|
|
695
|
-
if (completion.active)
|
|
696
|
-
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
697
|
-
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
698
|
-
let parsed;
|
|
699
|
-
try {
|
|
700
|
-
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
701
|
-
} catch (error) {
|
|
702
|
-
const message = parseError(error);
|
|
703
|
-
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
704
|
-
}
|
|
705
|
-
const values = parsed.values;
|
|
706
|
-
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
707
|
-
if (values.help === true) {
|
|
708
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
709
|
-
throw new HelpShown;
|
|
710
|
-
}
|
|
711
|
-
checkChoices(parsed.values, all);
|
|
712
|
-
checkConflicts(parsed.values, all);
|
|
713
|
-
if (settings.positionals !== undefined)
|
|
714
|
-
checkPositionals(parsed.positionals, settings.positionals);
|
|
715
|
-
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
716
|
-
}
|
|
717
|
-
function splitRest(args, passes) {
|
|
718
|
-
const separator = passes ? args.indexOf("--") : -1;
|
|
719
|
-
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
720
|
-
}
|
|
721
|
-
function splitTrailing(args, options, count) {
|
|
722
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
723
|
-
let seen = 0;
|
|
724
|
-
if (count === 0)
|
|
725
|
-
return { own: args, rest: undefined };
|
|
726
|
-
for (let at = 0;at < args.length; at++) {
|
|
727
|
-
const word = args[at];
|
|
728
|
-
if (word === "--")
|
|
729
|
-
break;
|
|
730
|
-
if (word.startsWith("-")) {
|
|
731
|
-
if (takesValue(word))
|
|
732
|
-
at++;
|
|
733
|
-
continue;
|
|
734
|
-
}
|
|
735
|
-
seen++;
|
|
736
|
-
if (seen === count)
|
|
737
|
-
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
738
|
-
}
|
|
739
|
-
return { own: args, rest: undefined };
|
|
740
|
-
}
|
|
741
|
-
function listed(options, allowNegative) {
|
|
742
|
-
if (!allowNegative)
|
|
743
|
-
return options;
|
|
744
|
-
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
745
|
-
if (option.type !== "boolean" || option.negative === undefined)
|
|
746
|
-
return [[name, option]];
|
|
747
|
-
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
748
|
-
}));
|
|
749
|
-
}
|
|
750
|
-
function withAliases(args, options) {
|
|
751
|
-
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
752
|
-
if (named.size === 0)
|
|
753
|
-
return args;
|
|
754
|
-
const separator = args.indexOf("--");
|
|
755
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
756
|
-
return [...own.map((arg) => {
|
|
757
|
-
const at = arg.indexOf("=");
|
|
758
|
-
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
759
|
-
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
760
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
761
|
-
}
|
|
762
|
-
function withBare(args, options) {
|
|
763
|
-
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
764
|
-
if (bare.size === 0)
|
|
765
|
-
return args;
|
|
766
|
-
const separator = args.indexOf("--");
|
|
767
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
768
|
-
return [...own.flatMap((arg, index) => {
|
|
769
|
-
const optional = bare.get(arg);
|
|
770
|
-
const next = own[index + 1];
|
|
771
|
-
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
772
|
-
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
773
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
774
|
-
}
|
|
775
|
-
function checkConflicts(values, options) {
|
|
776
|
-
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
777
|
-
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
778
|
-
const other = given(name) ? conflicts.find(given) : undefined;
|
|
779
|
-
if (other !== undefined)
|
|
780
|
-
badUsage(`--${name} cannot be used with --${other}`);
|
|
781
|
-
}
|
|
782
|
-
}
|
|
783
|
-
function checkChoices(values, options) {
|
|
784
|
-
for (const [name, option] of Object.entries(options)) {
|
|
785
|
-
if (option.choices === undefined)
|
|
786
|
-
continue;
|
|
787
|
-
const given = values[name];
|
|
788
|
-
for (const value of Array.isArray(given) ? given : [given]) {
|
|
789
|
-
if (typeof value === "string")
|
|
790
|
-
oneOf(value, name, option.choices);
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
function oneOf(value, name, choices) {
|
|
795
|
-
if (!choices.includes(value))
|
|
796
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
797
|
-
return value;
|
|
798
|
-
}
|
|
799
|
-
function checkPositionals(given, names) {
|
|
800
|
-
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
801
|
-
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
802
|
-
if (given.length < required)
|
|
803
|
-
badUsage(`missing ${names[given.length]}`);
|
|
804
|
-
if (!variadic && given.length > names.length)
|
|
805
|
-
badUsage(`unexpected argument ${given[names.length]}`);
|
|
806
|
-
}
|
|
807
|
-
function joinDashValues(args, options) {
|
|
808
|
-
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
809
|
-
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
810
|
-
const joined = [];
|
|
811
|
-
for (let i = 0;i < args.length; i++) {
|
|
812
|
-
const arg = args[i] ?? "";
|
|
813
|
-
if (arg === "--")
|
|
814
|
-
return [...joined, ...args.slice(i)];
|
|
815
|
-
const name = longOf.get(arg);
|
|
816
|
-
const next = args[i + 1];
|
|
817
|
-
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
818
|
-
joined.push(`--${name}=${next}`);
|
|
819
|
-
i++;
|
|
820
|
-
} else {
|
|
821
|
-
joined.push(arg);
|
|
822
|
-
}
|
|
823
|
-
}
|
|
824
|
-
return joined;
|
|
825
|
-
}
|
|
826
|
-
function parseError(error) {
|
|
827
|
-
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
828
|
-
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
829
|
-
}
|
|
830
|
-
function nearestOption(message, options, allowNegative) {
|
|
831
|
-
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
832
|
-
if (typed === undefined)
|
|
833
|
-
return;
|
|
834
|
-
const word = typed.replace(DASHES, "");
|
|
835
|
-
if (word.length < 2 && !typed.startsWith("--"))
|
|
836
|
-
return;
|
|
837
|
-
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
838
|
-
...option.short === undefined ? [] : [`-${option.short}`],
|
|
839
|
-
`--${name}`,
|
|
840
|
-
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
841
|
-
]);
|
|
842
|
-
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
843
|
-
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
844
|
-
}
|
|
845
|
-
var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
|
|
846
|
-
var init_args = __esm(() => {
|
|
847
|
-
init_format2();
|
|
848
|
-
init_help();
|
|
849
|
-
init_text2();
|
|
850
|
-
init_help();
|
|
851
|
-
init_input();
|
|
852
|
-
DASHES = /^-+/;
|
|
853
|
-
EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
|
|
854
|
-
Exit = class Exit extends Error {
|
|
855
|
-
code;
|
|
856
|
-
hint;
|
|
857
|
-
[EXIT] = true;
|
|
858
|
-
constructor(message, code, hint) {
|
|
859
|
-
super(message);
|
|
860
|
-
this.code = code;
|
|
861
|
-
this.hint = hint;
|
|
862
|
-
}
|
|
863
|
-
static [Symbol.hasInstance](value) {
|
|
864
|
-
if (this !== Exit)
|
|
865
|
-
return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
866
|
-
return typeof value === "object" && value !== null && value[EXIT] === true;
|
|
867
|
-
}
|
|
868
|
-
};
|
|
869
|
-
UsageError = class UsageError extends Exit {
|
|
870
|
-
constructor(message, hint) {
|
|
871
|
-
super(message, 2, hint);
|
|
872
|
-
}
|
|
873
|
-
};
|
|
874
|
-
HelpShown = class HelpShown extends Exit {
|
|
875
|
-
constructor() {
|
|
876
|
-
super("help shown", 0);
|
|
877
|
-
}
|
|
878
|
-
};
|
|
879
|
-
completion = { active: false };
|
|
880
|
-
OUTPUT_OPTIONS = {
|
|
881
|
-
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
882
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
883
|
-
};
|
|
884
|
-
UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
885
|
-
});
|
|
886
|
-
|
|
887
|
-
// ../kit/src/folders.ts
|
|
888
|
-
var SKIPPED_FOLDERS;
|
|
889
|
-
var init_folders = __esm(() => {
|
|
890
|
-
init_user_config();
|
|
891
|
-
SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
892
|
-
});
|
|
893
|
-
|
|
894
|
-
// ../kit/src/answers.ts
|
|
895
|
-
var init_answers = __esm(() => {
|
|
896
|
-
init_folders();
|
|
897
|
-
});
|
|
898
|
-
|
|
899
|
-
// ../kit/src/job.ts
|
|
900
|
-
import process19 from "process";
|
|
901
|
-
function stopJob() {
|
|
902
|
-
process19.kill(0, "SIGTSTP");
|
|
903
|
-
}
|
|
904
|
-
var init_job = () => {};
|
|
905
|
-
|
|
906
|
-
// ../kit/src/picker/line.ts
|
|
907
|
-
function isEditKey(key) {
|
|
908
|
-
return EDIT_KEYS.has(key);
|
|
909
|
-
}
|
|
910
|
-
var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS;
|
|
911
|
-
var init_line = __esm(() => {
|
|
912
|
-
EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
|
|
913
|
-
BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
|
|
914
|
-
FORWARD_KILLS = new Set(["killnext", "killend"]);
|
|
915
|
-
});
|
|
916
|
-
|
|
917
|
-
// ../kit/src/picker/score.ts
|
|
918
|
-
var BOUNDARY_AFTER, NONE;
|
|
919
|
-
var init_score = __esm(() => {
|
|
920
|
-
BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
921
|
-
NONE = Number.NEGATIVE_INFINITY;
|
|
922
|
-
});
|
|
923
|
-
|
|
924
|
-
// ../kit/src/picker/state.ts
|
|
925
|
-
function repeat(value, count) {
|
|
926
|
-
return Array.from({ length: count }).fill(value);
|
|
927
|
-
}
|
|
928
|
-
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
929
|
-
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
930
|
-
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
931
|
-
const wheel = MOUSE.exec(sequence)?.[1];
|
|
932
|
-
if (wheel !== undefined)
|
|
933
|
-
return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
|
|
934
|
-
const named = codes.get(sequence);
|
|
935
|
-
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
936
|
-
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
937
|
-
paste.active = sequence === PASTE_START;
|
|
938
|
-
return [];
|
|
939
|
-
}
|
|
940
|
-
if (paste.active && (sequence === "\r" || sequence === `
|
|
941
|
-
`))
|
|
942
|
-
return [];
|
|
943
|
-
if (key !== undefined)
|
|
944
|
-
return [key];
|
|
945
|
-
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
946
|
-
});
|
|
947
|
-
}
|
|
948
|
-
var IS_CONTROL, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
|
|
949
|
-
var init_state = __esm(() => {
|
|
950
|
-
init_text2();
|
|
951
|
-
init_line();
|
|
952
|
-
init_score();
|
|
953
|
-
IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
954
|
-
KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
|
|
955
|
-
MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
|
|
956
|
-
KEYS = {
|
|
957
|
-
"\x1B[A": "up",
|
|
958
|
-
"\x1BOA": "up",
|
|
959
|
-
"\x10": "up",
|
|
960
|
-
"\x1B[B": "down",
|
|
961
|
-
"\x1BOB": "down",
|
|
962
|
-
"\x0E": "down",
|
|
963
|
-
"\x1B[5~": "pageup",
|
|
964
|
-
"\x1B[6~": "pagedown",
|
|
965
|
-
"\x1B[H": "home",
|
|
966
|
-
"\x1B[1~": "home",
|
|
967
|
-
"\x1BOH": "home",
|
|
968
|
-
"\x1B[F": "end",
|
|
969
|
-
"\x1B[4~": "end",
|
|
970
|
-
"\x1BOF": "end",
|
|
971
|
-
"\r": "enter",
|
|
972
|
-
"\n": "enter",
|
|
973
|
-
"\x03": "cancel",
|
|
974
|
-
"\x1B": "cancel",
|
|
975
|
-
"\x1B[D": "left",
|
|
976
|
-
"\x1BOD": "left",
|
|
977
|
-
"\x1B[C": "right",
|
|
978
|
-
"\x1BOC": "right",
|
|
979
|
-
"\x1B[1;5D": "wordleft",
|
|
980
|
-
"\x1B[1;3D": "wordleft",
|
|
981
|
-
"\x1Bb": "wordleft",
|
|
982
|
-
"\x1B[1;5C": "wordright",
|
|
983
|
-
"\x1B[1;3C": "wordright",
|
|
984
|
-
"\x1Bf": "wordright",
|
|
985
|
-
"\x01": "linestart",
|
|
986
|
-
"\x05": "lineend",
|
|
987
|
-
"\x7F": "erase",
|
|
988
|
-
"\x1B[3~": "delete",
|
|
989
|
-
"\b": "killword",
|
|
990
|
-
"\x1B\x7F": "killword",
|
|
991
|
-
"\x1B[3;5~": "killnext",
|
|
992
|
-
"\x1Bd": "killnext",
|
|
993
|
-
"\x15": "clear",
|
|
994
|
-
"\v": "killend",
|
|
995
|
-
"\x17": "word",
|
|
996
|
-
"\x19": "yank",
|
|
997
|
-
"\x1A": "suspend",
|
|
998
|
-
"\t": "tab",
|
|
999
|
-
"\x1F": "help",
|
|
1000
|
-
"\x1BOP": "help",
|
|
1001
|
-
"\x1B[11~": "help"
|
|
1002
|
-
};
|
|
1003
|
-
});
|
|
1004
|
-
|
|
1005
|
-
// ../kit/src/redraw.ts
|
|
1006
|
-
function overwrite(lines, columns) {
|
|
1007
|
-
return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
|
|
1008
|
-
`);
|
|
1009
|
-
}
|
|
1010
|
-
function rowsTaken(lines, columns) {
|
|
1011
|
-
return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
|
|
1012
|
-
}
|
|
1013
|
-
var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
|
|
1014
|
-
var init_redraw = __esm(() => {
|
|
1015
|
-
init_format2();
|
|
1016
|
-
});
|
|
1017
|
-
|
|
1018
|
-
// ../kit/src/prompt.ts
|
|
1019
|
-
import process20 from "process";
|
|
1020
|
-
function readKeys(input, paste = { active: false }) {
|
|
1021
|
-
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
|
|
1022
|
-
}
|
|
1023
|
-
async function confirm(question, { default: fallback, ...settings } = {}) {
|
|
1024
|
-
let answered = fallback;
|
|
1025
|
-
const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
|
|
1026
|
-
const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
|
|
1027
|
-
if (key === "cancel")
|
|
1028
|
-
return "cancel";
|
|
1029
|
-
if (key === "enter")
|
|
1030
|
-
return answered === undefined ? undefined : "enter";
|
|
1031
|
-
const letter = typeof key === "object" ? key.text.toLowerCase() : "";
|
|
1032
|
-
if (letter !== "y" && letter !== "n")
|
|
1033
|
-
return;
|
|
1034
|
-
answered = letter === "y";
|
|
1035
|
-
return "enter";
|
|
1036
|
-
});
|
|
1037
|
-
return accepted ? answered : undefined;
|
|
1038
|
-
}
|
|
1039
|
-
function asking(colors, question, typed, keys) {
|
|
1040
|
-
return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
|
|
1041
|
-
}
|
|
1042
|
-
function answer(colors, question, state, picked) {
|
|
1043
|
-
return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
|
|
1044
|
-
}
|
|
1045
|
-
async function ask(question, { hint, terminal = process20 }, render, press) {
|
|
1046
|
-
const { stdin, stderr } = terminal;
|
|
1047
|
-
if (!isInteractive(terminal))
|
|
1048
|
-
fail(`cannot ask "${question}" off a terminal`, 2, hint);
|
|
1049
|
-
const colors = paint(stderr);
|
|
1050
|
-
let current = "asking";
|
|
1051
|
-
let outcome;
|
|
1052
|
-
const columns = () => stderr.columns || 80;
|
|
1053
|
-
const draw = (state, last = false) => {
|
|
1054
|
-
const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
|
|
1055
|
-
const rows = rowsTaken(frame, columns());
|
|
1056
|
-
stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
|
|
1057
|
-
current = state;
|
|
1058
|
-
};
|
|
1059
|
-
const redraw = () => draw(current);
|
|
1060
|
-
const paste = { active: false };
|
|
1061
|
-
const stop = terminal.stop ?? (terminal === process20 ? stopJob : undefined);
|
|
1062
|
-
const suspend = () => {
|
|
1063
|
-
if (stop === undefined)
|
|
1064
|
-
return;
|
|
1065
|
-
stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
|
|
1066
|
-
stdin.setRawMode(false);
|
|
1067
|
-
stop();
|
|
1068
|
-
stdin.setRawMode(true);
|
|
1069
|
-
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1070
|
-
};
|
|
1071
|
-
try {
|
|
1072
|
-
stderr.on?.("resize", redraw);
|
|
1073
|
-
stdin.setRawMode(true);
|
|
1074
|
-
stdin.resume();
|
|
1075
|
-
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1076
|
-
draw("asking");
|
|
1077
|
-
return await new Promise((resolve) => {
|
|
1078
|
-
function onData(data) {
|
|
1079
|
-
for (const key of readKeys(data.toString(), paste)) {
|
|
1080
|
-
if (key === "suspend") {
|
|
1081
|
-
suspend();
|
|
1082
|
-
continue;
|
|
1083
|
-
}
|
|
1084
|
-
const pressed = press(key);
|
|
1085
|
-
if (pressed !== undefined) {
|
|
1086
|
-
settle(pressed);
|
|
1087
|
-
return;
|
|
1088
|
-
}
|
|
1089
|
-
}
|
|
1090
|
-
draw("asking");
|
|
1091
|
-
}
|
|
1092
|
-
function onEnd() {
|
|
1093
|
-
settle("cancel");
|
|
1094
|
-
}
|
|
1095
|
-
function settle(settled) {
|
|
1096
|
-
outcome = settled;
|
|
1097
|
-
stdin.off("data", onData);
|
|
1098
|
-
stdin.off("end", onEnd);
|
|
1099
|
-
resolve(settled === "enter");
|
|
1100
|
-
}
|
|
1101
|
-
stdin.on("data", onData);
|
|
1102
|
-
stdin.on("end", onEnd);
|
|
1103
|
-
});
|
|
1104
|
-
} finally {
|
|
1105
|
-
stderr.off?.("resize", redraw);
|
|
1106
|
-
draw(outcome ?? "cancel", true);
|
|
1107
|
-
stderr.write(`
|
|
1108
|
-
\x1B[?25h\x1B[?2004l`);
|
|
1109
|
-
stdin.setRawMode(false);
|
|
1110
|
-
stdin.pause();
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
|
-
var PROMPT_KEYS;
|
|
1114
|
-
var init_prompt = __esm(() => {
|
|
1115
|
-
init_answers();
|
|
1116
|
-
init_args();
|
|
1117
|
-
init_format2();
|
|
1118
|
-
init_job();
|
|
1119
|
-
init_mode();
|
|
1120
|
-
init_line();
|
|
1121
|
-
init_state();
|
|
1122
|
-
init_redraw();
|
|
1123
|
-
init_style();
|
|
1124
|
-
PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
|
|
1125
|
-
});
|
|
1126
|
-
|
|
1127
|
-
// src/proc-cli.ts
|
|
1128
|
-
import process23 from "process";
|
|
1129
|
-
|
|
1130
|
-
// ../kit/src/index.ts
|
|
1131
|
-
init_args();
|
|
1132
|
-
|
|
1133
|
-
// ../kit/src/argv.ts
|
|
1134
|
-
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
1135
|
-
import { resolve as resolve3 } from "path";
|
|
1136
|
-
import process10 from "process";
|
|
1137
|
-
function commandLine() {
|
|
1138
|
-
try {
|
|
1139
|
-
return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
1140
|
-
} catch {
|
|
1141
|
-
return;
|
|
1142
|
-
}
|
|
1143
|
-
}
|
|
1144
|
-
function realPath(word) {
|
|
1145
|
-
try {
|
|
1146
|
-
return realpathSync(resolve3(word));
|
|
1147
|
-
} catch {
|
|
1148
|
-
return;
|
|
1149
|
-
}
|
|
1150
|
-
}
|
|
1151
|
-
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
1152
|
-
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
1153
|
-
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
1154
|
-
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
1155
|
-
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
1156
|
-
}
|
|
1157
|
-
// ../kit/src/chart.ts
|
|
1158
|
-
init_format2();
|
|
1159
|
-
init_mode();
|
|
1160
|
-
init_style();
|
|
1161
|
-
init_theme();
|
|
1162
|
-
// ../kit/src/ci.ts
|
|
1163
|
-
init_args();
|
|
1164
|
-
init_format2();
|
|
1165
|
-
|
|
1166
|
-
// ../kit/src/progress.ts
|
|
1167
|
-
init_format2();
|
|
1168
|
-
|
|
1169
|
-
// ../kit/src/process.ts
|
|
1170
|
-
import { constants } from "os";
|
|
1171
|
-
import process11 from "process";
|
|
1172
|
-
var KILL_GRACE_MS = 2000;
|
|
1173
|
-
var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
1174
|
-
function exitCodeOf(code, signal) {
|
|
1175
|
-
if (code !== null)
|
|
1176
|
-
return code;
|
|
1177
|
-
if (typeof signal === "number")
|
|
1178
|
-
return 128 + signal;
|
|
1179
|
-
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
1180
|
-
}
|
|
1181
|
-
async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
1182
|
-
const chunks = [];
|
|
1183
|
-
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
1184
|
-
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 } : {} });
|
|
1185
|
-
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
1186
|
-
const timers = [];
|
|
1187
|
-
const killGroup = (killing) => {
|
|
1188
|
-
if (state.done)
|
|
1189
|
-
return;
|
|
1190
|
-
try {
|
|
1191
|
-
if (grouped)
|
|
1192
|
-
process11.kill(-proc.pid, killing);
|
|
1193
|
-
else
|
|
1194
|
-
proc.kill(killing);
|
|
1195
|
-
} catch {}
|
|
1196
|
-
};
|
|
1197
|
-
const stop = () => {
|
|
1198
|
-
killGroup("SIGTERM");
|
|
1199
|
-
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
1200
|
-
};
|
|
1201
|
-
const onAbort = () => stop();
|
|
1202
|
-
if (timeoutMs !== undefined) {
|
|
1203
|
-
timers.push(setTimeout(() => {
|
|
1204
|
-
state.timedOut = true;
|
|
1205
|
-
stop();
|
|
1206
|
-
}, timeoutMs));
|
|
1207
|
-
}
|
|
1208
|
-
if (signal?.aborted === true)
|
|
1209
|
-
onAbort();
|
|
1210
|
-
else
|
|
1211
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1212
|
-
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
1213
|
-
const drain = async (stream, name) => {
|
|
1214
|
-
for await (const data of stream) {
|
|
1215
|
-
if (state.failure !== undefined)
|
|
1216
|
-
continue;
|
|
1217
|
-
try {
|
|
1218
|
-
onChunk?.({ stream: name, data });
|
|
1219
|
-
} catch (error) {
|
|
1220
|
-
state.failure = error;
|
|
1221
|
-
stop();
|
|
1222
|
-
continue;
|
|
1223
|
-
}
|
|
1224
|
-
if (state.truncated)
|
|
1225
|
-
continue;
|
|
1226
|
-
let kept = data;
|
|
1227
|
-
if (state.kept + data.length > maxBytes) {
|
|
1228
|
-
let cut = maxBytes - state.kept;
|
|
1229
|
-
while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
|
|
1230
|
-
cut--;
|
|
1231
|
-
kept = data.subarray(0, cut);
|
|
1232
|
-
state.truncated = true;
|
|
1233
|
-
}
|
|
1234
|
-
state.kept += kept.length;
|
|
1235
|
-
if (kept.length > 0)
|
|
1236
|
-
chunks.push({ stream: name, data: kept });
|
|
1237
|
-
}
|
|
1238
|
-
};
|
|
1239
|
-
try {
|
|
1240
|
-
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
1241
|
-
await proc.exited;
|
|
1242
|
-
} finally {
|
|
1243
|
-
state.done = true;
|
|
1244
|
-
for (const timer of timers)
|
|
1245
|
-
clearTimeout(timer);
|
|
1246
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1247
|
-
}
|
|
1248
|
-
if (state.failure !== undefined)
|
|
1249
|
-
throw state.failure;
|
|
1250
|
-
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
1251
|
-
let output;
|
|
1252
|
-
let text;
|
|
1253
|
-
let stdout;
|
|
1254
|
-
return {
|
|
1255
|
-
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
1256
|
-
chunks,
|
|
1257
|
-
timedOut: state.timedOut,
|
|
1258
|
-
truncated: state.truncated,
|
|
1259
|
-
get output() {
|
|
1260
|
-
return output ??= joined();
|
|
1261
|
-
},
|
|
1262
|
-
get text() {
|
|
1263
|
-
return text ??= (output ??= joined()).toString();
|
|
1264
|
-
},
|
|
1265
|
-
get stdout() {
|
|
1266
|
-
return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
|
|
1267
|
-
}
|
|
1268
|
-
};
|
|
1269
|
-
}
|
|
1270
|
-
|
|
1271
|
-
// ../kit/src/progress.ts
|
|
1272
|
-
init_style();
|
|
1273
|
-
init_theme();
|
|
1274
|
-
var ESC = String.fromCharCode(27);
|
|
1275
|
-
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
1276
|
-
var RESET_STYLE = `${ESC}[0m`;
|
|
1277
|
-
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
1278
|
-
|
|
1279
|
-
// ../kit/src/ci.ts
|
|
1280
|
-
init_style();
|
|
1281
|
-
|
|
1282
|
-
// ../kit/src/tool.ts
|
|
1283
|
-
init_format2();
|
|
1284
|
-
// ../kit/src/cli.ts
|
|
1285
|
-
init_args();
|
|
1286
|
-
import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
|
|
1287
|
-
import { dirname as dirname3, join as join5 } from "path";
|
|
1288
|
-
import process15 from "process";
|
|
1289
|
-
|
|
1290
|
-
// ../kit/src/askpass.ts
|
|
1291
|
-
import process12 from "process";
|
|
1292
|
-
var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
|
|
1293
|
-
async function askpassClient(argv) {
|
|
1294
|
-
const socketPath = process12.env[SOCKET_VARIABLE];
|
|
1295
|
-
if (socketPath === undefined)
|
|
1296
|
-
return;
|
|
1297
|
-
const request = { prompt: argv[0] ?? "", ...process12.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
1298
|
-
const { promise, resolve } = Promise.withResolvers();
|
|
1299
|
-
let received = "";
|
|
1300
|
-
try {
|
|
1301
|
-
await Bun.connect({
|
|
1302
|
-
unix: socketPath,
|
|
1303
|
-
socket: {
|
|
1304
|
-
open: (socket) => void socket.write(`${JSON.stringify(request)}
|
|
1305
|
-
`),
|
|
1306
|
-
data: (_, chunk) => {
|
|
1307
|
-
received += chunk.toString();
|
|
1308
|
-
},
|
|
1309
|
-
close: () => resolve(received),
|
|
1310
|
-
error: () => resolve("")
|
|
1311
|
-
}
|
|
1312
|
-
});
|
|
1313
|
-
} catch {
|
|
1314
|
-
return 1;
|
|
1315
|
-
}
|
|
1316
|
-
const reply = await promise;
|
|
1317
|
-
if (reply === "")
|
|
1318
|
-
return 1;
|
|
1319
|
-
const { answer } = JSON.parse(reply);
|
|
1320
|
-
if (request.notice === true)
|
|
1321
|
-
return 0;
|
|
1322
|
-
if (answer === undefined)
|
|
1323
|
-
return 1;
|
|
1324
|
-
process12.stdout.write(`${answer}
|
|
1325
|
-
`);
|
|
1326
|
-
return 0;
|
|
1327
|
-
}
|
|
1328
|
-
|
|
1329
|
-
// ../kit/src/completions.ts
|
|
1330
|
-
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
1331
|
-
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'
|
|
3
|
+
var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};function a(e,t,o){return JSON.stringify([e??null,t??null,o])}function y(e,t){let o=a(e,t),n=i.get(o);if(!n)n=new Intl.NumberFormat(e,t),i.set(o,n);return n}var i;var init_chunk_n6z2kk96=__esm(()=>{i=new Map});function Ao(t,e,r="..."){let{suffix:n="...",includeSuffix:s=!1,wordBoundary:o=!1}=typeof r==="string"?{suffix:r}:r;if(t.length<=e)return t;let l=Math.max(0,e),c=t.substring(0,Math.max(0,s?l-n.length:l));if(o&&!Y.test(t[c.length]??" "))c=c.replace(Nt,"")||c;if(o)c=c.trimEnd();return s?(c+n).slice(0,l):c+n}var Nt,Y,be;var init_chunk_rkhsft4a=__esm(()=>{Nt=/\s+\S*$/,Y=/\s/;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))});var init_text=__esm(()=>{init_chunk_rkhsft4a()});import process2 from"process";function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process2.stdout,env=process2.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}function isHumanTerminal(stream=process2.stdout,env=process2.env){return outputMode(stream,env)==="terminal"}function isInteractive(streams=process2,env=process2.env){return streams.stdin?.isTTY===!0&&isHumanTerminal(streams.stderr??{},env)}var MODES,AGENT_VARIABLES;var init_mode=__esm(()=>{MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"]});function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var G2,B,h,o;var init_chunk_x450vn3m=__esm(()=>{G2=/^[a-f0-9]+$/i;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")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);o=Fe()});var init_colors=__esm(()=>{init_chunk_x450vn3m()});import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process3 from"process";function findUp(names,from=process3.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}var init_config=__esm(()=>{init_args()});import{existsSync as existsSync2,mkdirSync,readFileSync,statSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname as dirname2,isAbsolute,join as join2}from"path";import process4 from"process";function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process4.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function mainConfigPath(where={}){let jsonc=join2(configBase(where),"kaynooo-cli","config.jsonc");return existsSync2(jsonc)?jsonc:userConfigPath("config",where)}function readCachedObject(path){let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0||!stat.isFile())return FILE_CACHE.delete(path),{};let cached=FILE_CACHE.get(path);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs&&cached.size===stat.size)return cached.data;try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8")),data=isRecord(parsed)?parsed:{};return FILE_CACHE.set(path,{mtimeMs:stat.mtimeMs,size:stat.size,data}),data}catch{return{}}}function readMainConfig(where={}){return readCachedObject(mainConfigPath(where))}var FILE_CACHE;var init_user_config=__esm(()=>{FILE_CACHE=new Map});import{existsSync as existsSync3,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process5 from"process";function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process5.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync2(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=Bun.JSONC.parse(readFileSync2(path,"utf8"));if(isRecord2(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord2(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord2(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord2(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}function warnOnce(message){if(warned.has(message))return;warned.add(message),console.error(`warning: theme ${message}`)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process5.env,from=process5.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];if(chosen===""){let mainTheme=readMainConfig({home,xdg:env.XDG_CONFIG_HOME}).theme;if(isRecord2(mainTheme))files.push({path:`${mainConfigPath({home,xdg:env.XDG_CONFIG_HOME})}#theme`,file:mainTheme})}for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}function activeTheme(){let key=`${process5.cwd()}\x00${process5.env.KIT_THEME??""}\x00${process5.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var DEFAULT,BRIGHT,LIGHT,MONO,ASCII,PRESETS,STYLES,HEX,CONTROL,MAX_FILE_BYTES=65536,SPACES,CUBE,warned,current,currentKey="";var init_theme=__esm(()=>{init_config();init_user_config();DEFAULT={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"},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"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},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"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},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"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",rule:"-",corner:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},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"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,SPACES=/\s+/;CUBE=[0,95,135,175,215,255];warned=new Set});import process6 from"process";function takesControlCodes(stream,env=process6.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process6.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function marked(mark,text,stream,detail,env=process6.env){let colors=paint(stream,env),head=MARK_WORDS[mark];if(takesControlCodes(stream,env)){let{theme}=activeTheme();head=tinted(colors.bold,theme.colors[mark],env)(theme.glyphs[mark])}return`${head} ${text}${detail===void 0?"":` ${colors.dim(detail)}`}`}function problem(text,detail){console.error(marked("problem",text,process6.stderr,detail))}var MARK_WORDS,STATUS_WORDS,STATUS_OF;var init_style=__esm(()=>{init_colors();init_mode();init_theme();MARK_WORDS={ok:"ok:",warn:"warning:",problem:"error:",note:"note:",plan:"would:"};STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])))});function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}function cutToWidth(line,width,suffix=""){if(Bun.stringWidth(line)<=width)return line;let suffixWidth=suffix===""?0:Bun.stringWidth(suffix),room=Math.max(0,width-suffixWidth),kept="",index=0,styled=!1,linked=!1;while(index<line.length){ESCAPE_CODE.lastIndex=index;let escape=ESCAPE_CODE.exec(line);if(escape!==null){if(kept+=escape[0],escape[0].startsWith(`${ESC}]`))linked=!0;else styled=!0;index=ESCAPE_CODE.lastIndex;continue}let char=String.fromCodePoint(line.codePointAt(index)),columns=Bun.stringWidth(char);if(columns>room)break;kept+=char,room-=columns,index+=char.length}return`${kept}${styled?RESET_STYLE:""}${linked?CLOSE_LINK:""}${suffix}`}var ESC,ESCAPE_CODE,RESET_STYLE,CLOSE_LINK;var init_text2=__esm(()=>{ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`});function tt(i,{units:r="iec",dp:t=1,locale:n}={}){let e=r==="si"?1000:1024;if(Math.abs(i)<e)return`${i} B`;let s=r==="iec"?["KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"]:["kB","MB","GB","TB","PB","EB","ZB","YB"],o=-1,a=10**t;do i/=e,++o;while(Math.round(Math.abs(i)*a)/a>=e&&o<s.length-1);return`${n?y(n,{minimumFractionDigits:t,maximumFractionDigits:t}).format(i):i.toFixed(t)} ${s[o]}`}var init_chunk_knqbxp56=__esm(()=>{init_chunk_n6z2kk96()});var init_format=__esm(()=>{init_chunk_knqbxp56()});import process7 from"process";function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function truncate(text,width){return Ao(text,width,{suffix:"\u2026",includeSuffix:!0})}function textWidth(text){return Bun.stringWidth(text)}function table(rows,{cellWidth,header=!1,align=[],fit,stream=process7.stdout,env=process7.env}={}){let cells=cellWidth===void 0?rows:rows.map((row)=>row.map((cell)=>truncate(cell.replaceAll(LINE_BREAKS," "),cellWidth)));if(outputMode(stream,env)==="agent")return cells.map((row)=>row.map((cell)=>Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g," ")).join("\t")).join(`
|
|
4
|
+
`);let widths=[];for(let row of cells)for(let[index,cell]of row.entries())widths[index]=Math.max(widths[index]??0,textWidth(cell));let shown=fit===void 0?cells:narrow(cells,widths,fit),colors=paint(stream,env),lines=shown.map((row)=>row.map((cell,index)=>{let width=widths[index]??0,gap=" ".repeat(Math.max(0,width-textWidth(cell)));if(align[index]==="right")return`${gap}${cell}`;return index===row.length-1?cell:`${cell}${gap}`}).join(" ").trimEnd()),rule=header&&takesControlCodes(stream,env)&&lines.length>1?[colors.dim(activeTheme().theme.glyphs.rule.repeat(Math.max(...lines.map(textWidth))))]:[];return lines.flatMap((line,index)=>header&&index===0?[colors.bold(line),...rule]:[line]).join(`
|
|
5
|
+
`)}function narrow(rows,widths,limit){let used=()=>widths.reduce((sum,width)=>sum+width,0)+2*Math.max(0,widths.length-1),floor=8;while(used()>limit){let widest=-1;for(let[index,width]of widths.entries())if(width>8&&width>(widths[widest]??0))widest=index;if(widest===-1)break;widths[widest]=Math.max(8,(widths[widest]??0)-(used()-limit))}return rows.map((row)=>row.map((cell,index)=>textWidth(cell)>(widths[index]??0)?cutToWidth(cell,widths[index]??0,"\u2026"):cell))}function jsonText(value,replacer,{stream=process7.stdout,env=process7.env}={}){return JSON.stringify(value,replacer,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}var UNITS,LINE_BREAKS;var init_format2=__esm(()=>{init_text();init_mode();init_style();init_text2();init_theme();init_format();UNITS=[["d",86400],["h",3600],["m",60],["s",1]];LINE_BREAKS=/\s*\n\s*/g});import process8 from"process";function usageLine(usage,colors=paint(process8.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
6
|
+
`),blank=lines.indexOf(""),synopses=blank===-1?lines:lines.slice(0,blank),details=blank===-1?[]:lines.slice(blank+1),colon=synopses[0].indexOf(": "),inline=synopses[0].slice(colon+2),summary=colon===-1?details.shift():`${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;if(colon!==-1)synopses[0]=synopses[0].slice(0,colon);let head=`${colors.bold("Usage:")} ${synopses.map((line)=>line.replaceAll(OPTIONAL,(part)=>colors.dim(part))).join(`
|
|
7
|
+
`)}`,lead=summary===void 0||!withSummary?[]:["",colors.bold(prose(summary,colors))],rest=details.length===0?[]:["",...details.map((line)=>prose(line,colors))];return[head,...lead,...rest].join(`
|
|
8
|
+
`)}function prose(line,colors){if(colors.cyan("x")==="x")return line;return line.replaceAll(PROSE_MARKS,(match,code,flag)=>code===void 0?colors.cyan(flag??match):colors.bold(code))}function helpText(usage,options,colors=paint(process8.stdout),{examples=[],exits=[],bin,columns}={}){let{summary}=description(usage);return[...bin===void 0?[usageLine(usage,colors)]:[`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary===""?"":` ${summary}`}`,"",usageLine(usage,colors,{summary:!1})],"",colors.bold("Options:"),...optionRows(options,colors,columns),...exitRows(exits,colors),...exampleRows(examples,colors)].join(`
|
|
9
|
+
`)}function exitRows(exits,colors=paint(process8.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process8.env,argv){if(env.KIT_HELP==="json")return!0;if(argv===void 0)return!1;let end=argv.indexOf("--"),own=end===-1?argv:argv.slice(0,end);if(own.includes("--help=json"))return!0;return(own.includes("--help")||own.includes("-h")||own[0]==="help")&&own.includes("--json")}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
10
|
+
`),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}function exampleRows(examples,colors=paint(process8.stdout)){if(examples.length===0)return[];let shown=outputMode()==="agent"?examples.slice(0,MAX_AGENT_EXAMPLES):examples;return["",colors.bold("Examples:"),...shown.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}function wrapText(text,limit){if(text.length<=limit)return[text];let lines=[],current="";for(let word of text.split(" "))if(current==="")current=word;else if(current.length+1+word.length<=limit)current=`${current} ${word}`;else lines.push(current),current=word;if(current!=="")lines.push(current);return lines}function optionRows(options,colors=paint(process8.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapText(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}var OPTIONAL,USAGE_PREFIX,FULL_STOP,PROSE_MARKS,MAX_AGENT_EXAMPLES=2,MAX_INLINE_CHOICES=24;var init_help=__esm(()=>{init_mode();init_style();OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi});function wholeNumber(value,name,fallback,min=1){if(value===void 0)return fallback;let number=Number(value);if(!WHOLE.test(value)||!Number.isSafeInteger(number)||number<min)badUsage(`${name.startsWith("<")?name:`--${name}`} takes a whole number from ${min}, not ${value}`);return number}function durationMs(text,unit){if(BARE_DURATION.test(text))return Number(text)*UNIT_MS[unit];if(!DURATION.test(text))return 0;let ms=0;for(let[,amount,part]of text.matchAll(DURATION_PART))ms+=Number(amount)*UNIT_MS[part];return ms}function duration(value,name,fallback,unit="s"){if(value===void 0)return fallback;let ms=durationMs(value.trim(),unit);if(ms<1)badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);return ms}var WHOLE,BARE_DURATION,DURATION,DURATION_PART,UNIT_MS;var init_input=__esm(()=>{init_args();WHOLE=/^\d+$/;BARE_DURATION=/^\d+(?:\.\d+)?$/,DURATION=/^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/,DURATION_PART=/(\d+(?:\.\d+)?)(ms|min|[smhd])/g,UNIT_MS={ms:1,s:1000,m:60000,min:60000,h:3600000,d:86400000}});import process9 from"process";import{parseArgs}from"util";function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}function badUsage(message){throw new UsageError(message)}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}function applyOutput(color,plain,env=process9.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),helpJson=wantsHelpJson(process9.env,own),stripHelpJson=(arg)=>{if(arg==="--help=json")return["--help"];return arg==="--json"&&!("json"in options)?[]:[arg]},normalized=helpJson?own.flatMap(stripHelpJson):own,parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(normalized,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process9.stdout)?process9.stdout.columns:void 0;throw console.log(helpJson?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}var DASHES,EXIT,Exit,UsageError,HelpShown,completion,heading,OUTPUT_OPTIONS,UNKNOWN_OPTION;var init_args=__esm(()=>{init_format2();init_help();init_style();init_text2();init_help();init_input();DASHES=/^-+/;EXIT=Symbol.for("@kaynooo/cli-kit/Exit");Exit=class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}};UsageError=class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}};HelpShown=class HelpShown extends Exit{constructor(){super("help shown",0)}};completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};UNKNOWN_OPTION=/^unknown option '(-[^']+)'/});var init_folders=__esm(()=>{init_user_config()});var init_answers=__esm(()=>{init_folders()});import process18 from"process";function stopJob(){process18.kill(0,"SIGTSTP")}var init_job=()=>{};function isEditKey(key){return EDIT_KEYS.has(key)}var EDIT_KEYS;var init_line=__esm(()=>{EDIT_KEYS=new Set(["left","right","wordleft","wordright","linestart","lineend","erase","delete","word","killword","killnext","clear","killend","yank"])});var NONE;var init_score=__esm(()=>{NONE=Number.NEGATIVE_INFINITY});function repeat(value,count){return Array.from({length:count}).fill(value)}function parseKeys(input,paste={active:!1},ctrls=[]){let codes=new Map(ctrls.map((name)=>[String.fromCharCode(name.codePointAt(name.length-1)-96),name]));return(input.match(KEY_SEQUENCES)??[]).flatMap((sequence)=>{let wheel=MOUSE.exec(sequence)?.[1];if(wheel!==void 0)return repeat(wheel==="64"?"up":"down",wheel==="64"||wheel==="65"?WHEEL_LINES:0);let named=codes.get(sequence),key=named===void 0?KEYS[sequence]:{ctrl:named};if(sequence===PASTE_START||sequence===PASTE_END)return paste.active=sequence===PASTE_START,[];if(paste.active&&(sequence==="\r"||sequence===`
|
|
11
|
+
`))return[];if(key!==void 0)return[key];return IS_CONTROL.test(sequence)||sequence.startsWith("\x1B")?[]:[{text:sequence}]})}var IS_CONTROL,PASTE_START="\x1B[200~",PASTE_END="\x1B[201~",KEY_SEQUENCES,MOUSE,WHEEL_LINES=3,KEYS;var init_state=__esm(()=>{init_text2();init_line();init_score();IS_CONTROL=/[\x00-\x1F\x7F-\x9F]/,KEY_SEQUENCES=/\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu,MOUSE=/^\x1B\[<(\d+);\d+;\d+[a-z]$/i,KEYS={"\x1B[A":"up","\x1BOA":"up","\x10":"up","\x1B[B":"down","\x1BOB":"down","\x0E":"down","\x1B[5~":"pageup","\x1B[6~":"pagedown","\x1B[H":"home","\x1B[1~":"home","\x1BOH":"home","\x1B[F":"end","\x1B[4~":"end","\x1BOF":"end","\r":"enter","\n":"enter","\x03":"cancel","\x1B":"cancel","\x1B[D":"left","\x1BOD":"left","\x1B[C":"right","\x1BOC":"right","\x1B[1;5D":"wordleft","\x1B[1;3D":"wordleft","\x1Bb":"wordleft","\x1B[1;5C":"wordright","\x1B[1;3C":"wordright","\x1Bf":"wordright","\x01":"linestart","\x05":"lineend","\x7F":"erase","\x1B[3~":"delete","\b":"killword","\x1B\x7F":"killword","\x1B[3;5~":"killnext","\x1Bd":"killnext","\x15":"clear","\v":"killend","\x17":"word","\x19":"yank","\x1A":"suspend","\t":"tab","\x1F":"help","\x1BOP":"help","\x1B[11~":"help"}});function overwrite(lines,columns){return lines.map((line)=>textWidth(line)%columns===0?`\x1B[2K${line}`:`${line}\x1B[K`).join(`
|
|
12
|
+
`)}function rowsTaken(lines,columns){return lines.reduce((rows,line)=>rows+Math.max(1,Math.ceil(textWidth(line)/columns)),0)}var SYNC_START="\x1B[?2026h",SYNC_END="\x1B[?2026l";var init_redraw=__esm(()=>{init_format2()});import process19 from"process";function readKeys(input,paste={active:!1}){return parseKeys(input,paste).filter((key)=>typeof key==="object"?"text"in key:PROMPT_KEYS.has(key)||isEditKey(key))}async function confirm(question,{default:fallback,...settings}){let answered=fallback,choices={true:"Y/n",false:"y/N",undefined:"y/n"}[String(fallback)];return await ask(question,settings,(colors,state)=>[state==="asking"?asking(colors,question,"",choices):answer(colors,question,state,answered?"yes":"no")],(key)=>{if(key==="cancel")return"cancel";if(key==="enter")return answered===void 0?void 0:"enter";let letter=typeof key==="object"?key.text.toLowerCase():"";if(letter!=="y"&&letter!=="n")return;return answered=letter==="y","enter"})?answered:void 0}function asking(colors,question,typed,keys){return`${colors.cyan("?")} ${question} ${typed===""?colors.dim(`(${keys})`):typed}`}function answer(colors,question,state,picked){return state==="enter"?`${colors.green("\u2713")} ${question} ${colors.cyan(picked)}`:`${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`}async function ask(question,{hint,terminal=process19},render,press){let{stdin,stderr}=terminal;if(!isInteractive(terminal))fail(`cannot ask "${question}" off a terminal`,2,hint);let colors=paint(stderr),current="asking",outcome,columns=()=>stderr.columns||80,draw=(state,last=!1)=>{let frame=render(colors,state,{columns:columns(),rows:stderr.rows||24}),rows=rowsTaken(frame,columns());stderr.write(`${SYNC_START}\r${overwrite(frame,columns())}\x1B[0J${last||rows<2?"":`\x1B[${rows-1}A`}${last?"":"\r"}${SYNC_END}`),current=state},redraw=()=>draw(current),paste={active:!1},stop=terminal.stop??(terminal===process19?stopJob:void 0),suspend=()=>{if(stop===void 0)return;stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l"),stdin.setRawMode(!1),stop(),stdin.setRawMode(!0),stderr.write("\x1B[?25l\x1B[?2004h")};try{return stderr.on?.("resize",redraw),stdin.setRawMode(!0),stdin.resume(),stderr.write("\x1B[?25l\x1B[?2004h"),draw("asking"),await new Promise((resolve)=>{function onData(data){for(let key of readKeys(data.toString(),paste)){if(key==="suspend"){suspend();continue}let pressed=press(key);if(pressed!==void 0){settle(pressed);return}}draw("asking")}function onEnd(){settle("cancel")}function settle(settled){outcome=settled,stdin.off("data",onData),stdin.off("end",onEnd),resolve(settled==="enter")}stdin.on("data",onData),stdin.on("end",onEnd)})}finally{stderr.off?.("resize",redraw),draw(outcome??"cancel",!0),stderr.write(`
|
|
13
|
+
\x1B[?25h\x1B[?2004l`),stdin.setRawMode(!1),stdin.pause()}}var PROMPT_KEYS;var init_prompt=__esm(()=>{init_answers();init_args();init_format2();init_job();init_mode();init_line();init_score();init_state();init_redraw();init_style();PROMPT_KEYS=new Set(["up","down","pageup","pagedown","home","end","enter","cancel","suspend","tab"])});import process24 from"process";init_args();import{readFileSync as readFileSync3,realpathSync}from"fs";import{resolve as resolve3}from"path";import process10 from"process";function commandLine(){try{return readFileSync3("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve3(word))}catch{return}}function scriptArgs(argv=process10.argv.slice(2),cmdline=commandLine(),script=process10.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve3(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}init_format2();init_mode();init_style();init_theme();init_args();init_format2();init_format2();import{constants}from"os";import process11 from"process";var KILL_GRACE_MS=2000;function exitCodeOf(code,signal){if(code!==null)return code;if(typeof signal==="number")return 128+signal;return signal===null?129:128+constants.signals[signal]}async function runCommand(argv,{cwd,env,stdin="ignore",input,timeoutMs,signal,maxBytes=1/0,onChunk,onStart}={}){let chunks=[],grouped=timeoutMs!==void 0||signal!==void 0||onStart!==void 0||onChunk!==void 0,proc=Bun.spawn(argv,{...cwd===void 0?{}:{cwd},...env===void 0?{}:{env},stdin:input===void 0?stdin:new TextEncoder().encode(input),stdout:"pipe",stderr:"pipe",...grouped?{detached:!0}:{}}),state={kept:0,truncated:!1,timedOut:!1,failure:void 0,done:!1},timers=[],killGroup=(killing)=>{if(state.done)return;try{if(grouped)process11.kill(-proc.pid,killing);else proc.kill(killing)}catch{}},stop=()=>{killGroup("SIGTERM"),timers.push(setTimeout(killGroup,KILL_GRACE_MS,"SIGKILL"))},onAbort=()=>stop();if(timeoutMs!==void 0)timers.push(setTimeout(()=>{state.timedOut=!0,stop()},timeoutMs));if(signal?.aborted===!0)onAbort();else signal?.addEventListener("abort",onAbort,{once:!0});onStart?.({kill:(killing)=>killGroup(killing)});let drain=async(stream,name)=>{for await(let data of stream){if(state.failure!==void 0)continue;try{onChunk?.({stream:name,data})}catch(error){state.failure=error,stop();continue}if(state.truncated)continue;let kept=data;if(state.kept+data.length>maxBytes){let cut=maxBytes-state.kept;while(cut>0&&((data[cut]??0)&192)===128)cut--;kept=data.subarray(0,cut),state.truncated=!0}if(state.kept+=kept.length,kept.length>0)chunks.push({stream:name,data:kept})}};try{await Promise.all([drain(proc.stdout,"stdout"),drain(proc.stderr,"stderr")]),await proc.exited}finally{state.done=!0;for(let timer of timers)clearTimeout(timer);signal?.removeEventListener("abort",onAbort)}if(state.failure!==void 0)throw state.failure;let joined=()=>Buffer.concat(chunks.map(({data})=>data)),output,text,stdout;return{code:exitCodeOf(proc.exitCode,proc.signalCode),chunks,timedOut:state.timedOut,truncated:state.truncated,get output(){return output??=joined()},get text(){return text??=(output??=joined()).toString()},get stdout(){return stdout??=Buffer.concat(chunks.filter((chunk)=>chunk.stream==="stdout").map((chunk)=>chunk.data)).toString()}}}init_style();init_text2();init_theme();init_style();init_format2();init_args();import{readFileSync as readFileSync5,realpathSync as realpathSync2}from"fs";import{dirname as dirname4,join as join5}from"path";import process15 from"process";import process12 from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process12.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process12.env.SSH_ASKPASS_PROMPT==="none"?{notice:!0}:{}},{promise,resolve}=Promise.withResolvers(),received="";try{await Bun.connect({unix:socketPath,socket:{open:(socket)=>void socket.write(`${JSON.stringify(request)}
|
|
14
|
+
`),data:(_,chunk)=>{received+=chunk.toString()},close:()=>resolve(received),error:()=>resolve("")}})}catch{return 1}let reply=await promise;if(reply==="")return 1;let{answer}=JSON.parse(reply);if(request.notice===!0)return 0;if(answer===void 0)return 1;return process12.stdout.write(`${answer}
|
|
15
|
+
`),0}init_args();var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
|
|
16
|
+
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'
|
|
1332
17
|
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
1333
18
|
set -l current (commandline -ct)
|
|
1334
19
|
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
@@ -1338,8 +23,10 @@ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_
|
|
|
1338
23
|
echo $line
|
|
1339
24
|
end
|
|
1340
25
|
end
|
|
1341
|
-
end
|
|
1342
|
-
|
|
26
|
+
end
|
|
27
|
+
${bins.map((bin)=>`complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
28
|
+
`).join("")}`;if(shell==="bash")return`${header}
|
|
29
|
+
__kaynooo_cli_complete() {
|
|
1343
30
|
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
1344
31
|
local -a lines
|
|
1345
32
|
COMPREPLY=()
|
|
@@ -1352,8 +39,10 @@ var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
|
1352
39
|
fi
|
|
1353
40
|
done
|
|
1354
41
|
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1355
|
-
}
|
|
1356
|
-
|
|
42
|
+
}
|
|
43
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
44
|
+
`;return`${header}
|
|
45
|
+
__kaynooo_cli_complete() {
|
|
1357
46
|
local line
|
|
1358
47
|
local -a described plain
|
|
1359
48
|
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
@@ -1368,1419 +57,34 @@ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
|
1368
57
|
(( \${#described} )) && _describe -V value described
|
|
1369
58
|
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
1370
59
|
return 0
|
|
1371
|
-
}`;
|
|
1372
|
-
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1373
|
-
if (shell === "fish")
|
|
1374
|
-
return `${header}
|
|
1375
|
-
${FISH_FUNCTION}
|
|
1376
|
-
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1377
|
-
`).join("")}`;
|
|
1378
|
-
if (shell === "bash")
|
|
1379
|
-
return `${header}
|
|
1380
|
-
${BASH_FUNCTION}
|
|
1381
|
-
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1382
|
-
`;
|
|
1383
|
-
return `${header}
|
|
1384
|
-
${ZSH_FUNCTION}
|
|
1385
|
-
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
1386
|
-
`;
|
|
1387
|
-
}
|
|
1388
|
-
|
|
1389
|
-
// ../kit/src/notify.ts
|
|
1390
|
-
init_format2();
|
|
1391
|
-
init_mode();
|
|
1392
|
-
import process13 from "process";
|
|
1393
|
-
var NOTIFY_AFTER_MS = 1e4;
|
|
1394
|
-
var CANCELLED = 130;
|
|
1395
|
-
function base64(text) {
|
|
1396
|
-
return Buffer.from(text).toString("base64");
|
|
1397
|
-
}
|
|
1398
|
-
function notification(title, body, env = process13.env) {
|
|
1399
|
-
const id = `kit${process13.pid}`;
|
|
1400
|
-
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\\`];
|
|
1401
|
-
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1402
|
-
}
|
|
1403
|
-
function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
|
|
1404
|
-
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1405
|
-
return;
|
|
1406
|
-
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1407
|
-
}
|
|
1408
|
-
|
|
1409
|
-
// ../kit/src/cli.ts
|
|
1410
|
-
init_style();
|
|
1411
|
-
init_text2();
|
|
1412
|
-
|
|
1413
|
-
// ../kit/src/usage.ts
|
|
1414
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
1415
|
-
import { homedir as homedir3 } from "os";
|
|
1416
|
-
import { dirname as dirname2, join as join4 } from "path";
|
|
1417
|
-
import process14 from "process";
|
|
1418
|
-
|
|
1419
|
-
// ../kit/src/logs.ts
|
|
1420
|
-
init_user_config();
|
|
1421
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1422
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
1423
|
-
|
|
1424
|
-
// ../kit/src/usage.ts
|
|
1425
|
-
init_user_config();
|
|
1426
|
-
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1427
|
-
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1428
|
-
var LONGEST_NAME = 40;
|
|
1429
|
-
var usageError;
|
|
1430
|
-
function noteUsageError(message) {
|
|
1431
|
-
usageError = message;
|
|
1432
|
-
}
|
|
1433
|
-
function stateHome(env = process14.env) {
|
|
1434
|
-
return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
|
|
1435
|
-
}
|
|
1436
|
-
function usagePath(env = process14.env) {
|
|
1437
|
-
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1438
|
-
}
|
|
1439
|
-
function usageRecorded(env = process14.env) {
|
|
1440
|
-
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1441
|
-
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1442
|
-
}
|
|
1443
|
-
function flagNames(argv) {
|
|
1444
|
-
const end = argv.indexOf("--");
|
|
1445
|
-
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1446
|
-
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1447
|
-
}
|
|
1448
|
-
function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
1449
|
-
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1450
|
-
usageError = undefined;
|
|
1451
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
1452
|
-
}
|
|
1453
|
-
function recordUsage(entry, env = process14.env) {
|
|
1454
|
-
if (!usageRecorded(env))
|
|
1455
|
-
return;
|
|
1456
|
-
try {
|
|
1457
|
-
const path = usagePath(env);
|
|
1458
|
-
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1459
|
-
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1460
|
-
`, { mode: 384 });
|
|
1461
|
-
} catch {}
|
|
1462
|
-
}
|
|
1463
|
-
|
|
1464
|
-
// ../kit/src/cli.ts
|
|
1465
|
-
var LEVEL_OPTIONS = {
|
|
1466
|
-
...OUTPUT_OPTIONS,
|
|
1467
|
-
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1468
|
-
};
|
|
1469
|
-
var TOP_OPTIONS = {
|
|
1470
|
-
...LEVEL_OPTIONS,
|
|
1471
|
-
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1472
|
-
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1473
|
-
};
|
|
1474
|
-
async function commandRows(all, colors) {
|
|
1475
|
-
const commands = shown(all);
|
|
1476
|
-
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
1477
|
-
const groups = new Map([["Commands:", []]]);
|
|
1478
|
-
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
1479
|
-
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
1480
|
-
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
1481
|
-
const rows = groups.get(heading) ?? [];
|
|
1482
|
-
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
1483
|
-
groups.set(heading, rows);
|
|
1484
|
-
}
|
|
1485
|
-
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
1486
|
-
}
|
|
1487
|
-
function shown(commands) {
|
|
1488
|
-
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
1489
|
-
}
|
|
1490
|
-
function takeOutputFlags(argv) {
|
|
1491
|
-
let index = 0;
|
|
1492
|
-
for (;index < argv.length; index++) {
|
|
1493
|
-
const word = argv[index];
|
|
1494
|
-
if (word === "--plain")
|
|
1495
|
-
applyOutput(undefined, true);
|
|
1496
|
-
else if (word.startsWith("--color="))
|
|
1497
|
-
applyOutput(word.slice("--color=".length), undefined);
|
|
1498
|
-
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
1499
|
-
applyOutput(argv[++index], undefined);
|
|
1500
|
-
else
|
|
1501
|
-
break;
|
|
1502
|
-
}
|
|
1503
|
-
return argv.slice(index);
|
|
1504
|
-
}
|
|
1505
|
-
async function resolveSummary(summary) {
|
|
1506
|
-
return typeof summary === "string" ? summary : summary();
|
|
1507
|
-
}
|
|
1508
|
-
function lookup({ commands, aliases }, word) {
|
|
1509
|
-
const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
|
|
1510
|
-
return Object.hasOwn(commands, name) ? commands[name] : undefined;
|
|
1511
|
-
}
|
|
1512
|
-
function scopeOf(commands, extra, aliases) {
|
|
1513
|
-
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
1514
|
-
}
|
|
1515
|
-
async function expand(scope, words) {
|
|
1516
|
-
if (scope.lazy.length === 0)
|
|
1517
|
-
return scope;
|
|
1518
|
-
const commands = { ...scope.commands };
|
|
1519
|
-
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
1520
|
-
for (const [name, command] of Object.entries(added))
|
|
1521
|
-
commands[name] ??= command;
|
|
1522
|
-
}
|
|
1523
|
-
return { ...scope, commands, lazy: [] };
|
|
1524
|
-
}
|
|
1525
|
-
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
1526
|
-
const colors = paint(stream);
|
|
1527
|
-
const prefix = path.join(" ");
|
|
1528
|
-
const summary = await resolveSummary(lazySummary);
|
|
1529
|
-
if (wantsHelpJson())
|
|
1530
|
-
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
1531
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1532
|
-
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
1533
|
-
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
1534
|
-
return [
|
|
1535
|
-
header(colors, summary),
|
|
1536
|
-
"",
|
|
1537
|
-
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
1538
|
-
"",
|
|
1539
|
-
...await commandRows(commands, colors),
|
|
1540
|
-
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
1541
|
-
"",
|
|
1542
|
-
colors.bold("Options:"),
|
|
1543
|
-
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
1544
|
-
...exampleRows(examples ?? [], colors),
|
|
1545
|
-
"",
|
|
1546
|
-
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
1547
|
-
].join(`
|
|
1548
|
-
`);
|
|
1549
|
-
}
|
|
1550
|
-
function printError(prefix, message, hint, cause) {
|
|
1551
|
-
const colors = paint(process15.stderr);
|
|
1552
|
-
const styled = takesControlCodes(process15.stderr);
|
|
1553
|
-
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1554
|
-
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1555
|
-
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1556
|
-
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1557
|
-
}
|
|
1558
|
-
function printJsonError(message, hint, cause) {
|
|
1559
|
-
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1560
|
-
}
|
|
1561
|
-
function wantsJson(argv) {
|
|
1562
|
-
const end = argv.indexOf("--");
|
|
1563
|
-
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1564
|
-
}
|
|
1565
|
-
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1566
|
-
if (error instanceof HelpShown)
|
|
1567
|
-
return 0;
|
|
1568
|
-
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1569
|
-
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1570
|
-
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1571
|
-
if (error instanceof Exit && error.code === 2)
|
|
1572
|
-
noteUsageError(error.message);
|
|
1573
|
-
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1574
|
-
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1575
|
-
return error instanceof Exit ? error.code : 1;
|
|
1576
|
-
}
|
|
1577
|
-
async function dispatch(level, typed, { version, redact }) {
|
|
1578
|
-
const prefix = level.path.join(" ");
|
|
1579
|
-
let argv;
|
|
1580
|
-
try {
|
|
1581
|
-
argv = takeOutputFlags(typed);
|
|
1582
|
-
} catch (error) {
|
|
1583
|
-
return reportThrown(prefix, error);
|
|
1584
|
-
}
|
|
1585
|
-
const [name, ...args] = argv;
|
|
1586
|
-
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
1587
|
-
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
1588
|
-
try {
|
|
1589
|
-
return await fallback.run([]);
|
|
1590
|
-
} catch (error) {
|
|
1591
|
-
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
1592
|
-
}
|
|
1593
|
-
}
|
|
1594
|
-
if (name === undefined && level.path.length > 1) {
|
|
1595
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
|
|
1596
|
-
return 2;
|
|
1597
|
-
}
|
|
1598
|
-
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1599
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
|
|
1600
|
-
return 0;
|
|
1601
|
-
}
|
|
1602
|
-
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1603
|
-
console.log(version);
|
|
1604
|
-
return 0;
|
|
1605
|
-
}
|
|
1606
|
-
let command = lookup(level, name);
|
|
1607
|
-
let rest = args;
|
|
1608
|
-
let ran = name;
|
|
1609
|
-
if (command === undefined && level.lazy.length > 0) {
|
|
1610
|
-
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1611
|
-
command = lookup(level, name);
|
|
1612
|
-
}
|
|
1613
|
-
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1614
|
-
command = level.commands[level.defaultCommand];
|
|
1615
|
-
rest = argv;
|
|
1616
|
-
ran = level.defaultCommand;
|
|
1617
|
-
}
|
|
1618
|
-
if (command === undefined) {
|
|
1619
|
-
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
1620
|
-
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
1621
|
-
return 2;
|
|
1622
|
-
}
|
|
1623
|
-
if ("commands" in command) {
|
|
1624
|
-
const { summary } = command;
|
|
1625
|
-
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
1626
|
-
}
|
|
1627
|
-
try {
|
|
1628
|
-
return await command.run(rest);
|
|
1629
|
-
} catch (error) {
|
|
1630
|
-
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
1631
|
-
}
|
|
1632
|
-
}
|
|
1633
|
-
var COMPLETE = "__complete";
|
|
1634
|
-
var FILES = "__files__";
|
|
1635
|
-
async function completingOf(run) {
|
|
1636
|
-
completion.active = true;
|
|
1637
|
-
try {
|
|
1638
|
-
await run([]);
|
|
1639
|
-
} catch (error) {
|
|
1640
|
-
if (error instanceof Completing)
|
|
1641
|
-
return error;
|
|
1642
|
-
} finally {
|
|
1643
|
-
completion.active = false;
|
|
1644
|
-
}
|
|
1645
|
-
return new Completing({});
|
|
1646
|
-
}
|
|
1647
|
-
async function optionsOf(run) {
|
|
1648
|
-
return (await completingOf(run)).options;
|
|
1649
60
|
}
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
}
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
else if (takesValue(word))
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1673
|
-
}
|
|
1674
|
-
async function leafCandidates(run, words) {
|
|
1675
|
-
const completing = await completingOf(run);
|
|
1676
|
-
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1677
|
-
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1678
|
-
const flag = words.at(-2);
|
|
1679
|
-
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1680
|
-
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1681
|
-
if (option?.type === "string") {
|
|
1682
|
-
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1683
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1684
|
-
}
|
|
1685
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1686
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1687
|
-
}
|
|
1688
|
-
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1689
|
-
const [word = "", ...rest] = words;
|
|
1690
|
-
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1691
|
-
let { commands } = scope;
|
|
1692
|
-
let command = lookup(scope, word);
|
|
1693
|
-
if (listing || command === undefined) {
|
|
1694
|
-
const expanded = await expand(scope, [...before, ...words]);
|
|
1695
|
-
commands = expanded.commands;
|
|
1696
|
-
command = lookup(expanded, word);
|
|
1697
|
-
}
|
|
1698
|
-
if (listing) {
|
|
1699
|
-
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1700
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1701
|
-
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1702
|
-
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1703
|
-
return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
|
|
1704
|
-
}
|
|
1705
|
-
if (command === undefined) {
|
|
1706
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1707
|
-
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1708
|
-
}
|
|
1709
|
-
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1710
|
-
}
|
|
1711
|
-
var COMPLETIONS = "--completions";
|
|
1712
|
-
function flagValue([flag = "", ...rest]) {
|
|
1713
|
-
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1714
|
-
}
|
|
1715
|
-
function printCompletionScript(name, args) {
|
|
1716
|
-
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1717
|
-
if (shell === undefined || args.length !== 1) {
|
|
1718
|
-
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1719
|
-
return 2;
|
|
1720
|
-
}
|
|
1721
|
-
console.log(completionScript(shell, [name]).trimEnd());
|
|
1722
|
-
return 0;
|
|
1723
|
-
}
|
|
1724
|
-
async function printCandidates(found) {
|
|
1725
|
-
for (const line of await found)
|
|
1726
|
-
console.log(line);
|
|
1727
|
-
return 0;
|
|
1728
|
-
}
|
|
1729
|
-
function packageVersion(entry = Bun.main) {
|
|
1730
|
-
let resolved = entry;
|
|
1731
|
-
try {
|
|
1732
|
-
resolved = realpathSync2(entry);
|
|
1733
|
-
} catch {}
|
|
1734
|
-
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1735
|
-
try {
|
|
1736
|
-
const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
|
|
1737
|
-
if (typeof version === "string")
|
|
1738
|
-
return version;
|
|
1739
|
-
} catch {}
|
|
1740
|
-
if (dirname3(dir) === dir)
|
|
1741
|
-
return "0.0.0";
|
|
1742
|
-
}
|
|
1743
|
-
}
|
|
1744
|
-
async function runCli(cli, argv = scriptArgs()) {
|
|
1745
|
-
const version = cli.version ?? packageVersion();
|
|
1746
|
-
const answered = await askpassClient(argv);
|
|
1747
|
-
if (answered !== undefined)
|
|
1748
|
-
return answered;
|
|
1749
|
-
if (argv[0] === COMPLETE)
|
|
1750
|
-
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1751
|
-
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1752
|
-
return printCompletionScript(cli.name, flagValue(argv));
|
|
1753
|
-
const started = performance.now();
|
|
1754
|
-
const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
|
|
1755
|
-
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1756
|
-
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1757
|
-
if (cli.usage !== false) {
|
|
1758
|
-
try {
|
|
1759
|
-
recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
|
|
1760
|
-
} catch {}
|
|
1761
|
-
}
|
|
1762
|
-
return code;
|
|
1763
|
-
}
|
|
1764
|
-
function commandPath(scope, argv) {
|
|
1765
|
-
const path = [];
|
|
1766
|
-
let level = scope;
|
|
1767
|
-
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1768
|
-
const command = lookup(level, word);
|
|
1769
|
-
if (command === undefined)
|
|
1770
|
-
break;
|
|
1771
|
-
path.push(word);
|
|
1772
|
-
if (!("commands" in command))
|
|
1773
|
-
break;
|
|
1774
|
-
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1775
|
-
}
|
|
1776
|
-
return path.length === 0 ? undefined : path.join(" ");
|
|
1777
|
-
}
|
|
1778
|
-
|
|
1779
|
-
// ../kit/src/index.ts
|
|
1780
|
-
init_config();
|
|
1781
|
-
|
|
1782
|
-
// ../kit/src/excerpt.ts
|
|
1783
|
-
init_text2();
|
|
1784
|
-
|
|
1785
|
-
// ../kit/src/index.ts
|
|
1786
|
-
init_folders();
|
|
1787
|
-
init_format2();
|
|
1788
|
-
|
|
1789
|
-
// ../kit/src/git.ts
|
|
1790
|
-
init_args();
|
|
1791
|
-
// ../kit/src/limit.ts
|
|
1792
|
-
init_args();
|
|
1793
|
-
|
|
1794
|
-
// ../kit/src/index.ts
|
|
1795
|
-
init_mode();
|
|
1796
|
-
|
|
1797
|
-
// ../kit/src/report.ts
|
|
1798
|
-
init_style();
|
|
1799
|
-
init_text2();
|
|
1800
|
-
// ../kit/src/secrets.ts
|
|
1801
|
-
var SECRET_PART = /token|secret|passw|passphrase|credential|private|dsn|apikey|accesskey|authorization|sess(?:ion)?id|connectionstring|key$/i;
|
|
1802
|
-
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1803
|
-
var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
|
|
1804
|
-
var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
|
|
1805
|
-
function isSecretWord(word) {
|
|
1806
|
-
const lower = word.toLowerCase();
|
|
1807
|
-
return SECRET_WORDS.has(lower) || lower.endsWith("pass") && !NOT_PASSWORDS.has(lower);
|
|
1808
|
-
}
|
|
1809
|
-
function isSecretName(name) {
|
|
1810
|
-
return SECRET_PART.test(name) || name.split(WORD_BREAKS).some(isSecretWord);
|
|
1811
|
-
}
|
|
1812
|
-
// ../kit/src/sessions.ts
|
|
1813
|
-
var {Glob } = globalThis.Bun;
|
|
1814
|
-
var SESSION_FILES = new Glob("*.json");
|
|
1815
|
-
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1816
|
-
// ../kit/src/size.ts
|
|
1817
|
-
var SIZE = /^(\d+(?:\.\d+)?)\s*(?:([kmgt])i?b?|(b))?$/i;
|
|
1818
|
-
var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
|
|
1819
|
-
function parseSize(text, bareUnit = 1) {
|
|
1820
|
-
const match = SIZE.exec(text.trim());
|
|
1821
|
-
if (match === null)
|
|
1822
|
-
return;
|
|
1823
|
-
const suffix = match[2]?.toLowerCase();
|
|
1824
|
-
let unit = bareUnit;
|
|
1825
|
-
if (match[3] !== undefined)
|
|
1826
|
-
unit = 1;
|
|
1827
|
-
else if (suffix !== undefined)
|
|
1828
|
-
unit = 1024 ** POWERS[suffix];
|
|
1829
|
-
return Math.round(Number(match[1]) * unit);
|
|
1830
|
-
}
|
|
1831
|
-
|
|
1832
|
-
// ../kit/src/index.ts
|
|
1833
|
-
init_style();
|
|
1834
|
-
init_text2();
|
|
1835
|
-
init_theme();
|
|
1836
|
-
init_user_config();
|
|
1837
|
-
|
|
1838
|
-
// ../kit/src/watch.ts
|
|
1839
|
-
init_args();
|
|
1840
|
-
init_input();
|
|
1841
|
-
init_style();
|
|
1842
|
-
import process16 from "process";
|
|
1843
|
-
import { format } from "util";
|
|
1844
|
-
var CLEAR_SCREEN = "\x1B[H\x1B[2J";
|
|
1845
|
-
var DEFAULT_SECONDS = 2;
|
|
1846
|
-
var ATTACHED_SHORT = /^-w./;
|
|
1847
|
-
var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
|
|
1848
|
-
function watchOption(what) {
|
|
1849
|
-
return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
|
|
1850
|
-
}
|
|
1851
|
-
function withoutWatch(args) {
|
|
1852
|
-
const rest = [];
|
|
1853
|
-
for (let at = 0;at < args.length; at++) {
|
|
1854
|
-
const arg = args[at];
|
|
1855
|
-
if (arg === "--watch" || arg === "-w") {
|
|
1856
|
-
if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
|
|
1857
|
-
at++;
|
|
1858
|
-
} else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
|
|
1859
|
-
rest.push(arg);
|
|
1860
|
-
}
|
|
1861
|
-
}
|
|
1862
|
-
return rest;
|
|
1863
|
-
}
|
|
1864
|
-
async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
|
|
1865
|
-
const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
|
|
1866
|
-
if (!takesControlCodes(stream))
|
|
1867
|
-
badUsage("--watch redraws the screen, so it needs a terminal");
|
|
1868
|
-
let code = 0;
|
|
1869
|
-
for (let round = 0;round < rounds; round++) {
|
|
1870
|
-
const held = [];
|
|
1871
|
-
const { log, info } = console;
|
|
1872
|
-
const write = process16.stdout.write.bind(process16.stdout);
|
|
1873
|
-
const hold = (...parts) => void held.push(`${format(...parts)}
|
|
1874
|
-
`);
|
|
1875
|
-
console.log = hold;
|
|
1876
|
-
console.info = hold;
|
|
1877
|
-
process16.stdout.write = (text) => {
|
|
1878
|
-
held.push(typeof text === "string" ? text : Buffer.from(text).toString());
|
|
1879
|
-
return true;
|
|
1880
|
-
};
|
|
1881
|
-
try {
|
|
1882
|
-
code = await step();
|
|
1883
|
-
} finally {
|
|
1884
|
-
console.log = log;
|
|
1885
|
-
console.info = info;
|
|
1886
|
-
process16.stdout.write = write;
|
|
1887
|
-
}
|
|
1888
|
-
stream.write(`${CLEAR_SCREEN}${held.join("")}`);
|
|
1889
|
-
await sleep(interval);
|
|
1890
|
-
}
|
|
1891
|
-
return code;
|
|
1892
|
-
}
|
|
1893
|
-
// ../kit/src/workspace-root.ts
|
|
1894
|
-
init_user_config();
|
|
1895
|
-
// src/pid.ts
|
|
1896
|
-
import process18 from "process";
|
|
1897
|
-
|
|
1898
|
-
// src/mask.ts
|
|
1899
|
-
import { basename } from "path";
|
|
1900
|
-
var MASK = "***";
|
|
1901
|
-
var URL_PASSWORD = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi;
|
|
1902
|
-
var TOKEN = /\b(?:gh[pousr]_|github_pat_|glpat-|sk-|xox[abprs]-|npm_|[sr]k_(?:live|test)_)[\w-]{10,}|\beyJ[\w-]+\.[\w-]+\.[\w-]+|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bBearer\s+[\w.~+/=-]{16,}/g;
|
|
1903
|
-
var OPAQUE = /(?<![\w-])(?=[\w-]{32,}(?![\w-]))(?=[\w-]*[A-Z])(?=[\w-]*\d)[\w-]+/gi;
|
|
1904
|
-
var PEM = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*/;
|
|
1905
|
-
function maskText(value) {
|
|
1906
|
-
return value.replace(PEM, MASK).replace(URL_PASSWORD, `$1${MASK}@`).replace(TOKEN, MASK).replace(OPAQUE, MASK);
|
|
1907
|
-
}
|
|
1908
|
-
function maskValue(name, value) {
|
|
1909
|
-
if (value === "")
|
|
1910
|
-
return value;
|
|
1911
|
-
return isSecretName(name) ? MASK : maskText(value);
|
|
1912
|
-
}
|
|
1913
|
-
function maskEnviron(entries) {
|
|
1914
|
-
return entries.map(([name, value]) => [name, maskValue(name, value)]);
|
|
1915
|
-
}
|
|
1916
|
-
var FLAG = /^-{1,2}([\w.-]+)(=|$)/;
|
|
1917
|
-
var ASSIGNMENT_NAME = /^[\w.-]+$/;
|
|
1918
|
-
var PASSWORD_SPLIT = new Set(["sshpass"]);
|
|
1919
|
-
var PASSWORD_JOINED = new Set(["mysql", "mysqldump", "mysqladmin", "mariadb", "mariadb-dump"]);
|
|
1920
|
-
function maskArgs(args) {
|
|
1921
|
-
const command = basename(args[0] ?? "");
|
|
1922
|
-
let hidden = false;
|
|
1923
|
-
return args.map((arg, index) => {
|
|
1924
|
-
if (hidden) {
|
|
1925
|
-
hidden = false;
|
|
1926
|
-
return arg.startsWith("-") ? maskText(arg) : MASK;
|
|
1927
|
-
}
|
|
1928
|
-
if (index > 0 && arg === "-p" && PASSWORD_SPLIT.has(command)) {
|
|
1929
|
-
hidden = true;
|
|
1930
|
-
return arg;
|
|
1931
|
-
}
|
|
1932
|
-
if (index > 0 && arg.length > 2 && arg.startsWith("-p") && PASSWORD_JOINED.has(command))
|
|
1933
|
-
return `-p${MASK}`;
|
|
1934
|
-
const flag = FLAG.exec(arg);
|
|
1935
|
-
if (flag !== null) {
|
|
1936
|
-
if (flag[2] === "=")
|
|
1937
|
-
return isSecretName(flag[1]) ? `${arg.slice(0, flag[0].length)}${MASK}` : maskText(arg);
|
|
1938
|
-
hidden = isSecretName(flag[1]);
|
|
1939
|
-
return arg;
|
|
1940
|
-
}
|
|
1941
|
-
const equals = arg.indexOf("=");
|
|
1942
|
-
return equals > 0 && ASSIGNMENT_NAME.test(arg.slice(0, equals)) ? `${arg.slice(0, equals + 1)}${maskValue(arg.slice(0, equals), arg.slice(equals + 1))}` : maskText(arg);
|
|
1943
|
-
});
|
|
1944
|
-
}
|
|
1945
|
-
|
|
1946
|
-
// src/parse.ts
|
|
1947
|
-
var LISTENING = { tcp: "0A", udp: "07" };
|
|
1948
|
-
var WHITESPACE = /\s+/;
|
|
1949
|
-
var HEX_PAIR = /../g;
|
|
1950
|
-
var SOCKET_LINK = /^socket:\[(\d+)\]$/;
|
|
1951
|
-
var UNIT_SCOPE = /\.(?:service|scope)$/;
|
|
1952
|
-
var CONTAINER_ID = /(?:docker-|libpod-|\/docker\/)([0-9a-f]{64})/;
|
|
1953
|
-
var DOCKER_PORT = /:(\d+)(?:-(\d+))?->[\d-]+\/(tcp|udp)/;
|
|
1954
|
-
function word(hex) {
|
|
1955
|
-
const bytes = (hex.match(HEX_PAIR) ?? []).reverse().map((byte) => Number.parseInt(byte, 16));
|
|
1956
|
-
return [bytes[0] << 8 | bytes[1], bytes[2] << 8 | bytes[3]];
|
|
1957
|
-
}
|
|
1958
|
-
function parseAddress(hex) {
|
|
1959
|
-
if (hex.length === 8) {
|
|
1960
|
-
const [high, low] = word(hex);
|
|
1961
|
-
return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
|
|
1962
|
-
}
|
|
1963
|
-
const hextets = (hex.match(/.{8}/g) ?? []).flatMap(word);
|
|
1964
|
-
if (hextets.length !== 8)
|
|
1965
|
-
return hex;
|
|
1966
|
-
if (hextets.slice(0, 5).every((part) => part === 0) && hextets[5] === 65535)
|
|
1967
|
-
return `::ffff:${hextets[6] >> 8}.${hextets[6] & 255}.${hextets[7] >> 8}.${hextets[7] & 255}`;
|
|
1968
|
-
return compress(hextets);
|
|
1969
|
-
}
|
|
1970
|
-
function compress(hextets) {
|
|
1971
|
-
let best = { start: -1, length: 0 };
|
|
1972
|
-
let run = { start: 0, length: 0 };
|
|
1973
|
-
for (const [at, part] of hextets.entries()) {
|
|
1974
|
-
run = part === 0 ? { start: run.length === 0 ? at : run.start, length: run.length + 1 } : { start: 0, length: 0 };
|
|
1975
|
-
if (run.length > best.length)
|
|
1976
|
-
best = run;
|
|
1977
|
-
}
|
|
1978
|
-
const text = (parts) => parts.map((part) => part.toString(16)).join(":");
|
|
1979
|
-
if (best.length < 2)
|
|
1980
|
-
return text(hextets);
|
|
1981
|
-
return `${text(hextets.slice(0, best.start))}::${text(hextets.slice(best.start + best.length))}`;
|
|
1982
|
-
}
|
|
1983
|
-
function parseNetTable(text, protocol, family) {
|
|
1984
|
-
const sockets = [];
|
|
1985
|
-
for (const line of text.split(`
|
|
1986
|
-
`).slice(1)) {
|
|
1987
|
-
const columns = line.trim().split(WHITESPACE);
|
|
1988
|
-
const [address = "", port = ""] = (columns[1] ?? "").split(":");
|
|
1989
|
-
if (columns.length < 10 || columns[3] !== LISTENING[protocol])
|
|
1990
|
-
continue;
|
|
1991
|
-
const number = Number.parseInt(port, 16);
|
|
1992
|
-
if (number === 0 || Number.isNaN(number))
|
|
1993
|
-
continue;
|
|
1994
|
-
sockets.push({ protocol, family, address: parseAddress(address), port: number, uid: Number(columns[7]), inode: Number(columns[9]) });
|
|
1995
|
-
}
|
|
1996
|
-
return sockets;
|
|
1997
|
-
}
|
|
1998
|
-
function socketInode(link) {
|
|
1999
|
-
const match = SOCKET_LINK.exec(link);
|
|
2000
|
-
return match === null ? undefined : Number(match[1]);
|
|
2001
|
-
}
|
|
2002
|
-
function parseStat(text) {
|
|
2003
|
-
const open = text.indexOf("(");
|
|
2004
|
-
const close = text.lastIndexOf(")");
|
|
2005
|
-
if (open === -1 || close < open)
|
|
2006
|
-
return;
|
|
2007
|
-
const rest = text.slice(close + 2).trim().split(WHITESPACE);
|
|
2008
|
-
const field = (number) => Number(rest[number - 3]);
|
|
2009
|
-
if (rest.length < 20)
|
|
2010
|
-
return;
|
|
2011
|
-
return { comm: text.slice(open + 1, close), state: rest[0], ppid: field(4), pgrp: field(5), session: field(6), tty: field(7), threads: field(20), startTicks: field(22) };
|
|
2012
|
-
}
|
|
2013
|
-
function parseStatus(text) {
|
|
2014
|
-
const fields = new Map;
|
|
2015
|
-
for (const line of text.split(`
|
|
2016
|
-
`)) {
|
|
2017
|
-
const colon = line.indexOf(":");
|
|
2018
|
-
if (colon > 0)
|
|
2019
|
-
fields.set(line.slice(0, colon), line.slice(colon + 1).trim());
|
|
2020
|
-
}
|
|
2021
|
-
return fields;
|
|
2022
|
-
}
|
|
2023
|
-
function statusBytes(fields, key) {
|
|
2024
|
-
const value = Number.parseInt(fields.get(key) ?? "", 10);
|
|
2025
|
-
return Number.isNaN(value) ? undefined : value * 1024;
|
|
2026
|
-
}
|
|
2027
|
-
function statusUid(fields) {
|
|
2028
|
-
const value = Number.parseInt(fields.get("Uid") ?? "", 10);
|
|
2029
|
-
return Number.isNaN(value) ? undefined : value;
|
|
2030
|
-
}
|
|
2031
|
-
var LIMIT_LINE = /^(\S+(?: \S+)*)\s{2,}(\S+)\s+(\S+)(?:\s+(\S+))?\s*$/;
|
|
2032
|
-
function parseLimits(text) {
|
|
2033
|
-
const limits = [];
|
|
2034
|
-
for (const line of text.split(`
|
|
2035
|
-
`).slice(1)) {
|
|
2036
|
-
const match = LIMIT_LINE.exec(line);
|
|
2037
|
-
if (match !== null)
|
|
2038
|
-
limits.push({ name: match[1], soft: match[2], hard: match[3], units: match[4] ?? "" });
|
|
2039
|
-
}
|
|
2040
|
-
return limits;
|
|
2041
|
-
}
|
|
2042
|
-
function parseCmdline(text) {
|
|
2043
|
-
return text.split("\x00").filter((_, at, parts) => at < parts.length - 1 || parts[at] !== "");
|
|
2044
|
-
}
|
|
2045
|
-
function parseEnviron(text) {
|
|
2046
|
-
return parseCmdline(text).map((entry) => {
|
|
2047
|
-
const equals = entry.indexOf("=");
|
|
2048
|
-
return equals === -1 ? [entry, ""] : [entry.slice(0, equals), entry.slice(equals + 1)];
|
|
2049
|
-
});
|
|
2050
|
-
}
|
|
2051
|
-
function parseCgroup(text) {
|
|
2052
|
-
return text.split(`
|
|
2053
|
-
`).filter((line) => line !== "").map((line) => {
|
|
2054
|
-
const [hierarchy = "", controllers = "", ...path] = line.split(":");
|
|
2055
|
-
return { hierarchy, controllers, path: path.join(":") };
|
|
2056
|
-
});
|
|
2057
|
-
}
|
|
2058
|
-
function cgroupUnit(entries) {
|
|
2059
|
-
const path = (entries.find((entry) => entry.hierarchy === "0") ?? entries[0])?.path ?? "";
|
|
2060
|
-
return path.split("/").reverse().find((part) => UNIT_SCOPE.test(part));
|
|
2061
|
-
}
|
|
2062
|
-
function cgroupContainer(entries) {
|
|
2063
|
-
for (const { path } of entries) {
|
|
2064
|
-
const match = CONTAINER_ID.exec(path);
|
|
2065
|
-
if (match !== null)
|
|
2066
|
-
return match[1];
|
|
2067
|
-
}
|
|
2068
|
-
return;
|
|
2069
|
-
}
|
|
2070
|
-
function userNameOf(passwd, uid) {
|
|
2071
|
-
for (const line of passwd.split(`
|
|
2072
|
-
`)) {
|
|
2073
|
-
const [name, , id] = line.split(":");
|
|
2074
|
-
if (id === String(uid) && name !== undefined && name !== "")
|
|
2075
|
-
return name;
|
|
2076
|
-
}
|
|
2077
|
-
return;
|
|
2078
|
-
}
|
|
2079
|
-
function parseDockerPs(text) {
|
|
2080
|
-
const containers = [];
|
|
2081
|
-
for (const line of text.split(`
|
|
2082
|
-
`)) {
|
|
2083
|
-
const [name = "", ports = "", project = "", service = ""] = line.split("\t");
|
|
2084
|
-
if (name === "")
|
|
2085
|
-
continue;
|
|
2086
|
-
const published = [];
|
|
2087
|
-
for (const entry of ports.split(",")) {
|
|
2088
|
-
const match = DOCKER_PORT.exec(entry);
|
|
2089
|
-
if (match === null)
|
|
2090
|
-
continue;
|
|
2091
|
-
const first = Number(match[1]);
|
|
2092
|
-
for (let host = first;host <= Number(match[2] ?? first); host++)
|
|
2093
|
-
published.push({ host, protocol: match[3] });
|
|
2094
|
-
}
|
|
2095
|
-
containers.push({ name, project: project === "" ? undefined : project, service: service === "" ? undefined : service, published });
|
|
2096
|
-
}
|
|
2097
|
-
return containers;
|
|
2098
|
-
}
|
|
2099
|
-
|
|
2100
|
-
// src/read.ts
|
|
2101
|
-
import { readdir, readFile, readlink } from "fs/promises";
|
|
2102
|
-
var CLOCK_TICKS = 100;
|
|
2103
|
-
async function text2(path) {
|
|
2104
|
-
try {
|
|
2105
|
-
return await readFile(path, "utf8");
|
|
2106
|
-
} catch {
|
|
2107
|
-
return;
|
|
2108
|
-
}
|
|
2109
|
-
}
|
|
2110
|
-
async function link(path) {
|
|
2111
|
-
try {
|
|
2112
|
-
return await readlink(path);
|
|
2113
|
-
} catch {
|
|
2114
|
-
return;
|
|
2115
|
-
}
|
|
2116
|
-
}
|
|
2117
|
-
var DIGITS = /^\d+$/;
|
|
2118
|
-
var BOOT_TIME = /^btime\s+(\d+)/m;
|
|
2119
|
-
async function listPids(root = "/proc") {
|
|
2120
|
-
return (await readdir(root)).filter((name) => DIGITS.test(name)).map(Number);
|
|
2121
|
-
}
|
|
2122
|
-
async function bootMs(root = "/proc") {
|
|
2123
|
-
const match = BOOT_TIME.exec(await text2(`${root}/stat`) ?? "");
|
|
2124
|
-
return match === null ? Date.now() : Number(match[1]) * 1000;
|
|
2125
|
-
}
|
|
2126
|
-
async function readProc(pid, boot, { root = "/proc", detail = true } = {}) {
|
|
2127
|
-
const dir = `${root}/${pid}`;
|
|
2128
|
-
const [statText, statusText, cmdline] = await Promise.all([text2(`${dir}/stat`), text2(`${dir}/status`), text2(`${dir}/cmdline`)]);
|
|
2129
|
-
const stat = statText === undefined ? undefined : parseStat(statText);
|
|
2130
|
-
if (stat === undefined || statusText === undefined)
|
|
2131
|
-
return;
|
|
2132
|
-
const status = parseStatus(statusText);
|
|
2133
|
-
const info = {
|
|
2134
|
-
pid,
|
|
2135
|
-
ppid: stat.ppid,
|
|
2136
|
-
comm: stat.comm,
|
|
2137
|
-
args: parseCmdline(cmdline ?? ""),
|
|
2138
|
-
uid: statusUid(status) ?? -1,
|
|
2139
|
-
state: stat.state,
|
|
2140
|
-
session: stat.session,
|
|
2141
|
-
rss: statusBytes(status, "VmRSS") ?? 0,
|
|
2142
|
-
startMs: boot + stat.startTicks / CLOCK_TICKS * 1000
|
|
2143
|
-
};
|
|
2144
|
-
if (!detail)
|
|
2145
|
-
return info;
|
|
2146
|
-
const [cwd, exe, cgroup] = await Promise.all([link(`${dir}/cwd`), link(`${dir}/exe`), text2(`${dir}/cgroup`)]);
|
|
2147
|
-
const groups = parseCgroup(cgroup ?? "");
|
|
2148
|
-
return { ...info, cwd, exe, unit: cgroupUnit(groups), container: cgroupContainer(groups) };
|
|
2149
|
-
}
|
|
2150
|
-
async function snapshot(root = "/proc", detailed = () => true) {
|
|
2151
|
-
const boot = await bootMs(root);
|
|
2152
|
-
const found = [];
|
|
2153
|
-
for (const pid of await listPids(root)) {
|
|
2154
|
-
const light = await readProc(pid, boot, { root, detail: false });
|
|
2155
|
-
if (light === undefined)
|
|
2156
|
-
continue;
|
|
2157
|
-
found.push(detailed(light.uid) ? await readProc(pid, boot, { root }) ?? light : light);
|
|
2158
|
-
}
|
|
2159
|
-
return found;
|
|
2160
|
-
}
|
|
2161
|
-
function ancestry(pid, byPid) {
|
|
2162
|
-
const chain = [];
|
|
2163
|
-
let at = pid;
|
|
2164
|
-
while (at !== undefined && at > 0 && !chain.includes(at)) {
|
|
2165
|
-
chain.push(at);
|
|
2166
|
-
at = byPid.get(at)?.ppid;
|
|
2167
|
-
}
|
|
2168
|
-
return chain;
|
|
2169
|
-
}
|
|
2170
|
-
async function readSockets(root = "/proc") {
|
|
2171
|
-
const tables = [["tcp", "tcp", 4], ["tcp6", "tcp", 6], ["udp", "udp", 4], ["udp6", "udp", 6]];
|
|
2172
|
-
const sockets = [];
|
|
2173
|
-
for (const [file, protocol, family] of tables)
|
|
2174
|
-
sockets.push(...parseNetTable(await text2(`${root}/net/${file}`) ?? "", protocol, family));
|
|
2175
|
-
return sockets;
|
|
2176
|
-
}
|
|
2177
|
-
async function socketsOf(pid, root = "/proc") {
|
|
2178
|
-
const inodes = new Set;
|
|
2179
|
-
try {
|
|
2180
|
-
for (const fd of await readdir(`${root}/${pid}/fd`)) {
|
|
2181
|
-
const inode = socketInode(await link(`${root}/${pid}/fd/${fd}`) ?? "");
|
|
2182
|
-
if (inode !== undefined)
|
|
2183
|
-
inodes.add(inode);
|
|
2184
|
-
}
|
|
2185
|
-
} catch {}
|
|
2186
|
-
return inodes;
|
|
2187
|
-
}
|
|
2188
|
-
async function socketOwners(root = "/proc") {
|
|
2189
|
-
const holders = new Map;
|
|
2190
|
-
for (const pid of await listPids(root)) {
|
|
2191
|
-
for (const inode of await socketsOf(pid, root))
|
|
2192
|
-
holders.set(inode, [...holders.get(inode) ?? [], pid]);
|
|
2193
|
-
}
|
|
2194
|
-
const owners = new Map;
|
|
2195
|
-
const parents = new Map;
|
|
2196
|
-
for (const [inode, pids] of holders) {
|
|
2197
|
-
const [first = 0] = pids;
|
|
2198
|
-
if (pids.length > 1) {
|
|
2199
|
-
for (const pid of pids) {
|
|
2200
|
-
if (!parents.has(pid))
|
|
2201
|
-
parents.set(pid, parseStat(await text2(`${root}/${pid}/stat`) ?? "")?.ppid);
|
|
2202
|
-
}
|
|
2203
|
-
}
|
|
2204
|
-
owners.set(inode, pids.find((pid) => !pids.includes(parents.get(pid) ?? -1)) ?? first);
|
|
2205
|
-
}
|
|
2206
|
-
return owners;
|
|
2207
|
-
}
|
|
2208
|
-
async function fdCount(pid, root = "/proc") {
|
|
2209
|
-
try {
|
|
2210
|
-
return (await readdir(`${root}/${pid}/fd`)).length;
|
|
2211
|
-
} catch {
|
|
2212
|
-
return;
|
|
2213
|
-
}
|
|
2214
|
-
}
|
|
2215
|
-
var passwd;
|
|
2216
|
-
async function userName(uid) {
|
|
2217
|
-
passwd ??= await text2("/etc/passwd") ?? "";
|
|
2218
|
-
return userNameOf(passwd, uid);
|
|
2219
|
-
}
|
|
2220
|
-
|
|
2221
|
-
// src/pid.ts
|
|
2222
|
-
var usage2 = `proc pid <pid>: shows what a process is, from its executable and command line to its parent chain, memory, open files, listening ports and cgroup
|
|
61
|
+
__kaynooo_cli_register() {
|
|
62
|
+
add-zsh-hook -d precmd __kaynooo_cli_register
|
|
63
|
+
(( $+functions[compdef] )) || { autoload -Uz compinit && compinit }
|
|
64
|
+
compdef __kaynooo_cli_complete $__kaynooo_cli_bins
|
|
65
|
+
}
|
|
66
|
+
autoload -Uz add-zsh-hook
|
|
67
|
+
add-zsh-hook precmd __kaynooo_cli_register
|
|
68
|
+
typeset -gaU __kaynooo_cli_bins
|
|
69
|
+
__kaynooo_cli_bins+=(${bins.join(" ")})
|
|
70
|
+
`}var COMPLETE="__complete",FILES="__files__",COMPLETIONS="--completions";function shown(commands){return Object.fromEntries(Object.entries(commands).filter(([,{hidden}])=>hidden!==!0))}async function resolveSummary(summary){return typeof summary==="string"?summary:summary()}function lookup({commands,aliases},word){let name=aliases!==void 0&&Object.hasOwn(aliases,word)?aliases[word]??word:word;return Object.hasOwn(commands,name)?commands[name]:void 0}function scopeOf(commands,extra,aliases){return{commands:typeof commands==="function"?{}:commands,lazy:[...typeof commands==="function"?[commands]:[],...extra===void 0?[]:[extra]],aliases}}async function expand(scope,words){if(scope.lazy.length===0)return scope;let commands={...scope.commands};for(let added of await Promise.all(scope.lazy.map(async(lazy)=>lazy(words))))for(let[name,command]of Object.entries(added))commands[name]??=command;return{...scope,commands,lazy:[]}}async function completingOf(run){completion.active=!0;try{await run([])}catch(error){if(error instanceof Completing)return error}finally{completion.active=!1}return new Completing({})}async function optionsOf(run){return(await completingOf(run)).options}function candidateLine(candidate){return typeof candidate==="string"?candidate:candidate.join("\t")}function positionalBeingTyped(before,{options,positionals}){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),typed=[],at=0;while(at<before.length){let word=before[at];if(word==="--"){typed.push(...before.slice(at+1));break}if(!word.startsWith("-"))typed.push(word);else if(takesValue(word))at++;at++}let last=positionals.at(-1);if(typed.length<positionals.length)return{name:positionals[typed.length],typed};return{name:last?.replace("]","").endsWith("...")===!0?last:void 0,typed}}async function leafCandidates(run,words){let completing=await completingOf(run);if((words.at(-1)??"").startsWith("-"))return Object.entries(completing.options).map(([name,option])=>option.description===void 0?`--${name}`:`--${name} ${option.description}`);let flag=words.at(-2),option=flag?.startsWith("-")===!0?Object.entries(completing.options).find(([name,{short}])=>flag===`--${name}`||flag===`-${short}`)?.[1]:void 0,{name,typed}=positionalBeingTyped(words.slice(0,-1),completing);if(option?.type==="string"){let values=option.choices===void 0?await option.candidates?.(typed):option.choices;return values===void 0?[FILES]:values.map(candidateLine)}let values=name===void 0?void 0:await completing.candidates[name]?.(typed);return values===void 0?[FILES]:values.map(candidateLine)}async function candidates(scope,defaultCommand,words,before=[]){let[word="",...rest]=words,listing=rest.length===0&&!word.startsWith("-"),{commands}=scope,command=lookup(scope,word);if(listing||command===void 0){let expanded=await expand(scope,[...before,...words]);commands=expanded.commands,command=lookup(expanded,word)}if(listing){let own=await Promise.all(Object.entries(shown(commands)).map(async([name,{summary}])=>`${name} ${await resolveSummary(summary)}`)),fallback=defaultCommand===void 0?void 0:commands[defaultCommand],values=fallback!==void 0&&"run"in fallback?await leafCandidates(fallback.run,[word]):[],valueOf=(line)=>line.slice(0,line.includes("\t")?line.indexOf("\t"):void 0);return[...own,...values.filter((line)=>line!==FILES&&!Object.hasOwn(commands,valueOf(line)))]}if(command===void 0){let fallback=defaultCommand===void 0?void 0:commands[defaultCommand];return fallback!==void 0&&"run"in fallback?leafCandidates(fallback.run,words):[]}return"commands"in command?candidates(scopeOf(command.commands,command.extraCommands,command.aliases),void 0,rest,[...before,word]):leafCandidates(command.run,rest)}function flagValue([flag="",...rest]){return flag.includes("=")?[flag.slice(flag.indexOf("=")+1),...rest]:rest}function printCompletionScript(name,args,reportError){let shell=COMPLETION_SHELLS.find((each)=>each===args[0]);if(shell===void 0||args.length!==1)return reportError(name,`${COMPLETIONS} takes one of ${COMPLETIONS_SHELLS_LIST()}`,`${name} ${COMPLETIONS} fish`),2;return console.log(completionScript(shell,[name]).trimEnd()),0}function COMPLETIONS_SHELLS_LIST(){return COMPLETION_SHELLS.join(", ")}async function printCandidates(found){for(let line of await found)console.log(line);return 0}init_mode();init_format2();init_mode();import process13 from"process";var NOTIFY_AFTER_MS=1e4,CANCELLED=130;function base64(text){return Buffer.from(text).toString("base64")}function sanitizeOsc(text){return text.replaceAll(/[\x00-\x1F\x7F;]/g," ")}function wrapTmux(codes,env){return codes.map((code)=>env.TMUX===void 0||env.TMUX===""?code:`\x1BPtmux;${code.replaceAll("\x1B","\x1B\x1B")}\x1B\\`).join("")}function notification(title,body,env=process13.env){let program=env.TERM_PROGRAM??"",term=env.TERM??"";if(program==="WezTerm"||term.startsWith("foot")||term.startsWith("rxvt"))return wrapTmux([`\x1B]777;notify;${sanitizeOsc(title)};${sanitizeOsc(body)}\x1B\\`],env);if(program==="iTerm.app"||env.WT_SESSION!==void 0&&env.WT_SESSION!=="")return wrapTmux([`\x1B]9;${sanitizeOsc(title)}: ${sanitizeOsc(body)}\x1B\\`],env);let id=`kit${process13.pid}`,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\\`];return wrapTmux(codes,env)}function notifyEnd(command,code,ms,{stream=process13.stderr,env=process13.env}={}){if(ms<NOTIFY_AFTER_MS||code===CANCELLED||outputMode(stream,env)!=="terminal")return;stream.write(notification(command,code===0?`done in ${formatDuration(ms)}`:`failed with exit ${code} after ${formatDuration(ms)}`,env))}init_style();init_text2();import{appendFileSync,mkdirSync as mkdirSync2,readFileSync as readFileSync4,renameSync,statSync as statSync3,writeFileSync as writeFileSync2}from"fs";import{homedir as homedir3}from"os";import{dirname as dirname3,join as join4}from"path";import process14 from"process";init_user_config();var CLI_FOLDER="kaynooo-cli";init_user_config();var MAX_USAGE_BYTES=2097152,UNKNOWN_OPTION2=/unknown option '(--[a-z][a-z0-9-]*)[=']/,FLAG_NAME=/^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/,LONGEST_NAME=40,usageError;function noteUsageError(message){usageError=message}function stateHome(env=process14.env){return xdgFolder(env.XDG_STATE_HOME,join4(homedir3(),".local","state"))}function usagePath(env=process14.env){return join4(stateHome(env),CLI_FOLDER,"usage.jsonl")}function usageRecorded(env=process14.env){let off=env.KAYNOOO_CLI_NO_USAGE;return env.NODE_ENV!=="test"&&(off===void 0||off===""||off==="0")}function flagNames(argv){let end=argv.indexOf("--"),names=(end===-1?argv:argv.slice(0,end)).filter((word)=>word.startsWith("-")&&word!=="-").map((word)=>word.includes("=")?word.slice(0,word.indexOf("=")):word);return[...new Set(names)].filter((name)=>name.length<=LONGEST_NAME&&FLAG_NAME.test(name))}function usageEntry(bin,command,argv,code,{ms,mode,now=new Date}={}){let unknown=code===2&&usageError!==void 0?UNKNOWN_OPTION2.exec(usageError)?.[1]:void 0;return usageError=void 0,{at:now.toISOString(),bin,...command===void 0?{}:{command},flags:flagNames(argv),code,...unknown===void 0?{}:{unknown},...ms===void 0?{}:{ms:Math.round(ms)},...mode===void 0?{}:{mode}}}function trimUsage(path,maxBytes){let info=statSync3(path,{throwIfNoEntry:!1});if(info===void 0||info.size<=maxBytes)return;let lines=readFileSync4(path,"utf8").split(`
|
|
71
|
+
`).filter(Boolean),kept=`${lines.slice(Math.floor(lines.length/2)).join(`
|
|
72
|
+
`)}
|
|
73
|
+
`,temp=`${path}.${process14.pid}.tmp`;writeFileSync2(temp,kept,{mode:384}),renameSync(temp,path)}function recordUsage(entry,env=process14.env,maxBytes=MAX_USAGE_BYTES){if(!usageRecorded(env))return;try{let path=usagePath(env);mkdirSync2(dirname3(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
|
|
74
|
+
`,{mode:384}),trimUsage(path,maxBytes)}catch{}}var LEVEL_OPTIONS={...OUTPUT_OPTIONS,help:{type:"boolean",short:"h",description:"show this help"}},TOP_OPTIONS={...LEVEL_OPTIONS,version:{type:"boolean",short:"v",description:"print the version"},completions:{type:"string",choices:COMPLETION_SHELLS,description:"print the shell completion script"}};async function commandRows(all,colors){let commands=shown(all),width=Math.max(0,...Object.keys(commands).map((name)=>name.length)),groups=new Map([["Commands:",[]]]),summaries=await Promise.all(Object.values(commands).map(async({summary})=>resolveSummary(summary)));for(let[index,[name,{group}]]of Object.entries(commands).entries()){let label=group===void 0?"Commands:":`${group}:`,rows=groups.get(label)??[];rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`),groups.set(label,rows)}return[...groups].filter(([,rows])=>rows.length>0).flatMap(([label,rows],index)=>[...index===0?[]:[""],colors.bold(label),...rows])}function takeOutputFlags(argv){let index=0;for(;index<argv.length;index++){let word=argv[index];if(word==="--plain")applyOutput(void 0,!0);else if(word.startsWith("--color="))applyOutput(word.slice(8),void 0);else if(word==="--color"&&argv[index+1]!==void 0)applyOutput(argv[++index],void 0);else break}return argv.slice(index)}async function help2({path,header,summary:lazySummary,commands,defaultCommand,examples,replaces},stream,json=!1){let colors=paint(stream),prefix=path.join(" "),summary=await resolveSummary(lazySummary);if(json||wantsHelpJson())return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`,{examples,replaces}));let columns=takesControlCodes(stream)?stream.columns:void 0,fallback=defaultCommand===void 0?void 0:commands[defaultCommand],options=fallback!==void 0&&"run"in fallback?await optionsOf(fallback.run):void 0,own=Object.entries(options??{}).filter(([name])=>!(name in TOP_OPTIONS));return[header(colors,summary),"",usageLine(`${prefix} ${defaultCommand===void 0?colors.cyan("<command>"):`[${colors.cyan("<command>")}]`} [options]`,colors),"",...await commandRows(commands,colors),...own.length===0?[]:["",`${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`,...optionRows(Object.fromEntries(own),colors,columns)],"",colors.bold("Options:"),...optionRows(path.length===1?TOP_OPTIONS:LEVEL_OPTIONS,colors,columns),...exampleRows(examples??[],colors),"",`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`].join(`
|
|
75
|
+
`)}function printError(prefix,message,hint,cause){let colors=paint(process15.stderr),styled=takesControlCodes(process15.stderr),head=styled?`${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}`:`error: ${prefix}:`,under=(label,text,tint)=>text===void 0?"":`
|
|
76
|
+
${styled?tint(label):`${label}:`} ${text}`;console.error(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause,extra){console.error(JSON.stringify({error:message,...extra?.code===void 0?{}:{code:extra.code},...extra?.command===void 0?{}:{command:extra.command},...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}function wantsJson(argv){let end=argv.indexOf("--");return(end===-1?argv:argv.slice(0,end)).includes("--json")}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let code=error instanceof Exit?error.code:1,helpHint=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?(message,hint,causeText)=>printJsonError(message,hint,causeText,{code,command:prefix}):(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??helpHint:void 0,cause),code}async function dispatch(level,typed,{version,redact}){let prefix=level.path.join(" "),argv;try{argv=takeOutputFlags(typed)}catch(error){return{code:reportThrown(prefix,error,redact,wantsJson(typed)),meta:!1}}let[name,...args]=argv,fallback=level.defaultCommand===void 0?void 0:level.commands[level.defaultCommand];if(name===void 0&&level.runBare&&fallback!==void 0&&"run"in fallback)try{return{code:await fallback.run([]),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${level.defaultCommand}`,error,redact,!1),meta:error instanceof HelpShown}}if(name===void 0&&level.path.length>1)return console.error(await help2(await expand(level,[...level.path.slice(1),...argv]),process15.stderr)),{code:2,meta:!0};if(name==="help"&&args.length>0&&args[0]!=="--json")return dispatch(level,[...args,"--help"],{version,redact});if(name===void 0||name==="help"||name==="--help"||name==="-h"||name==="--help=json")return console.log(await help2(await expand(level,[...level.path.slice(1),...argv]),process15.stdout,wantsHelpJson(process15.env,argv))),{code:0,meta:!0};if(level.path.length===1&&(name==="--version"||name==="-v"))return console.log(version()),{code:0,meta:!0};let command=lookup(level,name),rest=args,ran=name;if(command===void 0&&level.lazy.length>0)level=await expand(level,[...level.path.slice(1),...argv]),command=lookup(level,name);if(command===void 0&&level.defaultCommand!==void 0)command=level.commands[level.defaultCommand],rest=argv,ran=level.defaultCommand;if(command===void 0){let meant=closest(name,Object.keys(shown(level.commands))),hint=meant===void 0?`run ${prefix} --help for its commands`:`did you mean ${meant}?`;if(wantsJson(argv))printJsonError(`no command ${name}`,hint,void 0,{code:2,command:prefix});else printError(prefix,`no command ${name}`,hint);return{code:2,meta:!1}}if("commands"in command){let{summary}=command;return dispatch({path:[...level.path,name],header:(colors,text)=>`${colors.bold(`${prefix} ${name}`)} ${text}`,summary,...scopeOf(command.commands,command.extraCommands,command.aliases),defaultCommand:command.defaultCommand,runBare:command.runBare===!0,examples:command.examples,replaces:void 0},rest,{version,redact})}try{return{code:await command.run(rest),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${ran}`,error,redact,wantsJson(rest)),meta:error instanceof HelpShown}}}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname4(resolved);;dir=dirname4(dir)){try{let{version}=JSON.parse(readFileSync5(join5(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname4(dir)===dir)return"0.0.0"}}async function runCli(cli,argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(candidates(scopeOf(cli.commands,cli.extraCommands,cli.aliases),cli.defaultCommand,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(cli.name,flagValue(argv),printError);let version=()=>cli.version??packageVersion(),started=performance.now(),{code,meta}=await dispatch({path:[cli.name],header:(colors,about)=>`${colors.bold(cli.name)} ${colors.dim(version())} ${about}`,summary:cli.about,...scopeOf(cli.commands,cli.extraCommands,cli.aliases),defaultCommand:cli.defaultCommand,runBare:cli.runBare===!0,examples:cli.examples,replaces:cli.replaces},argv,{version,redact:cli.redact}),command=commandPath(scopeOf(cli.commands,cli.extraCommands,cli.aliases),argv);if(notifyEnd(command===void 0?cli.name:`${cli.name} ${command}`,code,performance.now()-started),cli.usage!==!1&&!meta)try{recordUsage(usageEntry(cli.name,command,argv,code,{ms:performance.now()-started,mode:outputMode()}))}catch{}return code}function commandPath(scope,argv){let path=[],level=scope;for(let word of argv.filter((each)=>!each.startsWith("-"))){let command=lookup(level,word);if(command===void 0)break;if(path.push(word),!("commands"in command))break;level=scopeOf(command.commands,command.extraCommands,command.aliases)}return path.length===0?void 0:path.join(" ")}init_args();var SHELLS=new Set(["sh","bash","zsh","dash","ash","ksh","fish","csh","tcsh","nu","xonsh","elvish","pwsh","powershell"]),SCANNED_PROGRAMS=new Set(["su","runuser","flock"]),COMMAND_STRING_PROGRAMS=new Set([...SHELLS,...SCANNED_PROGRAMS]);function wrapper(short="",long=[],operands=0,runsString=!1){return{short,long,operands,runsString}}var RUNNER={...wrapper(),afterDashes:!0},WRAPPERS=new Map([["command",wrapper()],["builtin",wrapper()],["nohup",wrapper()],["setsid",wrapper()],["busybox",wrapper()],["exec",wrapper("a")],["time",wrapper("fo",["--format","--output"])],["env",wrapper("uCS",["--unset","--chdir","--split-string","--argv0"])],["sudo",wrapper("ughpCTrtUDR",["--user","--group","--host","--prompt","--close-from","--command-timeout","--role","--type","--other-user","--chdir","--chroot"])],["doas",wrapper("uC")],["timeout",wrapper("sk",["--signal","--kill-after"],1)],["nice",wrapper("n",["--adjustment"])],["ionice",wrapper("cnpPu",["--class","--classdata","--pid","--pgid","--uid"])],["stdbuf",wrapper("ioe",["--input","--output","--error"])],["chroot",wrapper("",["--userspec","--groups"],1)],["watch",wrapper("n",["--interval"],0,!0)],["flock",wrapper("wE",["--timeout","--conflict-exit-code"],1)],["parallel",wrapper("jnNSaIPlLdTsC",["--jobs","--max-args","--max-replace-args","--sshlogin","--arg-file","--delimiter","--colsep"],0,!0)],["unbuffer",wrapper()],["systemd-run",wrapper("puEMH",["--property","--unit","--description","--slice","--setenv","--machine","--host","--uid","--gid","--working-directory","--nice","--service-type"])],["xargs",wrapper("IndsEaPL",["--max-args","--max-procs","--max-chars","--delimiter","--arg-file","--eof","--max-lines","--process-slot-var"])],["strace",wrapper("abeEIoOpPsSuUX",["--trace","--output","--attach","--string-limit","--user","--env","--columns","--trace-path","--signal","--status","--summary-sort-by","--summary-columns","--const-print-style","--interruptible","--detach-on"])],["ltrace",wrapper("aeFlnopsuxX",["--output","--user","--library","--config","--align","--indent"])],["taskset",wrapper("",[],1)],["fakeroot",wrapper("lsib",["--lib","--faked"])],["sshpass",wrapper("pfdP")],["coproc",wrapper()],["proxychains",wrapper("f")],["proxychains4",wrapper("f")],["torsocks",wrapper("upaP",["--user","--pass","--address","--port"])],["chrt",wrapper("TPD",["--sched-runtime","--sched-period","--sched-deadline"],1)],["unshare",wrapper("SGRw",["--setuid","--setgid","--root","--wd","--map-user","--map-group","--map-users","--map-groups","--propagation","--setgroups"])],["nsenter",wrapper("tSG",["--target","--setuid","--setgid"])],["out",RUNNER],["slot",RUNNER],["waitfor",RUNNER],["base",RUNNER]]);init_style();init_config();init_text2();init_folders();init_format2();init_args();init_args();init_mode();init_style();init_text2();var SECRET_PART=/token|secret|passw|passphrase|credential|private|dsn|apikey|accesskey|authorization|sess(?:ion)?id|connectionstring|key$/i,SECRET_WORDS=new Set(["key","pass","pwd","auth","salt","cookie","session","jwt","ssn","iban","card","cvv","otp"]),WORD_BREAKS=/[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/,NOT_PASSWORDS=new Set(["compass","encompass","bypass","overpass","underpass","surpass","trespass"]);function isSecretWord(word){let lower=word.toLowerCase();return SECRET_WORDS.has(lower)||lower.endsWith("pass")&&!NOT_PASSWORDS.has(lower)}function isSecretName(name){return SECRET_PART.test(name)||name.split(WORD_BREAKS).some(isSecretWord)}var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");var SIZE=/^(\d+(?:\.\d+)?)\s*(?:([kmgt])i?b?|(b))?$/i,POWERS={"":0,k:1,m:2,g:3,t:4};function parseSize(text,bareUnit=1){let match=SIZE.exec(text.trim());if(match===null)return;let suffix=match[2]?.toLowerCase(),unit=bareUnit;if(match[3]!==void 0)unit=1;else if(suffix!==void 0)unit=1024**POWERS[suffix];return Math.round(Number(match[1])*unit)}init_style();init_text2();init_theme();init_user_config();init_args();init_input();init_style();import process16 from"process";import{format}from"util";var CLEAR_SCREEN="\x1B[H\x1B[2J",DEFAULT_SECONDS=2,ATTACHED_SHORT=/^-w./,INTERVAL=/^\d+(?:\.\d+)?(?:ms|[smh])?$/;function watchOption(what){return{type:"string",short:"w",optional:{bare:"",accepts:INTERVAL},description:`redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c`}}function withoutWatch(args){let rest=[];for(let at=0;at<args.length;at++){let arg=args[at];if(arg==="--watch"||arg==="-w"){if(args[at+1]!==void 0&&INTERVAL.test(args[at+1]))at++}else if(!arg.startsWith("--watch=")&&!ATTACHED_SHORT.test(arg))rest.push(arg)}return rest}async function watching(value,step,stream=process16.stdout,sleep=Bun.sleep,rounds=Number.POSITIVE_INFINITY){let interval=value===""?DEFAULT_SECONDS*1000:duration(value,"watch",DEFAULT_SECONDS*1000);if(!takesControlCodes(stream))badUsage("--watch redraws the screen, so it needs a terminal");let code=0;for(let round=0;round<rounds;round++){let held=[],{log,info}=console,write=process16.stdout.write.bind(process16.stdout),hold=(...parts)=>void held.push(`${format(...parts)}
|
|
77
|
+
`);console.log=hold,console.info=hold,process16.stdout.write=(text)=>(held.push(typeof text==="string"?text:Buffer.from(text).toString()),!0);try{code=await step()}finally{console.log=log,console.info=info,process16.stdout.write=write}stream.write(`${CLEAR_SCREEN}${held.join("")}`),await sleep(interval)}return code}init_user_config();import{basename,dirname as dirname5,join as join6,relative,sep}from"path";var PARENT=`..${sep}`;import process20 from"process";init_prompt();import{readdir,readFile,readlink}from"fs/promises";var LISTENING={tcp:"0A",udp:"07"},WHITESPACE=/\s+/,HEX_PAIR=/../g,SOCKET_LINK=/^socket:\[(\d+)\]$/,UNIT_SCOPE=/\.(?:service|scope)$/,CONTAINER_ID=/(?:docker-|libpod-|\/docker\/)([0-9a-f]{64})/,DOCKER_PORT=/:(\d+)(?:-(\d+))?->[\d-]+\/(tcp|udp)/;function word(hex){let bytes=(hex.match(HEX_PAIR)??[]).reverse().map((byte)=>Number.parseInt(byte,16));return[bytes[0]<<8|bytes[1],bytes[2]<<8|bytes[3]]}function parseAddress(hex){if(hex.length===8){let[high,low]=word(hex);return`${high>>8}.${high&255}.${low>>8}.${low&255}`}let hextets=(hex.match(/.{8}/g)??[]).flatMap(word);if(hextets.length!==8)return hex;if(hextets.slice(0,5).every((part)=>part===0)&&hextets[5]===65535)return`::ffff:${hextets[6]>>8}.${hextets[6]&255}.${hextets[7]>>8}.${hextets[7]&255}`;return compress(hextets)}function compress(hextets){let best={start:-1,length:0},run={start:0,length:0};for(let[at,part]of hextets.entries())if(run=part===0?{start:run.length===0?at:run.start,length:run.length+1}:{start:0,length:0},run.length>best.length)best=run;let text=(parts)=>parts.map((part)=>part.toString(16)).join(":");if(best.length<2)return text(hextets);return`${text(hextets.slice(0,best.start))}::${text(hextets.slice(best.start+best.length))}`}function parseNetTable(text,protocol,family){let sockets=[];for(let line of text.split(`
|
|
78
|
+
`).slice(1)){let columns=line.trim().split(WHITESPACE),[address="",port=""]=(columns[1]??"").split(":");if(columns.length<10||columns[3]!==LISTENING[protocol])continue;let number=Number.parseInt(port,16);if(number===0||Number.isNaN(number))continue;sockets.push({protocol,family,address:parseAddress(address),port:number,uid:Number(columns[7]),inode:Number(columns[9])})}return sockets}function socketInode(link){let match=SOCKET_LINK.exec(link);return match===null?void 0:Number(match[1])}function parseStat(text){let open=text.indexOf("("),close=text.lastIndexOf(")");if(open===-1||close<open)return;let rest=text.slice(close+2).trim().split(WHITESPACE),field=(number)=>Number(rest[number-3]);if(rest.length<20)return;return{comm:text.slice(open+1,close),state:rest[0],ppid:field(4),pgrp:field(5),session:field(6),tty:field(7),threads:field(20),startTicks:field(22)}}function parseStatus(text){let fields=new Map;for(let line of text.split(`
|
|
79
|
+
`)){let colon=line.indexOf(":");if(colon>0)fields.set(line.slice(0,colon),line.slice(colon+1).trim())}return fields}function statusBytes(fields,key){let value=Number.parseInt(fields.get(key)??"",10);return Number.isNaN(value)?void 0:value*1024}function statusUid(fields){let value=Number.parseInt(fields.get("Uid")??"",10);return Number.isNaN(value)?void 0:value}var LIMIT_LINE=/^(\S+(?: \S+)*)\s{2,}(\S+)\s+(\S+)(?:\s+(\S+))?\s*$/;function parseLimits(text){let limits=[];for(let line of text.split(`
|
|
80
|
+
`).slice(1)){let match=LIMIT_LINE.exec(line);if(match!==null)limits.push({name:match[1],soft:match[2],hard:match[3],units:match[4]??""})}return limits}function parseCmdline(text){return text.split("\x00").filter((_,at,parts)=>at<parts.length-1||parts[at]!=="")}function parseEnviron(text){return parseCmdline(text).map((entry)=>{let equals=entry.indexOf("=");return equals===-1?[entry,""]:[entry.slice(0,equals),entry.slice(equals+1)]})}function parseCgroup(text){return text.split(`
|
|
81
|
+
`).filter((line)=>line!=="").map((line)=>{let[hierarchy="",controllers="",...path]=line.split(":");return{hierarchy,controllers,path:path.join(":")}})}function cgroupUnit(entries){return((entries.find((entry)=>entry.hierarchy==="0")??entries[0])?.path??"").split("/").reverse().find((part)=>UNIT_SCOPE.test(part))}function cgroupContainer(entries){for(let{path}of entries){let match=CONTAINER_ID.exec(path);if(match!==null)return match[1]}return}function userNameOf(passwd,uid){for(let line of passwd.split(`
|
|
82
|
+
`)){let[name,,id]=line.split(":");if(id===String(uid)&&name!==void 0&&name!=="")return name}return}function parseDockerPs(text){let containers=[];for(let line of text.split(`
|
|
83
|
+
`)){let[name="",ports="",project="",service=""]=line.split("\t");if(name==="")continue;let published=[];for(let entry of ports.split(",")){let match=DOCKER_PORT.exec(entry);if(match===null)continue;let first=Number(match[1]);for(let host=first;host<=Number(match[2]??first);host++)published.push({host,protocol:match[3]})}containers.push({name,project:project===""?void 0:project,service:service===""?void 0:service,published})}return containers}var CLOCK_TICKS=100;async function text2(path){try{return await readFile(path,"utf8")}catch{return}}async function link(path){try{return await readlink(path)}catch{return}}var DIGITS=/^\d+$/,BOOT_TIME=/^btime\s+(\d+)/m;async function listPids(root="/proc"){return(await readdir(root)).filter((name)=>DIGITS.test(name)).map(Number)}async function bootMs(root="/proc"){let match=BOOT_TIME.exec(await text2(`${root}/stat`)??"");return match===null?Date.now():Number(match[1])*1000}async function mapBounded(items,limit,fn){let results=Array.from({length:items.length}),cursor=0;async function worker(){while(cursor<items.length){let idx=cursor++;results[idx]=await fn(items[idx])}}return await Promise.all(Array.from({length:Math.min(limit,items.length)},worker)),results}var PROC_CONCURRENCY=32;async function readDetail(pid,root){let dir=`${root}/${pid}`,[cwd,exe,cgroup]=await Promise.all([link(`${dir}/cwd`),link(`${dir}/exe`),text2(`${dir}/cgroup`)]),groups=parseCgroup(cgroup??"");return{cwd,exe,unit:cgroupUnit(groups),container:cgroupContainer(groups)}}async function readProc(pid,boot,{root="/proc",detail=!0}={}){let dir=`${root}/${pid}`,[statText,statusText,cmdline]=await Promise.all([text2(`${dir}/stat`),text2(`${dir}/status`),text2(`${dir}/cmdline`)]),stat=statText===void 0?void 0:parseStat(statText);if(stat===void 0||statusText===void 0)return;let status=parseStatus(statusText),info={pid,ppid:stat.ppid,comm:stat.comm,args:parseCmdline(cmdline??""),uid:statusUid(status)??-1,state:stat.state,session:stat.session,rss:statusBytes(status,"VmRSS")??0,startMs:boot+stat.startTicks/CLOCK_TICKS*1000};return detail?{...info,...await readDetail(pid,root)}:info}async function snapshot(root="/proc",detailed=()=>!0){let[boot,pids]=await Promise.all([bootMs(root),listPids(root)]);return(await mapBounded(pids,PROC_CONCURRENCY,async(pid)=>{let light=await readProc(pid,boot,{root,detail:!1});if(light===void 0)return;return detailed(light.uid)?{...light,...await readDetail(pid,root)}:light})).filter((entry)=>entry!==void 0)}function ancestry(pid,byPid){let chain=[],at=pid;while(at!==void 0&&at>0&&!chain.includes(at))chain.push(at),at=byPid.get(at)?.ppid;return chain}async function readSockets(root="/proc"){let tables=[["tcp","tcp",4],["tcp6","tcp",6],["udp","udp",4],["udp6","udp",6]],sockets=[];for(let[file,protocol,family]of tables)sockets.push(...parseNetTable(await text2(`${root}/net/${file}`)??"",protocol,family));return sockets}async function socketsOf(pid,root="/proc"){let inodes=new Set;try{for(let fd of await readdir(`${root}/${pid}/fd`)){let inode=socketInode(await link(`${root}/${pid}/fd/${fd}`)??"");if(inode!==void 0)inodes.add(inode)}}catch{}return inodes}async function socketOwners(root="/proc"){let pids=await listPids(root),perPid=await mapBounded(pids,PROC_CONCURRENCY,async(pid)=>({pid,inodes:await socketsOf(pid,root)})),holders=new Map;for(let{pid,inodes}of perPid)for(let inode of inodes)holders.set(inode,[...holders.get(inode)??[],pid]);let owners=new Map,parents=new Map;for(let[inode,pids]of holders){let[first=0]=pids;if(pids.length>1){for(let pid of pids)if(!parents.has(pid))parents.set(pid,parseStat(await text2(`${root}/${pid}/stat`)??"")?.ppid)}owners.set(inode,pids.find((pid)=>!pids.includes(parents.get(pid)??-1))??first)}return owners}async function fdCount(pid,root="/proc"){try{return(await readdir(`${root}/${pid}/fd`)).length}catch{return}}var passwd;async function userName(uid){return passwd??=await text2("/etc/passwd")??"",userNameOf(passwd,uid)}var SHELLS2=new Set(["sh","bash","zsh","fish","dash","ash","nu","tcsh","ksh","elvish","xonsh"]),TERMINALS=new Set(["kitty","alacritty","konsole","wezterm-gui","foot","footclient","xterm","gnome-terminal-","ghostty","tmux: server","tmux","screen","terminator","tilix","urxvt","st","yakuake","ptyxis"]);function protectionOf(proc,{uid,mine}){if(proc.pid===1)return"pid 1";if(proc.uid!==uid)return"another user's process";if(mine.has(proc.pid))return"this command or one of its ancestors";if(SHELLS2.has(proc.comm))return"a shell";return TERMINALS.has(proc.comm)?"a terminal":void 0}var realSignaller={send(pid,signal){try{return process.kill(pid,signal),!0}catch{return!1}},async alive(pid){let stat=await text2(`/proc/${pid}/stat`);return stat!==void 0&&!stat.slice(stat.lastIndexOf(")")+2).startsWith("Z")},sleep:async(ms)=>Bun.sleep(ms)},POLL_MS=100;async function waitGone(pids,graceMs,signaller){let alive=pids,waited=0;while(alive.length>0&&waited<graceMs)await signaller.sleep(POLL_MS),waited+=POLL_MS,alive=await filterAlive(alive,signaller);return alive}async function filterAlive(pids,signaller){let alive=[];for(let pid of pids)if(await signaller.alive(pid))alive.push(pid);return alive}async function terminate(pids,{escalate,graceMs,signaller=realSignaller}){let failed=pids.filter((pid)=>!signaller.send(pid,"SIGTERM")),refused=await filterAlive(failed,signaller),sent=pids.filter((pid)=>!failed.includes(pid)),remaining=await waitGone(sent,graceMs,signaller),terminated=pids.filter((pid)=>failed.includes(pid)?!refused.includes(pid):!remaining.includes(pid));if(!escalate||remaining.length===0)return{terminated,killed:[],survived:[...refused,...remaining]};for(let pid of remaining)signaller.send(pid,"SIGKILL");let stuck=await waitGone(remaining,2000,signaller);return{terminated,killed:remaining.filter((pid)=>!stuck.includes(pid)),survived:[...refused,...stuck]}}import{basename as basename2}from"path";var MASK="***",URL_PASSWORD=/(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi,TOKEN=/\b(?:gh[pousr]_|github_pat_|glpat-|sk-|xox[abprs]-|npm_|[sr]k_(?:live|test)_)[\w-]{10,}|\beyJ[\w-]+\.[\w-]+\.[\w-]+|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bBearer\s+[\w.~+/=-]{16,}/g,OPAQUE=/(?<![\w-])(?=[\w-]{32,}(?![\w-]))(?=[\w-]*[A-Z])(?=[\w-]*\d)[\w-]+/gi,PEM=/-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*/;function maskText(value){return value.replace(PEM,MASK).replace(URL_PASSWORD,`$1${MASK}@`).replace(TOKEN,MASK).replace(OPAQUE,MASK)}function maskValue(name,value){if(value==="")return value;return isSecretName(name)?MASK:maskText(value)}function maskEnviron(entries){return entries.map(([name,value])=>[name,maskValue(name,value)])}var FLAG=/^-{1,2}([\w.-]+)(=|$)/,ASSIGNMENT_NAME=/^[\w.-]+$/,PASSWORD_SPLIT=new Set(["sshpass"]),PASSWORD_JOINED=new Set(["mysql","mysqldump","mysqladmin","mariadb","mariadb-dump"]);function maskArgs(args){let command=basename2(args[0]??""),hidden=!1;return args.map((arg,index)=>{if(hidden)return hidden=!1,arg.startsWith("-")?maskText(arg):MASK;if(index>0&&arg==="-p"&&PASSWORD_SPLIT.has(command))return hidden=!0,arg;if(index>0&&arg.length>2&&arg.startsWith("-p")&&PASSWORD_JOINED.has(command))return`-p${MASK}`;let flag=FLAG.exec(arg);if(flag!==null){if(flag[2]==="=")return isSecretName(flag[1])?`${arg.slice(0,flag[0].length)}${MASK}`:maskText(arg);return hidden=isSecretName(flag[1]),arg}let equals=arg.indexOf("=");return equals>0&&ASSIGNMENT_NAME.test(arg.slice(0,equals))?`${arg.slice(0,equals+1)}${maskValue(arg.slice(0,equals),arg.slice(equals+1))}`:maskText(arg)})}var DIGITS2=/^\d+$/;function commandOf(proc){return maskArgs(proc.args).join(" ")||`[${proc.comm}]`}var LS_USAGE="proc ls [pattern]: lists processes matching an optional pattern (substring or regex) on command, comm or cwd",LS_EXITS=[[0,"listed matching processes"],[1,"no process matched"],[2,"a usage error"]],LS_OPTIONS={all:{type:"boolean",short:"a",description:"include processes of other users (default: calling user only)"},sort:{type:"string",short:"s",choices:["rss","pid","age"],description:"sort order: rss (default), pid, or age"},limit:{type:"string",short:"n",description:"maximum rows to print (50)"},json:jsonOption("[{pid, ppid, comm, command, cwd, rss, ageSeconds}]")};async function lsCmd(args){let{values,positionals}=parse(args,LS_USAGE,LS_OPTIONS,{exits:LS_EXITS,positionals:["[pattern]"],examples:["proc ls","proc ls vite","proc find bun --sort age"]}),[pattern]=positionals,regex;if(pattern!==void 0)try{regex=new RegExp(pattern,"i")}catch(error){badUsage(`invalid pattern: ${error instanceof Error?error.message:String(error)}`)}let uid=process20.getuid?.()??-1,all=await snapshot("/proc",(owner)=>values.all===!0||owner===uid),now=Date.now(),filtered=all.filter((proc)=>(values.all===!0||proc.uid===uid)&&proc.pid!==process20.pid).filter((proc)=>{if(regex===void 0)return!0;return regex.test(commandOf(proc))||regex.test(proc.comm)||proc.cwd!==void 0&®ex.test(proc.cwd)}),sortBy=values.sort??"rss";if(filtered.sort((a,b)=>{if(sortBy==="pid")return a.pid-b.pid;return sortBy==="age"?a.startMs-b.startMs:b.rss-a.rss||a.pid-b.pid}),pattern!==void 0&&filtered.length===0){if(values.json===!0)printJson([]);else problem(`no process matched ${pattern}`);return 1}let limit=wholeNumber(values.limit,"limit",50,1),shown=filtered.slice(0,limit);if(values.json===!0)return printJson(shown.map((proc)=>({pid:proc.pid,ppid:proc.ppid,comm:proc.comm,command:commandOf(proc),cwd:proc.cwd,rss:proc.rss,ageSeconds:Math.max(0,Math.round((now-proc.startMs)/1000))}))),0;let colors=paint(process20.stdout);return console.log(table([["PID","PPID","RSS","AGE","COMMAND","CWD"],...shown.map((proc)=>[colors.cyan(String(proc.pid)),colors.dim(String(proc.ppid)),tt(proc.rss),formatSeconds(Math.max(0,(now-proc.startMs)/1000)),truncate(commandOf(proc),60),colors.dim(proc.cwd??"-")])],{header:!0,align:["right","right","right","right","left","left"]})),0}var TREE_USAGE="proc tree [pid]: prints the process hierarchy rooted at pid (or the calling user's top-level processes)",TREE_EXITS=[[0,"printed process tree"],[1,"no process has this pid"],[2,"a usage error"]],TREE_OPTIONS={all:{type:"boolean",short:"a",description:"include processes of all users when no pid is given"},json:jsonOption("[{pid, ppid, comm, command, rss, children: [...]}]")};async function treeCmd(args){let{values,positionals}=parse(args,TREE_USAGE,TREE_OPTIONS,{exits:TREE_EXITS,positionals:["[pid]"],examples:["proc tree","proc tree 1234"]}),[given]=positionals;if(given!==void 0&&!DIGITS2.test(given))fail(`the pid takes a number, not ${given}`,2);let uid=process20.getuid?.()??-1,all=await snapshot("/proc",(owner)=>owner===uid),byPid=new Map(all.map((proc)=>[proc.pid,proc])),childrenByPid=new Map;for(let proc of all)childrenByPid.set(proc.ppid,[...childrenByPid.get(proc.ppid)??[],proc]);for(let list of childrenByPid.values())list.sort((a,b)=>a.pid-b.pid);let build=(proc,seen=new Set)=>(seen.add(proc.pid),{pid:proc.pid,ppid:proc.ppid,comm:proc.comm,command:commandOf(proc),rss:proc.rss,children:(childrenByPid.get(proc.pid)??[]).filter((child)=>!seen.has(child.pid)).map((child)=>build(child,seen))}),roots;if(given!==void 0){let rootProc=byPid.get(Number(given));if(rootProc===void 0)return fail(`no process with pid ${given}`,1);roots=[build(rootProc)]}else{let visible=all.filter((proc)=>values.all===!0||proc.uid===uid),visiblePids=new Set(visible.map((proc)=>proc.pid));roots=visible.filter((proc)=>!visiblePids.has(proc.ppid)).sort((a,b)=>a.pid-b.pid).map((proc)=>build(proc))}if(values.json===!0)return printJson(roots),0;let colors=paint(process20.stdout),renderNode=(node,prefix,isLast,isRoot)=>{let branch="";if(!isRoot)branch=isLast?"\u2514\u2500 ":"\u251C\u2500 ";console.log(`${prefix}${branch}${colors.cyan(String(node.pid))} ${node.comm} ${colors.dim(tt(node.rss))} ${colors.dim(truncate(node.command,70))}`);let nextPrefix=isRoot?"":`${prefix}${isLast?" ":"\u2502 "}`;for(let[idx,child]of node.children.entries())renderNode(child,nextPrefix,idx===node.children.length-1,!1)};for(let root of roots)renderNode(root,"",!0,!0);return 0}var TOP_USAGE="proc top [options]: shows the heaviest processes by resident memory, open file descriptors, or age",TOP_EXITS=[[0,"listed top processes"],[2,"a usage error"]],TOP_OPTIONS2={by:{type:"string",choices:["rss","fds","age"],description:"rank by: rss (default), fds, or age"},limit:{type:"string",short:"n",description:"how many processes to show (15)"},all:{type:"boolean",short:"a",description:"include processes of other users"},watch:watchOption("top processes"),json:jsonOption("[{pid, comm, command, rss, fds, ageSeconds, cwd}]")};async function topCmd(args){let{values}=parse(args,TOP_USAGE,TOP_OPTIONS2,{exits:TOP_EXITS,examples:["proc top","proc top --by fds -n 10","proc top --watch 2s"]});if(values.watch!==void 0)return watching(values.watch,async()=>topCmd(withoutWatch(args)));let uid=process20.getuid?.()??-1,by=values.by??"rss",limit=wholeNumber(values.limit,"limit",15,1),now=Date.now(),procs=(await snapshot("/proc",(owner)=>owner===uid)).filter((proc)=>values.all===!0||proc.uid===uid),rows=await Promise.all(procs.map(async(proc)=>({pid:proc.pid,comm:proc.comm,command:commandOf(proc),rss:proc.rss,fds:by==="fds"?await fdCount(proc.pid)??0:void 0,ageSeconds:Math.max(0,Math.round((now-proc.startMs)/1000)),cwd:proc.cwd})));rows.sort((a,b)=>{if(by==="fds")return(b.fds??0)-(a.fds??0)||b.rss-a.rss;return by==="age"?b.ageSeconds-a.ageSeconds||b.rss-a.rss:b.rss-a.rss||a.pid-b.pid});let shown=rows.slice(0,limit);if(values.json===!0)return printJson(shown),0;let colors=paint(process20.stdout);return console.log(table([by==="fds"?["PID","FDS","RSS","AGE","COMMAND"]:["PID","RSS","AGE","COMMAND"],...shown.map((row)=>by==="fds"?[colors.cyan(String(row.pid)),String(row.fds??0),tt(row.rss),formatSeconds(row.ageSeconds),truncate(row.command,70)]:[colors.cyan(String(row.pid)),tt(row.rss),formatSeconds(row.ageSeconds),truncate(row.command,70)])],{header:!0,align:by==="fds"?["right","right","right","right","left"]:["right","right","right","left"]})),0}var KILL_USAGE="proc kill <pid>...: safely stops one or more processes owned by the calling user (SIGTERM, with --force escalating to SIGKILL)",KILL_EXITS=[[0,"stopped every target process"],[1,"a pid was missing, refused, or survived"],[2,"a usage error"]],KILL_OPTIONS={force:{type:"boolean",short:"f",description:"escalate to SIGKILL if SIGTERM does not stop the process within --grace"},yes:{type:"boolean",short:"y",description:"do not ask for confirmation on a terminal"},grace:{type:"string",description:"time SIGTERM gets before SIGKILL with --force (5s)"},json:jsonOption("{terminated: number[], killed: number[], survived: number[]}")};async function killCmd(args){let{values,positionals}=parse(args,KILL_USAGE,KILL_OPTIONS,{exits:KILL_EXITS,positionals:["<pid>..."],examples:["proc kill 4242 --yes","proc kill 4242 4243 --force --yes"]}),pids=positionals.map((given)=>{if(!DIGITS2.test(given))badUsage(`the pid takes a number, not ${given}`);return Number(given)}),uid=process20.getuid?.()??-1,all=await snapshot("/proc",(owner)=>owner===uid),byPid=new Map(all.map((proc)=>[proc.pid,proc])),guard={uid,mine:new Set(ancestry(process20.pid,byPid))},allowed=[],refused=!1;for(let pid of new Set(pids)){let proc=byPid.get(pid);if(proc===void 0){problem(`no process with pid ${pid}`),refused=!0;continue}let reason=protectionOf(proc,guard);if(reason!==void 0){problem(`pid ${pid} is ${reason}`),refused=!0;continue}allowed.push(proc)}if(allowed.length===0)return 1;let names=allowed.map((proc)=>`${proc.pid} (${truncate(commandOf(proc),40)})`).join(", ");if(values.yes!==!0){if(!process20.stdin.isTTY)fail(`stopping ${names} needs a terminal to ask on: pass --yes`,2);if(await confirm(`Stop ${names}?`,{default:!1,hint:"pass --yes to stop without asking"})!==!0)return 1}let outcome=await terminate(allowed.map((proc)=>proc.pid),{escalate:values.force===!0,graceMs:duration(values.grace,"grace",5000)});if(values.json===!0)printJson(outcome);else{for(let pid of[...outcome.terminated,...outcome.killed])console.log(`stopped ${pid}${outcome.killed.includes(pid)?" (SIGKILL)":""}`);for(let pid of outcome.survived)problem(`${pid} is still running${values.force===!0?"":", pass --force to SIGKILL it"}`)}return refused||outcome.survived.length>0?1:0}import process21 from"process";var usage2=`proc pid <pid>: shows what a process is, from its executable and command line to its parent chain, memory, open files, listening ports and cgroup
|
|
2223
84
|
|
|
2224
85
|
Everything is read from \`/proc\`; what the calling user cannot read of another user's process is left out and named at the end.
|
|
2225
|
-
The environment is not shown unless --env is given, with every secret masked
|
|
2226
|
-
var EXITS = [[0, "it showed the process"], [1, "no process has this pid"], [2, "a usage error"]];
|
|
2227
|
-
var DIGITS2 = /^\d+$/;
|
|
2228
|
-
var options = {
|
|
2229
|
-
env: { type: "boolean", description: "show the environment, secrets masked" },
|
|
2230
|
-
json: jsonOption("everything, with the environment under env when --env is given")
|
|
2231
|
-
};
|
|
2232
|
-
async function parentsOf(proc, boot) {
|
|
2233
|
-
const parents = [];
|
|
2234
|
-
const seen = new Set([proc.pid]);
|
|
2235
|
-
let at = proc.ppid;
|
|
2236
|
-
while (at > 0 && !seen.has(at)) {
|
|
2237
|
-
seen.add(at);
|
|
2238
|
-
const parent = await readProc(at, boot, { detail: false });
|
|
2239
|
-
if (parent === undefined)
|
|
2240
|
-
break;
|
|
2241
|
-
parents.push({ pid: parent.pid, comm: parent.comm, command: maskArgs(parent.args).join(" ") });
|
|
2242
|
-
at = parent.ppid;
|
|
2243
|
-
}
|
|
2244
|
-
return parents;
|
|
2245
|
-
}
|
|
2246
|
-
async function report2(pid, showEnv) {
|
|
2247
|
-
const boot = await bootMs();
|
|
2248
|
-
const proc = await readProc(pid, boot);
|
|
2249
|
-
if (proc === undefined)
|
|
2250
|
-
return;
|
|
2251
|
-
const unreadable = [];
|
|
2252
|
-
const status = parseStatus(await text2(`/proc/${pid}/status`) ?? "");
|
|
2253
|
-
const limitsText = await text2(`/proc/${pid}/limits`);
|
|
2254
|
-
const sockets = await socketsOf(pid);
|
|
2255
|
-
const listening = sockets.size === 0 ? [] : (await readSockets()).filter((socket) => sockets.has(socket.inode));
|
|
2256
|
-
const environText = showEnv ? await text2(`/proc/${pid}/environ`) : undefined;
|
|
2257
|
-
const cgroup = parseCgroup(await text2(`/proc/${pid}/cgroup`) ?? "")[0]?.path;
|
|
2258
|
-
const files = await fdCount(pid);
|
|
2259
|
-
const stat = parseStat(await text2(`/proc/${pid}/stat`) ?? "");
|
|
2260
|
-
const uid = proc.uid;
|
|
2261
|
-
if (proc.exe === undefined)
|
|
2262
|
-
unreadable.push("executable");
|
|
2263
|
-
if (proc.cwd === undefined)
|
|
2264
|
-
unreadable.push("working directory");
|
|
2265
|
-
if (files === undefined)
|
|
2266
|
-
unreadable.push("open files");
|
|
2267
|
-
if (limitsText === undefined)
|
|
2268
|
-
unreadable.push("limits");
|
|
2269
|
-
if (showEnv && environText === undefined)
|
|
2270
|
-
unreadable.push("environment");
|
|
2271
|
-
return {
|
|
2272
|
-
pid,
|
|
2273
|
-
comm: proc.comm,
|
|
2274
|
-
state: proc.state,
|
|
2275
|
-
exe: proc.exe,
|
|
2276
|
-
cwd: proc.cwd,
|
|
2277
|
-
command: maskArgs(proc.args),
|
|
2278
|
-
parents: await parentsOf(proc, boot),
|
|
2279
|
-
user: { uid, name: await userName(uid) },
|
|
2280
|
-
startedAt: new Date(proc.startMs).toISOString(),
|
|
2281
|
-
ageSeconds: Math.max(0, (Date.now() - proc.startMs) / 1000),
|
|
2282
|
-
threads: stat?.threads,
|
|
2283
|
-
memory: { rss: statusBytes(status, "VmRSS"), peak: statusBytes(status, "VmHWM"), virtual: statusBytes(status, "VmSize"), swap: statusBytes(status, "VmSwap") },
|
|
2284
|
-
openFiles: files,
|
|
2285
|
-
limits: parseLimits(limitsText ?? ""),
|
|
2286
|
-
listening: listening.map(({ protocol, address, port }) => ({ protocol, address, port })),
|
|
2287
|
-
cgroup: cgroup === "" ? undefined : cgroup,
|
|
2288
|
-
container: proc.container,
|
|
2289
|
-
env: environText === undefined ? undefined : maskEnviron(parseEnviron(environText)).map(([name, value]) => ({ name, value })),
|
|
2290
|
-
unreadable
|
|
2291
|
-
};
|
|
2292
|
-
}
|
|
2293
|
-
function limitLine(limits, name) {
|
|
2294
|
-
const limit = limits.find((candidate) => candidate.name === name);
|
|
2295
|
-
return limit === undefined ? "-" : `soft ${limit.soft}, hard ${limit.hard}`;
|
|
2296
|
-
}
|
|
2297
|
-
function render(info, showEnv) {
|
|
2298
|
-
const colors = paint(process18.stdout);
|
|
2299
|
-
const memory = info.memory;
|
|
2300
|
-
const size = (bytes) => bytes === undefined ? "-" : tt(bytes);
|
|
2301
|
-
const rows = [
|
|
2302
|
-
["Executable", info.exe ?? "-"],
|
|
2303
|
-
["Directory", info.cwd ?? "-"],
|
|
2304
|
-
["Command", info.command.join(" ") || `[${info.comm}]`],
|
|
2305
|
-
["Parents", info.parents.length === 0 ? "none (init)" : info.parents.map((parent) => `${parent.pid} ${parent.comm}`).join(" < ")],
|
|
2306
|
-
["User", `${info.user.name ?? "?"} (${info.user.uid})`],
|
|
2307
|
-
["State", info.state],
|
|
2308
|
-
["Started", `${info.startedAt} (${formatSeconds(info.ageSeconds)} ago)`],
|
|
2309
|
-
["Memory", `rss ${size(memory.rss)}, peak ${size(memory.peak)}, virtual ${size(memory.virtual)}, swap ${size(memory.swap)}`],
|
|
2310
|
-
["Open files", `${info.openFiles ?? "-"} (limit ${limitLine(info.limits, "Max open files")})`],
|
|
2311
|
-
["Processes", `${info.threads ?? "-"} threads (limit ${limitLine(info.limits, "Max processes")})`],
|
|
2312
|
-
["Listening", info.listening.length === 0 ? "nothing" : info.listening.map(({ protocol, address, port }) => `${protocol} ${address.includes(":") ? `[${address}]` : address}:${port}`).join(", ")]
|
|
2313
|
-
];
|
|
2314
|
-
if (info.cgroup !== undefined)
|
|
2315
|
-
rows.push(["Cgroup", info.cgroup]);
|
|
2316
|
-
const lines = [colors.bold(`pid ${info.pid} ${info.comm}`), ...rows.map(([label, value]) => `${colors.dim(label.padEnd(11))} ${value}`)];
|
|
2317
|
-
if (showEnv && info.env !== undefined)
|
|
2318
|
-
lines.push("", colors.bold("Environment"), ...info.env.map(({ name, value }) => `${name}=${value}`));
|
|
2319
|
-
else if (!showEnv)
|
|
2320
|
-
lines.push("", colors.dim("Environment hidden, pass --env to show it with secrets masked"));
|
|
2321
|
-
if (info.unreadable.length > 0)
|
|
2322
|
-
lines.push("", colors.yellow(`Could not read: ${info.unreadable.join(", ")} (a process of another user: rerun as that user)`));
|
|
2323
|
-
return lines.join(`
|
|
2324
|
-
`);
|
|
2325
|
-
}
|
|
2326
|
-
async function pid(args) {
|
|
2327
|
-
const { values, positionals } = parse(args, usage2, options, {
|
|
2328
|
-
exits: EXITS,
|
|
2329
|
-
positionals: ["<pid>"],
|
|
2330
|
-
replaces: "cat /proc/<pid>/{cmdline,environ,limits}, readlink /proc/<pid>/{exe,cwd}, the fish pid function",
|
|
2331
|
-
examples: [
|
|
2332
|
-
["proc pid 4242", "executable, directory, command, parents, memory, limits and ports"],
|
|
2333
|
-
["proc pid 4242 --env", "with the environment, secrets masked"],
|
|
2334
|
-
"proc pid 4242 --json"
|
|
2335
|
-
]
|
|
2336
|
-
});
|
|
2337
|
-
const [given] = positionals;
|
|
2338
|
-
if (!DIGITS2.test(given))
|
|
2339
|
-
fail(`the pid takes a number, not ${given}`, 2);
|
|
2340
|
-
const info = await report2(Number(given), values.env === true);
|
|
2341
|
-
if (info === undefined)
|
|
2342
|
-
return fail(`no process with pid ${given}`, 1);
|
|
2343
|
-
if (values.json === true)
|
|
2344
|
-
printJson(info);
|
|
2345
|
-
else
|
|
2346
|
-
console.log(render(info, values.env === true));
|
|
2347
|
-
return 0;
|
|
2348
|
-
}
|
|
2349
|
-
|
|
2350
|
-
// src/ports.ts
|
|
2351
|
-
import { basename as basename2 } from "path";
|
|
2352
|
-
import process21 from "process";
|
|
2353
|
-
init_prompt();
|
|
2354
|
-
|
|
2355
|
-
// src/docker.ts
|
|
2356
|
-
var FORMAT = '{{.Names}}\t{{.Ports}}\t{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.service"}}';
|
|
2357
|
-
async function dockerContainers() {
|
|
2358
|
-
if (Bun.which("docker") === null)
|
|
2359
|
-
return [];
|
|
2360
|
-
try {
|
|
2361
|
-
const ran = await runCommand(["docker", "ps", "--format", FORMAT], { timeoutMs: 4000 });
|
|
2362
|
-
return ran.code === 0 ? parseDockerPs(ran.text) : [];
|
|
2363
|
-
} catch {
|
|
2364
|
-
return [];
|
|
2365
|
-
}
|
|
2366
|
-
}
|
|
2367
|
-
|
|
2368
|
-
// src/kill.ts
|
|
2369
|
-
var SHELLS = new Set(["sh", "bash", "zsh", "fish", "dash", "ash", "nu", "tcsh", "ksh", "elvish", "xonsh"]);
|
|
2370
|
-
var TERMINALS = new Set(["kitty", "alacritty", "konsole", "wezterm-gui", "foot", "footclient", "xterm", "gnome-terminal-", "ghostty", "tmux: server", "tmux", "screen", "terminator", "tilix", "urxvt", "st", "yakuake", "ptyxis"]);
|
|
2371
|
-
function protectionOf(proc, { uid, mine }) {
|
|
2372
|
-
if (proc.pid === 1)
|
|
2373
|
-
return "pid 1";
|
|
2374
|
-
if (proc.uid !== uid)
|
|
2375
|
-
return "another user's process";
|
|
2376
|
-
if (mine.has(proc.pid))
|
|
2377
|
-
return "this command or one of its ancestors";
|
|
2378
|
-
if (SHELLS.has(proc.comm))
|
|
2379
|
-
return "a shell";
|
|
2380
|
-
return TERMINALS.has(proc.comm) ? "a terminal" : undefined;
|
|
2381
|
-
}
|
|
2382
|
-
var realSignaller = {
|
|
2383
|
-
send(pid, signal) {
|
|
2384
|
-
try {
|
|
2385
|
-
process.kill(pid, signal);
|
|
2386
|
-
return true;
|
|
2387
|
-
} catch {
|
|
2388
|
-
return false;
|
|
2389
|
-
}
|
|
2390
|
-
},
|
|
2391
|
-
async alive(pid) {
|
|
2392
|
-
const stat = await text2(`/proc/${pid}/stat`);
|
|
2393
|
-
return stat !== undefined && !stat.slice(stat.lastIndexOf(")") + 2).startsWith("Z");
|
|
2394
|
-
},
|
|
2395
|
-
sleep: async (ms) => Bun.sleep(ms)
|
|
2396
|
-
};
|
|
2397
|
-
var POLL_MS = 100;
|
|
2398
|
-
async function waitGone(pids, graceMs, signaller) {
|
|
2399
|
-
let alive = pids;
|
|
2400
|
-
let waited = 0;
|
|
2401
|
-
while (alive.length > 0 && waited < graceMs) {
|
|
2402
|
-
await signaller.sleep(POLL_MS);
|
|
2403
|
-
waited += POLL_MS;
|
|
2404
|
-
alive = await filterAlive(alive, signaller);
|
|
2405
|
-
}
|
|
2406
|
-
return alive;
|
|
2407
|
-
}
|
|
2408
|
-
async function filterAlive(pids, signaller) {
|
|
2409
|
-
const alive = [];
|
|
2410
|
-
for (const pid of pids) {
|
|
2411
|
-
if (await signaller.alive(pid))
|
|
2412
|
-
alive.push(pid);
|
|
2413
|
-
}
|
|
2414
|
-
return alive;
|
|
2415
|
-
}
|
|
2416
|
-
async function terminate(pids, { escalate, graceMs, signaller = realSignaller }) {
|
|
2417
|
-
const failed = pids.filter((pid) => !signaller.send(pid, "SIGTERM"));
|
|
2418
|
-
const refused = await filterAlive(failed, signaller);
|
|
2419
|
-
const sent = pids.filter((pid) => !failed.includes(pid));
|
|
2420
|
-
const remaining = await waitGone(sent, graceMs, signaller);
|
|
2421
|
-
const terminated = pids.filter((pid) => failed.includes(pid) ? !refused.includes(pid) : !remaining.includes(pid));
|
|
2422
|
-
if (!escalate || remaining.length === 0)
|
|
2423
|
-
return { terminated, killed: [], survived: [...refused, ...remaining] };
|
|
2424
|
-
for (const pid of remaining)
|
|
2425
|
-
signaller.send(pid, "SIGKILL");
|
|
2426
|
-
const stuck = await waitGone(remaining, 2000, signaller);
|
|
2427
|
-
return { terminated, killed: remaining.filter((pid) => !stuck.includes(pid)), survived: [...refused, ...stuck] };
|
|
2428
|
-
}
|
|
2429
|
-
|
|
2430
|
-
// src/ports.ts
|
|
2431
|
-
var usage3 = `proc ports [port]: lists what listens on this machine, one row per port with its owning process, command and working directory
|
|
2432
|
-
|
|
2433
|
-
A port Docker publishes shows as its compose project and service; the owner of another user's socket shows as -. \`proc ports <port>\` keeps that port alone and exits 1 when nothing listens on it.
|
|
2434
|
-
\`proc ports <port> --kill\` stops its owner, after asking on a terminal unless --yes is given. It refuses processes of other users, pid 1, this command and its ancestors, and docker-proxy, for which it names the container to stop instead.`;
|
|
2435
|
-
var EXITS2 = [[0, "it listed or stopped"], [1, "nothing listens on the given port or the owner could not be stopped"], [2, "a usage error"]];
|
|
2436
|
-
var options2 = {
|
|
2437
|
-
json: jsonOption("[{ port, protocol, addresses, pid, command, cwd, container }]"),
|
|
2438
|
-
kill: { type: "boolean", conflicts: ["watch"], description: "stop the owner of the given port" },
|
|
2439
|
-
watch: watchOption("the ports"),
|
|
2440
|
-
force: { type: "boolean", description: "with --kill, SIGKILL what SIGTERM did not stop within --grace" },
|
|
2441
|
-
yes: { type: "boolean", short: "y", description: "with --kill, do not ask first" },
|
|
2442
|
-
quiet: { type: "boolean", short: "q", description: "with --kill, print nothing about what was stopped" },
|
|
2443
|
-
grace: { type: "string", description: "with --force, how long SIGTERM gets before SIGKILL (5s)" }
|
|
2444
|
-
};
|
|
2445
|
-
function buildRows(sockets, owners, procs, containers) {
|
|
2446
|
-
const rows = new Map;
|
|
2447
|
-
for (const socket of sockets) {
|
|
2448
|
-
const pid = owners.get(socket.inode);
|
|
2449
|
-
const proc = pid === undefined ? undefined : procs.get(pid);
|
|
2450
|
-
const key = `${socket.protocol}/${socket.port}/${pid ?? "unknown"}`;
|
|
2451
|
-
const row = rows.get(key);
|
|
2452
|
-
if (row !== undefined) {
|
|
2453
|
-
if (!row.addresses.includes(socket.address))
|
|
2454
|
-
row.addresses.push(socket.address);
|
|
2455
|
-
continue;
|
|
2456
|
-
}
|
|
2457
|
-
const held = proc === undefined || proc.comm === "docker-proxy";
|
|
2458
|
-
const container = held ? containers.find((candidate) => candidate.published.some((port) => port.host === socket.port && port.protocol === socket.protocol)) : undefined;
|
|
2459
|
-
rows.set(key, {
|
|
2460
|
-
port: socket.port,
|
|
2461
|
-
protocol: socket.protocol,
|
|
2462
|
-
addresses: [socket.address],
|
|
2463
|
-
pid,
|
|
2464
|
-
command: proc === undefined ? undefined : maskArgs([basename2(proc.args[0] ?? proc.comm), ...proc.args.slice(1)]).join(" "),
|
|
2465
|
-
cwd: proc?.cwd,
|
|
2466
|
-
uid: proc?.uid ?? socket.uid,
|
|
2467
|
-
container: container === undefined ? undefined : { name: container.name, project: container.project, service: container.service }
|
|
2468
|
-
});
|
|
2469
|
-
}
|
|
2470
|
-
return [...rows.values()].sort((a, b) => a.port - b.port || a.protocol.localeCompare(b.protocol) || (a.pid ?? 0) - (b.pid ?? 0));
|
|
2471
|
-
}
|
|
2472
|
-
function containerLabel(container) {
|
|
2473
|
-
return container.project === undefined ? container.name : `${container.project}/${container.service ?? container.name}`;
|
|
2474
|
-
}
|
|
2475
|
-
function refusal(row, proc, guard) {
|
|
2476
|
-
if (row.container !== undefined && (proc === undefined || proc.comm === "docker-proxy"))
|
|
2477
|
-
return `published by the container ${row.container.name} (${containerLabel(row.container)}): stop it with \`docker stop ${row.container.name}\``;
|
|
2478
|
-
if (proc === undefined || row.pid === undefined)
|
|
2479
|
-
return "its owner is not readable (another user's process): rerun as that user";
|
|
2480
|
-
const reason = protectionOf(proc, guard);
|
|
2481
|
-
return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`;
|
|
2482
|
-
}
|
|
2483
|
-
function render2(rows) {
|
|
2484
|
-
const colors = paint(process21.stdout);
|
|
2485
|
-
const cells = rows.map((row) => [
|
|
2486
|
-
colors.cyan(String(row.port)),
|
|
2487
|
-
row.protocol,
|
|
2488
|
-
row.addresses.join(", "),
|
|
2489
|
-
row.pid === undefined ? "-" : String(row.pid),
|
|
2490
|
-
row.container === undefined ? truncate(row.command ?? "-", 60) : colors.yellow(`docker ${containerLabel(row.container)}`),
|
|
2491
|
-
colors.dim(row.cwd ?? "-")
|
|
2492
|
-
]);
|
|
2493
|
-
return table([["PORT", "PROTO", "ADDRESS", "PID", "COMMAND", "CWD"], ...cells], { header: true });
|
|
2494
|
-
}
|
|
2495
|
-
async function stop(port, rows, procs, values) {
|
|
2496
|
-
const guard = { uid: process21.getuid?.() ?? -1, mine: new Set(ancestry(process21.pid, procs)) };
|
|
2497
|
-
const targets = new Map;
|
|
2498
|
-
for (const row of rows) {
|
|
2499
|
-
const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard);
|
|
2500
|
-
if (reason !== undefined)
|
|
2501
|
-
problem(`port ${port}: ${reason}`);
|
|
2502
|
-
else if (row.pid !== undefined)
|
|
2503
|
-
targets.set(row.pid, row);
|
|
2504
|
-
}
|
|
2505
|
-
if (targets.size === 0)
|
|
2506
|
-
return 1;
|
|
2507
|
-
const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? "", 40)})`).join(", ");
|
|
2508
|
-
if (values.yes !== true) {
|
|
2509
|
-
if (!process21.stdin.isTTY)
|
|
2510
|
-
fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2);
|
|
2511
|
-
if (await confirm(`Stop ${names}?`, { default: false }) !== true)
|
|
2512
|
-
return 1;
|
|
2513
|
-
}
|
|
2514
|
-
const outcome = await terminate([...targets.keys()], { escalate: values.force === true, graceMs: duration(values.grace, "grace", 5000) });
|
|
2515
|
-
for (const pid of values.quiet === true ? [] : [...outcome.terminated, ...outcome.killed])
|
|
2516
|
-
console.log(`stopped ${pid}${outcome.killed.includes(pid) ? " (SIGKILL)" : ""}`);
|
|
2517
|
-
for (const pid of outcome.survived)
|
|
2518
|
-
problem(`${pid} is still running${values.force === true ? "" : ", pass --force to SIGKILL it"}`);
|
|
2519
|
-
return outcome.survived.length === 0 ? 0 : 1;
|
|
2520
|
-
}
|
|
2521
|
-
async function ports(args) {
|
|
2522
|
-
const { values, positionals } = parse(args, usage3, options2, {
|
|
2523
|
-
exits: EXITS2,
|
|
2524
|
-
positionals: ["[port]"],
|
|
2525
|
-
replaces: "ss -ltnp | grep, lsof -i, fuser -k and lookups of docker-proxy by hand",
|
|
2526
|
-
examples: [
|
|
2527
|
-
["proc ports", "every listening port with its owner"],
|
|
2528
|
-
["proc ports 3000", "who holds 3000, exit 1 when nobody does"],
|
|
2529
|
-
["proc ports 3000 --kill --yes", "stop it"],
|
|
2530
|
-
"proc ports --json"
|
|
2531
|
-
]
|
|
2532
|
-
});
|
|
2533
|
-
if (values.watch !== undefined)
|
|
2534
|
-
return watching(values.watch, async () => ports(withoutWatch(args)));
|
|
2535
|
-
const [given] = positionals;
|
|
2536
|
-
const port = given === undefined ? undefined : wholeNumber(given, "<port>", 0);
|
|
2537
|
-
if (port !== undefined && port > 65535)
|
|
2538
|
-
badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
|
|
2539
|
-
if (values.kill === true && port === undefined)
|
|
2540
|
-
badUsage("--kill takes the port to free: proc ports <port> --kill");
|
|
2541
|
-
const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process21.getuid?.())]);
|
|
2542
|
-
const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
|
|
2543
|
-
const wanted = sockets.filter((socket) => port === undefined || socket.port === port);
|
|
2544
|
-
const needsDocker = wanted.some((socket) => {
|
|
2545
|
-
const pid = owners.get(socket.inode);
|
|
2546
|
-
return pid === undefined || byPid.get(pid)?.comm === "docker-proxy";
|
|
2547
|
-
});
|
|
2548
|
-
const rows = buildRows(wanted, owners, byPid, needsDocker ? await dockerContainers() : []);
|
|
2549
|
-
if (port !== undefined && rows.length === 0) {
|
|
2550
|
-
problem(`nothing listens on port ${port}`);
|
|
2551
|
-
return 1;
|
|
2552
|
-
}
|
|
2553
|
-
if (values.kill === true && port !== undefined)
|
|
2554
|
-
return stop(port, rows, byPid, values);
|
|
2555
|
-
if (values.json === true) {
|
|
2556
|
-
printJson(rows);
|
|
2557
|
-
return 0;
|
|
2558
|
-
}
|
|
2559
|
-
console.log(render2(rows));
|
|
2560
|
-
const unknown = rows.filter((row) => row.pid === undefined && row.container === undefined).length;
|
|
2561
|
-
if (unknown > 0)
|
|
2562
|
-
console.error(paint(process21.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
|
|
2563
|
-
return 0;
|
|
2564
|
-
}
|
|
2565
|
-
|
|
2566
|
-
// src/procs.ts
|
|
2567
|
-
import { existsSync as existsSync3 } from "fs";
|
|
2568
|
-
import { homedir as homedir4 } from "os";
|
|
2569
|
-
import process22 from "process";
|
|
2570
|
-
|
|
2571
|
-
// src/select.ts
|
|
2572
|
-
import { basename as basename3, join as join6, relative } from "path";
|
|
2573
|
-
var BROWSERS = /^(?:chrom(?:e|ium)(?:-browser)?|google-chrome(?:-stable|-beta|-unstable)?|chrome_crashpad_handler|chrome-headless-shell|headless_shell|chromium-headless-shell|brave|brave-browser|msedge|microsoft-edge|webkitwebprocess|webkitnetworkprocess|webkitgpuprocess|minibrowser|webkitwebdriver|wpewebprocess|wpenetworkprocess|bun-webview.*)$/i;
|
|
2574
|
-
var NATIVE = new Set(["rust-analyzer", "gopls", "clangd", "lua-language-server", "pyright-langserver", "pylsp", "intelephense", "phpactor", "tsgo", "esbuild", "biome", "ruff", "phpunit", "pytest", "vitest", "jest"]);
|
|
2575
|
-
var RUNTIMES = new Set(["node", "bun", "bunx", "deno", "nodejs"]);
|
|
2576
|
-
var SCRIPTS = new Set(["vite", "vitest", "nuxt", "nuxi", "next", "jest", "playwright", "playwright-core", "tsserver", "typescript-language-server", "vue-language-server", "vtsls", "eslint_d", "esbuild", "webpack", "turbo", "astro", "tsgo", "svelte-kit", "remix", "storybook", "biome", "prettierd", "tailwindcss", "bun-webview"]);
|
|
2577
|
-
var EXTENSION = /\.[cm]?[jt]s$/;
|
|
2578
|
-
var MARKERS = ["package.json", "composer.json", "Cargo.toml", "go.mod", "pyproject.toml"];
|
|
2579
|
-
var AUTOMATION = /^--(?:headless|remote-debugging-(?:pipe|port)|enable-automation)/;
|
|
2580
|
-
var HEAVY_DEFAULT = 500 * 1024 ** 2;
|
|
2581
|
-
function toolOf(proc) {
|
|
2582
|
-
const names = [proc.exe, proc.args[0], proc.comm].filter((name) => name !== undefined && name !== "").map((name) => basename3(name));
|
|
2583
|
-
for (const name of names) {
|
|
2584
|
-
if (BROWSERS.test(name))
|
|
2585
|
-
return name.toLowerCase().startsWith("webkit") || name.toLowerCase().startsWith("wpe") || name.toLowerCase() === "minibrowser" ? "webkit" : "chromium";
|
|
2586
|
-
if (NATIVE.has(name))
|
|
2587
|
-
return name;
|
|
2588
|
-
}
|
|
2589
|
-
const runtime = names.find((name) => RUNTIMES.has(name));
|
|
2590
|
-
if (runtime === undefined)
|
|
2591
|
-
return;
|
|
2592
|
-
for (const arg of proc.args.slice(1)) {
|
|
2593
|
-
if (arg.startsWith("-"))
|
|
2594
|
-
continue;
|
|
2595
|
-
const script = basename3(arg).replace(EXTENSION, "");
|
|
2596
|
-
if (SCRIPTS.has(script))
|
|
2597
|
-
return script;
|
|
2598
|
-
}
|
|
2599
|
-
return runtime === "nodejs" ? "node" : runtime;
|
|
2600
|
-
}
|
|
2601
|
-
function userDataDir(args) {
|
|
2602
|
-
const arg = args.find((word) => word.startsWith("--user-data-dir="));
|
|
2603
|
-
return arg?.slice("--user-data-dir=".length);
|
|
2604
|
-
}
|
|
2605
|
-
function projectOf(cwd, exists, home) {
|
|
2606
|
-
if (cwd === undefined || !cwd.startsWith(`${home}/`))
|
|
2607
|
-
return;
|
|
2608
|
-
const folders = [];
|
|
2609
|
-
for (let dir = cwd;dir.startsWith(`${home}/`); dir = join6(dir, ".."))
|
|
2610
|
-
folders.push(dir);
|
|
2611
|
-
return folders.find((dir) => exists(join6(dir, ".git"))) ?? folders.find((dir) => MARKERS.some((marker) => exists(join6(dir, marker))));
|
|
2612
|
-
}
|
|
2613
|
-
function isOrphan(proc, byPid) {
|
|
2614
|
-
if (proc.unit?.endsWith(".service") === true)
|
|
2615
|
-
return false;
|
|
2616
|
-
const parent = byPid.get(proc.ppid);
|
|
2617
|
-
const userManager = parent !== undefined && parent.comm === "systemd" && parent.uid === proc.uid && parent.uid !== 0;
|
|
2618
|
-
const reparented = proc.ppid === 1 || userManager;
|
|
2619
|
-
const tool = toolOf(proc);
|
|
2620
|
-
if (!reparented || tool !== "chromium" && tool !== "webkit")
|
|
2621
|
-
return reparented;
|
|
2622
|
-
if (basename3(proc.exe ?? proc.args[0] ?? proc.comm).includes("crashpad"))
|
|
2623
|
-
return false;
|
|
2624
|
-
return proc.args.some((arg) => arg.startsWith("--type=")) || proc.args.some((arg) => AUTOMATION.test(arg));
|
|
2625
|
-
}
|
|
2626
|
-
function originOf(proc, tool, { exists, home }) {
|
|
2627
|
-
const profile = userDataDir(proc.args);
|
|
2628
|
-
if (profile !== undefined)
|
|
2629
|
-
return { key: `profile:${profile}`, origin: `${tool} profile ${profile}`, kind: "profile" };
|
|
2630
|
-
const project = projectOf(proc.cwd, exists, home);
|
|
2631
|
-
if (project !== undefined)
|
|
2632
|
-
return { key: `project:${project}`, origin: `~/${relative(home, project)}`, kind: "project" };
|
|
2633
|
-
return { key: `command:${tool}`, origin: tool, kind: "command" };
|
|
2634
|
-
}
|
|
2635
|
-
function selectGroups(procs, options) {
|
|
2636
|
-
const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
|
|
2637
|
-
const heavyFrom = options.minMem ?? HEAVY_DEFAULT;
|
|
2638
|
-
const candidates = procs.filter((proc) => proc.uid === options.guard.uid && proc.pid !== 1 && toolOf(proc) !== undefined);
|
|
2639
|
-
const chosen = new Map;
|
|
2640
|
-
let protectedCount = 0;
|
|
2641
|
-
for (const proc of candidates) {
|
|
2642
|
-
const ageMs = options.now - proc.startMs;
|
|
2643
|
-
const orphan = isOrphan(proc, byPid);
|
|
2644
|
-
const heavy = proc.rss >= heavyFrom;
|
|
2645
|
-
if (!(heavy || orphan && proc.rss >= (options.minMem ?? 0)) || ageMs < (options.olderMs ?? 0))
|
|
2646
|
-
continue;
|
|
2647
|
-
if (protectionOf(proc, options.guard) !== undefined) {
|
|
2648
|
-
protectedCount++;
|
|
2649
|
-
continue;
|
|
2650
|
-
}
|
|
2651
|
-
chosen.set(proc.pid, { orphan, heavy });
|
|
2652
|
-
}
|
|
2653
|
-
const profiles = new Set([...chosen.keys()].map((pid) => userDataDir(byPid.get(pid).args)).filter((dir) => dir !== undefined));
|
|
2654
|
-
let grew = true;
|
|
2655
|
-
while (grew) {
|
|
2656
|
-
grew = false;
|
|
2657
|
-
for (const proc of candidates) {
|
|
2658
|
-
const dir = userDataDir(proc.args);
|
|
2659
|
-
const joins = chosen.has(proc.ppid) || dir !== undefined && profiles.has(dir);
|
|
2660
|
-
if (chosen.has(proc.pid) || !joins || protectionOf(proc, options.guard) !== undefined)
|
|
2661
|
-
continue;
|
|
2662
|
-
chosen.set(proc.pid, { orphan: isOrphan(proc, byPid), heavy: proc.rss >= heavyFrom });
|
|
2663
|
-
grew = true;
|
|
2664
|
-
}
|
|
2665
|
-
}
|
|
2666
|
-
const groups = new Map;
|
|
2667
|
-
for (const [pid, flags] of chosen) {
|
|
2668
|
-
const proc = byPid.get(pid);
|
|
2669
|
-
const tool = toolOf(proc);
|
|
2670
|
-
const { key, origin, kind } = originOf(proc, tool, options);
|
|
2671
|
-
const group = groups.get(key) ?? { key, origin, kind, members: [], rss: 0, oldestMs: 0, orphans: 0 };
|
|
2672
|
-
const ageMs = options.now - proc.startMs;
|
|
2673
|
-
group.members.push({ proc, tool, ageMs, ...flags });
|
|
2674
|
-
group.rss += proc.rss;
|
|
2675
|
-
group.oldestMs = Math.max(group.oldestMs, ageMs);
|
|
2676
|
-
group.orphans += flags.orphan ? 1 : 0;
|
|
2677
|
-
groups.set(key, group);
|
|
2678
|
-
}
|
|
2679
|
-
for (const group of groups.values())
|
|
2680
|
-
group.members.sort((a, b) => a.proc.pid - b.proc.pid);
|
|
2681
|
-
return { groups: [...groups.values()].sort((a, b) => b.rss - a.rss), protectedCount };
|
|
2682
|
-
}
|
|
2683
|
-
|
|
2684
|
-
// src/procs.ts
|
|
2685
|
-
var usage4 = `proc procs: lists the calling user's leftover or heavy dev processes, grouped by project folder, browser profile or command
|
|
86
|
+
The environment is not shown unless --env is given, with every secret masked.`,EXITS=[[0,"it showed the process"],[1,"no process has this pid"],[2,"a usage error"]],DIGITS3=/^\d+$/,options={env:{type:"boolean",description:"show the environment, secrets masked"},json:jsonOption("everything, with the environment under env when --env is given")};async function parentsOf(proc,boot){let parents=[],seen=new Set([proc.pid]),at=proc.ppid;while(at>0&&!seen.has(at)){seen.add(at);let parent=await readProc(at,boot,{detail:!1});if(parent===void 0)break;parents.push({pid:parent.pid,comm:parent.comm,command:maskArgs(parent.args).join(" ")}),at=parent.ppid}return parents}async function report2(pid,showEnv){let boot=await bootMs(),proc=await readProc(pid,boot);if(proc===void 0)return;let unreadable=[],status=parseStatus(await text2(`/proc/${pid}/status`)??""),limitsText=await text2(`/proc/${pid}/limits`),sockets=await socketsOf(pid),listening=sockets.size===0?[]:(await readSockets()).filter((socket)=>sockets.has(socket.inode)),environText=showEnv?await text2(`/proc/${pid}/environ`):void 0,cgroup=parseCgroup(await text2(`/proc/${pid}/cgroup`)??"")[0]?.path,files=await fdCount(pid),stat=parseStat(await text2(`/proc/${pid}/stat`)??""),uid=proc.uid;if(proc.exe===void 0)unreadable.push("executable");if(proc.cwd===void 0)unreadable.push("working directory");if(files===void 0)unreadable.push("open files");if(limitsText===void 0)unreadable.push("limits");if(showEnv&&environText===void 0)unreadable.push("environment");let[allProcs,parents]=await Promise.all([snapshot("/proc",()=>!1),parentsOf(proc,boot)]),children=allProcs.filter((child)=>child.ppid===pid).sort((a,b)=>a.pid-b.pid).map((child)=>({pid:child.pid,comm:child.comm,command:maskArgs(child.args).join(" ")}));return{pid,comm:proc.comm,state:proc.state,exe:proc.exe,cwd:proc.cwd,command:maskArgs(proc.args),parents,children,user:{uid,name:await userName(uid)},startedAt:new Date(proc.startMs).toISOString(),ageSeconds:Math.max(0,(Date.now()-proc.startMs)/1000),threads:stat?.threads,memory:{rss:statusBytes(status,"VmRSS"),peak:statusBytes(status,"VmHWM"),virtual:statusBytes(status,"VmSize"),swap:statusBytes(status,"VmSwap")},openFiles:files,limits:parseLimits(limitsText??""),listening:listening.map(({protocol,address,port})=>({protocol,address,port})),cgroup:cgroup===""?void 0:cgroup,container:proc.container,env:environText===void 0?void 0:maskEnviron(parseEnviron(environText)).map(([name,value])=>({name,value})),unreadable}}function limitLine(limits,name){let limit=limits.find((candidate)=>candidate.name===name);return limit===void 0?"-":`soft ${limit.soft}, hard ${limit.hard}`}function render(info,showEnv){let colors=paint(process21.stdout),memory=info.memory,size=(bytes)=>bytes===void 0?"-":tt(bytes),rows=[["Executable",info.exe??"-"],["Directory",info.cwd??"-"],["Command",info.command.join(" ")||`[${info.comm}]`],["Parents",info.parents.length===0?"none (init)":info.parents.map((parent)=>`${parent.pid} ${parent.comm}`).join(" < ")],...info.children.length===0?[]:[["Children",info.children.map((child)=>`${child.pid} ${child.comm}`).join(", ")]],["User",`${info.user.name??"?"} (${info.user.uid})`],["State",info.state],["Started",`${info.startedAt} (${formatSeconds(info.ageSeconds)} ago)`],["Memory",`rss ${size(memory.rss)}, peak ${size(memory.peak)}, virtual ${size(memory.virtual)}, swap ${size(memory.swap)}`],["Open files",`${info.openFiles??"-"} (limit ${limitLine(info.limits,"Max open files")})`],["Processes",`${info.threads??"-"} threads (limit ${limitLine(info.limits,"Max processes")})`],["Listening",info.listening.length===0?"nothing":info.listening.map(({protocol,address,port})=>`${protocol} ${address.includes(":")?`[${address}]`:address}:${port}`).join(", ")]];if(info.container!==void 0)rows.push(["Container",info.container]);if(info.cgroup!==void 0)rows.push(["Cgroup",info.cgroup]);let lines=[colors.bold(`pid ${info.pid} ${info.comm}`),...rows.map(([label,value])=>`${colors.dim(label.padEnd(11))} ${value}`)];if(showEnv&&info.env!==void 0)lines.push("",colors.bold("Environment"),...info.env.map(({name,value})=>`${name}=${value}`));else if(!showEnv)lines.push("",colors.dim("Environment hidden, pass --env to show it with secrets masked"));if(info.unreadable.length>0)lines.push("",colors.yellow(`Could not read: ${info.unreadable.join(", ")} (a process of another user: rerun as that user)`));return lines.join(`
|
|
87
|
+
`)}async function pid(args){let{values,positionals}=parse(args,usage2,options,{exits:EXITS,positionals:["<pid>"],replaces:"cat /proc/<pid>/{cmdline,environ,limits}, readlink /proc/<pid>/{exe,cwd}, the fish pid function",examples:[["proc pid 4242","executable, directory, command, parents, memory, limits and ports"],["proc pid 4242 --env","with the environment, secrets masked"],"proc pid 4242 --json"]}),[given]=positionals;if(!DIGITS3.test(given))fail(`the pid takes a number, not ${given}`,2);let info=await report2(Number(given),values.env===!0);if(info===void 0)return fail(`no process with pid ${given}`,1);if(values.json===!0)printJson(info);else console.log(render(info,values.env===!0));return 0}import{basename as basename3}from"path";import process22 from"process";init_prompt();var FORMAT='{{.Names}}\t{{.Ports}}\t{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.service"}}';async function dockerContainers(){if(Bun.which("docker")===null)return[];try{let ran=await runCommand(["docker","ps","--format",FORMAT],{timeoutMs:4000});return ran.code===0?parseDockerPs(ran.text):[]}catch{return[]}}var usage3="proc ports [port]: lists what listens on this machine, one row per port with its owning process, command and working directory\n\nA port Docker publishes shows as its compose project and service; the owner of another user's socket shows as -. `proc ports <port>` keeps that port alone and exits 1 when nothing listens on it.\n`proc ports <port> --kill` stops its owner, after asking on a terminal unless --yes is given. It refuses processes of other users, pid 1, this command and its ancestors, and docker-proxy, for which it names the container to stop instead.",EXITS2=[[0,"it listed or stopped"],[1,"nothing listens on the given port or the owner could not be stopped"],[2,"a usage error"]],options2={json:jsonOption("[{ port, protocol, addresses, pid, command, cwd, container }]"),kill:{type:"boolean",conflicts:["watch"],description:"stop the owner of the given port"},docker:{type:"boolean",description:"with --kill, also stop Docker containers publishing the port"},watch:watchOption("the ports"),force:{type:"boolean",description:"with --kill, SIGKILL what SIGTERM did not stop within --grace"},yes:{type:"boolean",short:"y",description:"with --kill, do not ask first"},quiet:{type:"boolean",short:"q",description:"with --kill, print nothing about what was stopped"},grace:{type:"string",description:"with --force, how long SIGTERM gets before SIGKILL (5s)"}};function buildRows(sockets,owners,procs,containers){let rows=new Map;for(let socket of sockets){let pid=owners.get(socket.inode),proc=pid===void 0?void 0:procs.get(pid),key=`${socket.protocol}/${socket.port}/${pid??"unknown"}`,row=rows.get(key);if(row!==void 0){if(!row.addresses.includes(socket.address))row.addresses.push(socket.address);continue}let container=proc===void 0||proc.comm==="docker-proxy"?containers.find((candidate)=>candidate.published.some((port)=>port.host===socket.port&&port.protocol===socket.protocol)):void 0;rows.set(key,{port:socket.port,protocol:socket.protocol,addresses:[socket.address],pid,command:proc===void 0?void 0:maskArgs([basename3(proc.args[0]??proc.comm),...proc.args.slice(1)]).join(" "),cwd:proc?.cwd,uid:proc?.uid??socket.uid,container:container===void 0?void 0:{name:container.name,project:container.project,service:container.service}})}return[...rows.values()].sort((a,b)=>a.port-b.port||a.protocol.localeCompare(b.protocol)||(a.pid??0)-(b.pid??0))}function containerLabel(container){return container.project===void 0?container.name:`${container.project}/${container.service??container.name}`}function refusal(row,proc,guard){if(row.container!==void 0&&(proc===void 0||proc.comm==="docker-proxy"))return`published by the container ${row.container.name} (${containerLabel(row.container)}): stop it with \`docker stop ${row.container.name}\``;if(proc===void 0||row.pid===void 0)return"its owner is not readable (another user's process): rerun as that user";let reason=protectionOf(proc,guard);return reason===void 0?void 0:`pid ${row.pid} is ${reason}`}function render2(rows){let colors=paint(process22.stdout),cells=rows.map((row)=>[colors.cyan(String(row.port)),row.protocol,row.addresses.join(", "),row.pid===void 0?"-":String(row.pid),row.container===void 0?truncate(row.command??"-",60):colors.yellow(`docker ${containerLabel(row.container)}`),colors.dim(row.cwd??"-")]);return table([["PORT","PROTO","ADDRESS","PID","COMMAND","CWD"],...cells],{header:!0})}async function stop(port,rows,procs,values){let guard={uid:process22.getuid?.()??-1,mine:new Set(ancestry(process22.pid,procs))},targets=new Map,containers=new Map;for(let row of rows){let proc=row.pid===void 0?void 0:procs.get(row.pid);if(values.docker===!0&&row.container!==void 0&&(proc===void 0||proc.comm==="docker-proxy")){containers.set(row.container.name,row.container);continue}let reason=refusal(row,proc,guard);if(reason!==void 0)problem(`port ${port}: ${reason}`);else if(row.pid!==void 0)targets.set(row.pid,row)}if(targets.size===0&&containers.size===0)return 1;let names=[...[...targets].map(([pid,row])=>`${pid} (${truncate(row.command??"",40)})`),...[...containers.values()].map((c)=>`docker ${containerLabel(c)}`)].join(", ");if(values.yes!==!0){if(!process22.stdin.isTTY)fail(`stopping ${names} needs a terminal to ask on: pass --yes`,2);if(await confirm(`Stop ${names}?`,{default:!1,hint:"pass --yes to stop without asking"})!==!0)return 1}let code=0;if(containers.size>0)for(let name of containers.keys()){let ran=await runCommand(["docker","stop",name]);if(ran.code===0){if(values.quiet!==!0)console.log(`stopped container ${name}`)}else problem(`could not stop container ${name}: ${ran.text.trim()||`exit ${ran.code}`}`),code=1}if(targets.size>0){let outcome=await terminate([...targets.keys()],{escalate:values.force===!0,graceMs:duration(values.grace,"grace",5000)});for(let pid of values.quiet===!0?[]:[...outcome.terminated,...outcome.killed])console.log(`stopped ${pid}${outcome.killed.includes(pid)?" (SIGKILL)":""}`);for(let pid of outcome.survived)problem(`${pid} is still running${values.force===!0?"":", pass --force to SIGKILL it"}`);if(outcome.survived.length>0)code=1}return code}async function ports(args){let{values,positionals}=parse(args,usage3,options2,{exits:EXITS2,positionals:["[port]"],replaces:"ss -ltnp | grep, lsof -i, fuser -k and lookups of docker-proxy by hand",examples:[["proc ports","every listening port with its owner"],["proc ports 3000","who holds 3000, exit 1 when nobody does"],["proc ports 3000 --kill --yes","stop it"],"proc ports --json"]});if(values.watch!==void 0)return watching(values.watch,async()=>ports(withoutWatch(args)));let[given]=positionals,port=given===void 0?void 0:wholeNumber(given,"<port>",0);if(port!==void 0&&port>65535)badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);if(values.kill===!0&&port===void 0)badUsage("--kill takes the port to free: proc ports <port> --kill");let[sockets,owners,procs]=await Promise.all([readSockets(),socketOwners(),snapshot("/proc",(uid)=>uid===process22.getuid?.())]),byPid=new Map(procs.map((proc)=>[proc.pid,proc])),wanted=sockets.filter((socket)=>port===void 0||socket.port===port),needsDocker=wanted.some((socket)=>{let pid=owners.get(socket.inode);return pid===void 0||byPid.get(pid)?.comm==="docker-proxy"}),rows=buildRows(wanted,owners,byPid,needsDocker?await dockerContainers():[]);if(port!==void 0&&rows.length===0)return problem(`nothing listens on port ${port}`),1;if(values.kill===!0&&port!==void 0)return stop(port,rows,byPid,values);if(values.json===!0)return printJson(rows),0;console.log(render2(rows));let unknown=rows.filter((row)=>row.pid===void 0&&row.container===void 0).length;if(unknown>0)console.error(paint(process22.stderr).dim(`${unknown} ${unknown===1?"port has":"ports have"} an owner this user cannot read, shown as -`));return 0}import{existsSync as existsSync4}from"fs";import{homedir as homedir4}from"os";import process23 from"process";import{basename as basename4,join as join7,relative as relative2}from"path";var BROWSERS=/^(?:chrom(?:e|ium)(?:-browser)?|google-chrome(?:-stable|-beta|-unstable)?|chrome_crashpad_handler|chrome-headless-shell|headless_shell|chromium-headless-shell|brave|brave-browser|msedge|microsoft-edge|webkitwebprocess|webkitnetworkprocess|webkitgpuprocess|minibrowser|webkitwebdriver|wpewebprocess|wpenetworkprocess|bun-webview.*)$/i,NATIVE=new Set(["rust-analyzer","gopls","clangd","lua-language-server","pyright-langserver","pylsp","intelephense","phpactor","tsgo","esbuild","biome","ruff","phpunit","pytest","vitest","jest"]),RUNTIMES=new Set(["node","bun","bunx","deno","nodejs"]),SCRIPTS=new Set(["vite","vitest","nuxt","nuxi","next","jest","playwright","playwright-core","tsserver","typescript-language-server","vue-language-server","vtsls","eslint_d","esbuild","webpack","turbo","astro","tsgo","svelte-kit","remix","storybook","biome","prettierd","tailwindcss","bun-webview"]),EXTENSION=/\.[cm]?[jt]s$/,MARKERS=["package.json","composer.json","Cargo.toml","go.mod","pyproject.toml"],AUTOMATION=/^--(?:headless|remote-debugging-(?:pipe|port)|enable-automation)/,HEAVY_DEFAULT=524288000;function toolOf(proc){let names=[proc.exe,proc.args[0],proc.comm].filter((name)=>name!==void 0&&name!=="").map((name)=>basename4(name));for(let name of names){if(BROWSERS.test(name))return name.toLowerCase().startsWith("webkit")||name.toLowerCase().startsWith("wpe")||name.toLowerCase()==="minibrowser"?"webkit":"chromium";if(NATIVE.has(name))return name}let runtime=names.find((name)=>RUNTIMES.has(name));if(runtime===void 0)return;for(let arg of proc.args.slice(1)){if(arg.startsWith("-"))continue;let script=basename4(arg).replace(EXTENSION,"");if(SCRIPTS.has(script))return script}return runtime==="nodejs"?"node":runtime}function userDataDir(args){return args.find((word)=>word.startsWith("--user-data-dir="))?.slice(16)}function projectOf(cwd,exists,home){if(cwd===void 0||!cwd.startsWith(`${home}/`))return;let folders=[];for(let dir=cwd;dir.startsWith(`${home}/`);dir=join7(dir,".."))folders.push(dir);return folders.find((dir)=>exists(join7(dir,".git")))??folders.find((dir)=>MARKERS.some((marker)=>exists(join7(dir,marker))))}function isOrphan(proc,byPid){if(proc.unit?.endsWith(".service")===!0)return!1;let parent=byPid.get(proc.ppid),userManager=parent!==void 0&&parent.comm==="systemd"&&parent.uid===proc.uid&&parent.uid!==0,reparented=proc.ppid===1||userManager,tool=toolOf(proc);if(!reparented||tool!=="chromium"&&tool!=="webkit")return reparented;if(basename4(proc.exe??proc.args[0]??proc.comm).includes("crashpad"))return!1;return proc.args.some((arg)=>arg.startsWith("--type="))||proc.args.some((arg)=>AUTOMATION.test(arg))}function originOf(proc,tool,{exists,home}){let profile=userDataDir(proc.args);if(profile!==void 0)return{key:`profile:${profile}`,origin:`${tool} profile ${profile}`,kind:"profile"};let project=projectOf(proc.cwd,exists,home);if(project!==void 0)return{key:`project:${project}`,origin:`~/${relative2(home,project)}`,kind:"project"};return{key:`command:${tool}`,origin:tool,kind:"command"}}function selectGroups(procs,options){let byPid=new Map(procs.map((proc)=>[proc.pid,proc])),heavyFrom=options.minMem??HEAVY_DEFAULT,candidates=procs.filter((proc)=>proc.uid===options.guard.uid&&proc.pid!==1&&toolOf(proc)!==void 0),chosen=new Map,protectedCount=0;for(let proc of candidates){let ageMs=options.now-proc.startMs,orphan=isOrphan(proc,byPid),heavy=proc.rss>=heavyFrom;if(!(heavy||orphan&&proc.rss>=(options.minMem??0))||ageMs<(options.olderMs??0))continue;if(protectionOf(proc,options.guard)!==void 0){protectedCount++;continue}chosen.set(proc.pid,{orphan,heavy})}let profiles=new Set([...chosen.keys()].map((pid)=>userDataDir(byPid.get(pid).args)).filter((dir)=>dir!==void 0)),grew=!0;while(grew){grew=!1;for(let proc of candidates){let dir=userDataDir(proc.args),joins=chosen.has(proc.ppid)||dir!==void 0&&profiles.has(dir);if(chosen.has(proc.pid)||!joins||protectionOf(proc,options.guard)!==void 0)continue;chosen.set(proc.pid,{orphan:isOrphan(proc,byPid),heavy:proc.rss>=heavyFrom}),grew=!0}}let groups=new Map;for(let[pid,flags]of chosen){let proc=byPid.get(pid),tool=toolOf(proc),{key,origin,kind}=originOf(proc,tool,options),group=groups.get(key)??{key,origin,kind,members:[],rss:0,oldestMs:0,orphans:0},ageMs=options.now-proc.startMs;group.members.push({proc,tool,ageMs,...flags}),group.rss+=proc.rss,group.oldestMs=Math.max(group.oldestMs,ageMs),group.orphans+=flags.orphan?1:0,groups.set(key,group)}for(let group of groups.values())group.members.sort((a,b)=>a.proc.pid-b.proc.pid);return{groups:[...groups.values()].sort((a,b)=>b.rss-a.rss),protectedCount}}var usage4=`proc cleanup: lists the calling user's leftover or heavy dev processes, grouped by project folder, browser profile or command
|
|
2686
88
|
|
|
2687
89
|
A process is listed when it is a dev tool (bun, node, vite, chromium, playwright, language servers, test runners) and either an orphan, reparented to init or to the user's systemd, or heavy (500M resident by default); the processes below it and those sharing its browser profile come with it.
|
|
2688
|
-
\`--kill\` is a dry run that names what it would stop unless --yes is given.
|
|
2689
|
-
var EXITS3 = [[0, "it listed or stopped everything"], [1, "a process survived SIGKILL"], [2, "a usage error"]];
|
|
2690
|
-
var options3 = {
|
|
2691
|
-
json: jsonOption("{ groups: [{ origin, kind, count, rss, oldestSeconds, tools, orphans, pids, processes }], skipped }"),
|
|
2692
|
-
kill: { type: "boolean", conflicts: ["watch"], description: "stop the listed processes: a dry run without --yes" },
|
|
2693
|
-
watch: watchOption("the processes"),
|
|
2694
|
-
yes: { type: "boolean", short: "y", description: "with --kill, really stop them, without asking" },
|
|
2695
|
-
quiet: { type: "boolean", short: "q", description: "with --kill --yes, print nothing about what was stopped" },
|
|
2696
|
-
"min-mem": { type: "string", description: "heavy from this resident size (500M), and the least a left over process must use to be listed; a bare number counts megabytes" },
|
|
2697
|
-
older: { type: "string", description: "only processes at least this old: 30m, 2h, 1d" },
|
|
2698
|
-
grace: { type: "string", description: "how long SIGTERM gets before SIGKILL (5s)" }
|
|
2699
|
-
};
|
|
2700
|
-
function summary(group) {
|
|
2701
|
-
const tools = {};
|
|
2702
|
-
for (const { tool } of group.members)
|
|
2703
|
-
tools[tool] = (tools[tool] ?? 0) + 1;
|
|
2704
|
-
return {
|
|
2705
|
-
origin: group.origin,
|
|
2706
|
-
kind: group.kind,
|
|
2707
|
-
count: group.members.length,
|
|
2708
|
-
rss: group.rss,
|
|
2709
|
-
oldestSeconds: Math.round(group.oldestMs / 1000),
|
|
2710
|
-
tools,
|
|
2711
|
-
orphans: group.orphans,
|
|
2712
|
-
pids: group.members.map(({ proc }) => proc.pid),
|
|
2713
|
-
processes: group.members.map(({ proc, tool, orphan, heavy, ageMs }) => ({ pid: proc.pid, ppid: proc.ppid, tool, command: maskArgs(proc.args).join(" ") || proc.comm, cwd: proc.cwd, rss: proc.rss, ageSeconds: Math.round(ageMs / 1000), orphan, heavy }))
|
|
2714
|
-
};
|
|
2715
|
-
}
|
|
2716
|
-
function render3(groups) {
|
|
2717
|
-
const colors = paint(process22.stdout);
|
|
2718
|
-
const rows = groups.map((group) => [
|
|
2719
|
-
group.origin,
|
|
2720
|
-
String(group.members.length),
|
|
2721
|
-
tt(group.rss),
|
|
2722
|
-
formatSeconds(group.oldestMs / 1000),
|
|
2723
|
-
colors.dim(truncate(Object.entries(Object.groupBy(group.members, ({ tool }) => tool)).map(([tool, list]) => `${tool}${list.length > 1 ? ` x${list.length}` : ""}`).join(", "), 50)),
|
|
2724
|
-
group.orphans === 0 ? "" : colors.yellow(`${group.orphans} orphaned`)
|
|
2725
|
-
]);
|
|
2726
|
-
return table([["ORIGIN", "PROCS", "RSS", "OLDEST", "WHAT", ""], ...rows], { header: true, align: ["left", "right", "right", "right"] });
|
|
2727
|
-
}
|
|
2728
|
-
async function procs(args) {
|
|
2729
|
-
const { values } = parse(args, usage4, options3, {
|
|
2730
|
-
exits: EXITS3,
|
|
2731
|
-
replaces: "pkill -f and pgrep -f one-liners (which match their own shell), ps aux | grep for leftover chromium, bun or vite processes",
|
|
2732
|
-
examples: [
|
|
2733
|
-
["proc procs", "leftover and heavy dev processes, by origin"],
|
|
2734
|
-
["proc procs --min-mem 1G --older 1h", "only the big ones that have run a while"],
|
|
2735
|
-
["proc procs --kill", "dry run: what would be stopped"],
|
|
2736
|
-
"proc procs --kill --yes"
|
|
2737
|
-
]
|
|
2738
|
-
});
|
|
2739
|
-
const minMem = values["min-mem"] === undefined ? undefined : parseSize(values["min-mem"], 1024 ** 2);
|
|
2740
|
-
if (values["min-mem"] !== undefined && minMem === undefined)
|
|
2741
|
-
fail(`--min-mem takes a size such as 500M or 1.5G, not ${values["min-mem"]}`, 2);
|
|
2742
|
-
if (values.watch !== undefined)
|
|
2743
|
-
return watching(values.watch, async () => procs(withoutWatch(args)));
|
|
2744
|
-
const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0, "m");
|
|
2745
|
-
const uid = process22.getuid?.() ?? -1;
|
|
2746
|
-
const all = await snapshot("/proc", (owner) => owner === uid);
|
|
2747
|
-
const mine = new Set(ancestry(process22.pid, new Map(all.map((proc) => [proc.pid, proc]))));
|
|
2748
|
-
const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir4(), exists: existsSync3, minMem, olderMs });
|
|
2749
|
-
const pids = groups.flatMap((group) => group.members.map(({ proc }) => proc.pid));
|
|
2750
|
-
const show = (extra = {}) => {
|
|
2751
|
-
if (values.json === true) {
|
|
2752
|
-
printJson({ groups: groups.map(summary), skipped: protectedCount, ...extra });
|
|
2753
|
-
} else {
|
|
2754
|
-
console.log(groups.length === 0 ? "nothing to clean" : render3(groups));
|
|
2755
|
-
}
|
|
2756
|
-
};
|
|
2757
|
-
if (values.kill !== true || pids.length === 0 || values.yes !== true) {
|
|
2758
|
-
show();
|
|
2759
|
-
if (values.json !== true && protectedCount > 0)
|
|
2760
|
-
console.error(paint(process22.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
|
|
2761
|
-
if (values.kill === true && pids.length > 0)
|
|
2762
|
-
console.error(`dry run: would stop ${pids.length} ${pids.length === 1 ? "process" : "processes"} (${pids.join(" ")}), pass --yes to do it`);
|
|
2763
|
-
return 0;
|
|
2764
|
-
}
|
|
2765
|
-
const outcome = await terminate(pids, { escalate: true, graceMs: duration(values.grace, "grace", 5000) });
|
|
2766
|
-
if (values.quiet !== true || values.json === true)
|
|
2767
|
-
show({ stopped: [...outcome.terminated, ...outcome.killed], killed: outcome.killed, survived: outcome.survived });
|
|
2768
|
-
if (values.json !== true && values.quiet !== true)
|
|
2769
|
-
console.log(`stopped ${outcome.terminated.length + outcome.killed.length} of ${pids.length}${outcome.killed.length === 0 ? "" : `, ${outcome.killed.length} needed SIGKILL`}`);
|
|
2770
|
-
if (outcome.survived.length > 0)
|
|
2771
|
-
problem(`still running: ${outcome.survived.join(" ")}`);
|
|
2772
|
-
return outcome.survived.length === 0 ? 0 : 1;
|
|
2773
|
-
}
|
|
2774
|
-
|
|
2775
|
-
// src/proc-cli.ts
|
|
2776
|
-
process23.exitCode = await runCli({
|
|
2777
|
-
name: "proc",
|
|
2778
|
-
about: "what a process is, who listens on a port and which dev processes are worth cleaning, read from /proc",
|
|
2779
|
-
replaces: "cat /proc/<pid>/..., ss -ltnp, lsof -i and pgrep -f one-liners",
|
|
2780
|
-
examples: ["proc pid 1234", "proc ports", ["proc procs", "the leftover or heavy processes, dry-run first"]],
|
|
2781
|
-
commands: {
|
|
2782
|
-
pid: { summary: "what a process is: executable, parents, memory, limits and listening ports", run: pid },
|
|
2783
|
-
ports: { summary: "what listens on this machine, with its owner, and a safe --kill", run: ports },
|
|
2784
|
-
procs: { summary: "the leftover or heavy processes of the calling user, grouped by origin", run: procs }
|
|
2785
|
-
}
|
|
2786
|
-
});
|
|
90
|
+
Filter by --origin or --tool before running --kill --yes. \`--kill\` is a dry run that names what it would stop unless --yes is given.`,EXITS3=[[0,"it listed or stopped everything"],[1,"a process survived SIGKILL"],[2,"a usage error"]],options3={json:jsonOption("{ groups: [{ origin, kind, count, rss, oldestSeconds, tools, orphans, pids, processes }], skipped }"),origin:{type:"string",description:"keep only groups whose origin contains this substring (case-insensitive)"},tool:{type:"string",description:"keep only processes matching this tool name (comma-separated, e.g. chromium,vite)"},kill:{type:"boolean",conflicts:["watch"],description:"stop the listed processes: a dry run without --yes"},watch:watchOption("the processes"),yes:{type:"boolean",short:"y",description:"with --kill, really stop them, without asking"},quiet:{type:"boolean",short:"q",description:"with --kill --yes, print nothing about what was stopped"},"min-mem":{type:"string",description:"heavy from this resident size (500M), and the least a left over process must use to be listed; a bare number counts megabytes"},older:{type:"string",description:"only processes at least this old: 30m, 2h, 1d"},grace:{type:"string",description:"how long SIGTERM gets before SIGKILL (5s)"}};function summary(group){let tools={};for(let{tool}of group.members)tools[tool]=(tools[tool]??0)+1;return{origin:group.origin,kind:group.kind,count:group.members.length,rss:group.rss,oldestSeconds:Math.round(group.oldestMs/1000),tools,orphans:group.orphans,pids:group.members.map(({proc})=>proc.pid),processes:group.members.map(({proc,tool,orphan,heavy,ageMs})=>({pid:proc.pid,ppid:proc.ppid,tool,command:maskArgs(proc.args).join(" ")||proc.comm,cwd:proc.cwd,rss:proc.rss,ageSeconds:Math.round(ageMs/1000),orphan,heavy}))}}function render3(groups){let colors=paint(process23.stdout),rows=groups.map((group)=>[group.origin,String(group.members.length),tt(group.rss),formatSeconds(group.oldestMs/1000),colors.dim(truncate(Object.entries(Object.groupBy(group.members,({tool})=>tool)).map(([tool,list])=>`${tool}${list.length>1?` x${list.length}`:""}`).join(", "),50)),group.orphans===0?"":colors.yellow(`${group.orphans} orphaned`)]);return table([["ORIGIN","PROCS","RSS","OLDEST","WHAT",""],...rows],{header:!0,align:["left","right","right","right"]})}async function cleanup(args){let{values}=parse(args,usage4,options3,{exits:EXITS3,replaces:"pkill -f and pgrep -f one-liners (which match their own shell), ps aux | grep for leftover chromium, bun or vite processes",examples:[["proc cleanup","leftover and heavy dev processes, by origin"],["proc cleanup --tool chromium --kill --yes","stop leftover Chromium processes"],["proc cleanup --origin workspace/app --min-mem 1G","filter by project origin and memory"]]}),minMem=values["min-mem"]===void 0?void 0:parseSize(values["min-mem"],1048576);if(values["min-mem"]!==void 0&&minMem===void 0)fail(`--min-mem takes a size such as 500M or 1.5G, not ${values["min-mem"]}`,2);if(values.watch!==void 0)return watching(values.watch,async()=>cleanup(withoutWatch(args)));let olderMs=values.older===void 0?void 0:duration(values.older,"older",0,"m"),uid=process23.getuid?.()??-1,all=await snapshot("/proc",(owner)=>owner===uid),mine=new Set(ancestry(process23.pid,new Map(all.map((proc)=>[proc.pid,proc])))),selected=selectGroups(all,{guard:{uid,mine},now:Date.now(),home:homedir4(),exists:existsSync4,minMem,olderMs}),originFilter=values.origin?.toLowerCase(),toolFilter=values.tool===void 0?void 0:new Set(values.tool.split(",").map((item)=>item.trim().toLowerCase()).filter(Boolean)),groups=selected.groups.filter((group)=>originFilter===void 0||group.origin.toLowerCase().includes(originFilter)).map((group)=>{if(toolFilter===void 0)return group;let members=group.members.filter((member)=>toolFilter.has(member.tool.toLowerCase()));if(members.length===0)return;return{...group,members,rss:members.reduce((sum,member)=>sum+member.proc.rss,0),oldestMs:Math.max(...members.map((member)=>member.ageMs)),orphans:members.filter((member)=>member.orphan).length}}).filter((group)=>group!==void 0),{protectedCount}=selected,pids=groups.flatMap((group)=>group.members.map(({proc})=>proc.pid)),show=(extra={})=>{if(values.json===!0)printJson({groups:groups.map(summary),skipped:protectedCount,...extra});else console.log(groups.length===0?"nothing to clean":render3(groups))};if(values.kill!==!0||pids.length===0||values.yes!==!0){if(show(),values.json!==!0&&protectedCount>0)console.error(paint(process23.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));if(values.kill===!0&&pids.length>0)console.error(`dry run: would stop ${pids.length} ${pids.length===1?"process":"processes"} (${pids.join(" ")}), pass --yes to do it`);return 0}let outcome=await terminate(pids,{escalate:!0,graceMs:duration(values.grace,"grace",5000)});if(values.quiet!==!0||values.json===!0)show({stopped:[...outcome.terminated,...outcome.killed],killed:outcome.killed,survived:outcome.survived});if(values.json!==!0&&values.quiet!==!0)console.log(`stopped ${outcome.terminated.length+outcome.killed.length} of ${pids.length}${outcome.killed.length===0?"":`, ${outcome.killed.length} needed SIGKILL`}`);if(outcome.survived.length>0)problem(`still running: ${outcome.survived.join(" ")}`);return outcome.survived.length===0?0:1}process24.exitCode=await runCli({name:"proc",about:"inspect, search, tree, rank and safely clean processes and listening ports from /proc",replaces:"cat /proc/<pid>/..., ps aux | grep, pstree, ss -ltnp, lsof -i and pkill -f one-liners",examples:["proc pid 1234","proc ports","proc ls vite","proc tree","proc top",["proc cleanup","leftover or heavy dev processes, dry-run first"]],aliases:{find:"ls",procs:"cleanup"},commands:{pid:{summary:"inspect one process: executable, parents, children, container, memory, limits and ports",run:pid},ports:{summary:"listening ports with owner/container and safe --kill (--docker for containers)",run:ports},cleanup:{summary:"leftover or heavy dev processes grouped by origin (--origin/--tool filters)",run:cleanup},ls:{summary:"list or search processes by pattern (alias: find)",run:lsCmd},tree:{summary:"process hierarchy rooted at a pid or user roots",run:treeCmd},top:{summary:"top processes by memory, open files or age",run:topCmd},kill:{summary:"safely stop one or more processes with protection checks",run:killCmd}}});
|