@kaynooo/cli-base 0.11.1 → 0.12.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/README.md +3 -3
- package/dist/cli.js +2 -26
- package/package.json +7 -9
- package/dist/proof-cli.js +0 -1640
package/dist/proof-cli.js
DELETED
|
@@ -1,1640 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
|
-
// @bun
|
|
3
|
-
|
|
4
|
-
// src/proof-cli.ts
|
|
5
|
-
import process18 from "process";
|
|
6
|
-
// ../kit/src/args.ts
|
|
7
|
-
import process9 from "process";
|
|
8
|
-
import { parseArgs } from "util";
|
|
9
|
-
|
|
10
|
-
// ../kit/src/format.ts
|
|
11
|
-
import process7 from "process";
|
|
12
|
-
|
|
13
|
-
// ../kit/src/mode.ts
|
|
14
|
-
import process2 from "process";
|
|
15
|
-
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
16
|
-
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
17
|
-
function isSet(value) {
|
|
18
|
-
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
19
|
-
}
|
|
20
|
-
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
21
|
-
const chosen = env.KIT_MODE;
|
|
22
|
-
if (chosen !== undefined && MODES.has(chosen))
|
|
23
|
-
return chosen;
|
|
24
|
-
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
25
|
-
return "agent";
|
|
26
|
-
if (stream.isTTY === true)
|
|
27
|
-
return "terminal";
|
|
28
|
-
return isSet(env.CI) ? "ci" : "pipe";
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
// ../kit/src/style.ts
|
|
32
|
-
import process6 from "process";
|
|
33
|
-
|
|
34
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
35
|
-
var G = /^[a-f0-9]+$/i;
|
|
36
|
-
function b(r) {
|
|
37
|
-
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
38
|
-
if (!G.test(e))
|
|
39
|
-
return [0, 0, 0];
|
|
40
|
-
if (e.length === 3 || e.length === 4)
|
|
41
|
-
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
42
|
-
if (e.length !== 6 && e.length !== 8)
|
|
43
|
-
throw Error(`Invalid hex color length: ${e.length}`);
|
|
44
|
-
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
45
|
-
}
|
|
46
|
-
var 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") => {
|
|
47
|
-
let [l, n, c] = b(r);
|
|
48
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
49
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
50
|
-
var h = new Set(["", "1", "2", "3", "true"]);
|
|
51
|
-
function C(r, e = globalThis.process?.env ?? {}) {
|
|
52
|
-
if (e.FORCE_COLOR !== undefined)
|
|
53
|
-
return h.has(e.FORCE_COLOR);
|
|
54
|
-
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
55
|
-
return false;
|
|
56
|
-
return r?.isTTY === true;
|
|
57
|
-
}
|
|
58
|
-
function f(r, e = []) {
|
|
59
|
-
let l = "", n = "";
|
|
60
|
-
for (let t = 0, i = e.length;t < i; t++)
|
|
61
|
-
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
62
|
-
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
63
|
-
return new Proxy(c, { get(t, i) {
|
|
64
|
-
let a = B[i];
|
|
65
|
-
if (Array.isArray(a)) {
|
|
66
|
-
let s = g.get(i);
|
|
67
|
-
if (s === undefined)
|
|
68
|
-
s = f(r, [...e, a]), g.set(i, s);
|
|
69
|
-
return s;
|
|
70
|
-
}
|
|
71
|
-
if (typeof a === "function")
|
|
72
|
-
return (...s) => {
|
|
73
|
-
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
74
|
-
if (u === undefined) {
|
|
75
|
-
if (g.size >= 64)
|
|
76
|
-
g.clear();
|
|
77
|
-
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
78
|
-
}
|
|
79
|
-
return u;
|
|
80
|
-
};
|
|
81
|
-
throw Error(`Unknown style: ${String(i)}`);
|
|
82
|
-
} });
|
|
83
|
-
}
|
|
84
|
-
function Fe(r = {}) {
|
|
85
|
-
return f(r);
|
|
86
|
-
}
|
|
87
|
-
var o = Fe();
|
|
88
|
-
|
|
89
|
-
// ../kit/src/theme.ts
|
|
90
|
-
import { existsSync as existsSync2, readFileSync, statSync } from "fs";
|
|
91
|
-
import { homedir as homedir2 } from "os";
|
|
92
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
93
|
-
import process5 from "process";
|
|
94
|
-
|
|
95
|
-
// ../kit/src/config.ts
|
|
96
|
-
import { existsSync } from "fs";
|
|
97
|
-
import { dirname, join, resolve } from "path";
|
|
98
|
-
import process3 from "process";
|
|
99
|
-
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
100
|
-
const wanted = typeof names === "string" ? [names] : names;
|
|
101
|
-
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
102
|
-
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
103
|
-
if (found !== undefined)
|
|
104
|
-
return found;
|
|
105
|
-
if (stop(dir) || dirname(dir) === dir)
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// ../kit/src/user-config.ts
|
|
111
|
-
import { homedir } from "os";
|
|
112
|
-
import { join as join2 } from "path";
|
|
113
|
-
import process4 from "process";
|
|
114
|
-
function configBase(where = {}) {
|
|
115
|
-
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
116
|
-
return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
|
|
117
|
-
}
|
|
118
|
-
function userConfigPath(bin, where = {}) {
|
|
119
|
-
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
// ../kit/src/theme.ts
|
|
123
|
-
var ENDS = new Map;
|
|
124
|
-
var DEFAULT = {
|
|
125
|
-
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" },
|
|
126
|
-
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" },
|
|
127
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
128
|
-
bins: {},
|
|
129
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
130
|
-
};
|
|
131
|
-
var 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" };
|
|
132
|
-
var 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" };
|
|
133
|
-
var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
134
|
-
var PRESETS = {
|
|
135
|
-
default: {},
|
|
136
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
137
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
138
|
-
ascii: { glyphs: ASCII }
|
|
139
|
-
};
|
|
140
|
-
var 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"]);
|
|
141
|
-
var HEX = /^#[0-9a-f]{6}$/i;
|
|
142
|
-
var CONTROL = /\p{Cc}/u;
|
|
143
|
-
var MAX_FILE_BYTES = 64 * 1024;
|
|
144
|
-
var SPACES = /\s+/;
|
|
145
|
-
function isColorSpec(spec) {
|
|
146
|
-
if (typeof spec === "number")
|
|
147
|
-
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
148
|
-
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
149
|
-
}
|
|
150
|
-
var CUBE = [0, 95, 135, 175, 215, 255];
|
|
151
|
-
function cubeLevel(channel) {
|
|
152
|
-
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
153
|
-
}
|
|
154
|
-
function nearest256(hex) {
|
|
155
|
-
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
156
|
-
const levels = rgb.map(cubeLevel);
|
|
157
|
-
const cube = levels.map((level) => CUBE[level]);
|
|
158
|
-
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
159
|
-
const greyValue = 8 + grey * 10;
|
|
160
|
-
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
161
|
-
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
162
|
-
}
|
|
163
|
-
function hasTrueColor(env) {
|
|
164
|
-
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
165
|
-
}
|
|
166
|
-
function tinted(colors, spec, env = process5.env) {
|
|
167
|
-
if (typeof spec === "number")
|
|
168
|
-
return colors.ansi256(spec);
|
|
169
|
-
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
170
|
-
if (HEX.test(token))
|
|
171
|
-
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
172
|
-
return chain[token] ?? chain;
|
|
173
|
-
}, colors);
|
|
174
|
-
}
|
|
175
|
-
function isRecord(value) {
|
|
176
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
177
|
-
}
|
|
178
|
-
function readThemeFile(path, warn) {
|
|
179
|
-
try {
|
|
180
|
-
const stat = statSync(path, { throwIfNoEntry: false });
|
|
181
|
-
if (stat === undefined)
|
|
182
|
-
return;
|
|
183
|
-
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
184
|
-
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
185
|
-
return;
|
|
186
|
-
}
|
|
187
|
-
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
188
|
-
if (isRecord(parsed))
|
|
189
|
-
return parsed;
|
|
190
|
-
warn(`${path} is not a JSON object, theme ignored`);
|
|
191
|
-
} catch (error) {
|
|
192
|
-
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
193
|
-
}
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
function applyPreset(theme, name, warn, where) {
|
|
197
|
-
if (name === undefined)
|
|
198
|
-
return;
|
|
199
|
-
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
200
|
-
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
201
|
-
return;
|
|
202
|
-
}
|
|
203
|
-
const preset = PRESETS[name];
|
|
204
|
-
Object.assign(theme.colors, preset.colors);
|
|
205
|
-
Object.assign(theme.glyphs, preset.glyphs);
|
|
206
|
-
if (preset.accents !== undefined)
|
|
207
|
-
theme.accents = [...preset.accents];
|
|
208
|
-
if (Object.hasOwn(preset, "gradient"))
|
|
209
|
-
theme.gradient = preset.gradient;
|
|
210
|
-
return name;
|
|
211
|
-
}
|
|
212
|
-
function applyFile(theme, file, where, warn) {
|
|
213
|
-
if (isRecord(file.colors)) {
|
|
214
|
-
for (const [key, value] of Object.entries(file.colors)) {
|
|
215
|
-
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
216
|
-
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
217
|
-
else if (!isColorSpec(value))
|
|
218
|
-
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
219
|
-
else
|
|
220
|
-
theme.colors[key] = value;
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
if (isRecord(file.glyphs)) {
|
|
224
|
-
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
225
|
-
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
226
|
-
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
227
|
-
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
228
|
-
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
229
|
-
else
|
|
230
|
-
theme.glyphs[key] = value;
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
234
|
-
theme.accents = [...file.accents];
|
|
235
|
-
else if (file.accents !== undefined)
|
|
236
|
-
warn(`${where}: accents must be a non-empty list of colours`);
|
|
237
|
-
if (file.gradient === null)
|
|
238
|
-
theme.gradient = undefined;
|
|
239
|
-
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
240
|
-
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
241
|
-
else if (file.gradient !== undefined)
|
|
242
|
-
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
243
|
-
if (isRecord(file.bins)) {
|
|
244
|
-
for (const [bin, value] of Object.entries(file.bins)) {
|
|
245
|
-
if (isColorSpec(value))
|
|
246
|
-
theme.bins[bin] = value;
|
|
247
|
-
else
|
|
248
|
-
warn(`${where}: bin ${bin} has no valid colour`);
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
function endsWalk(home) {
|
|
253
|
-
return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
|
|
254
|
-
}
|
|
255
|
-
var warned = new Set;
|
|
256
|
-
function warnOnce(message) {
|
|
257
|
-
if (warned.has(message))
|
|
258
|
-
return;
|
|
259
|
-
warned.add(message);
|
|
260
|
-
console.error(`warning: theme ${message}`);
|
|
261
|
-
}
|
|
262
|
-
function isPath(chosen) {
|
|
263
|
-
return chosen.includes("/") || chosen.endsWith(".json");
|
|
264
|
-
}
|
|
265
|
-
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
266
|
-
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
267
|
-
const sources = [];
|
|
268
|
-
const chosen = env.KIT_THEME ?? "";
|
|
269
|
-
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
270
|
-
if (isPath(chosen))
|
|
271
|
-
wanted.push(resolve2(from, chosen));
|
|
272
|
-
const files = [];
|
|
273
|
-
for (const path of wanted) {
|
|
274
|
-
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
275
|
-
if (path !== undefined && file !== undefined)
|
|
276
|
-
files.push({ path, file });
|
|
277
|
-
}
|
|
278
|
-
let preset = "default";
|
|
279
|
-
if (chosen !== "" && !isPath(chosen)) {
|
|
280
|
-
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
281
|
-
} else {
|
|
282
|
-
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
283
|
-
if (named !== undefined)
|
|
284
|
-
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
285
|
-
}
|
|
286
|
-
for (const { path, file } of files) {
|
|
287
|
-
applyFile(theme, file, path, warn);
|
|
288
|
-
sources.push(path);
|
|
289
|
-
}
|
|
290
|
-
return { theme, sources, preset };
|
|
291
|
-
}
|
|
292
|
-
var current;
|
|
293
|
-
var currentKey = "";
|
|
294
|
-
function activeTheme() {
|
|
295
|
-
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
296
|
-
if (current === undefined || key !== currentKey) {
|
|
297
|
-
current = loadTheme();
|
|
298
|
-
currentKey = key;
|
|
299
|
-
}
|
|
300
|
-
return current;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
// ../kit/src/style.ts
|
|
304
|
-
function takesControlCodes(stream, env = process6.env) {
|
|
305
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
306
|
-
}
|
|
307
|
-
function paint(stream, env = process6.env) {
|
|
308
|
-
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
309
|
-
}
|
|
310
|
-
function role(name, stream, env = process6.env) {
|
|
311
|
-
const colors = paint(stream, env);
|
|
312
|
-
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
313
|
-
}
|
|
314
|
-
var STATUS_WORDS = {
|
|
315
|
-
passed: ["passed", "success", "succeeded", "ok"],
|
|
316
|
-
failed: ["failed", "failure", "error", "errored"],
|
|
317
|
-
running: ["running", "in_progress", "started", "holding"],
|
|
318
|
-
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
319
|
-
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
320
|
-
};
|
|
321
|
-
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
322
|
-
|
|
323
|
-
// ../kit/src/format.ts
|
|
324
|
-
var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
325
|
-
function formatSeconds(total) {
|
|
326
|
-
let rest = Math.max(0, Math.round(total));
|
|
327
|
-
const amounts = UNITS.map(([unit, size]) => {
|
|
328
|
-
const amount = Math.floor(rest / size);
|
|
329
|
-
rest -= amount * size;
|
|
330
|
-
return `${amount}${unit}`;
|
|
331
|
-
});
|
|
332
|
-
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
333
|
-
if (first === -1)
|
|
334
|
-
return "0s";
|
|
335
|
-
const next = amounts[first + 1];
|
|
336
|
-
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
337
|
-
}
|
|
338
|
-
function formatDuration(ms) {
|
|
339
|
-
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
340
|
-
}
|
|
341
|
-
function upTo(text, separator) {
|
|
342
|
-
const end = text.indexOf(separator);
|
|
343
|
-
return end === -1 ? text : text.slice(0, end);
|
|
344
|
-
}
|
|
345
|
-
var ESCAPE = String.fromCharCode(27);
|
|
346
|
-
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
347
|
-
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
348
|
-
}
|
|
349
|
-
function printJson(value) {
|
|
350
|
-
console.log(jsonText(value));
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
// ../kit/src/help.ts
|
|
354
|
-
import process8 from "process";
|
|
355
|
-
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
356
|
-
var USAGE_PREFIX = /^usage:\s*/i;
|
|
357
|
-
var FULL_STOP = /\.$/;
|
|
358
|
-
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
359
|
-
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
360
|
-
}
|
|
361
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
362
|
-
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
363
|
-
`);
|
|
364
|
-
}
|
|
365
|
-
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
366
|
-
if (exits.length === 0)
|
|
367
|
-
return [];
|
|
368
|
-
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
369
|
-
}
|
|
370
|
-
function wantsHelpJson(env = process8.env) {
|
|
371
|
-
return env.KIT_HELP === "json";
|
|
372
|
-
}
|
|
373
|
-
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
374
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
375
|
-
`);
|
|
376
|
-
const first = lines[0];
|
|
377
|
-
const colon = first.indexOf(": ");
|
|
378
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
379
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
380
|
-
return {
|
|
381
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
382
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
383
|
-
...replaces === undefined ? {} : { replaces },
|
|
384
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
385
|
-
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
386
|
-
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
387
|
-
};
|
|
388
|
-
}
|
|
389
|
-
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
390
|
-
if (examples.length === 0 || outputMode() === "agent")
|
|
391
|
-
return [];
|
|
392
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
393
|
-
}
|
|
394
|
-
var MAX_INLINE_CHOICES = 24;
|
|
395
|
-
function optionRows(options, colors = paint(process8.stdout)) {
|
|
396
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
397
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
398
|
-
const choices = option.choices?.join("|");
|
|
399
|
-
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
400
|
-
const named = inline ? `<${choices}>` : "<value>";
|
|
401
|
-
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
402
|
-
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
403
|
-
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
404
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
405
|
-
});
|
|
406
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
407
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
// ../kit/src/text.ts
|
|
411
|
-
function distance(a, b) {
|
|
412
|
-
const left = [...a];
|
|
413
|
-
const right = [...b];
|
|
414
|
-
let before = [];
|
|
415
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
416
|
-
for (const [i, x] of left.entries()) {
|
|
417
|
-
const current = [i + 1];
|
|
418
|
-
for (const [j, y] of right.entries()) {
|
|
419
|
-
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
420
|
-
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
421
|
-
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
422
|
-
current.push(cost);
|
|
423
|
-
}
|
|
424
|
-
before = previous;
|
|
425
|
-
previous = current;
|
|
426
|
-
}
|
|
427
|
-
return previous[right.length] ?? 0;
|
|
428
|
-
}
|
|
429
|
-
function closest(name, names) {
|
|
430
|
-
const started = names.find((known) => known.startsWith(name));
|
|
431
|
-
if (started !== undefined)
|
|
432
|
-
return started;
|
|
433
|
-
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
434
|
-
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
435
|
-
}
|
|
436
|
-
// ../kit/src/input.ts
|
|
437
|
-
var WHOLE = /^\d+$/;
|
|
438
|
-
function wholeNumber(value, name, fallback, min = 1) {
|
|
439
|
-
if (value === undefined)
|
|
440
|
-
return fallback;
|
|
441
|
-
const number = Number(value);
|
|
442
|
-
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
443
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
444
|
-
return number;
|
|
445
|
-
}
|
|
446
|
-
var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
|
|
447
|
-
var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
448
|
-
function duration(value, name, fallback, unit = "s") {
|
|
449
|
-
if (value === undefined)
|
|
450
|
-
return fallback;
|
|
451
|
-
const match = DURATION.exec(value.trim());
|
|
452
|
-
const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
|
|
453
|
-
if (ms < 1)
|
|
454
|
-
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
455
|
-
return ms;
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
// ../kit/src/args.ts
|
|
459
|
-
var DASHES = /^-+/;
|
|
460
|
-
function jsonOption(holds) {
|
|
461
|
-
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
462
|
-
}
|
|
463
|
-
class Exit extends Error {
|
|
464
|
-
code;
|
|
465
|
-
hint;
|
|
466
|
-
constructor(message, code, hint) {
|
|
467
|
-
super(message);
|
|
468
|
-
this.code = code;
|
|
469
|
-
this.hint = hint;
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
function fail(message, code = 2, hint) {
|
|
473
|
-
throw new Exit(message, code, hint);
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
class UsageError extends Exit {
|
|
477
|
-
constructor(message, hint) {
|
|
478
|
-
super(message, 2, hint);
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
function badUsage(message) {
|
|
482
|
-
throw new UsageError(message);
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
class HelpShown extends Exit {
|
|
486
|
-
constructor() {
|
|
487
|
-
super("help shown", 0);
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
class Completing {
|
|
492
|
-
options;
|
|
493
|
-
positionals;
|
|
494
|
-
candidates;
|
|
495
|
-
constructor(options, positionals = [], candidates = {}) {
|
|
496
|
-
this.options = options;
|
|
497
|
-
this.positionals = positionals;
|
|
498
|
-
this.candidates = candidates;
|
|
499
|
-
}
|
|
500
|
-
}
|
|
501
|
-
var completion = { active: false };
|
|
502
|
-
var OUTPUT_OPTIONS = {
|
|
503
|
-
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
504
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
505
|
-
};
|
|
506
|
-
function applyOutput(color, plain, env = process9.env) {
|
|
507
|
-
const when = plain === true ? "never" : color ?? "auto";
|
|
508
|
-
if (when === "auto")
|
|
509
|
-
return;
|
|
510
|
-
if (when !== "always" && when !== "never")
|
|
511
|
-
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
512
|
-
if (when === "always") {
|
|
513
|
-
env.FORCE_COLOR = "1";
|
|
514
|
-
delete env.NO_COLOR;
|
|
515
|
-
} else {
|
|
516
|
-
env.NO_COLOR = "1";
|
|
517
|
-
delete env.FORCE_COLOR;
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
function parse(args, usage, options, settings = {}) {
|
|
521
|
-
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
522
|
-
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
523
|
-
const listing = listed(all, settings.allowNegative === true);
|
|
524
|
-
if (completion.active)
|
|
525
|
-
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
526
|
-
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
527
|
-
let parsed;
|
|
528
|
-
try {
|
|
529
|
-
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
530
|
-
} catch (error) {
|
|
531
|
-
const message = parseError(error);
|
|
532
|
-
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
533
|
-
}
|
|
534
|
-
const values = parsed.values;
|
|
535
|
-
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
536
|
-
if (values.help === true) {
|
|
537
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
538
|
-
throw new HelpShown;
|
|
539
|
-
}
|
|
540
|
-
checkChoices(parsed.values, all);
|
|
541
|
-
checkConflicts(parsed.values, all);
|
|
542
|
-
if (settings.positionals !== undefined)
|
|
543
|
-
checkPositionals(parsed.positionals, settings.positionals);
|
|
544
|
-
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
545
|
-
}
|
|
546
|
-
function splitRest(args, passes) {
|
|
547
|
-
const separator = passes ? args.indexOf("--") : -1;
|
|
548
|
-
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
549
|
-
}
|
|
550
|
-
function splitTrailing(args, options, count) {
|
|
551
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
552
|
-
let seen = 0;
|
|
553
|
-
if (count === 0)
|
|
554
|
-
return { own: args, rest: undefined };
|
|
555
|
-
for (let at = 0;at < args.length; at++) {
|
|
556
|
-
const word = args[at];
|
|
557
|
-
if (word === "--")
|
|
558
|
-
break;
|
|
559
|
-
if (word.startsWith("-")) {
|
|
560
|
-
if (takesValue(word))
|
|
561
|
-
at++;
|
|
562
|
-
continue;
|
|
563
|
-
}
|
|
564
|
-
seen++;
|
|
565
|
-
if (seen === count)
|
|
566
|
-
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
567
|
-
}
|
|
568
|
-
return { own: args, rest: undefined };
|
|
569
|
-
}
|
|
570
|
-
function listed(options, allowNegative) {
|
|
571
|
-
if (!allowNegative)
|
|
572
|
-
return options;
|
|
573
|
-
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
574
|
-
if (option.type !== "boolean" || option.negative === undefined)
|
|
575
|
-
return [[name, option]];
|
|
576
|
-
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
577
|
-
}));
|
|
578
|
-
}
|
|
579
|
-
function withAliases(args, options) {
|
|
580
|
-
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
581
|
-
if (named.size === 0)
|
|
582
|
-
return args;
|
|
583
|
-
const separator = args.indexOf("--");
|
|
584
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
585
|
-
return [...own.map((arg) => {
|
|
586
|
-
const at = arg.indexOf("=");
|
|
587
|
-
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
588
|
-
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
589
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
590
|
-
}
|
|
591
|
-
function withBare(args, options) {
|
|
592
|
-
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
593
|
-
if (bare.size === 0)
|
|
594
|
-
return args;
|
|
595
|
-
const separator = args.indexOf("--");
|
|
596
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
597
|
-
return [...own.flatMap((arg, index) => {
|
|
598
|
-
const optional = bare.get(arg);
|
|
599
|
-
const next = own[index + 1];
|
|
600
|
-
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
601
|
-
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
602
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
603
|
-
}
|
|
604
|
-
function checkConflicts(values, options) {
|
|
605
|
-
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
606
|
-
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
607
|
-
const other = given(name) ? conflicts.find(given) : undefined;
|
|
608
|
-
if (other !== undefined)
|
|
609
|
-
badUsage(`--${name} cannot be used with --${other}`);
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
function checkChoices(values, options) {
|
|
613
|
-
for (const [name, option] of Object.entries(options)) {
|
|
614
|
-
if (option.choices === undefined)
|
|
615
|
-
continue;
|
|
616
|
-
const given = values[name];
|
|
617
|
-
for (const value of Array.isArray(given) ? given : [given]) {
|
|
618
|
-
if (typeof value === "string")
|
|
619
|
-
oneOf(value, name, option.choices);
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
function oneOf(value, name, choices) {
|
|
624
|
-
if (!choices.includes(value))
|
|
625
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
626
|
-
return value;
|
|
627
|
-
}
|
|
628
|
-
function checkPositionals(given, names) {
|
|
629
|
-
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
630
|
-
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
631
|
-
if (given.length < required)
|
|
632
|
-
badUsage(`missing ${names[given.length]}`);
|
|
633
|
-
if (!variadic && given.length > names.length)
|
|
634
|
-
badUsage(`unexpected argument ${given[names.length]}`);
|
|
635
|
-
}
|
|
636
|
-
function joinDashValues(args, options) {
|
|
637
|
-
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
638
|
-
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
639
|
-
const joined = [];
|
|
640
|
-
for (let i = 0;i < args.length; i++) {
|
|
641
|
-
const arg = args[i] ?? "";
|
|
642
|
-
if (arg === "--")
|
|
643
|
-
return [...joined, ...args.slice(i)];
|
|
644
|
-
const name = longOf.get(arg);
|
|
645
|
-
const next = args[i + 1];
|
|
646
|
-
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
647
|
-
joined.push(`--${name}=${next}`);
|
|
648
|
-
i++;
|
|
649
|
-
} else {
|
|
650
|
-
joined.push(arg);
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
return joined;
|
|
654
|
-
}
|
|
655
|
-
function parseError(error) {
|
|
656
|
-
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
657
|
-
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
658
|
-
}
|
|
659
|
-
var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
660
|
-
function nearestOption(message, options, allowNegative) {
|
|
661
|
-
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
662
|
-
if (typed === undefined)
|
|
663
|
-
return;
|
|
664
|
-
const word = typed.replace(DASHES, "");
|
|
665
|
-
if (word.length < 2 && !typed.startsWith("--"))
|
|
666
|
-
return;
|
|
667
|
-
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
668
|
-
...option.short === undefined ? [] : [`-${option.short}`],
|
|
669
|
-
`--${name}`,
|
|
670
|
-
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
671
|
-
]);
|
|
672
|
-
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
673
|
-
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
674
|
-
}
|
|
675
|
-
// ../kit/src/argv.ts
|
|
676
|
-
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
677
|
-
import { resolve as resolve3 } from "path";
|
|
678
|
-
import process10 from "process";
|
|
679
|
-
function commandLine() {
|
|
680
|
-
try {
|
|
681
|
-
return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
682
|
-
} catch {
|
|
683
|
-
return;
|
|
684
|
-
}
|
|
685
|
-
}
|
|
686
|
-
function realPath(word) {
|
|
687
|
-
try {
|
|
688
|
-
return realpathSync(resolve3(word));
|
|
689
|
-
} catch {
|
|
690
|
-
return;
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
694
|
-
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
695
|
-
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
696
|
-
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
697
|
-
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
698
|
-
}
|
|
699
|
-
// ../kit/src/process.ts
|
|
700
|
-
import { constants } from "os";
|
|
701
|
-
import process11 from "process";
|
|
702
|
-
var KILL_GRACE_MS = 2000;
|
|
703
|
-
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
704
|
-
function exitCodeOf(code, signal) {
|
|
705
|
-
if (code !== null)
|
|
706
|
-
return code;
|
|
707
|
-
if (typeof signal === "number")
|
|
708
|
-
return 128 + signal;
|
|
709
|
-
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
710
|
-
}
|
|
711
|
-
function holdSignals(cleanup) {
|
|
712
|
-
let received;
|
|
713
|
-
let child;
|
|
714
|
-
const held = {
|
|
715
|
-
get signal() {
|
|
716
|
-
return received;
|
|
717
|
-
},
|
|
718
|
-
forward: (to) => {
|
|
719
|
-
child = to;
|
|
720
|
-
},
|
|
721
|
-
release: () => {
|
|
722
|
-
for (const signal of SIGNALS)
|
|
723
|
-
process11.off(signal, onSignal);
|
|
724
|
-
}
|
|
725
|
-
};
|
|
726
|
-
function onSignal(signal) {
|
|
727
|
-
received = signal;
|
|
728
|
-
if (child !== undefined) {
|
|
729
|
-
child.kill(signal);
|
|
730
|
-
return;
|
|
731
|
-
}
|
|
732
|
-
if (cleanup === undefined)
|
|
733
|
-
return;
|
|
734
|
-
held.release();
|
|
735
|
-
cleanup(signal);
|
|
736
|
-
process11.kill(process11.pid, signal);
|
|
737
|
-
}
|
|
738
|
-
for (const signal of SIGNALS)
|
|
739
|
-
process11.on(signal, onSignal);
|
|
740
|
-
return held;
|
|
741
|
-
}
|
|
742
|
-
async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
743
|
-
const chunks = [];
|
|
744
|
-
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
745
|
-
const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
|
|
746
|
-
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
747
|
-
const timers = [];
|
|
748
|
-
const killGroup = (killing) => {
|
|
749
|
-
if (state.done)
|
|
750
|
-
return;
|
|
751
|
-
try {
|
|
752
|
-
if (grouped)
|
|
753
|
-
process11.kill(-proc.pid, killing);
|
|
754
|
-
else
|
|
755
|
-
proc.kill(killing);
|
|
756
|
-
} catch {}
|
|
757
|
-
};
|
|
758
|
-
const stop = () => {
|
|
759
|
-
killGroup("SIGTERM");
|
|
760
|
-
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
761
|
-
};
|
|
762
|
-
const onAbort = () => stop();
|
|
763
|
-
if (timeoutMs !== undefined) {
|
|
764
|
-
timers.push(setTimeout(() => {
|
|
765
|
-
state.timedOut = true;
|
|
766
|
-
stop();
|
|
767
|
-
}, timeoutMs));
|
|
768
|
-
}
|
|
769
|
-
if (signal?.aborted === true)
|
|
770
|
-
onAbort();
|
|
771
|
-
else
|
|
772
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
773
|
-
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
774
|
-
const drain = async (stream, name) => {
|
|
775
|
-
for await (const data of stream) {
|
|
776
|
-
if (state.failure !== undefined)
|
|
777
|
-
continue;
|
|
778
|
-
try {
|
|
779
|
-
onChunk?.({ stream: name, data });
|
|
780
|
-
} catch (error) {
|
|
781
|
-
state.failure = error;
|
|
782
|
-
stop();
|
|
783
|
-
continue;
|
|
784
|
-
}
|
|
785
|
-
if (state.kept + data.length > maxBytes) {
|
|
786
|
-
state.truncated = true;
|
|
787
|
-
continue;
|
|
788
|
-
}
|
|
789
|
-
state.kept += data.length;
|
|
790
|
-
chunks.push({ stream: name, data });
|
|
791
|
-
}
|
|
792
|
-
};
|
|
793
|
-
try {
|
|
794
|
-
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
795
|
-
await proc.exited;
|
|
796
|
-
} finally {
|
|
797
|
-
state.done = true;
|
|
798
|
-
for (const timer of timers)
|
|
799
|
-
clearTimeout(timer);
|
|
800
|
-
signal?.removeEventListener("abort", onAbort);
|
|
801
|
-
}
|
|
802
|
-
if (state.failure !== undefined)
|
|
803
|
-
throw state.failure;
|
|
804
|
-
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
805
|
-
let output;
|
|
806
|
-
let text;
|
|
807
|
-
return {
|
|
808
|
-
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
809
|
-
chunks,
|
|
810
|
-
timedOut: state.timedOut,
|
|
811
|
-
truncated: state.truncated,
|
|
812
|
-
get output() {
|
|
813
|
-
return output ??= joined();
|
|
814
|
-
},
|
|
815
|
-
get text() {
|
|
816
|
-
return text ??= (output ??= joined()).toString();
|
|
817
|
-
}
|
|
818
|
-
};
|
|
819
|
-
}
|
|
820
|
-
|
|
821
|
-
// ../kit/src/progress.ts
|
|
822
|
-
var ESC = String.fromCharCode(27);
|
|
823
|
-
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
824
|
-
var RESET_STYLE = `${ESC}[0m`;
|
|
825
|
-
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
826
|
-
// ../kit/src/cli.ts
|
|
827
|
-
import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
|
|
828
|
-
import { dirname as dirname3, join as join5 } from "path";
|
|
829
|
-
import process14 from "process";
|
|
830
|
-
|
|
831
|
-
// ../kit/src/completions.ts
|
|
832
|
-
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
833
|
-
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'
|
|
834
|
-
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
835
|
-
set -l current (commandline -ct)
|
|
836
|
-
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
837
|
-
if test "$line" = __files__
|
|
838
|
-
__fish_complete_path $current
|
|
839
|
-
else
|
|
840
|
-
echo $line
|
|
841
|
-
end
|
|
842
|
-
end
|
|
843
|
-
end`;
|
|
844
|
-
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
845
|
-
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
846
|
-
local -a lines
|
|
847
|
-
COMPREPLY=()
|
|
848
|
-
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
849
|
-
for line in "\${lines[@]}"; do
|
|
850
|
-
if [[ $line == __files__ ]]; then
|
|
851
|
-
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
852
|
-
else
|
|
853
|
-
words+="\${line%%$'\\t'*}"$'\\n'
|
|
854
|
-
fi
|
|
855
|
-
done
|
|
856
|
-
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
857
|
-
}`;
|
|
858
|
-
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
859
|
-
local line
|
|
860
|
-
local -a described plain
|
|
861
|
-
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
862
|
-
if [[ $line == __files__ ]]; then
|
|
863
|
-
_files
|
|
864
|
-
elif [[ $line == *$'\\t'* ]]; then
|
|
865
|
-
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
866
|
-
else
|
|
867
|
-
plain+=("$line")
|
|
868
|
-
fi
|
|
869
|
-
done
|
|
870
|
-
(( \${#described} )) && _describe -V value described
|
|
871
|
-
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
872
|
-
return 0
|
|
873
|
-
}`;
|
|
874
|
-
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
875
|
-
if (shell === "fish")
|
|
876
|
-
return `${header}
|
|
877
|
-
${FISH_FUNCTION}
|
|
878
|
-
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
879
|
-
`).join("")}`;
|
|
880
|
-
if (shell === "bash")
|
|
881
|
-
return `${header}
|
|
882
|
-
${BASH_FUNCTION}
|
|
883
|
-
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
884
|
-
`;
|
|
885
|
-
return `${header}
|
|
886
|
-
${ZSH_FUNCTION}
|
|
887
|
-
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
888
|
-
`;
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
// ../kit/src/notify.ts
|
|
892
|
-
import process12 from "process";
|
|
893
|
-
var NOTIFY_AFTER_MS = 1e4;
|
|
894
|
-
var CANCELLED = 130;
|
|
895
|
-
function base64(text) {
|
|
896
|
-
return Buffer.from(text).toString("base64");
|
|
897
|
-
}
|
|
898
|
-
function notification(title, body, env = process12.env) {
|
|
899
|
-
const id = `kit${process12.pid}`;
|
|
900
|
-
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\\`];
|
|
901
|
-
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
902
|
-
}
|
|
903
|
-
function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
|
|
904
|
-
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
905
|
-
return;
|
|
906
|
-
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
// ../kit/src/usage.ts
|
|
910
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
911
|
-
import { homedir as homedir3 } from "os";
|
|
912
|
-
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
913
|
-
import process13 from "process";
|
|
914
|
-
|
|
915
|
-
// ../kit/src/logs.ts
|
|
916
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
917
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
918
|
-
|
|
919
|
-
// ../kit/src/usage.ts
|
|
920
|
-
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
921
|
-
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
922
|
-
var LONGEST_NAME = 40;
|
|
923
|
-
var usageError;
|
|
924
|
-
function noteUsageError(message) {
|
|
925
|
-
usageError = message;
|
|
926
|
-
}
|
|
927
|
-
function stateHome(env = process13.env) {
|
|
928
|
-
const dir = env.XDG_STATE_HOME;
|
|
929
|
-
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
930
|
-
}
|
|
931
|
-
function usagePath(env = process13.env) {
|
|
932
|
-
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
933
|
-
}
|
|
934
|
-
function usageRecorded(env = process13.env) {
|
|
935
|
-
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
936
|
-
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
937
|
-
}
|
|
938
|
-
function flagNames(argv) {
|
|
939
|
-
const end = argv.indexOf("--");
|
|
940
|
-
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
941
|
-
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
942
|
-
}
|
|
943
|
-
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
944
|
-
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
945
|
-
usageError = undefined;
|
|
946
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
947
|
-
}
|
|
948
|
-
function recordUsage(entry, env = process13.env) {
|
|
949
|
-
if (!usageRecorded(env))
|
|
950
|
-
return;
|
|
951
|
-
try {
|
|
952
|
-
const path = usagePath(env);
|
|
953
|
-
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
954
|
-
appendFileSync(path, `${JSON.stringify(entry)}
|
|
955
|
-
`, { mode: 384 });
|
|
956
|
-
} catch {}
|
|
957
|
-
}
|
|
958
|
-
|
|
959
|
-
// ../kit/src/cli.ts
|
|
960
|
-
var LEVEL_OPTIONS = {
|
|
961
|
-
...OUTPUT_OPTIONS,
|
|
962
|
-
help: { type: "boolean", short: "h", description: "show this help" }
|
|
963
|
-
};
|
|
964
|
-
var TOP_OPTIONS = {
|
|
965
|
-
...LEVEL_OPTIONS,
|
|
966
|
-
version: { type: "boolean", short: "v", description: "print the version" },
|
|
967
|
-
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
968
|
-
};
|
|
969
|
-
async function commandRows(all, colors) {
|
|
970
|
-
const commands = shown(all);
|
|
971
|
-
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
972
|
-
const groups = new Map([["Commands:", []]]);
|
|
973
|
-
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
974
|
-
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
975
|
-
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
976
|
-
const rows = groups.get(heading) ?? [];
|
|
977
|
-
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
978
|
-
groups.set(heading, rows);
|
|
979
|
-
}
|
|
980
|
-
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
981
|
-
}
|
|
982
|
-
function shown(commands) {
|
|
983
|
-
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
984
|
-
}
|
|
985
|
-
function takeOutputFlags(argv) {
|
|
986
|
-
let index = 0;
|
|
987
|
-
for (;index < argv.length; index++) {
|
|
988
|
-
const word = argv[index];
|
|
989
|
-
if (word === "--plain")
|
|
990
|
-
applyOutput(undefined, true);
|
|
991
|
-
else if (word.startsWith("--color="))
|
|
992
|
-
applyOutput(word.slice("--color=".length), undefined);
|
|
993
|
-
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
994
|
-
applyOutput(argv[++index], undefined);
|
|
995
|
-
else
|
|
996
|
-
break;
|
|
997
|
-
}
|
|
998
|
-
return argv.slice(index);
|
|
999
|
-
}
|
|
1000
|
-
async function resolveSummary(summary) {
|
|
1001
|
-
return typeof summary === "string" ? summary : summary();
|
|
1002
|
-
}
|
|
1003
|
-
function scopeOf(commands, extra, aliases) {
|
|
1004
|
-
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
1005
|
-
}
|
|
1006
|
-
async function expand(scope, words) {
|
|
1007
|
-
if (scope.lazy.length === 0)
|
|
1008
|
-
return scope;
|
|
1009
|
-
const commands = { ...scope.commands };
|
|
1010
|
-
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
1011
|
-
for (const [name, command] of Object.entries(added))
|
|
1012
|
-
commands[name] ??= command;
|
|
1013
|
-
}
|
|
1014
|
-
return { ...scope, commands, lazy: [] };
|
|
1015
|
-
}
|
|
1016
|
-
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
1017
|
-
const colors = paint(stream);
|
|
1018
|
-
const prefix = path.join(" ");
|
|
1019
|
-
const summary = await resolveSummary(lazySummary);
|
|
1020
|
-
if (wantsHelpJson())
|
|
1021
|
-
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
1022
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1023
|
-
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
1024
|
-
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
1025
|
-
return [
|
|
1026
|
-
header(colors, summary),
|
|
1027
|
-
"",
|
|
1028
|
-
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
1029
|
-
"",
|
|
1030
|
-
...await commandRows(commands, colors),
|
|
1031
|
-
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
1032
|
-
"",
|
|
1033
|
-
colors.bold("Options:"),
|
|
1034
|
-
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
1035
|
-
...exampleRows(examples ?? [], colors),
|
|
1036
|
-
"",
|
|
1037
|
-
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
1038
|
-
].join(`
|
|
1039
|
-
`);
|
|
1040
|
-
}
|
|
1041
|
-
function printError(prefix, message, hint, cause) {
|
|
1042
|
-
const colors = paint(process14.stderr);
|
|
1043
|
-
const styled = takesControlCodes(process14.stderr);
|
|
1044
|
-
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1045
|
-
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1046
|
-
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1047
|
-
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1048
|
-
}
|
|
1049
|
-
function printJsonError(message, hint, cause) {
|
|
1050
|
-
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1051
|
-
}
|
|
1052
|
-
function wantsJson(argv) {
|
|
1053
|
-
const end = argv.indexOf("--");
|
|
1054
|
-
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1055
|
-
}
|
|
1056
|
-
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1057
|
-
if (error instanceof HelpShown)
|
|
1058
|
-
return 0;
|
|
1059
|
-
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1060
|
-
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1061
|
-
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1062
|
-
if (error instanceof Exit && error.code === 2)
|
|
1063
|
-
noteUsageError(error.message);
|
|
1064
|
-
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1065
|
-
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1066
|
-
return error instanceof Exit ? error.code : 1;
|
|
1067
|
-
}
|
|
1068
|
-
async function dispatch(level, typed, { version, redact }) {
|
|
1069
|
-
const prefix = level.path.join(" ");
|
|
1070
|
-
let argv;
|
|
1071
|
-
try {
|
|
1072
|
-
argv = takeOutputFlags(typed);
|
|
1073
|
-
} catch (error) {
|
|
1074
|
-
return reportThrown(prefix, error);
|
|
1075
|
-
}
|
|
1076
|
-
const [name, ...args] = argv;
|
|
1077
|
-
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
1078
|
-
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
1079
|
-
try {
|
|
1080
|
-
return await fallback.run([]);
|
|
1081
|
-
} catch (error) {
|
|
1082
|
-
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
1083
|
-
}
|
|
1084
|
-
}
|
|
1085
|
-
if (name === undefined && level.path.length > 1) {
|
|
1086
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
|
|
1087
|
-
return 2;
|
|
1088
|
-
}
|
|
1089
|
-
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1090
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
|
|
1091
|
-
return 0;
|
|
1092
|
-
}
|
|
1093
|
-
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1094
|
-
console.log(version);
|
|
1095
|
-
return 0;
|
|
1096
|
-
}
|
|
1097
|
-
let command = level.commands[level.aliases?.[name] ?? name];
|
|
1098
|
-
let rest = args;
|
|
1099
|
-
let ran = name;
|
|
1100
|
-
if (command === undefined && level.lazy.length > 0) {
|
|
1101
|
-
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1102
|
-
command = level.commands[level.aliases?.[name] ?? name];
|
|
1103
|
-
}
|
|
1104
|
-
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1105
|
-
command = level.commands[level.defaultCommand];
|
|
1106
|
-
rest = argv;
|
|
1107
|
-
ran = level.defaultCommand;
|
|
1108
|
-
}
|
|
1109
|
-
if (command === undefined) {
|
|
1110
|
-
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
1111
|
-
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
1112
|
-
return 2;
|
|
1113
|
-
}
|
|
1114
|
-
if ("commands" in command) {
|
|
1115
|
-
const { summary } = command;
|
|
1116
|
-
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 });
|
|
1117
|
-
}
|
|
1118
|
-
try {
|
|
1119
|
-
return await command.run(rest);
|
|
1120
|
-
} catch (error) {
|
|
1121
|
-
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
1122
|
-
}
|
|
1123
|
-
}
|
|
1124
|
-
var COMPLETE = "__complete";
|
|
1125
|
-
var FILES = "__files__";
|
|
1126
|
-
async function completingOf(run) {
|
|
1127
|
-
completion.active = true;
|
|
1128
|
-
try {
|
|
1129
|
-
await run([]);
|
|
1130
|
-
} catch (error) {
|
|
1131
|
-
if (error instanceof Completing)
|
|
1132
|
-
return error;
|
|
1133
|
-
} finally {
|
|
1134
|
-
completion.active = false;
|
|
1135
|
-
}
|
|
1136
|
-
return new Completing({});
|
|
1137
|
-
}
|
|
1138
|
-
async function optionsOf(run) {
|
|
1139
|
-
return (await completingOf(run)).options;
|
|
1140
|
-
}
|
|
1141
|
-
function candidateLine(candidate) {
|
|
1142
|
-
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1143
|
-
}
|
|
1144
|
-
function positionalBeingTyped(before, { options, positionals }) {
|
|
1145
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1146
|
-
const typed = [];
|
|
1147
|
-
let at = 0;
|
|
1148
|
-
while (at < before.length) {
|
|
1149
|
-
const word = before[at];
|
|
1150
|
-
if (word === "--") {
|
|
1151
|
-
typed.push(...before.slice(at + 1));
|
|
1152
|
-
break;
|
|
1153
|
-
}
|
|
1154
|
-
if (!word.startsWith("-"))
|
|
1155
|
-
typed.push(word);
|
|
1156
|
-
else if (takesValue(word))
|
|
1157
|
-
at++;
|
|
1158
|
-
at++;
|
|
1159
|
-
}
|
|
1160
|
-
const last = positionals.at(-1);
|
|
1161
|
-
if (typed.length < positionals.length)
|
|
1162
|
-
return { name: positionals[typed.length], typed };
|
|
1163
|
-
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1164
|
-
}
|
|
1165
|
-
async function leafCandidates(run, words) {
|
|
1166
|
-
const completing = await completingOf(run);
|
|
1167
|
-
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1168
|
-
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1169
|
-
const flag = words.at(-2);
|
|
1170
|
-
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1171
|
-
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1172
|
-
if (option?.type === "string") {
|
|
1173
|
-
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1174
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1175
|
-
}
|
|
1176
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1177
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1178
|
-
}
|
|
1179
|
-
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1180
|
-
const [word = "", ...rest] = words;
|
|
1181
|
-
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1182
|
-
let { commands, aliases } = scope;
|
|
1183
|
-
let command = commands[aliases?.[word] ?? word];
|
|
1184
|
-
if (listing || command === undefined) {
|
|
1185
|
-
({ commands, aliases } = await expand(scope, [...before, ...words]));
|
|
1186
|
-
command = commands[aliases?.[word] ?? word];
|
|
1187
|
-
}
|
|
1188
|
-
if (listing) {
|
|
1189
|
-
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1190
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1191
|
-
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1192
|
-
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1193
|
-
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
|
|
1194
|
-
}
|
|
1195
|
-
if (command === undefined) {
|
|
1196
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1197
|
-
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1198
|
-
}
|
|
1199
|
-
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1200
|
-
}
|
|
1201
|
-
var COMPLETIONS = "--completions";
|
|
1202
|
-
function flagValue([flag = "", ...rest]) {
|
|
1203
|
-
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1204
|
-
}
|
|
1205
|
-
function printCompletionScript(name, args) {
|
|
1206
|
-
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1207
|
-
if (shell === undefined || args.length !== 1) {
|
|
1208
|
-
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1209
|
-
return 2;
|
|
1210
|
-
}
|
|
1211
|
-
console.log(completionScript(shell, [name]).trimEnd());
|
|
1212
|
-
return 0;
|
|
1213
|
-
}
|
|
1214
|
-
async function printCandidates(found) {
|
|
1215
|
-
for (const line of await found)
|
|
1216
|
-
console.log(line);
|
|
1217
|
-
return 0;
|
|
1218
|
-
}
|
|
1219
|
-
function packageVersion(entry = Bun.main) {
|
|
1220
|
-
let resolved = entry;
|
|
1221
|
-
try {
|
|
1222
|
-
resolved = realpathSync2(entry);
|
|
1223
|
-
} catch {}
|
|
1224
|
-
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1225
|
-
try {
|
|
1226
|
-
const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
|
|
1227
|
-
if (typeof version === "string")
|
|
1228
|
-
return version;
|
|
1229
|
-
} catch {}
|
|
1230
|
-
if (dirname3(dir) === dir)
|
|
1231
|
-
return "0.0.0";
|
|
1232
|
-
}
|
|
1233
|
-
}
|
|
1234
|
-
async function runCli(cli, argv = scriptArgs()) {
|
|
1235
|
-
const version = cli.version ?? packageVersion();
|
|
1236
|
-
if (argv[0] === COMPLETE)
|
|
1237
|
-
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1238
|
-
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1239
|
-
return printCompletionScript(cli.name, flagValue(argv));
|
|
1240
|
-
const started = performance.now();
|
|
1241
|
-
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 });
|
|
1242
|
-
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1243
|
-
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1244
|
-
if (cli.usage !== false) {
|
|
1245
|
-
try {
|
|
1246
|
-
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1247
|
-
} catch {}
|
|
1248
|
-
}
|
|
1249
|
-
return code;
|
|
1250
|
-
}
|
|
1251
|
-
function commandPath(scope, argv) {
|
|
1252
|
-
const path = [];
|
|
1253
|
-
let level = scope;
|
|
1254
|
-
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1255
|
-
const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
|
|
1256
|
-
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
1257
|
-
if (command === undefined)
|
|
1258
|
-
break;
|
|
1259
|
-
path.push(word);
|
|
1260
|
-
if (!("commands" in command))
|
|
1261
|
-
break;
|
|
1262
|
-
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1263
|
-
}
|
|
1264
|
-
return path.length === 0 ? undefined : path.join(" ");
|
|
1265
|
-
}
|
|
1266
|
-
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1267
|
-
if (argv[0] === COMPLETE)
|
|
1268
|
-
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1269
|
-
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1270
|
-
return printCompletionScript(name, flagValue(argv));
|
|
1271
|
-
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1272
|
-
console.log(version ?? packageVersion());
|
|
1273
|
-
return 0;
|
|
1274
|
-
}
|
|
1275
|
-
let code;
|
|
1276
|
-
const started = performance.now();
|
|
1277
|
-
try {
|
|
1278
|
-
code = await run(argv);
|
|
1279
|
-
} catch (error) {
|
|
1280
|
-
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1281
|
-
}
|
|
1282
|
-
notifyEnd(name, code, performance.now() - started);
|
|
1283
|
-
if (usage !== false) {
|
|
1284
|
-
try {
|
|
1285
|
-
recordUsage(usageEntry(name, undefined, argv, code));
|
|
1286
|
-
} catch {}
|
|
1287
|
-
}
|
|
1288
|
-
return code;
|
|
1289
|
-
}
|
|
1290
|
-
// ../kit/src/folders.ts
|
|
1291
|
-
var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
1292
|
-
// ../kit/src/secrets.ts
|
|
1293
|
-
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1294
|
-
// ../kit/src/sessions.ts
|
|
1295
|
-
var {Glob } = globalThis.Bun;
|
|
1296
|
-
var SESSION_FILES = new Glob("*.json");
|
|
1297
|
-
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1298
|
-
// src/proof.ts
|
|
1299
|
-
import process17 from "process";
|
|
1300
|
-
|
|
1301
|
-
// src/worktree.ts
|
|
1302
|
-
import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync3, rmSync, symlinkSync, unlinkSync } from "fs";
|
|
1303
|
-
import { tmpdir } from "os";
|
|
1304
|
-
import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as resolve4, sep } from "path";
|
|
1305
|
-
import process16 from "process";
|
|
1306
|
-
var WHITESPACE = /\s/;
|
|
1307
|
-
var ORIGIN_PREFIX = /^origin\//;
|
|
1308
|
-
var ENV_FILE = /^\.env(?:\..+)?$/;
|
|
1309
|
-
var DEPENDENCIES = new Set(["node_modules", "vendor", ".venv"]);
|
|
1310
|
-
var TRAILING_SLASH = /\/$/;
|
|
1311
|
-
var PARENT = `..${sep}`;
|
|
1312
|
-
var BASE_DIR = /^base-\w{6}$/;
|
|
1313
|
-
var CONTAINER = /(?:^|[\s;&|(])(?:docker\s+compose|docker-compose)\s+(?:-\S+(?:\s+[^-\s]\S*)?\s+)*(?:exec|run)\b|(?:^|[\s;&|(])docker\s+exec\b/;
|
|
1314
|
-
function stdoutOf(ran) {
|
|
1315
|
-
return Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString().trim();
|
|
1316
|
-
}
|
|
1317
|
-
async function git2(args, cwd) {
|
|
1318
|
-
return runCommand(["git", ...args], { cwd });
|
|
1319
|
-
}
|
|
1320
|
-
function runsInContainer(command) {
|
|
1321
|
-
return CONTAINER.test(command.join(" "));
|
|
1322
|
-
}
|
|
1323
|
-
async function checkout(cwd) {
|
|
1324
|
-
const ran = await git2(["rev-parse", "--show-toplevel", "--show-prefix"], cwd);
|
|
1325
|
-
if (ran.code !== 0)
|
|
1326
|
-
fail("not inside a git repository");
|
|
1327
|
-
const [root = "", prefix = ""] = stdoutOf(ran).split(`
|
|
1328
|
-
`);
|
|
1329
|
-
return { root, prefix };
|
|
1330
|
-
}
|
|
1331
|
-
async function resolveRef(root, ref) {
|
|
1332
|
-
const ran = await git2(["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`], root);
|
|
1333
|
-
if (ran.code !== 0)
|
|
1334
|
-
fail(`no commit ${ref} in this repository`);
|
|
1335
|
-
return stdoutOf(ran);
|
|
1336
|
-
}
|
|
1337
|
-
async function defaultRemoteRef(root) {
|
|
1338
|
-
const head = await git2(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], root);
|
|
1339
|
-
return head.code === 0 && stdoutOf(head) !== "" ? stdoutOf(head) : "origin/main";
|
|
1340
|
-
}
|
|
1341
|
-
async function defaultProofRef(root) {
|
|
1342
|
-
const branch = await git2(["symbolic-ref", "--quiet", "--short", "HEAD"], root);
|
|
1343
|
-
const remote = await defaultRemoteRef(root);
|
|
1344
|
-
if (branch.code !== 0 || stdoutOf(branch) === remote.replace(ORIGIN_PREFIX, ""))
|
|
1345
|
-
return "HEAD";
|
|
1346
|
-
const base = await git2(["merge-base", "HEAD", remote], root);
|
|
1347
|
-
const head = await git2(["rev-parse", "HEAD"], root);
|
|
1348
|
-
return base.code === 0 && stdoutOf(base) !== stdoutOf(head) ? stdoutOf(base) : "HEAD";
|
|
1349
|
-
}
|
|
1350
|
-
function keptPaths(root, cwd, paths) {
|
|
1351
|
-
const realRoot = realpathSync3(root);
|
|
1352
|
-
return paths.map((path) => {
|
|
1353
|
-
const absolute = resolve4(cwd, path);
|
|
1354
|
-
if (!existsSync3(dirname4(absolute)))
|
|
1355
|
-
fail(`--keep ${path}: no such file`);
|
|
1356
|
-
const inRepo = relative(realRoot, join6(realpathSync3(dirname4(absolute)), basename(absolute)));
|
|
1357
|
-
if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute2(inRepo))
|
|
1358
|
-
fail(`--keep ${path} is outside the repository`);
|
|
1359
|
-
if (!existsSync3(absolute))
|
|
1360
|
-
fail(`--keep ${path}: no such file`);
|
|
1361
|
-
return inRepo;
|
|
1362
|
-
});
|
|
1363
|
-
}
|
|
1364
|
-
function checkNoSymlink(dir, path) {
|
|
1365
|
-
let current = dir;
|
|
1366
|
-
for (const part of dirname4(path).split(sep)) {
|
|
1367
|
-
current = join6(current, part);
|
|
1368
|
-
if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink() === true)
|
|
1369
|
-
fail(`--keep ${path} goes through the symlink ${relative(dir, current)} of the ref, which would write outside the worktree`);
|
|
1370
|
-
}
|
|
1371
|
-
}
|
|
1372
|
-
async function linkedEntries(root) {
|
|
1373
|
-
const ran = await git2(["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], root);
|
|
1374
|
-
if (ran.code !== 0)
|
|
1375
|
-
return [];
|
|
1376
|
-
return stdoutOf(ran).split("\x00").filter((entry) => {
|
|
1377
|
-
const folder = entry.endsWith("/");
|
|
1378
|
-
const name = basename(entry);
|
|
1379
|
-
return folder ? DEPENDENCIES.has(name) : ENV_FILE.test(name);
|
|
1380
|
-
}).map((entry) => entry.replace(TRAILING_SLASH, ""));
|
|
1381
|
-
}
|
|
1382
|
-
async function addWorktree(root, sha) {
|
|
1383
|
-
const dir = join6(mkdtempSync(join6(tmpdir(), "base-")), basename(root));
|
|
1384
|
-
const ran = await git2(["worktree", "add", "--detach", dir, sha], root);
|
|
1385
|
-
if (ran.code !== 0) {
|
|
1386
|
-
rmSync(dirname4(dir), { recursive: true, force: true });
|
|
1387
|
-
fail(`git worktree add failed:
|
|
1388
|
-
${ran.text.trim()}`);
|
|
1389
|
-
}
|
|
1390
|
-
return dir;
|
|
1391
|
-
}
|
|
1392
|
-
function copyKept(root, dir, paths) {
|
|
1393
|
-
for (const path of paths) {
|
|
1394
|
-
checkNoSymlink(dir, path);
|
|
1395
|
-
const target = join6(dir, path);
|
|
1396
|
-
rmSync(target, { recursive: true, force: true });
|
|
1397
|
-
mkdirSync2(dirname4(target), { recursive: true });
|
|
1398
|
-
cpSync(join6(root, path), target, { recursive: true });
|
|
1399
|
-
}
|
|
1400
|
-
}
|
|
1401
|
-
function linkEntries(root, dir, entries) {
|
|
1402
|
-
const links = [];
|
|
1403
|
-
for (const entry of entries) {
|
|
1404
|
-
const link = join6(dir, entry);
|
|
1405
|
-
if (existsSync3(link))
|
|
1406
|
-
continue;
|
|
1407
|
-
mkdirSync2(dirname4(link), { recursive: true });
|
|
1408
|
-
if (basename(entry) === "node_modules" && hasWorkspaceLinks(root, entry)) {
|
|
1409
|
-
links.push(...linkModules(root, dir, entry));
|
|
1410
|
-
continue;
|
|
1411
|
-
}
|
|
1412
|
-
symlinkSync(join6(root, entry), link);
|
|
1413
|
-
links.push(link);
|
|
1414
|
-
}
|
|
1415
|
-
return links;
|
|
1416
|
-
}
|
|
1417
|
-
function moduleLinks(root, folder) {
|
|
1418
|
-
const found = [];
|
|
1419
|
-
for (const entry of readdirSync(join6(root, folder), { withFileTypes: true })) {
|
|
1420
|
-
if (entry.isSymbolicLink())
|
|
1421
|
-
found.push({ path: join6(folder, entry.name), name: entry.name });
|
|
1422
|
-
else if (entry.isDirectory() && entry.name.startsWith("@"))
|
|
1423
|
-
found.push(...moduleLinks(root, join6(folder, entry.name)));
|
|
1424
|
-
}
|
|
1425
|
-
return found;
|
|
1426
|
-
}
|
|
1427
|
-
function workspaceTarget(root, path) {
|
|
1428
|
-
try {
|
|
1429
|
-
const inRepo = relative(realpathSync3(root), realpathSync3(join6(root, path)));
|
|
1430
|
-
return inRepo === "" || inRepo.startsWith(PARENT) || inRepo.split(sep).includes("node_modules") ? undefined : inRepo;
|
|
1431
|
-
} catch {
|
|
1432
|
-
return;
|
|
1433
|
-
}
|
|
1434
|
-
}
|
|
1435
|
-
function hasWorkspaceLinks(root, folder) {
|
|
1436
|
-
return moduleLinks(root, folder).some(({ path }) => workspaceTarget(root, path) !== undefined);
|
|
1437
|
-
}
|
|
1438
|
-
function linkModules(root, dir, folder) {
|
|
1439
|
-
const links = [];
|
|
1440
|
-
mkdirSync2(join6(dir, folder), { recursive: true });
|
|
1441
|
-
for (const entry of readdirSync(join6(root, folder), { withFileTypes: true })) {
|
|
1442
|
-
const path = join6(folder, entry.name);
|
|
1443
|
-
const link = join6(dir, path);
|
|
1444
|
-
if (entry.isDirectory() && entry.name.startsWith("@")) {
|
|
1445
|
-
links.push(...linkModules(root, dir, path));
|
|
1446
|
-
continue;
|
|
1447
|
-
}
|
|
1448
|
-
const workspace = entry.isSymbolicLink() ? workspaceTarget(root, path) : undefined;
|
|
1449
|
-
symlinkSync(workspace === undefined ? join6(root, path) : join6(dir, workspace), link);
|
|
1450
|
-
links.push(link);
|
|
1451
|
-
}
|
|
1452
|
-
return links;
|
|
1453
|
-
}
|
|
1454
|
-
var STALE_AFTER = 24 * 60 * 60 * 1000;
|
|
1455
|
-
async function sweepStale(root) {
|
|
1456
|
-
for (const name of readdirSync(tmpdir())) {
|
|
1457
|
-
if (!BASE_DIR.test(name))
|
|
1458
|
-
continue;
|
|
1459
|
-
const path = join6(tmpdir(), name);
|
|
1460
|
-
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
1461
|
-
if (stat?.isDirectory() === true && stat.uid === process16.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
|
|
1462
|
-
rmSync(path, { recursive: true, force: true });
|
|
1463
|
-
}
|
|
1464
|
-
await git2(["worktree", "prune"], root);
|
|
1465
|
-
}
|
|
1466
|
-
async function removeWorktree(root, dir, links) {
|
|
1467
|
-
for (const link of links) {
|
|
1468
|
-
if (lstatSync(link, { throwIfNoEntry: false })?.isSymbolicLink() === true)
|
|
1469
|
-
unlinkSync(link);
|
|
1470
|
-
}
|
|
1471
|
-
await git2(["worktree", "remove", "--force", dir], root);
|
|
1472
|
-
rmSync(dirname4(dir), { recursive: true, force: true });
|
|
1473
|
-
await git2(["worktree", "prune"], root);
|
|
1474
|
-
}
|
|
1475
|
-
function shellCommand(given) {
|
|
1476
|
-
const [only] = given;
|
|
1477
|
-
return given.length === 1 && only !== undefined && WHITESPACE.test(only) ? ["sh", "-c", only] : given;
|
|
1478
|
-
}
|
|
1479
|
-
var TIMEOUT_DRAIN_MS = 500;
|
|
1480
|
-
async function runIn(dir, command, signals, capture = false, timeoutMs) {
|
|
1481
|
-
if (signals.signal !== undefined)
|
|
1482
|
-
return { code: exitCodeOf(null, signals.signal), output: "", started: true };
|
|
1483
|
-
let child;
|
|
1484
|
-
try {
|
|
1485
|
-
child = Bun.spawn(command, { cwd: dir, stdin: "inherit", stdout: capture ? "pipe" : "inherit", stderr: capture ? "pipe" : "inherit" });
|
|
1486
|
-
} catch (error) {
|
|
1487
|
-
return { code: 127, output: `cannot run ${command[0]}: ${error instanceof Error ? error.message : String(error)}`, started: false };
|
|
1488
|
-
}
|
|
1489
|
-
signals.forward(child);
|
|
1490
|
-
const chunks = [];
|
|
1491
|
-
let timedOut = false;
|
|
1492
|
-
const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
1493
|
-
timedOut = true;
|
|
1494
|
-
child.kill("SIGKILL");
|
|
1495
|
-
}, timeoutMs);
|
|
1496
|
-
const collected = capture ? Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]) : Promise.resolve([]);
|
|
1497
|
-
await child.exited;
|
|
1498
|
-
clearTimeout(timer);
|
|
1499
|
-
await (timedOut ? Promise.race([collected, Bun.sleep(TIMEOUT_DRAIN_MS)]) : collected);
|
|
1500
|
-
return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true, ...timedOut ? { timedOut } : {} };
|
|
1501
|
-
}
|
|
1502
|
-
async function collect(stream, chunks) {
|
|
1503
|
-
for await (const chunk of stream)
|
|
1504
|
-
chunks.push(chunk);
|
|
1505
|
-
}
|
|
1506
|
-
var FOLD_OVER = 120;
|
|
1507
|
-
var FOLD_HEAD = 20;
|
|
1508
|
-
var FOLD_TAIL = 80;
|
|
1509
|
-
function folded(output) {
|
|
1510
|
-
const lines = output.trimEnd().split(`
|
|
1511
|
-
`);
|
|
1512
|
-
if (lines.length <= FOLD_OVER)
|
|
1513
|
-
return lines.join(`
|
|
1514
|
-
`);
|
|
1515
|
-
return [...lines.slice(0, FOLD_HEAD), `... ${lines.length - FOLD_HEAD - FOLD_TAIL} lines omitted, --json has them all ...`, ...lines.slice(-FOLD_TAIL)].join(`
|
|
1516
|
-
`);
|
|
1517
|
-
}
|
|
1518
|
-
async function inWorktree(options, body) {
|
|
1519
|
-
const { root, prefix, sha, ref, kept, link } = options;
|
|
1520
|
-
let links = [];
|
|
1521
|
-
const signals = options.signals ?? holdSignals();
|
|
1522
|
-
await sweepStale(root);
|
|
1523
|
-
const dir = await addWorktree(root, sha);
|
|
1524
|
-
try {
|
|
1525
|
-
copyKept(root, dir, kept);
|
|
1526
|
-
links = link ? linkEntries(root, dir, await linkedEntries(root)) : [];
|
|
1527
|
-
const runDir = join6(dir, prefix);
|
|
1528
|
-
if (!existsSync3(runDir))
|
|
1529
|
-
fail(`${prefix} does not exist at ${ref}`);
|
|
1530
|
-
return await body(runDir, signals);
|
|
1531
|
-
} finally {
|
|
1532
|
-
await removeWorktree(root, dir, links);
|
|
1533
|
-
if (options.signals === undefined)
|
|
1534
|
-
signals.release();
|
|
1535
|
-
}
|
|
1536
|
-
}
|
|
1537
|
-
|
|
1538
|
-
// src/proof.ts
|
|
1539
|
-
var USAGE = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--timeout <duration>] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
|
|
1540
|
-
|
|
1541
|
-
The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass. --timeout kills a run that lasts longer (a hung test), which says nothing about the change and ends with exit 2.`;
|
|
1542
|
-
var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start, ends with exit 126, 127, 125 or a signal, or runs past --timeout"], [130, "interrupted (128 plus the signal)"]];
|
|
1543
|
-
var OPTIONS = {
|
|
1544
|
-
ref: { type: "string", short: "r", description: "the commit to run before at (default: the merge base with the default branch of origin on a branch ahead of it, else HEAD)" },
|
|
1545
|
-
runs: { type: "string", short: "n", description: "run the command this many times now, every run must pass (1)" },
|
|
1546
|
-
keep: { type: "string", short: "k", multiple: true, description: "a working-tree file or folder copied over to the ref, such as the new test, repeatable" },
|
|
1547
|
-
timeout: { type: "string", short: "t", description: "kill each run lasting longer than this (30s, 5m, 1h), a result of neither side" },
|
|
1548
|
-
"no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" },
|
|
1549
|
-
json: jsonOption("{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}")
|
|
1550
|
-
};
|
|
1551
|
-
function abnormal(code) {
|
|
1552
|
-
return code === 125 || code === 126 || code === 127 || code > 128 && code < 160;
|
|
1553
|
-
}
|
|
1554
|
-
function outcomeOf(before, now) {
|
|
1555
|
-
const failed = now.filter((code) => code !== 0).length;
|
|
1556
|
-
if (before !== 0 && failed === 0)
|
|
1557
|
-
return "proved";
|
|
1558
|
-
if (before === 0 && failed === 0)
|
|
1559
|
-
return "passes-before";
|
|
1560
|
-
if (before !== 0)
|
|
1561
|
-
return failed < now.length ? "flaky" : "fails-both";
|
|
1562
|
-
return "regressed";
|
|
1563
|
-
}
|
|
1564
|
-
function describe(outcome, at, now) {
|
|
1565
|
-
switch (outcome) {
|
|
1566
|
-
case "proved":
|
|
1567
|
-
return { message: now.length > 1 ? `fails at ${at}, passes now in ${now.length} of ${now.length} runs` : `fails at ${at}, passes now`, side: "before" };
|
|
1568
|
-
case "passes-before":
|
|
1569
|
-
return { message: `passes at ${at} too: it does not fail without the change`, side: "before" };
|
|
1570
|
-
case "fails-both":
|
|
1571
|
-
return { message: `fails at ${at} and fails now too`, side: "now" };
|
|
1572
|
-
case "regressed":
|
|
1573
|
-
return { message: `passes at ${at}, fails now`, side: "now" };
|
|
1574
|
-
case "flaky":
|
|
1575
|
-
return { message: `fails at ${at}, but ${now.filter((code) => code !== 0).length} of ${now.length} runs fail now`, side: "now" };
|
|
1576
|
-
}
|
|
1577
|
-
}
|
|
1578
|
-
async function proof(argv) {
|
|
1579
|
-
const bare = argv[0] !== undefined && !argv[0].startsWith("-");
|
|
1580
|
-
const parsed = parse(bare ? [] : argv, USAGE, OPTIONS, { rest: true, exits: EXITS, replaces: "running a test, stashing the change and running it again", examples: [["proof --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the new test fails at HEAD and passes now"], ["proof --ref v1.2.0 --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the same against a release"]] });
|
|
1581
|
-
const given = bare ? argv : parsed.rest ?? [];
|
|
1582
|
-
if (given.length === 0 || parsed.positionals.length > 0)
|
|
1583
|
-
fail(`give the command after --
|
|
1584
|
-
|
|
1585
|
-
${USAGE}`);
|
|
1586
|
-
if (runsInContainer(given))
|
|
1587
|
-
fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
|
|
1588
|
-
const command = shellCommand(given);
|
|
1589
|
-
const cwd = process17.cwd();
|
|
1590
|
-
const { root, prefix } = await checkout(cwd);
|
|
1591
|
-
const runs = wholeNumber(parsed.values.runs, "runs", 1, 1);
|
|
1592
|
-
const ref = parsed.values.ref ?? await defaultProofRef(root);
|
|
1593
|
-
const sha = await resolveRef(root, ref);
|
|
1594
|
-
const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
|
|
1595
|
-
const timeoutMs = parsed.values.timeout === undefined ? undefined : duration(parsed.values.timeout, "timeout", 0);
|
|
1596
|
-
const signals = holdSignals();
|
|
1597
|
-
let before;
|
|
1598
|
-
const nowRuns = [];
|
|
1599
|
-
try {
|
|
1600
|
-
before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true, timeoutMs));
|
|
1601
|
-
for (let i = 0;i < runs && signals.signal === undefined; i++)
|
|
1602
|
-
nowRuns.push(await runIn(cwd, command, signals, true, timeoutMs));
|
|
1603
|
-
} finally {
|
|
1604
|
-
signals.release();
|
|
1605
|
-
}
|
|
1606
|
-
if (signals.signal !== undefined || nowRuns.length < runs)
|
|
1607
|
-
return exitCodeOf(null, signals.signal ?? null);
|
|
1608
|
-
for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], ...nowRuns.map((each, i) => [each, runs > 1 ? `now (run ${i + 1})` : "now"])]) {
|
|
1609
|
-
if (!run.started)
|
|
1610
|
-
fail(run.output);
|
|
1611
|
-
if (run.timedOut === true)
|
|
1612
|
-
fail(`the command ran past --timeout ${parsed.values.timeout} ${where} and was killed, which says nothing about the change${run.output.trim() === "" ? "" : `
|
|
1613
|
-
|
|
1614
|
-
${folded(run.output)}`}`);
|
|
1615
|
-
if (abnormal(run.code))
|
|
1616
|
-
fail(`the command did not run properly ${where}: exit ${run.code}, a missing command or a kill, not a test result${run.output.trim() === "" ? "" : `
|
|
1617
|
-
|
|
1618
|
-
${folded(run.output)}`}`);
|
|
1619
|
-
}
|
|
1620
|
-
const codes = nowRuns.map((run) => run.code);
|
|
1621
|
-
const now = nowRuns.find((run) => run.code !== 0) ?? nowRuns.at(-1) ?? before;
|
|
1622
|
-
const outcome = outcomeOf(before.code, codes);
|
|
1623
|
-
const { message, side } = describe(outcome, sha.slice(0, 7), codes);
|
|
1624
|
-
const proved = outcome === "proved";
|
|
1625
|
-
if (parsed.values.json === true) {
|
|
1626
|
-
printJson({ outcome, proved, ref, sha, before: { code: before.code, output: before.output }, now: { code: now.code, output: now.output }, runs: nowRuns.map((run) => ({ code: run.code })) });
|
|
1627
|
-
return proved ? 0 : 1;
|
|
1628
|
-
}
|
|
1629
|
-
console.log(role(proved ? "ok" : "problem", process17.stdout)(message));
|
|
1630
|
-
if (runs > 1)
|
|
1631
|
-
console.log(`now: ${codes.map((code, i) => `run ${i + 1} ${code === 0 ? "passed" : `failed (exit ${code})`}`).join(", ")}`);
|
|
1632
|
-
const shown = side === "before" ? before : now;
|
|
1633
|
-
if (shown.code !== 0 && shown.output.trim() !== "")
|
|
1634
|
-
console.log(`
|
|
1635
|
-
${folded(shown.output)}`);
|
|
1636
|
-
return proved ? 0 : 1;
|
|
1637
|
-
}
|
|
1638
|
-
|
|
1639
|
-
// src/proof-cli.ts
|
|
1640
|
-
process18.exitCode = await runMain({ name: "proof", run: proof });
|