@kaynooo/cli-base 0.0.0-stage → 0.4.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/cli.js ADDED
@@ -0,0 +1,948 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/cli.ts
5
+ import process7 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process2 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/style.ts
12
+ import process from "process";
13
+
14
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
+ function x(s) {
16
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
17
+ if (!/^[a-f0-9]+$/.test(r))
18
+ return [0, 0, 0];
19
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
20
+ if (t === 3 || t === 4) {
21
+ let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
22
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
23
+ }
24
+ if (t !== 6 && t !== 8)
25
+ throw Error(`Invalid hex color length: ${t}`);
26
+ let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
27
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
28
+ throw Error(`Invalid hex color value: ${s}`);
29
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
30
+ }
31
+ function A(s) {
32
+ let [r, t, n, a] = s;
33
+ if (a)
34
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
35
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
36
+ }
37
+ function R(s, r, t) {
38
+ s = (s % 360 + 360) % 360, t /= 100;
39
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
40
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
41
+ return Math.round(255 * y);
42
+ };
43
+ return [a(0), a(8), a(4)];
44
+ }
45
+ function k(s) {
46
+ let [r, t, n] = s;
47
+ r /= 255, t /= 255, n /= 255;
48
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
49
+ if (a !== b) {
50
+ let u = a - b;
51
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
52
+ o = (t - n) / u + (t < n ? 6 : 0);
53
+ else if (a === t)
54
+ o = (n - r) / u + 2;
55
+ else
56
+ o = (r - t) / u + 4;
57
+ o /= 6;
58
+ }
59
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
60
+ }
61
+ function H(s, r, t) {
62
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
63
+ let n = (a) => {
64
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
65
+ return Math.round(255 * o);
66
+ };
67
+ return [n(5), n(3), n(1)];
68
+ }
69
+ function f(s) {
70
+ let [r, t, n] = s;
71
+ r /= 255, t /= 255, n /= 255;
72
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
73
+ if (o !== 0) {
74
+ if (a === r)
75
+ y = (t - n) / o + (t < n ? 6 : 0);
76
+ else if (a === t)
77
+ y = (n - r) / o + 2;
78
+ else
79
+ y = (r - t) / o + 4;
80
+ y /= 6;
81
+ }
82
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
83
+ }
84
+ function O(s) {
85
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
86
+ if (a === 1)
87
+ return [0, 0, 0, 100];
88
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
89
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
90
+ }
91
+ function v(s, r, t, n) {
92
+ return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
93
+ }
94
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
95
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
96
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
97
+ function T(s) {
98
+ let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
99
+ return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
100
+ }
101
+ function M(s, r, t) {
102
+ let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
103
+ return [u(o), u(y), u(c)];
104
+ }
105
+ function d(s) {
106
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
107
+ return [i(r, 4), i(a, 4), i(b, 2)];
108
+ }
109
+ function C(s, r, t) {
110
+ let n = t * Math.PI / 180;
111
+ return M(s, r * Math.cos(n), r * Math.sin(n));
112
+ }
113
+ function l(s) {
114
+ let r = s / 255;
115
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
116
+ }
117
+
118
+ class e {
119
+ r;
120
+ g;
121
+ b;
122
+ a;
123
+ constructor(s, r, t, n = 1) {
124
+ this.r = s, this.g = r, this.b = t, this.a = n;
125
+ }
126
+ static from(s, r) {
127
+ if (s === "hex") {
128
+ let [t, n, a, b] = x(r);
129
+ return new e(t, n, a, b);
130
+ }
131
+ if (s === "rgb") {
132
+ if (Array.isArray(r)) {
133
+ let [o, y, c, u] = r;
134
+ return new e(o, y, c, u);
135
+ }
136
+ let { r: t, g: n, b: a, a: b } = r;
137
+ return new e(t, n, a, b);
138
+ }
139
+ if (s === "hsl") {
140
+ let t, n, a, b;
141
+ if (Array.isArray(r))
142
+ [t, n, a, b] = r;
143
+ else
144
+ ({ h: t, s: n, l: a, a: b } = r);
145
+ let [o, y, c] = R(t, n, a);
146
+ return new e(o, y, c, b);
147
+ }
148
+ if (s === "hsv") {
149
+ let t, n, a, b;
150
+ if (Array.isArray(r))
151
+ [t, n, a, b] = r;
152
+ else
153
+ ({ h: t, s: n, v: a, a: b } = r);
154
+ let [o, y, c] = H(t, n, a);
155
+ return new e(o, y, c, b);
156
+ }
157
+ if (s === "cmyk") {
158
+ let t, n, a, b, o;
159
+ if (Array.isArray(r))
160
+ [t, n, a, b, o] = r;
161
+ else
162
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
163
+ let [y, c, u] = v(t, n, a, b);
164
+ return new e(y, c, u, o);
165
+ }
166
+ if (s === "oklch") {
167
+ let t, n, a, b;
168
+ if (Array.isArray(r))
169
+ [t, n, a, b] = r;
170
+ else
171
+ ({ l: t, c: n, h: a, a: b } = r);
172
+ let [o, y, c] = C(t, n, a);
173
+ return new e(o, y, c, b);
174
+ }
175
+ if (s === "oklab") {
176
+ let t, n, a, b;
177
+ if (Array.isArray(r))
178
+ [t, n, a, b] = r;
179
+ else
180
+ ({ l: t, a: n, b: a, alpha: b } = r);
181
+ let [o, y, c] = M(t, n, a);
182
+ return new e(o, y, c, b);
183
+ }
184
+ throw Error("Invalid input");
185
+ }
186
+ to(s) {
187
+ switch (s) {
188
+ case "rgb":
189
+ return [this.r, this.g, this.b];
190
+ case "rgba":
191
+ return [this.r, this.g, this.b, this.a];
192
+ case "hex":
193
+ return A([this.r, this.g, this.b]);
194
+ case "hexa":
195
+ return A([this.r, this.g, this.b, this.a]);
196
+ case "hsl":
197
+ return k([this.r, this.g, this.b]);
198
+ case "hsla":
199
+ return [...k([this.r, this.g, this.b]), this.a];
200
+ case "hsv":
201
+ return f([this.r, this.g, this.b]);
202
+ case "hsva":
203
+ return [...f([this.r, this.g, this.b]), this.a];
204
+ case "cmyk":
205
+ return O([this.r, this.g, this.b]);
206
+ case "cmyka":
207
+ return [...O([this.r, this.g, this.b]), this.a];
208
+ case "oklch":
209
+ return d([this.r, this.g, this.b]);
210
+ case "oklcha":
211
+ return [...d([this.r, this.g, this.b]), this.a];
212
+ case "oklab":
213
+ return T([this.r, this.g, this.b]);
214
+ case "oklaba":
215
+ return [...T([this.r, this.g, this.b]), this.a];
216
+ default:
217
+ return [this.r, this.g, this.b];
218
+ }
219
+ }
220
+ getLuminance() {
221
+ let s = l(this.r), r = l(this.g), t = l(this.b);
222
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
223
+ }
224
+ contrastRatio(s) {
225
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
226
+ return (n + 0.05) / (a + 0.05);
227
+ }
228
+ bestContrastForeground() {
229
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
230
+ return t >= n ? s : r;
231
+ }
232
+ }
233
+
234
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
235
+ var r = 39;
236
+ var o = 49;
237
+ var f2 = "\x1B[";
238
+ var C2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
239
+ let [a, l, s] = e.from("hex", i).to("rgb");
240
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
241
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
242
+ var b = new Set(["", "1", "2", "3", "true"]);
243
+ function h(i, n = globalThis.process?.env ?? {}) {
244
+ if (n.FORCE_COLOR !== undefined)
245
+ return b.has(n.FORCE_COLOR);
246
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
247
+ return false;
248
+ return i?.isTTY === true;
249
+ }
250
+ function d2(i, n, a) {
251
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
252
+ return n;
253
+ let l = "", s = "";
254
+ for (let g = 0, y = i.length;g < y; g++) {
255
+ let [c, p] = i[g];
256
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
257
+ }
258
+ return l + n + s;
259
+ }
260
+ function u(i, n = []) {
261
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
262
+ let g = C2[s];
263
+ if (Array.isArray(g))
264
+ return u(i, [...n, g]);
265
+ if (typeof g === "function")
266
+ return (...y) => u(i, [...n, g(...y)]);
267
+ throw Error(`Unknown style: ${String(s)}`);
268
+ } });
269
+ }
270
+ function le(i = {}) {
271
+ return u(i);
272
+ }
273
+ var t = le();
274
+
275
+ // ../kit/src/style.ts
276
+ function takesControlCodes(stream, env = process.env) {
277
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
278
+ }
279
+ function paint(stream, env = process.env) {
280
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
281
+ }
282
+ var STATUSES = {
283
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
284
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
285
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
286
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
287
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
288
+ };
289
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
290
+
291
+ // ../kit/src/format.ts
292
+ function upTo(text, separator) {
293
+ const end = text.indexOf(separator);
294
+ return end === -1 ? text : text.slice(0, end);
295
+ }
296
+ var ESCAPE = String.fromCharCode(27);
297
+ function printJson(value) {
298
+ console.log(JSON.stringify(value, undefined, 2));
299
+ }
300
+
301
+ // ../kit/src/text.ts
302
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
303
+ function distance(a, b) {
304
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
305
+ for (const [i, left] of [...a].entries()) {
306
+ const current = [i + 1];
307
+ for (const [j, right] of [...b].entries())
308
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
309
+ previous = current;
310
+ }
311
+ return previous[b.length] ?? 0;
312
+ }
313
+ function closest(name, names) {
314
+ const started = names.find((known) => known.startsWith(name));
315
+ if (started !== undefined)
316
+ return started;
317
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
318
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
319
+ }
320
+
321
+ // ../kit/src/args.ts
322
+ function jsonOption(holds) {
323
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
324
+ }
325
+
326
+ class Exit extends Error {
327
+ code;
328
+ hint;
329
+ constructor(message, code, hint) {
330
+ super(message);
331
+ this.code = code;
332
+ this.hint = hint;
333
+ }
334
+ }
335
+ function fail(message, code = 2, hint) {
336
+ throw new Exit(message, code, hint);
337
+ }
338
+
339
+ class UsageError extends Exit {
340
+ constructor(message, hint) {
341
+ super(message, 2, hint);
342
+ }
343
+ }
344
+ function badUsage(message) {
345
+ throw new UsageError(message);
346
+ }
347
+
348
+ class HelpShown extends Exit {
349
+ constructor() {
350
+ super("help shown", 0);
351
+ }
352
+ }
353
+
354
+ class Completing {
355
+ options;
356
+ constructor(options) {
357
+ this.options = options;
358
+ }
359
+ }
360
+ var completion = { active: false };
361
+ var OPTIONAL = /\[[^\]]+\]/g;
362
+ var USAGE_PREFIX = /^usage:\s*/i;
363
+ var FULL_STOP = /\.$/;
364
+ var DASHES = /^-+/;
365
+ function usageLine(usage, colors = paint(process2.stdout)) {
366
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
367
+ }
368
+ function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
369
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
370
+ `);
371
+ }
372
+ function replacesRows(replaces, colors = paint(process2.stdout)) {
373
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
374
+ }
375
+ function wantsHelpJson(env = process2.env) {
376
+ return env.KIT_HELP === "json";
377
+ }
378
+ function description(usage, { examples = [], replaces } = {}) {
379
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
380
+ `);
381
+ const first = lines[0];
382
+ const colon = first.indexOf(": ");
383
+ const prose = lines[lines.indexOf("") + 1] ?? "";
384
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
385
+ return {
386
+ synopsis: colon === -1 ? first : first.slice(0, colon),
387
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
388
+ ...replaces === undefined ? {} : { replaces },
389
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
390
+ };
391
+ }
392
+ function exampleRows(examples, colors = paint(process2.stdout)) {
393
+ if (examples.length === 0)
394
+ return [];
395
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
396
+ }
397
+ function optionRows(options, colors = paint(process2.stdout)) {
398
+ const rows = Object.entries(options).map(([name, option]) => {
399
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
400
+ const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
401
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
402
+ });
403
+ const width = Math.max(0, ...rows.map((row) => row.width));
404
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
405
+ }
406
+ var OUTPUT_OPTIONS = {
407
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
408
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
409
+ };
410
+ function applyOutput(color, plain, env = process2.env) {
411
+ const when = plain === true ? "never" : color ?? "auto";
412
+ if (when === "auto")
413
+ return;
414
+ if (when !== "always" && when !== "never")
415
+ badUsage(`--color takes auto, always or never, not ${when}`);
416
+ if (when === "always") {
417
+ env.FORCE_COLOR = "1";
418
+ delete env.NO_COLOR;
419
+ } else {
420
+ env.NO_COLOR = "1";
421
+ delete env.FORCE_COLOR;
422
+ }
423
+ }
424
+ function parse(args, usage, options, settings = {}) {
425
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
426
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
427
+ if (completion.active)
428
+ throw new Completing(all);
429
+ const separator = settings.rest === true ? args.indexOf("--") : -1;
430
+ const own = separator === -1 ? args : args.slice(0, separator);
431
+ const rest = separator === -1 ? undefined : args.slice(separator + 1);
432
+ let parsed;
433
+ try {
434
+ parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
435
+ } catch (error) {
436
+ const message = parseError(error);
437
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
438
+ }
439
+ const values = parsed.values;
440
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
441
+ if (values.help === true) {
442
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
443
+ throw new HelpShown;
444
+ }
445
+ if (settings.positionals !== undefined)
446
+ checkPositionals(parsed.positionals, settings.positionals);
447
+ return { ...parsed, positionals: parsed.positionals, rest };
448
+ }
449
+ function checkPositionals(given, names) {
450
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
451
+ const required = names.filter((name) => !name.startsWith("[")).length;
452
+ if (given.length < required)
453
+ badUsage(`missing ${names[given.length]}`);
454
+ if (!variadic && given.length > names.length)
455
+ badUsage(`unexpected argument ${given[names.length]}`);
456
+ }
457
+ function joinDashValues(args, options) {
458
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
459
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
460
+ const joined = [];
461
+ for (let i = 0;i < args.length; i++) {
462
+ const arg = args[i] ?? "";
463
+ if (arg === "--")
464
+ return [...joined, ...args.slice(i)];
465
+ const name = longOf.get(arg);
466
+ const next = args[i + 1];
467
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
468
+ joined.push(`--${name}=${next}`);
469
+ i++;
470
+ } else {
471
+ joined.push(arg);
472
+ }
473
+ }
474
+ return joined;
475
+ }
476
+ function parseError(error) {
477
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
478
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
479
+ }
480
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
481
+ function nearestOption(message, options, allowNegative) {
482
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
483
+ if (typed === undefined)
484
+ return;
485
+ const word = typed.replace(DASHES, "");
486
+ if (word.length < 2 && !typed.startsWith("--"))
487
+ return;
488
+ const known = Object.entries(options).flatMap(([name, option]) => [
489
+ ...option.short === undefined ? [] : [`-${option.short}`],
490
+ `--${name}`,
491
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
492
+ ]);
493
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
494
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
495
+ }
496
+ // ../kit/src/process.ts
497
+ import { constants } from "os";
498
+ import process3 from "process";
499
+ var KILL_GRACE_MS = 2000;
500
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
501
+ function exitCodeOf(code, signal) {
502
+ if (code !== null)
503
+ return code;
504
+ if (typeof signal === "number")
505
+ return 128 + signal;
506
+ return signal === null ? 129 : 128 + constants.signals[signal];
507
+ }
508
+ function holdSignals(cleanup) {
509
+ let received;
510
+ let child;
511
+ const held = {
512
+ get signal() {
513
+ return received;
514
+ },
515
+ forward: (to) => {
516
+ child = to;
517
+ },
518
+ release: () => {
519
+ for (const signal of SIGNALS)
520
+ process3.off(signal, onSignal);
521
+ }
522
+ };
523
+ function onSignal(signal) {
524
+ received = signal;
525
+ if (child !== undefined) {
526
+ child.kill(signal);
527
+ return;
528
+ }
529
+ if (cleanup === undefined)
530
+ return;
531
+ held.release();
532
+ cleanup(signal);
533
+ process3.kill(process3.pid, signal);
534
+ }
535
+ for (const signal of SIGNALS)
536
+ process3.on(signal, onSignal);
537
+ return held;
538
+ }
539
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
540
+ const chunks = [];
541
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
542
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
543
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
544
+ const timers = [];
545
+ const killGroup = (killing) => {
546
+ if (state.done)
547
+ return;
548
+ try {
549
+ if (grouped)
550
+ process3.kill(-proc.pid, killing);
551
+ else
552
+ proc.kill(killing);
553
+ } catch {}
554
+ };
555
+ const stop = () => {
556
+ killGroup("SIGTERM");
557
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
558
+ };
559
+ const onAbort = () => stop();
560
+ if (timeoutMs !== undefined) {
561
+ timers.push(setTimeout(() => {
562
+ state.timedOut = true;
563
+ stop();
564
+ }, timeoutMs));
565
+ }
566
+ if (signal?.aborted === true)
567
+ onAbort();
568
+ else
569
+ signal?.addEventListener("abort", onAbort, { once: true });
570
+ onStart?.({ kill: (killing) => killGroup(killing) });
571
+ const drain = async (stream, name) => {
572
+ for await (const data of stream) {
573
+ if (state.failure !== undefined)
574
+ continue;
575
+ try {
576
+ onChunk?.({ stream: name, data });
577
+ } catch (error) {
578
+ state.failure = error;
579
+ stop();
580
+ continue;
581
+ }
582
+ if (state.kept + data.length > maxBytes) {
583
+ state.truncated = true;
584
+ continue;
585
+ }
586
+ state.kept += data.length;
587
+ chunks.push({ stream: name, data });
588
+ }
589
+ };
590
+ try {
591
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
592
+ await proc.exited;
593
+ } finally {
594
+ state.done = true;
595
+ for (const timer of timers)
596
+ clearTimeout(timer);
597
+ signal?.removeEventListener("abort", onAbort);
598
+ }
599
+ if (state.failure !== undefined)
600
+ throw state.failure;
601
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
602
+ let output;
603
+ let text;
604
+ return {
605
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
606
+ chunks,
607
+ timedOut: state.timedOut,
608
+ truncated: state.truncated,
609
+ get output() {
610
+ return output ??= joined();
611
+ },
612
+ get text() {
613
+ return text ??= (output ??= joined()).toString();
614
+ }
615
+ };
616
+ }
617
+
618
+ // ../kit/src/progress.ts
619
+ var ESC = String.fromCharCode(27);
620
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
621
+ var RESET_STYLE = `${ESC}[0m`;
622
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
623
+ // ../kit/src/cli.ts
624
+ import process4 from "process";
625
+ var LEVEL_OPTIONS = {
626
+ ...OUTPUT_OPTIONS,
627
+ help: { type: "boolean", short: "h", description: "show this help" }
628
+ };
629
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
630
+ function printError(prefix, message, hint, cause) {
631
+ const colors = paint(process4.stderr);
632
+ const styled = takesControlCodes(process4.stderr);
633
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
634
+ const under = (label, text, tint) => text === undefined ? "" : `
635
+ ${styled ? tint(label) : `${label}:`} ${text}`;
636
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
637
+ }
638
+ function printJsonError(message, hint, cause) {
639
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
640
+ }
641
+ function wantsJson(argv) {
642
+ const end = argv.indexOf("--");
643
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
644
+ }
645
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
646
+ if (error instanceof HelpShown)
647
+ return 0;
648
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
649
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
650
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
651
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
652
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
653
+ return error instanceof Exit ? error.code : 1;
654
+ }
655
+ var COMPLETE = "__complete";
656
+ var FILES = "__files__";
657
+ async function optionsOf(run) {
658
+ completion.active = true;
659
+ try {
660
+ await run([]);
661
+ } catch (error) {
662
+ if (error instanceof Completing)
663
+ return error.options;
664
+ } finally {
665
+ completion.active = false;
666
+ }
667
+ return {};
668
+ }
669
+ async function leafCandidates(run, words) {
670
+ if (!(words.at(-1) ?? "").startsWith("-"))
671
+ return [FILES];
672
+ return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
673
+ }
674
+ async function printCandidates(found) {
675
+ for (const line of await found)
676
+ console.log(line);
677
+ return 0;
678
+ }
679
+ async function runMain({ name, version, run, redact }, argv = process4.argv.slice(2)) {
680
+ if (argv[0] === COMPLETE)
681
+ return printCandidates(leafCandidates(run, argv.slice(1)));
682
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
683
+ console.log(version);
684
+ return 0;
685
+ }
686
+ try {
687
+ return await run(argv);
688
+ } catch (error) {
689
+ return reportThrown(name, error, redact, wantsJson(argv));
690
+ }
691
+ }
692
+ // ../kit/src/logs.ts
693
+ var DAY_MS = 24 * 60 * 60 * 1000;
694
+ // ../kit/src/secrets.ts
695
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
696
+ // ../kit/src/sessions.ts
697
+ var {Glob } = globalThis.Bun;
698
+ var SESSION_FILES = new Glob("*.json");
699
+ var ACCOUNT_DIRS = new Glob("*/sessions");
700
+ // package.json
701
+ var version = "0.4.0";
702
+
703
+ // src/worktree.ts
704
+ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "fs";
705
+ import { tmpdir } from "os";
706
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "path";
707
+ import process6 from "process";
708
+ var WHITESPACE = /\s/;
709
+ var ENV_FILE = /^\.env(?:\..+)?$/;
710
+ var DEPENDENCIES = new Set(["node_modules", "vendor", ".venv"]);
711
+ var TRAILING_SLASH = /\/$/;
712
+ var PARENT = `..${sep}`;
713
+ var BASE_DIR = /^base-\w{6}$/;
714
+ var CONTAINER = /(?:^|[\s;&|(])(?:docker\s+compose|docker-compose)\s+(?:-\S+(?:\s+[^-\s]\S*)?\s+)*(?:exec|run)\b|(?:^|[\s;&|(])docker\s+exec\b/;
715
+ function stdoutOf(ran) {
716
+ return Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString().trim();
717
+ }
718
+ async function git2(args, cwd) {
719
+ return runCommand(["git", ...args], { cwd });
720
+ }
721
+ function runsInContainer(command) {
722
+ return CONTAINER.test(command.join(" "));
723
+ }
724
+ async function checkout(cwd) {
725
+ const ran = await git2(["rev-parse", "--show-toplevel", "--show-prefix"], cwd);
726
+ if (ran.code !== 0)
727
+ fail("not inside a git repository");
728
+ const [root = "", prefix = ""] = stdoutOf(ran).split(`
729
+ `);
730
+ return { root, prefix };
731
+ }
732
+ async function resolveRef(root, ref) {
733
+ const ran = await git2(["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`], root);
734
+ if (ran.code !== 0)
735
+ fail(`no commit ${ref} in this repository`);
736
+ return stdoutOf(ran);
737
+ }
738
+ function keptPaths(root, cwd, paths) {
739
+ const realRoot = realpathSync(root);
740
+ return paths.map((path) => {
741
+ const absolute = resolve(cwd, path);
742
+ const inRepo = relative(realRoot, join(realpathSync(dirname(absolute)), basename(absolute)));
743
+ if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute(inRepo))
744
+ fail(`--keep ${path} is outside the repository`);
745
+ if (!existsSync(absolute))
746
+ fail(`--keep ${path}: no such file`);
747
+ return inRepo;
748
+ });
749
+ }
750
+ function checkNoSymlink(dir, path) {
751
+ let current = dir;
752
+ for (const part of dirname(path).split(sep)) {
753
+ current = join(current, part);
754
+ if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink() === true)
755
+ fail(`--keep ${path} goes through the symlink ${relative(dir, current)} of the ref, which would write outside the worktree`);
756
+ }
757
+ }
758
+ async function linkedEntries(root) {
759
+ const ran = await git2(["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], root);
760
+ if (ran.code !== 0)
761
+ return [];
762
+ return stdoutOf(ran).split("\x00").filter((entry) => {
763
+ const folder = entry.endsWith("/");
764
+ const name = basename(entry);
765
+ return folder ? DEPENDENCIES.has(name) : ENV_FILE.test(name);
766
+ }).map((entry) => entry.replace(TRAILING_SLASH, ""));
767
+ }
768
+ async function addWorktree(root, sha) {
769
+ const dir = join(mkdtempSync(join(tmpdir(), "base-")), basename(root));
770
+ const ran = await git2(["worktree", "add", "--detach", dir, sha], root);
771
+ if (ran.code !== 0) {
772
+ rmSync(dirname(dir), { recursive: true, force: true });
773
+ fail(`git worktree add failed:
774
+ ${ran.text.trim()}`);
775
+ }
776
+ return dir;
777
+ }
778
+ function copyKept(root, dir, paths) {
779
+ for (const path of paths) {
780
+ checkNoSymlink(dir, path);
781
+ const target = join(dir, path);
782
+ rmSync(target, { recursive: true, force: true });
783
+ mkdirSync(dirname(target), { recursive: true });
784
+ cpSync(join(root, path), target, { recursive: true });
785
+ }
786
+ }
787
+ function linkEntries(root, dir, entries) {
788
+ const links = [];
789
+ for (const entry of entries) {
790
+ const link = join(dir, entry);
791
+ if (existsSync(link))
792
+ continue;
793
+ mkdirSync(dirname(link), { recursive: true });
794
+ if (basename(entry) === "node_modules" && hasWorkspaceLinks(root, entry)) {
795
+ links.push(...linkModules(root, dir, entry));
796
+ continue;
797
+ }
798
+ symlinkSync(join(root, entry), link);
799
+ links.push(link);
800
+ }
801
+ return links;
802
+ }
803
+ function moduleLinks(root, folder) {
804
+ const found = [];
805
+ for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
806
+ if (entry.isSymbolicLink())
807
+ found.push({ path: join(folder, entry.name), name: entry.name });
808
+ else if (entry.isDirectory() && entry.name.startsWith("@"))
809
+ found.push(...moduleLinks(root, join(folder, entry.name)));
810
+ }
811
+ return found;
812
+ }
813
+ function workspaceTarget(root, path) {
814
+ try {
815
+ const inRepo = relative(realpathSync(root), realpathSync(join(root, path)));
816
+ return inRepo === "" || inRepo.startsWith(PARENT) || inRepo.split(sep).includes("node_modules") ? undefined : inRepo;
817
+ } catch {
818
+ return;
819
+ }
820
+ }
821
+ function hasWorkspaceLinks(root, folder) {
822
+ return moduleLinks(root, folder).some(({ path }) => workspaceTarget(root, path) !== undefined);
823
+ }
824
+ function linkModules(root, dir, folder) {
825
+ const links = [];
826
+ mkdirSync(join(dir, folder), { recursive: true });
827
+ for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
828
+ const path = join(folder, entry.name);
829
+ const link = join(dir, path);
830
+ if (entry.isDirectory() && entry.name.startsWith("@")) {
831
+ links.push(...linkModules(root, dir, path));
832
+ continue;
833
+ }
834
+ const workspace = entry.isSymbolicLink() ? workspaceTarget(root, path) : undefined;
835
+ symlinkSync(workspace === undefined ? join(root, path) : join(dir, workspace), link);
836
+ links.push(link);
837
+ }
838
+ return links;
839
+ }
840
+ var STALE_AFTER = 24 * 60 * 60 * 1000;
841
+ async function sweepStale(root) {
842
+ for (const name of readdirSync(tmpdir())) {
843
+ if (!BASE_DIR.test(name))
844
+ continue;
845
+ const path = join(tmpdir(), name);
846
+ const stat = lstatSync(path, { throwIfNoEntry: false });
847
+ if (stat?.isDirectory() === true && stat.uid === process6.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
848
+ rmSync(path, { recursive: true, force: true });
849
+ }
850
+ await git2(["worktree", "prune"], root);
851
+ }
852
+ async function removeWorktree(root, dir, links) {
853
+ for (const link of links) {
854
+ if (lstatSync(link, { throwIfNoEntry: false })?.isSymbolicLink() === true)
855
+ unlinkSync(link);
856
+ }
857
+ await git2(["worktree", "remove", "--force", dir], root);
858
+ rmSync(dirname(dir), { recursive: true, force: true });
859
+ await git2(["worktree", "prune"], root);
860
+ }
861
+ function shellCommand(given) {
862
+ const [only] = given;
863
+ return given.length === 1 && only !== undefined && WHITESPACE.test(only) ? ["sh", "-c", only] : given;
864
+ }
865
+ async function runIn(dir, command, signals, capture = false) {
866
+ if (signals.signal !== undefined)
867
+ return { code: exitCodeOf(null, signals.signal), output: "", started: true };
868
+ let child;
869
+ try {
870
+ child = Bun.spawn(command, { cwd: dir, stdin: "inherit", stdout: capture ? "pipe" : "inherit", stderr: capture ? "pipe" : "inherit" });
871
+ } catch (error) {
872
+ return { code: 127, output: `cannot run ${command[0]}: ${error instanceof Error ? error.message : String(error)}`, started: false };
873
+ }
874
+ signals.forward(child);
875
+ const chunks = [];
876
+ if (capture)
877
+ await Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]);
878
+ await child.exited;
879
+ return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true };
880
+ }
881
+ async function collect(stream, chunks) {
882
+ for await (const chunk of stream)
883
+ chunks.push(chunk);
884
+ }
885
+ var FOLD_OVER = 120;
886
+ var FOLD_HEAD = 20;
887
+ var FOLD_TAIL = 80;
888
+ function folded(output) {
889
+ const lines = output.trimEnd().split(`
890
+ `);
891
+ if (lines.length <= FOLD_OVER)
892
+ return lines.join(`
893
+ `);
894
+ return [...lines.slice(0, FOLD_HEAD), `... ${lines.length - FOLD_HEAD - FOLD_TAIL} lines omitted, --json has them all ...`, ...lines.slice(-FOLD_TAIL)].join(`
895
+ `);
896
+ }
897
+ async function inWorktree(options, body) {
898
+ const { root, prefix, sha, ref, kept, link } = options;
899
+ let links = [];
900
+ const signals = options.signals ?? holdSignals();
901
+ await sweepStale(root);
902
+ const dir = await addWorktree(root, sha);
903
+ try {
904
+ copyKept(root, dir, kept);
905
+ links = link ? linkEntries(root, dir, await linkedEntries(root)) : [];
906
+ const runDir = join(dir, prefix);
907
+ if (!existsSync(runDir))
908
+ fail(`${prefix} does not exist at ${ref}`);
909
+ return await body(runDir, signals);
910
+ } finally {
911
+ await removeWorktree(root, dir, links);
912
+ if (options.signals === undefined)
913
+ signals.release();
914
+ }
915
+ }
916
+
917
+ // src/cli.ts
918
+ var USAGE = `base [--ref <rev>] [--keep <path>...] [--no-link] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, the working tree untouched, exiting with its code
919
+
920
+ Exits with the code of the command, 127 when it cannot be started, 2 on a usage error, an unknown ref or a refused command.`;
921
+ var OPTIONS = {
922
+ ref: { type: "string", short: "r", description: "the commit to run at (default HEAD)" },
923
+ keep: { type: "string", short: "k", multiple: true, description: "a working-tree file or folder copied over, such as the new test, repeatable" },
924
+ "no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" }
925
+ };
926
+ async function main(argv) {
927
+ const bare = argv[0] !== undefined && !argv[0].startsWith("-");
928
+ const parsed = parse(bare ? [] : argv, USAGE, OPTIONS, { rest: true, replaces: "git stash, a test run, then git stash pop", examples: [["base -- bun test tests/api.test.ts", "the test at HEAD, the working tree changes left out"], ["base --ref main~3 --keep tests/new.test.ts -- bun test tests/new.test.ts", "a new test against an older commit"]] });
929
+ const given = bare ? argv : parsed.rest ?? [];
930
+ if (given.length === 0 || parsed.positionals.length > 0)
931
+ fail(`give the command after --
932
+
933
+ ${USAGE}`);
934
+ if (runsInContainer(given))
935
+ 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");
936
+ const command = shellCommand(given);
937
+ const cwd = process7.cwd();
938
+ const { root, prefix } = await checkout(cwd);
939
+ const ref = parsed.values.ref ?? "HEAD";
940
+ const sha = await resolveRef(root, ref);
941
+ const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
942
+ const ran = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true }, async (runDir, signals) => runIn(runDir, command, signals));
943
+ if (!ran.started)
944
+ console.error(`base: ${ran.output}`);
945
+ console.error(`base: ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
946
+ return ran.code;
947
+ }
948
+ process7.exitCode = await runMain({ name: "base", version, run: main });