@kaynooo/cli-git 0.15.0 → 0.16.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/gm.js ADDED
@@ -0,0 +1,2885 @@
1
+ #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
+ // @bun
3
+
4
+ // src/gm.ts
5
+ import { readFileSync as readFileSync5 } from "fs";
6
+ import process23 from "process";
7
+ // ../kit/src/args.ts
8
+ import process9 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/format.ts
12
+ import process7 from "process";
13
+
14
+ // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
15
+ var N = new Map;
16
+ var Nt = /\s+\S*$/;
17
+ var Y = /\s/;
18
+ function ko(t, e, r = "...") {
19
+ let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
20
+ if (t.length <= e)
21
+ return t;
22
+ let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
23
+ if (o && !Y.test(t[c.length] ?? " "))
24
+ c = c.replace(Nt, "") || c;
25
+ if (o)
26
+ c = c.trimEnd();
27
+ return s ? (c + n).slice(0, l) : c + n;
28
+ }
29
+ var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
30
+ var z = new Map;
31
+
32
+ // ../kit/src/mode.ts
33
+ import process2 from "process";
34
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
35
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
36
+ function isSet(value) {
37
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
38
+ }
39
+ function outputMode(stream = process2.stdout, env = process2.env) {
40
+ const chosen = env.KIT_MODE;
41
+ if (chosen !== undefined && MODES.has(chosen))
42
+ return chosen;
43
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
44
+ return "agent";
45
+ if (stream.isTTY === true)
46
+ return "terminal";
47
+ return isSet(env.CI) ? "ci" : "pipe";
48
+ }
49
+ function isInteractive(streams = process2) {
50
+ return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
51
+ }
52
+
53
+ // ../kit/src/style.ts
54
+ import process6 from "process";
55
+
56
+ // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
57
+ var G2 = /^[a-f0-9]+$/i;
58
+ function b(r) {
59
+ let e = r.startsWith("#") ? r.slice(1) : r;
60
+ if (!G2.test(e))
61
+ return [0, 0, 0];
62
+ if (e.length === 3 || e.length === 4)
63
+ return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
64
+ if (e.length !== 6 && e.length !== 8)
65
+ throw Error(`Invalid hex color length: ${e.length}`);
66
+ return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
67
+ }
68
+ var B2 = { 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") => {
69
+ let [l, n, c] = b(r);
70
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
71
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
72
+ var h = new Set(["", "1", "2", "3", "true"]);
73
+ function C(r, e = globalThis.process?.env ?? {}) {
74
+ if (e.FORCE_COLOR !== undefined)
75
+ return h.has(e.FORCE_COLOR);
76
+ if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
77
+ return false;
78
+ return r?.isTTY === true;
79
+ }
80
+ function f(r, e = []) {
81
+ let l = "", n = "";
82
+ for (let t = 0, i = e.length;t < i; t++)
83
+ l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
84
+ let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
85
+ return new Proxy(c, { get(t, i) {
86
+ let a = B2[i];
87
+ if (Array.isArray(a)) {
88
+ let s = g.get(i);
89
+ if (s === undefined)
90
+ s = f(r, [...e, a]), g.set(i, s);
91
+ return s;
92
+ }
93
+ if (typeof a === "function")
94
+ return (...s) => {
95
+ let y = `${i}:${s.join(",")}`, u = g.get(y);
96
+ if (u === undefined) {
97
+ if (g.size >= 64)
98
+ g.clear();
99
+ u = f(r, [...e, a(...s)]), g.set(y, u);
100
+ }
101
+ return u;
102
+ };
103
+ throw Error(`Unknown style: ${String(i)}`);
104
+ } });
105
+ }
106
+ function Fe(r = {}) {
107
+ return f(r);
108
+ }
109
+ var o = Fe();
110
+
111
+ // ../kit/src/theme.ts
112
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
113
+ import { homedir as homedir2 } from "os";
114
+ import { join as join3, resolve as resolve2 } from "path";
115
+ import process5 from "process";
116
+
117
+ // ../kit/src/config.ts
118
+ import { existsSync } from "fs";
119
+ import { dirname, join, resolve } from "path";
120
+ import process3 from "process";
121
+ function findUp(names, from = process3.cwd(), stop = () => false) {
122
+ const wanted = typeof names === "string" ? [names] : names;
123
+ for (let dir = resolve(from);; dir = dirname(dir)) {
124
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
125
+ if (found !== undefined)
126
+ return found;
127
+ if (stop(dir) || dirname(dir) === dir)
128
+ return;
129
+ }
130
+ }
131
+
132
+ // ../kit/src/user-config.ts
133
+ import { existsSync as existsSync2, readFileSync } from "fs";
134
+ import { homedir } from "os";
135
+ import { join as join2 } from "path";
136
+ import process4 from "process";
137
+ function configBase(where = {}) {
138
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
139
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
140
+ }
141
+ function userConfigPath(bin, where = {}) {
142
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
143
+ }
144
+ function userConfigReadPath(bin, legacy = [], where = {}) {
145
+ const current = userConfigPath(bin, where);
146
+ if (existsSync2(current))
147
+ return current;
148
+ const base = configBase(where);
149
+ return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
150
+ }
151
+ function readUserConfig(bin, where = {}, legacy = []) {
152
+ const path = userConfigReadPath(bin, legacy, where);
153
+ if (!existsSync2(path))
154
+ return {};
155
+ try {
156
+ const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
157
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
158
+ } catch {
159
+ return {};
160
+ }
161
+ }
162
+
163
+ // ../kit/src/theme.ts
164
+ function toLinear(channel) {
165
+ const value = channel / 255;
166
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
167
+ }
168
+ var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055)));
169
+ function toOklab(hex) {
170
+ const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
171
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
172
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
173
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
174
+ return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
175
+ }
176
+ function fromOklab([lightness, a, b]) {
177
+ const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
178
+ const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
179
+ const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
180
+ const channels = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
181
+ return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
182
+ }
183
+ var ENDS = new Map;
184
+ function gradientAt(theme, ratio) {
185
+ if (theme.gradient === undefined)
186
+ return;
187
+ const key = theme.gradient.join();
188
+ let ends = ENDS.get(key);
189
+ if (ends === undefined) {
190
+ ends = [toOklab(theme.gradient[0]), toOklab(theme.gradient[1])];
191
+ ENDS.set(key, ends);
192
+ }
193
+ const at = Math.min(1, Math.max(0, ratio));
194
+ const [from, to] = ends;
195
+ return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
196
+ }
197
+ var DEFAULT = {
198
+ 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" },
199
+ 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" },
200
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
201
+ bins: {},
202
+ gradient: ["#c084fc", "#67e8f9"]
203
+ };
204
+ 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" };
205
+ 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" };
206
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
207
+ var PRESETS = {
208
+ default: {},
209
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
210
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
211
+ ascii: { glyphs: ASCII }
212
+ };
213
+ 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"]);
214
+ var HEX = /^#[0-9a-f]{6}$/i;
215
+ var CONTROL = /\p{Cc}/u;
216
+ var MAX_FILE_BYTES = 64 * 1024;
217
+ var SPACES = /\s+/;
218
+ function isColorSpec(spec) {
219
+ if (typeof spec === "number")
220
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
221
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
222
+ }
223
+ var CUBE = [0, 95, 135, 175, 215, 255];
224
+ function cubeLevel(channel) {
225
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
226
+ }
227
+ function nearest256(hex) {
228
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
229
+ const levels = rgb.map(cubeLevel);
230
+ const cube = levels.map((level) => CUBE[level]);
231
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
232
+ const greyValue = 8 + grey * 10;
233
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
234
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
235
+ }
236
+ function hasTrueColor(env) {
237
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
238
+ }
239
+ function tinted(colors, spec, env = process5.env) {
240
+ if (typeof spec === "number")
241
+ return colors.ansi256(spec);
242
+ return spec.trim().split(SPACES).reduce((chain, token) => {
243
+ if (HEX.test(token))
244
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
245
+ return chain[token] ?? chain;
246
+ }, colors);
247
+ }
248
+ function shaded(theme, colors, glyph, cells, width, env = process5.env) {
249
+ return Array.from({ length: cells }, (_, index) => tinted(colors, gradientAt(theme, width <= 1 ? 0 : index / (width - 1)) ?? theme.colors.accent, env)(glyph)).join("");
250
+ }
251
+ function isRecord(value) {
252
+ return typeof value === "object" && value !== null && !Array.isArray(value);
253
+ }
254
+ function readThemeFile(path, warn) {
255
+ try {
256
+ const stat = statSync(path, { throwIfNoEntry: false });
257
+ if (stat === undefined)
258
+ return;
259
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
260
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
261
+ return;
262
+ }
263
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
264
+ if (isRecord(parsed))
265
+ return parsed;
266
+ warn(`${path} is not a JSON object, theme ignored`);
267
+ } catch (error) {
268
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
269
+ }
270
+ return;
271
+ }
272
+ function applyPreset(theme, name, warn, where) {
273
+ if (name === undefined)
274
+ return;
275
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
276
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
277
+ return;
278
+ }
279
+ const preset = PRESETS[name];
280
+ Object.assign(theme.colors, preset.colors);
281
+ Object.assign(theme.glyphs, preset.glyphs);
282
+ if (preset.accents !== undefined)
283
+ theme.accents = [...preset.accents];
284
+ if (Object.hasOwn(preset, "gradient"))
285
+ theme.gradient = preset.gradient;
286
+ return name;
287
+ }
288
+ function applyFile(theme, file, where, warn) {
289
+ if (isRecord(file.colors)) {
290
+ for (const [key, value] of Object.entries(file.colors)) {
291
+ if (!Object.hasOwn(DEFAULT.colors, key))
292
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
293
+ else if (!isColorSpec(value))
294
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
295
+ else
296
+ theme.colors[key] = value;
297
+ }
298
+ }
299
+ if (isRecord(file.glyphs)) {
300
+ for (const [key, value] of Object.entries(file.glyphs)) {
301
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
302
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
303
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
304
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
305
+ else
306
+ theme.glyphs[key] = value;
307
+ }
308
+ }
309
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
310
+ theme.accents = [...file.accents];
311
+ else if (file.accents !== undefined)
312
+ warn(`${where}: accents must be a non-empty list of colours`);
313
+ if (file.gradient === null)
314
+ theme.gradient = undefined;
315
+ else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
316
+ theme.gradient = [file.gradient[0], file.gradient[1]];
317
+ else if (file.gradient !== undefined)
318
+ warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
319
+ if (isRecord(file.bins)) {
320
+ for (const [bin, value] of Object.entries(file.bins)) {
321
+ if (isColorSpec(value))
322
+ theme.bins[bin] = value;
323
+ else
324
+ warn(`${where}: bin ${bin} has no valid colour`);
325
+ }
326
+ }
327
+ }
328
+ function endsWalk(home) {
329
+ return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
330
+ }
331
+ var warned = new Set;
332
+ function warnOnce(message) {
333
+ if (warned.has(message))
334
+ return;
335
+ warned.add(message);
336
+ console.error(`warning: theme ${message}`);
337
+ }
338
+ function isPath(chosen) {
339
+ return chosen.includes("/") || chosen.endsWith(".json");
340
+ }
341
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
342
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
343
+ const sources = [];
344
+ const chosen = env.KIT_THEME ?? "";
345
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
346
+ if (isPath(chosen))
347
+ wanted.push(resolve2(from, chosen));
348
+ const files = [];
349
+ for (const path of wanted) {
350
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
351
+ if (path !== undefined && file !== undefined)
352
+ files.push({ path, file });
353
+ }
354
+ let preset = "default";
355
+ if (chosen !== "" && !isPath(chosen)) {
356
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
357
+ } else {
358
+ const named = files.findLast(({ file }) => file.preset !== undefined);
359
+ if (named !== undefined)
360
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
361
+ }
362
+ for (const { path, file } of files) {
363
+ applyFile(theme, file, path, warn);
364
+ sources.push(path);
365
+ }
366
+ return { theme, sources, preset };
367
+ }
368
+ var current;
369
+ var currentKey = "";
370
+ function activeTheme() {
371
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
372
+ if (current === undefined || key !== currentKey) {
373
+ current = loadTheme();
374
+ currentKey = key;
375
+ }
376
+ return current;
377
+ }
378
+
379
+ // ../kit/src/style.ts
380
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
381
+ function takesControlCodes(stream, env = process6.env) {
382
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
383
+ }
384
+ function paint(stream, env = process6.env) {
385
+ return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
386
+ }
387
+ function marked(mark, text, stream, detail, env = process6.env) {
388
+ const colors = paint(stream, env);
389
+ let head = MARK_WORDS[mark];
390
+ if (takesControlCodes(stream, env)) {
391
+ const { theme } = activeTheme();
392
+ head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
393
+ }
394
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
395
+ }
396
+ function role(name, stream, env = process6.env) {
397
+ const colors = paint(stream, env);
398
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
399
+ }
400
+ var STATUS_WORDS = {
401
+ passed: ["passed", "success", "succeeded", "ok"],
402
+ failed: ["failed", "failure", "error", "errored"],
403
+ running: ["running", "in_progress", "started", "holding"],
404
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
405
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
406
+ };
407
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
408
+
409
+ // ../kit/src/format.ts
410
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
411
+ function formatSeconds(total) {
412
+ let rest = Math.max(0, Math.round(total));
413
+ const amounts = UNITS.map(([unit, size]) => {
414
+ const amount = Math.floor(rest / size);
415
+ rest -= amount * size;
416
+ return `${amount}${unit}`;
417
+ });
418
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
419
+ if (first === -1)
420
+ return "0s";
421
+ const next = amounts[first + 1];
422
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
423
+ }
424
+ function formatDuration(ms) {
425
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
426
+ }
427
+ function formatElapsed(ms) {
428
+ return formatSeconds(Math.floor(Math.max(0, ms) / 1000));
429
+ }
430
+ function upTo(text, separator) {
431
+ const end = text.indexOf(separator);
432
+ return end === -1 ? text : text.slice(0, end);
433
+ }
434
+ function formatAge(date, now = Date.now()) {
435
+ const at = typeof date === "number" ? date : Date.parse(date);
436
+ if (Number.isNaN(at))
437
+ return "-";
438
+ const seconds = (now - at) / 1000;
439
+ return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
440
+ }
441
+ function truncate(text, width) {
442
+ return ko(text, width, { suffix: "\u2026", includeSuffix: true });
443
+ }
444
+ var LINE_BREAKS = /\s*\n\s*/g;
445
+ var ESCAPE = String.fromCharCode(27);
446
+ function textWidth(text) {
447
+ return Bun.stringWidth(text);
448
+ }
449
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
450
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
451
+ if (outputMode(stream, env) === "agent")
452
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
453
+ `);
454
+ const widths = [];
455
+ for (const row of cells) {
456
+ for (const [index, cell] of row.entries())
457
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
458
+ }
459
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
460
+ const colors = paint(stream);
461
+ const lines = shown.map((row) => row.map((cell, index) => {
462
+ const width = widths[index] ?? 0;
463
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
464
+ if (align[index] === "right")
465
+ return `${gap}${cell}`;
466
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
467
+ }).join(" ").trimEnd());
468
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
469
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
470
+ `);
471
+ }
472
+ function narrow(rows, widths, limit) {
473
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
474
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
475
+ const floor = 8;
476
+ while (used() > limit) {
477
+ let widest = -1;
478
+ for (const [index, width] of widths.entries()) {
479
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
480
+ widest = index;
481
+ }
482
+ if (widest === -1)
483
+ break;
484
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
485
+ }
486
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
487
+ }
488
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
489
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
490
+ }
491
+ function printJson(value) {
492
+ console.log(jsonText(value));
493
+ }
494
+
495
+ // ../kit/src/help.ts
496
+ import process8 from "process";
497
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
498
+ var USAGE_PREFIX = /^usage:\s*/i;
499
+ var FULL_STOP = /\.$/;
500
+ function usageLine(usage, colors = paint(process8.stdout)) {
501
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
502
+ }
503
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
504
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
505
+ `);
506
+ }
507
+ function exitRows(exits, colors = paint(process8.stdout)) {
508
+ if (exits.length === 0)
509
+ return [];
510
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
511
+ }
512
+ function wantsHelpJson(env = process8.env) {
513
+ return env.KIT_HELP === "json";
514
+ }
515
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
516
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
517
+ `);
518
+ const first = lines[0];
519
+ const colon = first.indexOf(": ");
520
+ const prose = lines[lines.indexOf("") + 1] ?? "";
521
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
522
+ return {
523
+ synopsis: colon === -1 ? first : first.slice(0, colon),
524
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
525
+ ...replaces === undefined ? {} : { replaces },
526
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
527
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
528
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
529
+ };
530
+ }
531
+ function exampleRows(examples, colors = paint(process8.stdout)) {
532
+ if (examples.length === 0 || outputMode() === "agent")
533
+ return [];
534
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
535
+ }
536
+ var MAX_INLINE_CHOICES = 24;
537
+ function optionRows(options, colors = paint(process8.stdout)) {
538
+ const rows = Object.entries(options).map(([name, option]) => {
539
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
540
+ const choices = option.choices?.join("|");
541
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
542
+ const named = inline ? `<${choices}>` : "<value>";
543
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
544
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
545
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
546
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
547
+ });
548
+ const width = Math.max(0, ...rows.map((row) => row.width));
549
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
550
+ }
551
+
552
+ // ../kit/src/text.ts
553
+ var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
554
+ function distance(a, b) {
555
+ const left = [...a];
556
+ const right = [...b];
557
+ let before = [];
558
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
559
+ for (const [i, x] of left.entries()) {
560
+ const current = [i + 1];
561
+ for (const [j, y] of right.entries()) {
562
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
563
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
564
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
565
+ current.push(cost);
566
+ }
567
+ before = previous;
568
+ previous = current;
569
+ }
570
+ return previous[right.length] ?? 0;
571
+ }
572
+ function closest(name, names) {
573
+ const started = names.find((known) => known.startsWith(name));
574
+ if (started !== undefined)
575
+ return started;
576
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
577
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
578
+ }
579
+ // ../kit/src/input.ts
580
+ var WHOLE = /^\d+$/;
581
+ function wholeNumber(value, name, fallback, min = 1) {
582
+ if (value === undefined)
583
+ return fallback;
584
+ const number = Number(value);
585
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
586
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
587
+ return number;
588
+ }
589
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
590
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
591
+ function duration(value, name, fallback, unit = "s") {
592
+ if (value === undefined)
593
+ return fallback;
594
+ const match = DURATION.exec(value.trim());
595
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
596
+ if (ms < 1)
597
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
598
+ return ms;
599
+ }
600
+
601
+ // ../kit/src/args.ts
602
+ var DASHES = /^-+/;
603
+ function jsonOption(holds) {
604
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
605
+ }
606
+ class Exit extends Error {
607
+ code;
608
+ hint;
609
+ constructor(message, code, hint) {
610
+ super(message);
611
+ this.code = code;
612
+ this.hint = hint;
613
+ }
614
+ }
615
+ function fail(message, code = 2, hint) {
616
+ throw new Exit(message, code, hint);
617
+ }
618
+
619
+ class UsageError extends Exit {
620
+ constructor(message, hint) {
621
+ super(message, 2, hint);
622
+ }
623
+ }
624
+ function badUsage(message) {
625
+ throw new UsageError(message);
626
+ }
627
+
628
+ class HelpShown extends Exit {
629
+ constructor() {
630
+ super("help shown", 0);
631
+ }
632
+ }
633
+
634
+ class Completing {
635
+ options;
636
+ positionals;
637
+ candidates;
638
+ constructor(options, positionals = [], candidates = {}) {
639
+ this.options = options;
640
+ this.positionals = positionals;
641
+ this.candidates = candidates;
642
+ }
643
+ }
644
+ var completion = { active: false };
645
+ var OUTPUT_OPTIONS = {
646
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
647
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
648
+ };
649
+ function applyOutput(color, plain, env = process9.env) {
650
+ const when = plain === true ? "never" : color ?? "auto";
651
+ if (when === "auto")
652
+ return;
653
+ if (when !== "always" && when !== "never")
654
+ badUsage(`--color takes auto, always or never, not ${when}`);
655
+ if (when === "always") {
656
+ env.FORCE_COLOR = "1";
657
+ delete env.NO_COLOR;
658
+ } else {
659
+ env.NO_COLOR = "1";
660
+ delete env.FORCE_COLOR;
661
+ }
662
+ }
663
+ function parse(args, usage, options, settings = {}) {
664
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
665
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
666
+ const listing = listed(all, settings.allowNegative === true);
667
+ if (completion.active)
668
+ throw new Completing(listing, settings.positionals, settings.candidates);
669
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
670
+ let parsed;
671
+ try {
672
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
673
+ } catch (error) {
674
+ const message = parseError(error);
675
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
676
+ }
677
+ const values = parsed.values;
678
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
679
+ if (values.help === true) {
680
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
681
+ throw new HelpShown;
682
+ }
683
+ checkChoices(parsed.values, all);
684
+ checkConflicts(parsed.values, all);
685
+ if (settings.positionals !== undefined)
686
+ checkPositionals(parsed.positionals, settings.positionals);
687
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
688
+ }
689
+ function splitRest(args, passes) {
690
+ const separator = passes ? args.indexOf("--") : -1;
691
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
692
+ }
693
+ function splitTrailing(args, options, count) {
694
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
695
+ let seen = 0;
696
+ if (count === 0)
697
+ return { own: args, rest: undefined };
698
+ for (let at = 0;at < args.length; at++) {
699
+ const word = args[at];
700
+ if (word === "--")
701
+ break;
702
+ if (word.startsWith("-")) {
703
+ if (takesValue(word))
704
+ at++;
705
+ continue;
706
+ }
707
+ seen++;
708
+ if (seen === count)
709
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
710
+ }
711
+ return { own: args, rest: undefined };
712
+ }
713
+ function listed(options, allowNegative) {
714
+ if (!allowNegative)
715
+ return options;
716
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
717
+ if (option.type !== "boolean" || option.negative === undefined)
718
+ return [[name, option]];
719
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
720
+ }));
721
+ }
722
+ function withAliases(args, options) {
723
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
724
+ if (named.size === 0)
725
+ return args;
726
+ const separator = args.indexOf("--");
727
+ const own = separator === -1 ? args : args.slice(0, separator);
728
+ return [...own.map((arg) => {
729
+ const at = arg.indexOf("=");
730
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
731
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
732
+ }), ...separator === -1 ? [] : args.slice(separator)];
733
+ }
734
+ function withBare(args, options) {
735
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
736
+ if (bare.size === 0)
737
+ return args;
738
+ const separator = args.indexOf("--");
739
+ const own = separator === -1 ? args : args.slice(0, separator);
740
+ return [...own.flatMap((arg, index) => {
741
+ const optional = bare.get(arg);
742
+ const next = own[index + 1];
743
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
744
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
745
+ }), ...separator === -1 ? [] : args.slice(separator)];
746
+ }
747
+ function checkConflicts(values, options) {
748
+ const given = (name) => values[name] !== undefined && values[name] !== false;
749
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
750
+ const other = given(name) ? conflicts.find(given) : undefined;
751
+ if (other !== undefined)
752
+ badUsage(`--${name} cannot be used with --${other}`);
753
+ }
754
+ }
755
+ function checkChoices(values, options) {
756
+ for (const [name, option] of Object.entries(options)) {
757
+ if (option.choices === undefined)
758
+ continue;
759
+ const given = values[name];
760
+ for (const value of Array.isArray(given) ? given : [given]) {
761
+ if (typeof value === "string")
762
+ oneOf(value, name, option.choices);
763
+ }
764
+ }
765
+ }
766
+ function oneOf(value, name, choices) {
767
+ if (!choices.includes(value))
768
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
769
+ return value;
770
+ }
771
+ function checkPositionals(given, names) {
772
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
773
+ const required = names.filter((name) => !name.startsWith("[")).length;
774
+ if (given.length < required)
775
+ badUsage(`missing ${names[given.length]}`);
776
+ if (!variadic && given.length > names.length)
777
+ badUsage(`unexpected argument ${given[names.length]}`);
778
+ }
779
+ function joinDashValues(args, options) {
780
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
781
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
782
+ const joined = [];
783
+ for (let i = 0;i < args.length; i++) {
784
+ const arg = args[i] ?? "";
785
+ if (arg === "--")
786
+ return [...joined, ...args.slice(i)];
787
+ const name = longOf.get(arg);
788
+ const next = args[i + 1];
789
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
790
+ joined.push(`--${name}=${next}`);
791
+ i++;
792
+ } else {
793
+ joined.push(arg);
794
+ }
795
+ }
796
+ return joined;
797
+ }
798
+ function parseError(error) {
799
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
800
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
801
+ }
802
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
803
+ function nearestOption(message, options, allowNegative) {
804
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
805
+ if (typed === undefined)
806
+ return;
807
+ const word = typed.replace(DASHES, "");
808
+ if (word.length < 2 && !typed.startsWith("--"))
809
+ return;
810
+ const known = Object.entries(options).flatMap(([name, option]) => [
811
+ ...option.short === undefined ? [] : [`-${option.short}`],
812
+ `--${name}`,
813
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
814
+ ]);
815
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
816
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
817
+ }
818
+ // ../kit/src/argv.ts
819
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
820
+ import { resolve as resolve3 } from "path";
821
+ import process10 from "process";
822
+ function commandLine() {
823
+ try {
824
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
825
+ } catch {
826
+ return;
827
+ }
828
+ }
829
+ function realPath(word) {
830
+ try {
831
+ return realpathSync(resolve3(word));
832
+ } catch {
833
+ return;
834
+ }
835
+ }
836
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
837
+ const target = script === undefined ? undefined : realPath(script) ?? script;
838
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
839
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
840
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
841
+ }
842
+ // ../kit/src/progress.ts
843
+ import process12 from "process";
844
+
845
+ // ../kit/src/process.ts
846
+ import { constants } from "os";
847
+ import process11 from "process";
848
+ var KILL_GRACE_MS = 2000;
849
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
850
+ function exitCodeOf(code, signal) {
851
+ if (code !== null)
852
+ return code;
853
+ if (typeof signal === "number")
854
+ return 128 + signal;
855
+ return signal === null ? 129 : 128 + constants.signals[signal];
856
+ }
857
+ function holdSignals(cleanup) {
858
+ let received;
859
+ let child;
860
+ const held = {
861
+ get signal() {
862
+ return received;
863
+ },
864
+ forward: (to) => {
865
+ child = to;
866
+ },
867
+ release: () => {
868
+ for (const signal of SIGNALS)
869
+ process11.off(signal, onSignal);
870
+ }
871
+ };
872
+ function onSignal(signal) {
873
+ received = signal;
874
+ if (child !== undefined) {
875
+ child.kill(signal);
876
+ return;
877
+ }
878
+ if (cleanup === undefined)
879
+ return;
880
+ held.release();
881
+ cleanup(signal);
882
+ process11.kill(process11.pid, signal);
883
+ }
884
+ for (const signal of SIGNALS)
885
+ process11.on(signal, onSignal);
886
+ return held;
887
+ }
888
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
889
+ const chunks = [];
890
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
891
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
892
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
893
+ const timers = [];
894
+ const killGroup = (killing) => {
895
+ if (state.done)
896
+ return;
897
+ try {
898
+ if (grouped)
899
+ process11.kill(-proc.pid, killing);
900
+ else
901
+ proc.kill(killing);
902
+ } catch {}
903
+ };
904
+ const stop = () => {
905
+ killGroup("SIGTERM");
906
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
907
+ };
908
+ const onAbort = () => stop();
909
+ if (timeoutMs !== undefined) {
910
+ timers.push(setTimeout(() => {
911
+ state.timedOut = true;
912
+ stop();
913
+ }, timeoutMs));
914
+ }
915
+ if (signal?.aborted === true)
916
+ onAbort();
917
+ else
918
+ signal?.addEventListener("abort", onAbort, { once: true });
919
+ onStart?.({ kill: (killing) => killGroup(killing) });
920
+ const drain = async (stream, name) => {
921
+ for await (const data of stream) {
922
+ if (state.failure !== undefined)
923
+ continue;
924
+ try {
925
+ onChunk?.({ stream: name, data });
926
+ } catch (error) {
927
+ state.failure = error;
928
+ stop();
929
+ continue;
930
+ }
931
+ if (state.kept + data.length > maxBytes) {
932
+ state.truncated = true;
933
+ continue;
934
+ }
935
+ state.kept += data.length;
936
+ chunks.push({ stream: name, data });
937
+ }
938
+ };
939
+ try {
940
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
941
+ await proc.exited;
942
+ } finally {
943
+ state.done = true;
944
+ for (const timer of timers)
945
+ clearTimeout(timer);
946
+ signal?.removeEventListener("abort", onAbort);
947
+ }
948
+ if (state.failure !== undefined)
949
+ throw state.failure;
950
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
951
+ let output;
952
+ let text;
953
+ return {
954
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
955
+ chunks,
956
+ timedOut: state.timedOut,
957
+ truncated: state.truncated,
958
+ get output() {
959
+ return output ??= joined();
960
+ },
961
+ get text() {
962
+ return text ??= (output ??= joined()).toString();
963
+ }
964
+ };
965
+ }
966
+
967
+ // ../kit/src/progress.ts
968
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
969
+ var FRAME_MS = 200;
970
+ var BAR_WIDTH = 20;
971
+ var CLEAR_BELOW = "\r\x1B[J";
972
+ var ESC = String.fromCharCode(27);
973
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
974
+ var RESET_STYLE = `${ESC}[0m`;
975
+ var CTRL_C = 3;
976
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
977
+ var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
978
+ function liveRegion(render, stream = process12.stderr, env = process12.env) {
979
+ if (!takesControlCodes(stream, env))
980
+ return { redraw: () => {
981
+ return;
982
+ }, print: (text) => void stream.write(`${text}
983
+ `), stop: () => {
984
+ return;
985
+ } };
986
+ const write = stream.write.bind(stream);
987
+ let frame = 0;
988
+ let drawn = false;
989
+ const columns = () => {
990
+ const now = stream.getWindowSize?.()[0] ?? stream.columns;
991
+ return now === undefined || now === 0 ? 80 : now;
992
+ };
993
+ const clear = () => {
994
+ if (drawn)
995
+ write(CLEAR_BELOW);
996
+ drawn = false;
997
+ };
998
+ const draw = () => {
999
+ const width = columns() - 1;
1000
+ const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
1001
+ const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
1002
+ if (lines.length === 0) {
1003
+ clear();
1004
+ return;
1005
+ }
1006
+ write(`${CLEAR_BELOW}${lines.join(`
1007
+ `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
1008
+ drawn = true;
1009
+ };
1010
+ const timer = setInterval(draw, FRAME_MS);
1011
+ stream.on?.("resize", draw);
1012
+ const restore = interceptOutput(clear);
1013
+ const release = swallowInput();
1014
+ const onExit = () => {
1015
+ clear();
1016
+ release();
1017
+ };
1018
+ const signals = holdSignals(stop);
1019
+ function stop() {
1020
+ clearInterval(timer);
1021
+ stream.off?.("resize", draw);
1022
+ clear();
1023
+ restore();
1024
+ release();
1025
+ process12.off("exit", onExit);
1026
+ signals.release();
1027
+ }
1028
+ timer.unref();
1029
+ process12.on("exit", onExit);
1030
+ return {
1031
+ redraw: draw,
1032
+ print: (text) => {
1033
+ clear();
1034
+ write(`${text}
1035
+ `);
1036
+ draw();
1037
+ },
1038
+ stop
1039
+ };
1040
+ }
1041
+ function progressLine(stream = process12.stderr, env = process12.env) {
1042
+ const colors = paint(stream, env);
1043
+ const write = stream.write.bind(stream);
1044
+ const begun = performance.now();
1045
+ let started = begun;
1046
+ let current;
1047
+ const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
1048
+ const end = (line) => {
1049
+ region.stop();
1050
+ write(`${line}
1051
+ `);
1052
+ };
1053
+ return {
1054
+ update: (progress) => {
1055
+ const step = current?.step;
1056
+ current = progress;
1057
+ if (progress.step !== step) {
1058
+ started = performance.now();
1059
+ region.redraw();
1060
+ }
1061
+ },
1062
+ stop: region.stop,
1063
+ done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
1064
+ failed: (text) => end(marked("problem", text, stream, undefined, env))
1065
+ };
1066
+ }
1067
+ function progressParts({ step, done, total, unit }, spinner, ms) {
1068
+ const { theme } = activeTheme();
1069
+ const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
1070
+ if (total !== undefined && total > 0) {
1071
+ const counted = Math.min(done ?? 0, total);
1072
+ const filled = Math.round(counted / total * BAR_WIDTH);
1073
+ parts.push({ text: " ", tint: () => plain }, { text: theme.glyphs.bar.repeat(filled), tint: (colors) => () => shaded(theme, colors, theme.glyphs.bar, filled, BAR_WIDTH) }, { text: theme.glyphs.bar.repeat(BAR_WIDTH - filled), tint: (colors) => colors.dim }, { text: ` ${counted}/${total}${unit === undefined ? "" : ` ${unit}`}`, tint: (colors) => colors.dim });
1074
+ }
1075
+ parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
1076
+ return parts;
1077
+ }
1078
+ function plain(text) {
1079
+ return text;
1080
+ }
1081
+ function tintedParts(parts, colors) {
1082
+ return parts.map(({ text, tint }) => tint(colors)(text)).join("");
1083
+ }
1084
+ function cutToWidth(line, width) {
1085
+ if (Bun.stringWidth(line) <= width)
1086
+ return line;
1087
+ let room = width;
1088
+ let kept = "";
1089
+ let index = 0;
1090
+ let linked = false;
1091
+ while (index < line.length) {
1092
+ ESCAPE_CODE.lastIndex = index;
1093
+ const escape = ESCAPE_CODE.exec(line);
1094
+ if (escape !== null) {
1095
+ kept += escape[0];
1096
+ linked ||= escape[0].startsWith(`${ESC}]`);
1097
+ index = ESCAPE_CODE.lastIndex;
1098
+ continue;
1099
+ }
1100
+ const char = String.fromCodePoint(line.codePointAt(index));
1101
+ const columns = Bun.stringWidth(char);
1102
+ if (columns > room)
1103
+ break;
1104
+ kept += char;
1105
+ room -= columns;
1106
+ index += char.length;
1107
+ }
1108
+ return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1109
+ }
1110
+ function swallowInput() {
1111
+ const input = process12.stdin;
1112
+ if (!input.isTTY)
1113
+ return () => {
1114
+ return;
1115
+ };
1116
+ const onData = (data) => {
1117
+ if (data.includes(CTRL_C))
1118
+ process12.kill(process12.pid, "SIGINT");
1119
+ };
1120
+ input.setRawMode(true);
1121
+ input.on("data", onData);
1122
+ input.resume();
1123
+ let released = false;
1124
+ return () => {
1125
+ if (released)
1126
+ return;
1127
+ released = true;
1128
+ input.off("data", onData);
1129
+ input.pause();
1130
+ input.setRawMode(false);
1131
+ };
1132
+ }
1133
+ function interceptOutput(clear) {
1134
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1135
+ const wrapped = targets.map(([target, name]) => {
1136
+ const original = Reflect.get(target, name);
1137
+ const wrapper = (...args) => {
1138
+ clear();
1139
+ return original.apply(target, args);
1140
+ };
1141
+ Reflect.set(target, name, wrapper);
1142
+ return { target, name, original, wrapper };
1143
+ });
1144
+ return () => {
1145
+ for (const { target, name, original, wrapper } of wrapped) {
1146
+ if (Reflect.get(target, name) === wrapper)
1147
+ Reflect.set(target, name, original);
1148
+ }
1149
+ };
1150
+ }
1151
+ // ../kit/src/cli.ts
1152
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1153
+ import { dirname as dirname3, join as join5 } from "path";
1154
+ import process15 from "process";
1155
+
1156
+ // ../kit/src/notify.ts
1157
+ import process13 from "process";
1158
+ var NOTIFY_AFTER_MS = 1e4;
1159
+ var CANCELLED = 130;
1160
+ function base64(text) {
1161
+ return Buffer.from(text).toString("base64");
1162
+ }
1163
+ function notification(title, body, env = process13.env) {
1164
+ const id = `kit${process13.pid}`;
1165
+ 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\\`];
1166
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1167
+ }
1168
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1169
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1170
+ return;
1171
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1172
+ }
1173
+
1174
+ // ../kit/src/usage.ts
1175
+ import { appendFileSync, mkdirSync } from "fs";
1176
+ import { homedir as homedir3 } from "os";
1177
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1178
+ import process14 from "process";
1179
+
1180
+ // ../kit/src/logs.ts
1181
+ var DAY_MS = 24 * 60 * 60 * 1000;
1182
+ var CLI_FOLDER = "kaynooo-cli";
1183
+
1184
+ // ../kit/src/usage.ts
1185
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1186
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1187
+ var LONGEST_NAME = 40;
1188
+ var usageError;
1189
+ function noteUsageError(message) {
1190
+ usageError = message;
1191
+ }
1192
+ function stateHome(env = process14.env) {
1193
+ const dir = env.XDG_STATE_HOME;
1194
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1195
+ }
1196
+ function usagePath(env = process14.env) {
1197
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1198
+ }
1199
+ function usageRecorded(env = process14.env) {
1200
+ const off = env.KAYNOOO_CLI_NO_USAGE;
1201
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1202
+ }
1203
+ function flagNames(argv) {
1204
+ const end = argv.indexOf("--");
1205
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1206
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1207
+ }
1208
+ function usageEntry(bin, command, argv, code, now = new Date) {
1209
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1210
+ usageError = undefined;
1211
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1212
+ }
1213
+ function recordUsage(entry, env = process14.env) {
1214
+ if (!usageRecorded(env))
1215
+ return;
1216
+ try {
1217
+ const path = usagePath(env);
1218
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1219
+ appendFileSync(path, `${JSON.stringify(entry)}
1220
+ `, { mode: 384 });
1221
+ } catch {}
1222
+ }
1223
+
1224
+ // ../kit/src/cli.ts
1225
+ var LEVEL_OPTIONS = {
1226
+ ...OUTPUT_OPTIONS,
1227
+ help: { type: "boolean", short: "h", description: "show this help" }
1228
+ };
1229
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1230
+ function printError(prefix, message, hint, cause) {
1231
+ const colors = paint(process15.stderr);
1232
+ const styled = takesControlCodes(process15.stderr);
1233
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1234
+ const under = (label, text, tint) => text === undefined ? "" : `
1235
+ ${styled ? tint(label) : `${label}:`} ${text}`;
1236
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1237
+ }
1238
+ function runHint(command, effect) {
1239
+ return `run \`${command}\`${effect === undefined ? "" : ` to ${effect}`}`;
1240
+ }
1241
+ function printJsonError(message, hint, cause) {
1242
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1243
+ }
1244
+ function wantsJson(argv) {
1245
+ const end = argv.indexOf("--");
1246
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1247
+ }
1248
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
1249
+ if (error instanceof HelpShown)
1250
+ return 0;
1251
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1252
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1253
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1254
+ if (error instanceof Exit && error.code === 2)
1255
+ noteUsageError(error.message);
1256
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1257
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1258
+ return error instanceof Exit ? error.code : 1;
1259
+ }
1260
+ var COMPLETE = "__complete";
1261
+ var FILES = "__files__";
1262
+ async function completingOf(run) {
1263
+ completion.active = true;
1264
+ try {
1265
+ await run([]);
1266
+ } catch (error) {
1267
+ if (error instanceof Completing)
1268
+ return error;
1269
+ } finally {
1270
+ completion.active = false;
1271
+ }
1272
+ return new Completing({});
1273
+ }
1274
+ function candidateLine(candidate) {
1275
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1276
+ }
1277
+ function positionalBeingTyped(before, { options, positionals }) {
1278
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1279
+ const typed = [];
1280
+ let at = 0;
1281
+ while (at < before.length) {
1282
+ const word = before[at];
1283
+ if (word === "--") {
1284
+ typed.push(...before.slice(at + 1));
1285
+ break;
1286
+ }
1287
+ if (!word.startsWith("-"))
1288
+ typed.push(word);
1289
+ else if (takesValue(word))
1290
+ at++;
1291
+ at++;
1292
+ }
1293
+ const last = positionals.at(-1);
1294
+ if (typed.length < positionals.length)
1295
+ return { name: positionals[typed.length], typed };
1296
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1297
+ }
1298
+ async function leafCandidates(run, words) {
1299
+ const completing = await completingOf(run);
1300
+ if ((words.at(-1) ?? "").startsWith("-"))
1301
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1302
+ const flag = words.at(-2);
1303
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1304
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1305
+ if (option?.type === "string") {
1306
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1307
+ return values === undefined ? [FILES] : values.map(candidateLine);
1308
+ }
1309
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1310
+ return values === undefined ? [FILES] : values.map(candidateLine);
1311
+ }
1312
+ async function printCandidates(found) {
1313
+ for (const line of await found)
1314
+ console.log(line);
1315
+ return 0;
1316
+ }
1317
+ function packageVersion(entry = Bun.main) {
1318
+ let resolved = entry;
1319
+ try {
1320
+ resolved = realpathSync2(entry);
1321
+ } catch {}
1322
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1323
+ try {
1324
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1325
+ if (typeof version === "string")
1326
+ return version;
1327
+ } catch {}
1328
+ if (dirname3(dir) === dir)
1329
+ return "0.0.0";
1330
+ }
1331
+ }
1332
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1333
+ if (argv[0] === COMPLETE)
1334
+ return printCandidates(leafCandidates(run, argv.slice(1)));
1335
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1336
+ console.log(version ?? packageVersion());
1337
+ return 0;
1338
+ }
1339
+ let code;
1340
+ const started = performance.now();
1341
+ try {
1342
+ code = await run(argv);
1343
+ } catch (error) {
1344
+ code = reportThrown(name, error, redact, wantsJson(argv));
1345
+ }
1346
+ notifyEnd(name, code, performance.now() - started);
1347
+ if (usage !== false) {
1348
+ try {
1349
+ recordUsage(usageEntry(name, undefined, argv, code));
1350
+ } catch {}
1351
+ }
1352
+ return code;
1353
+ }
1354
+ // ../kit/src/folders.ts
1355
+ var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1356
+ // ../kit/src/secrets.ts
1357
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1358
+ // ../kit/src/sessions.ts
1359
+ var {Glob } = globalThis.Bun;
1360
+ var SESSION_FILES = new Glob("*.json");
1361
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1362
+ // ../kit/src/watch.ts
1363
+ import process16 from "process";
1364
+ import { format } from "util";
1365
+ var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1366
+ var DEFAULT_SECONDS = 2;
1367
+ var ATTACHED_SHORT = /^-w./;
1368
+ var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
1369
+ function watchOption(what) {
1370
+ return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
1371
+ }
1372
+ function withoutWatch(args) {
1373
+ const rest = [];
1374
+ for (let at = 0;at < args.length; at++) {
1375
+ const arg = args[at];
1376
+ if (arg === "--watch" || arg === "-w") {
1377
+ if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
1378
+ at++;
1379
+ } else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
1380
+ rest.push(arg);
1381
+ }
1382
+ }
1383
+ return rest;
1384
+ }
1385
+ async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1386
+ const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1387
+ if (!takesControlCodes(stream))
1388
+ badUsage("--watch redraws the screen, so it needs a terminal");
1389
+ let code = 0;
1390
+ for (let round = 0;round < rounds; round++) {
1391
+ const held = [];
1392
+ const { log, info } = console;
1393
+ const write = process16.stdout.write.bind(process16.stdout);
1394
+ const hold = (...parts) => void held.push(`${format(...parts)}
1395
+ `);
1396
+ console.log = hold;
1397
+ console.info = hold;
1398
+ process16.stdout.write = (text) => {
1399
+ held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1400
+ return true;
1401
+ };
1402
+ try {
1403
+ code = await step();
1404
+ } finally {
1405
+ console.log = log;
1406
+ console.info = info;
1407
+ process16.stdout.write = write;
1408
+ }
1409
+ stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1410
+ await sleep(interval);
1411
+ }
1412
+ return code;
1413
+ }
1414
+ // ../kit/src/workspace-root.ts
1415
+ import { homedir as homedir4 } from "os";
1416
+ import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1417
+ import process17 from "process";
1418
+ function expandHome(path, home) {
1419
+ if (path === "~")
1420
+ return home;
1421
+ return path.startsWith("~/") ? join6(home, path.slice(2)) : path;
1422
+ }
1423
+ function configured(env, home) {
1424
+ const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1425
+ return typeof folder === "string" && folder !== "" ? folder : undefined;
1426
+ }
1427
+ function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1428
+ const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1429
+ return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1430
+ }
1431
+ // ../kit/src/picker/line.ts
1432
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1433
+ var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1434
+ var FORWARD_KILLS = new Set(["killnext", "killend"]);
1435
+ function isEditKey(key) {
1436
+ return EDIT_KEYS.has(key);
1437
+ }
1438
+ function endsKills(key) {
1439
+ return typeof key !== "object" && !isEditKey(key);
1440
+ }
1441
+ var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1442
+ var SPACE = /\s/;
1443
+ function isWord(char) {
1444
+ return char !== undefined && WORD_CHARACTER.test(char);
1445
+ }
1446
+ function wordStart(chars, from) {
1447
+ let at = from;
1448
+ while (at > 0 && !isWord(chars[at - 1]))
1449
+ at--;
1450
+ while (at > 0 && isWord(chars[at - 1]))
1451
+ at--;
1452
+ return at;
1453
+ }
1454
+ function wordEnd(chars, from) {
1455
+ let at = from;
1456
+ while (at < chars.length && !isWord(chars[at]))
1457
+ at++;
1458
+ while (at < chars.length && isWord(chars[at]))
1459
+ at++;
1460
+ return at;
1461
+ }
1462
+ function spacedStart(chars, from) {
1463
+ let at = from;
1464
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
1465
+ at--;
1466
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
1467
+ at--;
1468
+ return at;
1469
+ }
1470
+ function cut(chars, from, to) {
1471
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1472
+ }
1473
+ function insert(chars, at, text) {
1474
+ const typed = [...text];
1475
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
1476
+ }
1477
+ function editLine(line, key) {
1478
+ const { killed = "", chained = false } = line;
1479
+ const chars = [...line.text];
1480
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
1481
+ const edited = edit(chars, at, key, killed);
1482
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1483
+ return line.killed === undefined ? edited : { ...edited, killed };
1484
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1485
+ if (taken === "")
1486
+ return { ...edited, killed, chained };
1487
+ if (!chained)
1488
+ return { ...edited, killed: taken, chained: true };
1489
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1490
+ }
1491
+ function edit(chars, at, key, killed) {
1492
+ const text = chars.join("");
1493
+ if (typeof key === "object")
1494
+ return insert(chars, at, key.text);
1495
+ switch (key) {
1496
+ case "left":
1497
+ return { text, caret: Math.max(at - 1, 0) };
1498
+ case "right":
1499
+ return { text, caret: Math.min(at + 1, chars.length) };
1500
+ case "wordleft":
1501
+ return { text, caret: wordStart(chars, at) };
1502
+ case "wordright":
1503
+ return { text, caret: wordEnd(chars, at) };
1504
+ case "linestart":
1505
+ return { text, caret: 0 };
1506
+ case "lineend":
1507
+ return { text, caret: chars.length };
1508
+ case "erase":
1509
+ return cut(chars, Math.max(at - 1, 0), at);
1510
+ case "delete":
1511
+ return cut(chars, at, Math.min(at + 1, chars.length));
1512
+ case "word":
1513
+ return cut(chars, spacedStart(chars, at), at);
1514
+ case "killword":
1515
+ return cut(chars, wordStart(chars, at), at);
1516
+ case "killnext":
1517
+ return cut(chars, at, wordEnd(chars, at));
1518
+ case "clear":
1519
+ return cut(chars, 0, at);
1520
+ case "killend":
1521
+ return cut(chars, at, chars.length);
1522
+ case "yank":
1523
+ return insert(chars, at, killed);
1524
+ }
1525
+ }
1526
+ function visible({ text, caret }, room) {
1527
+ const chars = [...text];
1528
+ const at = Math.min(Math.max(caret, 0), chars.length);
1529
+ const cells = at === chars.length ? [...chars, " "] : chars;
1530
+ const widths = cells.map((char) => Bun.stringWidth(char));
1531
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1532
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1533
+ let start = at;
1534
+ let end = at + 1;
1535
+ while (start > 0 && fits(start - 1, end))
1536
+ start--;
1537
+ while (end < cells.length && fits(start, end + 1))
1538
+ end++;
1539
+ const left = start > 0 ? "\u2026" : "";
1540
+ const right = end < cells.length ? "\u2026" : "";
1541
+ return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
1542
+ }
1543
+
1544
+ // ../kit/src/picker/score.ts
1545
+ var MATCH = 16;
1546
+ var CONSECUTIVE = 12;
1547
+ var BOUNDARY = 10;
1548
+ var PREFIX = 8;
1549
+ var GAP = 1;
1550
+ var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1551
+ var UPPER = /\p{Lu}/u;
1552
+ var LOWER = /\p{Ll}/u;
1553
+ var NONE = Number.NEGATIVE_INFINITY;
1554
+ function startsWord(text, index) {
1555
+ if (index === 0)
1556
+ return true;
1557
+ const before = text[index - 1];
1558
+ return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
1559
+ }
1560
+ function fuzzy(query, text) {
1561
+ if (query === "")
1562
+ return { score: 0, positions: [] };
1563
+ const exact = query !== query.toLowerCase();
1564
+ const needle = exact ? query : query.toLowerCase();
1565
+ const haystack = exact ? text : text.toLowerCase();
1566
+ if (haystack.length !== text.length || needle.length > haystack.length)
1567
+ return;
1568
+ const width = haystack.length;
1569
+ const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
1570
+ const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
1571
+ for (let j = 0;j < needle.length; j++) {
1572
+ let run = NONE;
1573
+ let runAt = -1;
1574
+ for (let i = j;i < width; i++) {
1575
+ if (j > 0 && i - 2 >= j - 1) {
1576
+ const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
1577
+ if (candidate > run) {
1578
+ run = candidate;
1579
+ runAt = i - 2;
1580
+ }
1581
+ }
1582
+ if (haystack[i] !== needle[j])
1583
+ continue;
1584
+ const here = MATCH + (startsWord(text, i) ? BOUNDARY : 0) + (i === 0 ? PREFIX : 0);
1585
+ if (j === 0) {
1586
+ best[0][i] = here - i * GAP;
1587
+ continue;
1588
+ }
1589
+ const joined = best[j - 1][i - 1] + CONSECUTIVE;
1590
+ const skipped = run - (i - 1) * GAP;
1591
+ if (joined > NONE && joined >= skipped) {
1592
+ best[j][i] = joined + here;
1593
+ from[j][i] = i - 1;
1594
+ } else if (skipped > NONE) {
1595
+ best[j][i] = skipped + here;
1596
+ from[j][i] = runAt;
1597
+ }
1598
+ }
1599
+ }
1600
+ const last = best[needle.length - 1];
1601
+ let end = -1;
1602
+ for (let i = 0;i < width; i++) {
1603
+ if (last[i] > NONE && (end === -1 || last[i] > last[end]))
1604
+ end = i;
1605
+ }
1606
+ if (end === -1)
1607
+ return;
1608
+ const positions = [];
1609
+ for (let j = needle.length - 1, i = end;j >= 0; j--) {
1610
+ positions.unshift(i);
1611
+ i = from[j][i];
1612
+ }
1613
+ return { score: last[end], positions };
1614
+ }
1615
+ function rank(query, lines) {
1616
+ if (query === "")
1617
+ return lines.map((_, index) => ({ index, positions: [] }));
1618
+ const found = [];
1619
+ for (const [index, line] of lines.entries()) {
1620
+ const match = fuzzy(query, line);
1621
+ if (match !== undefined)
1622
+ found.push({ index, positions: match.positions, score: match.score });
1623
+ }
1624
+ return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
1625
+ }
1626
+
1627
+ // ../kit/src/picker/state.ts
1628
+ var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1629
+ var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1630
+ var SGR = /^\x1B\[[0-9;]*m$/;
1631
+ var RESET = /^\x1B\[0?m$/;
1632
+ var COLUMN_GAP = 2;
1633
+ var PASTE_START = "\x1B[200~";
1634
+ var PASTE_END = "\x1B[201~";
1635
+ var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1636
+ var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1637
+ var WHEEL_LINES = 3;
1638
+ var KEYS = {
1639
+ "\x1B[A": "up",
1640
+ "\x1BOA": "up",
1641
+ "\x10": "up",
1642
+ "\x1B[B": "down",
1643
+ "\x1BOB": "down",
1644
+ "\x0E": "down",
1645
+ "\x1B[5~": "pageup",
1646
+ "\x1B[6~": "pagedown",
1647
+ "\x1B[H": "home",
1648
+ "\x1B[1~": "home",
1649
+ "\x1BOH": "home",
1650
+ "\x1B[F": "end",
1651
+ "\x1B[4~": "end",
1652
+ "\x1BOF": "end",
1653
+ "\r": "enter",
1654
+ "\n": "enter",
1655
+ "\x03": "cancel",
1656
+ "\x1B": "cancel",
1657
+ "\x1B[D": "left",
1658
+ "\x1BOD": "left",
1659
+ "\x1B[C": "right",
1660
+ "\x1BOC": "right",
1661
+ "\x1B[1;5D": "wordleft",
1662
+ "\x1B[1;3D": "wordleft",
1663
+ "\x1Bb": "wordleft",
1664
+ "\x1B[1;5C": "wordright",
1665
+ "\x1B[1;3C": "wordright",
1666
+ "\x1Bf": "wordright",
1667
+ "\x01": "linestart",
1668
+ "\x05": "lineend",
1669
+ "\x7F": "erase",
1670
+ "\x1B[3~": "delete",
1671
+ "\b": "killword",
1672
+ "\x1B\x7F": "killword",
1673
+ "\x1B[3;5~": "killnext",
1674
+ "\x1Bd": "killnext",
1675
+ "\x15": "clear",
1676
+ "\v": "killend",
1677
+ "\x17": "word",
1678
+ "\x19": "yank",
1679
+ "\x1A": "suspend",
1680
+ "\t": "tab",
1681
+ "\x1F": "help",
1682
+ "\x1BOP": "help",
1683
+ "\x1B[11~": "help"
1684
+ };
1685
+ var CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
1686
+ function repeat(value, count) {
1687
+ return Array.from({ length: count }).fill(value);
1688
+ }
1689
+ function styled(line) {
1690
+ let text = "";
1691
+ const styles = [];
1692
+ let active = "";
1693
+ let colored = false;
1694
+ let last = 0;
1695
+ function add(chunk) {
1696
+ const flat = chunk.replace(CONTROL2, " ");
1697
+ text += flat;
1698
+ colored ||= active !== "" && flat !== "";
1699
+ styles.push(...repeat(active, flat.length));
1700
+ }
1701
+ for (const found of line.matchAll(ANSI)) {
1702
+ add(line.slice(last, found.index));
1703
+ last = found.index + found[0].length;
1704
+ if (SGR.test(found[0]))
1705
+ active = RESET.test(found[0]) ? "" : active + found[0];
1706
+ }
1707
+ add(line.slice(last));
1708
+ return { text, styles: colored ? styles : undefined };
1709
+ }
1710
+ function lay(rows, searched) {
1711
+ const parsed = rows.map((row) => row.cells.map(styled));
1712
+ const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1713
+ return parsed.map((cells, at) => {
1714
+ let text = "";
1715
+ const styles = [];
1716
+ let colored = false;
1717
+ let searchEnd = 0;
1718
+ for (const [column, cell] of cells.entries()) {
1719
+ const last = column === cells.length - 1;
1720
+ const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1721
+ text += shown;
1722
+ colored ||= cell.styles !== undefined;
1723
+ styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1724
+ if (column < searched)
1725
+ searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1726
+ if (!last) {
1727
+ const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1728
+ text += " ".repeat(pad);
1729
+ styles.push(...repeat("", pad));
1730
+ }
1731
+ }
1732
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1733
+ });
1734
+ }
1735
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1736
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1737
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1738
+ const wheel = MOUSE.exec(sequence)?.[1];
1739
+ if (wheel !== undefined)
1740
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1741
+ const named = codes.get(sequence);
1742
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1743
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1744
+ paste.active = sequence === PASTE_START;
1745
+ return [];
1746
+ }
1747
+ if (paste.active && (sequence === "\r" || sequence === `
1748
+ `))
1749
+ return [];
1750
+ if (key !== undefined)
1751
+ return [key];
1752
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1753
+ });
1754
+ }
1755
+ function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1756
+ const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1757
+ return withRows(state, rows);
1758
+ }
1759
+ function withRows(state, rows, header = state.header) {
1760
+ const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1761
+ const laid = lay(cells, state.searched);
1762
+ const searchable = laid.map((row) => row.searchable);
1763
+ const matches = rank(state.query, searchable);
1764
+ return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
1765
+ }
1766
+ function withQuery(state, key) {
1767
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1768
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1769
+ }
1770
+ function move(state, by) {
1771
+ return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1772
+ }
1773
+ function highlighted(state) {
1774
+ return state.matches[state.cursor]?.index;
1775
+ }
1776
+ function press(state, key) {
1777
+ if (state.done !== undefined)
1778
+ return state;
1779
+ if (state.chained && endsKills(key))
1780
+ state = { ...state, chained: false };
1781
+ if (state.help)
1782
+ return { ...state, help: false };
1783
+ if (typeof key === "object") {
1784
+ if ("text" in key)
1785
+ return withQuery(state, key);
1786
+ return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1787
+ }
1788
+ if (isEditKey(key))
1789
+ return withQuery(state, key);
1790
+ switch (key) {
1791
+ case "up":
1792
+ return move(state, -1);
1793
+ case "down":
1794
+ return move(state, 1);
1795
+ case "pageup":
1796
+ return move(state, -state.page);
1797
+ case "pagedown":
1798
+ return move(state, state.page);
1799
+ case "home":
1800
+ return move(state, -state.matches.length);
1801
+ case "end":
1802
+ return move(state, state.matches.length);
1803
+ case "cancel":
1804
+ return { ...state, done: "cancel" };
1805
+ case "help":
1806
+ return { ...state, help: true };
1807
+ case "suspend":
1808
+ return state;
1809
+ case "enter":
1810
+ return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1811
+ case "tab": {
1812
+ const at = highlighted(state);
1813
+ if (!state.multi || at === undefined)
1814
+ return state;
1815
+ const marked = new Set(state.marked);
1816
+ if (!marked.delete(at))
1817
+ marked.add(at);
1818
+ return move({ ...state, marked }, 1);
1819
+ }
1820
+ }
1821
+ }
1822
+ function chosen(state) {
1823
+ if (state.marked.size > 0)
1824
+ return state.rows.filter((_, index) => state.marked.has(index));
1825
+ const at = highlighted(state);
1826
+ return at === undefined ? [] : [state.rows[at]];
1827
+ }
1828
+
1829
+ // ../kit/src/picker/terminal.ts
1830
+ import { openSync } from "fs";
1831
+ import process21 from "process";
1832
+ import tty from "tty";
1833
+
1834
+ // ../kit/src/job.ts
1835
+ import process19 from "process";
1836
+ function stopJob() {
1837
+ process19.kill(0, "SIGTSTP");
1838
+ }
1839
+
1840
+ // ../kit/src/redraw.ts
1841
+ var SYNC_START = "\x1B[?2026h";
1842
+ var SYNC_END = "\x1B[?2026l";
1843
+ function overwrite(lines, columns) {
1844
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1845
+ `);
1846
+ }
1847
+
1848
+ // ../kit/src/picker/preview.ts
1849
+ import process20 from "process";
1850
+
1851
+ // ../kit/src/shell.ts
1852
+ var SEPARATORS = new Set([`
1853
+ `, ";", "|"]);
1854
+ var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
1855
+ var GLOB_CHARS = new Set(["*", "?", "["]);
1856
+ var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
1857
+ var SAFE_WORD = /^[\w@%+=:,./-]+$/;
1858
+ var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
1859
+ var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
1860
+ var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
1861
+ var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
1862
+ var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
1863
+ var POWERSHELL = new Set(["pwsh", "powershell"]);
1864
+ var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
1865
+ var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
1866
+ var PRINTERS = new Set(["echo", "printf"]);
1867
+ var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
1868
+ function wrapper(short = "", long = [], operands = 0, runsString = false) {
1869
+ return { short, long, operands, runsString };
1870
+ }
1871
+ var WRAPPERS = new Map([
1872
+ ["command", wrapper()],
1873
+ ["builtin", wrapper()],
1874
+ ["nohup", wrapper()],
1875
+ ["setsid", wrapper()],
1876
+ ["busybox", wrapper()],
1877
+ ["exec", wrapper("a")],
1878
+ ["time", wrapper("fo", ["--format", "--output"])],
1879
+ ["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
1880
+ ["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
1881
+ ["doas", wrapper("uC")],
1882
+ ["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
1883
+ ["nice", wrapper("n", ["--adjustment"])],
1884
+ ["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
1885
+ ["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
1886
+ ["chroot", wrapper("", ["--userspec", "--groups"], 1)],
1887
+ ["watch", wrapper("n", ["--interval"], 0, true)],
1888
+ ["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
1889
+ ["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
1890
+ ["unbuffer", wrapper()],
1891
+ ["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
1892
+ ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
1893
+ ]);
1894
+ function shellQuote(word) {
1895
+ return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
1896
+ }
1897
+
1898
+ // ../kit/src/picker/preview.ts
1899
+ var PREVIEW_BYTES = 64 * 1024;
1900
+ var PREVIEW_LINES = 200;
1901
+ var PREVIEW_TIMEOUT_MS = 3000;
1902
+ var PLACEHOLDER = /\{([1-9]\d*)?\}/g;
1903
+ function previewCommand(template, line, hidden = []) {
1904
+ return template.replace(PLACEHOLDER, (_, field) => shellQuote(field === undefined ? line : hidden[Number(field) - 1] ?? ""));
1905
+ }
1906
+ function previewLines(output) {
1907
+ const lines = output.split(`
1908
+ `);
1909
+ if (lines.at(-1) === "")
1910
+ lines.pop();
1911
+ return lines.slice(0, PREVIEW_LINES);
1912
+ }
1913
+ async function runPreview(template, line, signal, hidden = []) {
1914
+ const proc = Bun.spawn(["sh", "-c", `exec 2>&1
1915
+ ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1916
+ const stop = () => {
1917
+ try {
1918
+ process20.kill(-proc.pid, "SIGKILL");
1919
+ } catch {
1920
+ proc.kill();
1921
+ }
1922
+ };
1923
+ const timer = setTimeout(stop, PREVIEW_TIMEOUT_MS);
1924
+ const chunks = [];
1925
+ let size = 0;
1926
+ signal.addEventListener("abort", stop);
1927
+ try {
1928
+ for await (const chunk of proc.stdout) {
1929
+ chunks.push(chunk);
1930
+ size += chunk.length;
1931
+ if (size >= PREVIEW_BYTES) {
1932
+ stop();
1933
+ break;
1934
+ }
1935
+ }
1936
+ } finally {
1937
+ clearTimeout(timer);
1938
+ signal.removeEventListener("abort", stop);
1939
+ }
1940
+ return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
1941
+ }
1942
+
1943
+ // ../kit/src/picker/view.ts
1944
+ var MIN_HEIGHT = 4;
1945
+ var PREVIEW_MIN_COLUMNS = 80;
1946
+ var PREVIEW_MIN_ROWS = 10;
1947
+ var PREVIEW_SHARE = 0.4;
1948
+ var RESET2 = "\x1B[0m";
1949
+ var SEPARATOR = " \u2502 ";
1950
+ var HEIGHT = /^(\d+)(%?)$/;
1951
+ function parseHeight(text) {
1952
+ const found = HEIGHT.exec(text);
1953
+ if (found === null || Number(found[1]) < 1)
1954
+ return;
1955
+ return found[2] === "%" ? { percent: Math.min(100, Number(found[1])) } : { lines: Number(found[1]) };
1956
+ }
1957
+ function layoutFor(size, height, previewing, position = "right") {
1958
+ const wanted = "lines" in height ? height.lines : Math.round(size.rows * height.percent / 100);
1959
+ const rows = Math.min(size.rows, Math.max(MIN_HEIGHT, wanted));
1960
+ if (position === "down") {
1961
+ const previewHeight = previewing && rows >= PREVIEW_MIN_ROWS ? Math.round(rows * PREVIEW_SHARE) : 0;
1962
+ return { height: rows, listHeight: rows - previewHeight, listWidth: size.columns, previewWidth: 0, previewHeight };
1963
+ }
1964
+ const split = previewing && size.columns >= PREVIEW_MIN_COLUMNS;
1965
+ const listWidth = split ? Math.floor(size.columns / 2) : size.columns;
1966
+ return { height: rows, listHeight: rows, listWidth, previewWidth: split ? size.columns - listWidth - SEPARATOR.length : 0, previewHeight: 0 };
1967
+ }
1968
+ function fit(text, width, plain, mark = plain, marked = new Set, styles) {
1969
+ const room = Bun.stringWidth(text) > width ? width - 1 : width;
1970
+ let out = "";
1971
+ let used = 0;
1972
+ let at = 0;
1973
+ for (const char of text) {
1974
+ const size = Bun.stringWidth(char);
1975
+ if (used + size > room)
1976
+ break;
1977
+ const style = marked.has(at) ? "" : styles?.[at] ?? "";
1978
+ out += style === "" ? (marked.has(at) ? mark : plain)(char) : `${style}${char}${RESET2}`;
1979
+ used += size;
1980
+ at += char.length;
1981
+ }
1982
+ if (room < width) {
1983
+ out += plain("\u2026");
1984
+ used += 1;
1985
+ }
1986
+ return { text: out, width: used };
1987
+ }
1988
+ var identity = (text) => text;
1989
+ function fitStyled(line, width, plain = identity) {
1990
+ const { text, styles } = styled(line);
1991
+ return fit(text, width, plain, plain, new Set, styles);
1992
+ }
1993
+ function queryShown(state, layout) {
1994
+ return visible({ text: state.query, caret: state.caret }, Math.max(1, layout.listWidth - Bun.stringWidth(state.prompt)));
1995
+ }
1996
+ function caretCell(state, layout) {
1997
+ const shown = queryShown(state, layout);
1998
+ return { column: Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + shown.column + 1), char: shown.at ?? " " };
1999
+ }
2000
+ function helpLines(state, layout, theme) {
2001
+ const lines = [
2002
+ "type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end, the wheel move",
2003
+ "left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word",
2004
+ "ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead",
2005
+ "ctrl-y puts back what they erased, ctrl-z suspends to the shell",
2006
+ `enter picks${state.multi ? ", tab marks" : ""}, esc or ctrl-c cancels`,
2007
+ ...state.expect.length > 0 ? [`${state.expect.join(", ")} end the pick as this command asks`] : []
2008
+ ];
2009
+ const title = "keys, any key closes this help";
2010
+ return [{ text: theme.accent(title), width: title.length }, ...lines.map((line) => fit(` ${line}`, layout.listWidth, theme.label))];
2011
+ }
2012
+ function listLines(state, layout, theme) {
2013
+ if (state.help)
2014
+ return helpLines(state, layout, theme);
2015
+ const header = state.header === "" ? [] : state.header.split(`
2016
+ `).map((line) => fitStyled(line, layout.listWidth, theme.label));
2017
+ const rows = Math.max(1, layout.listHeight - 2 - header.length);
2018
+ const prefixWidth = state.multi ? 4 : 2;
2019
+ const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
2020
+ const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
2021
+ const promptWidth = Bun.stringWidth(state.prompt);
2022
+ const shown = queryShown(state, layout);
2023
+ const text = `${shown.before}${shown.at ?? ""}${shown.after}`;
2024
+ const query = { text, width: Bun.stringWidth(text) };
2025
+ const place = state.matches.length > rows ? ` (${state.cursor + 1} of ${state.matches.length})` : "";
2026
+ const count = fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`, layout.listWidth, theme.label);
2027
+ const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
2028
+ if (state.matches.length === 0)
2029
+ lines.push(fit(" no match", layout.listWidth, theme.label));
2030
+ for (const [offset, match] of state.matches.slice(top, top + rows).entries()) {
2031
+ const current = top + offset === state.cursor;
2032
+ const pointer = current ? theme.accent("\u276F") : " ";
2033
+ const mark = state.multi ? `${state.marked.has(match.index) ? theme.id("\u25CF") : " "} ` : "";
2034
+ const text = fit(state.items[match.index], layout.listWidth - prefixWidth, current ? theme.value : identity, theme.match ?? theme.accent, new Set(match.positions), state.styles[match.index]);
2035
+ lines.push({ text: `${pointer} ${mark}${text.text}`, width: prefixWidth + text.width });
2036
+ }
2037
+ return lines;
2038
+ }
2039
+ function render(state, layout, theme, preview = []) {
2040
+ const left = listLines(state, layout, theme);
2041
+ return Array.from({ length: layout.height }, (_, row) => {
2042
+ if (row >= layout.listHeight)
2043
+ return row === layout.listHeight ? theme.label("\u2500".repeat(layout.listWidth)) : fitStyled(preview[row - layout.listHeight - 1] ?? "", layout.listWidth).text;
2044
+ const list = left[row] ?? { text: "", width: 0 };
2045
+ if (layout.previewWidth === 0)
2046
+ return list.text;
2047
+ return `${list.text}${" ".repeat(Math.max(0, layout.listWidth - list.width))}${theme.label(SEPARATOR)}${fitStyled(preview[row] ?? "", layout.previewWidth).text}`;
2048
+ });
2049
+ }
2050
+
2051
+ // ../kit/src/picker/terminal.ts
2052
+ var PREVIEW_DELAY_MS = 120;
2053
+ var ESCAPE_WAIT_MS = 30;
2054
+ var OPEN = { ctrl: "open" };
2055
+ var HIDE_CURSOR = "\x1B[?25l";
2056
+ var SHOW_CURSOR = "\x1B[?25h";
2057
+ var REVERSE = "\x1B[7m";
2058
+ var REVERSE_END = "\x1B[27m";
2059
+ var PASTE_ON = "\x1B[?2004h";
2060
+ var PASTE_OFF = "\x1B[?2004l";
2061
+ var MOUSE_ON = "\x1B[?1000h\x1B[?1006h";
2062
+ var MOUSE_OFF = "\x1B[?1006l\x1B[?1000l";
2063
+ var CLEAR_BELOW2 = "\r\x1B[J";
2064
+ var SIGNALS2 = ["SIGINT", "SIGTERM", "SIGHUP"];
2065
+ function up(lines) {
2066
+ return lines > 0 ? `\x1B[${lines}A` : "";
2067
+ }
2068
+ function openTerminal() {
2069
+ let mode;
2070
+ try {
2071
+ mode = new tty.ReadStream(openSync("/dev/tty", "r"));
2072
+ } catch {
2073
+ return fail("no terminal to read keys from (/dev/tty)");
2074
+ }
2075
+ const keys = Bun.file("/dev/tty").stream().getReader();
2076
+ const out = process21.stderr;
2077
+ let resize;
2078
+ async function read(onChunk) {
2079
+ const decoder = new TextDecoder;
2080
+ try {
2081
+ for (let chunk = await keys.read();!chunk.done; chunk = await keys.read())
2082
+ onChunk(decoder.decode(chunk.value, { stream: true }));
2083
+ } catch {
2084
+ onChunk("\x03");
2085
+ }
2086
+ }
2087
+ return {
2088
+ get columns() {
2089
+ return out.columns || 80;
2090
+ },
2091
+ get rows() {
2092
+ return out.rows || 24;
2093
+ },
2094
+ theme: { accent: role("accent", out), label: role("label", out), value: role("value", out), id: role("id", out), match: (text) => paint(out).underline(role("accent", out)(text)) },
2095
+ write: (text) => void out.write(text),
2096
+ listen(onChunk, onResize) {
2097
+ resize = onResize;
2098
+ mode.setRawMode(true);
2099
+ out.on("resize", onResize);
2100
+ read(onChunk);
2101
+ },
2102
+ suspend() {
2103
+ mode.setRawMode(false);
2104
+ stopJob();
2105
+ mode.setRawMode(true);
2106
+ },
2107
+ close() {
2108
+ if (resize !== undefined)
2109
+ out.off("resize", resize);
2110
+ try {
2111
+ mode.setRawMode(false);
2112
+ } finally {
2113
+ mode.destroy();
2114
+ keys.cancel();
2115
+ }
2116
+ }
2117
+ };
2118
+ }
2119
+ async function select(rows, settings, terminal = openTerminal()) {
2120
+ const { theme } = terminal;
2121
+ let state = createState(rows, settings);
2122
+ let preview = [];
2123
+ let reserved = 0;
2124
+ let previewTimer;
2125
+ let previewing = new AbortController;
2126
+ let shownLine;
2127
+ let finish;
2128
+ let restored = false;
2129
+ let escape;
2130
+ function draw(clear = false) {
2131
+ if (restored)
2132
+ return;
2133
+ const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
2134
+ let frame = SYNC_START + HIDE_CURSOR;
2135
+ if (reserved !== layout.height || clear) {
2136
+ frame += CLEAR_BELOW2 + `
2137
+ `.repeat(layout.height - 1) + up(layout.height - 1);
2138
+ reserved = layout.height;
2139
+ }
2140
+ const caret = caretCell(state, layout);
2141
+ frame += `\r${overwrite(render(state, layout, theme, preview), terminal.columns)}${up(layout.height - 1)}\r\x1B[${caret.column}G${REVERSE}${caret.char}${REVERSE_END}\r${SYNC_END}`;
2142
+ terminal.write(frame);
2143
+ }
2144
+ function pageSize() {
2145
+ const headerLines = state.header === "" ? 0 : state.header.split(`
2146
+ `).length;
2147
+ return Math.max(1, layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition).listHeight - 2 - headerLines);
2148
+ }
2149
+ function refreshPreview() {
2150
+ const at = highlighted(state);
2151
+ if (settings.preview === undefined || at === shownLine)
2152
+ return;
2153
+ shownLine = at;
2154
+ clearTimeout(previewTimer);
2155
+ previewing.abort();
2156
+ previewing = new AbortController;
2157
+ if (at === undefined) {
2158
+ preview = [];
2159
+ return;
2160
+ }
2161
+ const { signal } = previewing;
2162
+ const template = settings.preview;
2163
+ const row = state.rows[at];
2164
+ async function show() {
2165
+ const shown = typeof template === "string" ? await runPreview(template, row.cells.join(" "), signal, row.hidden) : await previewOf(template, row.hidden, signal);
2166
+ if (!signal.aborted) {
2167
+ preview = shown;
2168
+ draw();
2169
+ }
2170
+ }
2171
+ previewTimer = setTimeout(() => void show(), PREVIEW_DELAY_MS);
2172
+ }
2173
+ function restore() {
2174
+ if (restored)
2175
+ return;
2176
+ restored = true;
2177
+ clearTimeout(previewTimer);
2178
+ clearTimeout(escape);
2179
+ previewing.abort();
2180
+ terminal.write(`${CLEAR_BELOW2}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
2181
+ terminal.close();
2182
+ }
2183
+ function suspend() {
2184
+ if (terminal.suspend === undefined)
2185
+ return;
2186
+ terminal.write(`${CLEAR_BELOW2}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
2187
+ terminal.suspend();
2188
+ terminal.write(`${PASTE_ON}${MOUSE_ON}`);
2189
+ draw(true);
2190
+ }
2191
+ const stop = () => {
2192
+ state = { ...state, done: "cancel" };
2193
+ finish?.();
2194
+ };
2195
+ const paste = { active: false };
2196
+ const { reload } = settings;
2197
+ const pending = [];
2198
+ let busy = false;
2199
+ let draining = false;
2200
+ async function reloadRows() {
2201
+ if (reload === undefined)
2202
+ return;
2203
+ busy = true;
2204
+ state = { ...state, status: "reloading" };
2205
+ draw();
2206
+ try {
2207
+ const next = await reload.run();
2208
+ state = { ...withRows(state, next.rows, next.header), status: "" };
2209
+ shownLine = undefined;
2210
+ } catch (error) {
2211
+ state = { ...state, status: `reload failed: ${error instanceof Error ? error.message : String(error)}` };
2212
+ } finally {
2213
+ busy = false;
2214
+ }
2215
+ }
2216
+ async function drain() {
2217
+ if (draining)
2218
+ return;
2219
+ draining = true;
2220
+ try {
2221
+ for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
2222
+ if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
2223
+ await reloadRows();
2224
+ else if (key === "suspend")
2225
+ suspend();
2226
+ else
2227
+ state = press({ ...state, page: pageSize() }, key);
2228
+ }
2229
+ } finally {
2230
+ draining = false;
2231
+ }
2232
+ if (state.done !== undefined) {
2233
+ finish?.();
2234
+ return;
2235
+ }
2236
+ refreshPreview();
2237
+ draw();
2238
+ }
2239
+ function onChunk(chunk) {
2240
+ if (escape !== undefined) {
2241
+ clearTimeout(escape);
2242
+ escape = undefined;
2243
+ chunk = `\x1B${chunk}`;
2244
+ } else if (chunk === "\x1B") {
2245
+ escape = setTimeout(() => {
2246
+ escape = undefined;
2247
+ takeKeys("\x1B");
2248
+ }, ESCAPE_WAIT_MS);
2249
+ return;
2250
+ }
2251
+ takeKeys(chunk);
2252
+ }
2253
+ function takeKeys(chunk) {
2254
+ const keys = parseKeys(chunk, paste, [...settings.expect ?? [], ...reload?.key === undefined ? [] : [reload.key]]);
2255
+ if (busy && keys.includes("cancel")) {
2256
+ stop();
2257
+ return;
2258
+ }
2259
+ pending.push(...keys);
2260
+ drain();
2261
+ }
2262
+ const ended = new Promise((resolve) => {
2263
+ finish = resolve;
2264
+ });
2265
+ process21.once("exit", restore);
2266
+ for (const signal of SIGNALS2)
2267
+ process21.once(signal, stop);
2268
+ try {
2269
+ terminal.write(`${PASTE_ON}${MOUSE_ON}`);
2270
+ terminal.listen(onChunk, () => draw(true));
2271
+ refreshPreview();
2272
+ draw(true);
2273
+ if (reload?.onOpen === true) {
2274
+ pending.push(OPEN);
2275
+ drain();
2276
+ }
2277
+ await ended;
2278
+ } finally {
2279
+ for (const signal of SIGNALS2)
2280
+ process21.off(signal, stop);
2281
+ process21.off("exit", restore);
2282
+ restore();
2283
+ }
2284
+ return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
2285
+ }
2286
+ async function previewOf(preview, hidden, signal) {
2287
+ try {
2288
+ return previewLines(await preview(hidden, signal));
2289
+ } catch (error) {
2290
+ return [error instanceof Error ? error.message : String(error)];
2291
+ }
2292
+ }
2293
+ // ../kit/src/picker.ts
2294
+ function table2(rows) {
2295
+ const widths = rows[0]?.cells.map((_, index) => Math.max(...rows.map((row) => Bun.stringWidth(row.cells[index])))) ?? [];
2296
+ return rows.map((row) => [
2297
+ ...row.hidden,
2298
+ ...row.cells.map((cell, index) => index === row.cells.length - 1 ? cell.trimEnd() : `${cell}${" ".repeat(widths[index] + 1 - Bun.stringWidth(cell))}`)
2299
+ ].join("\t"));
2300
+ }
2301
+ async function pick(rows, options) {
2302
+ const height = parseHeight(options.height ?? "100%");
2303
+ const keys = [...options.expect ?? [], ...options.reload?.key === undefined ? [] : [options.reload.key]];
2304
+ if (height === undefined)
2305
+ throw new Error(`pick: the height is lines or a percentage, not ${options.height}`);
2306
+ for (const key of keys) {
2307
+ if (!CTRL_KEY.test(key))
2308
+ throw new Error(`pick: ${key} is not a key it can report, one of ctrl-a to ctrl-z but ctrl-c, h, i, j and m`);
2309
+ }
2310
+ const found = await select(rows, { multi: false, prompt: options.prompt, query: "", height, preview: options.preview, previewPosition: "down", header: options.header, expect: options.expect, searched: options.searched, reload: options.reload });
2311
+ return found === undefined ? undefined : { key: found.key, hidden: found.rows[0]?.hidden ?? [], query: found.query };
2312
+ }
2313
+ function word(arg) {
2314
+ if (typeof arg === "string")
2315
+ return `=${arg}`;
2316
+ return "given" in arg ? `+${arg.given}` : `?${arg.ask}`;
2317
+ }
2318
+ function emit(mode, typed, recorded, command) {
2319
+ const words = command.map(word);
2320
+ console.log([mode, typed, recorded, ...words].join(`
2321
+ `));
2322
+ }
2323
+ function list(rows) {
2324
+ console.log(JSON.stringify(rows));
2325
+ }
2326
+
2327
+ // src/branch.ts
2328
+ import { basename } from "path";
2329
+ import process22 from "process";
2330
+ var usage2 = `gb [branch]
2331
+ gb -
2332
+ gb -c <name>
2333
+ gb -d <branch>
2334
+
2335
+ Without a branch, picks one when a terminal is attached: the branches last checked out first, as the reflog has them, then the other local ones, then the remote ones with no local branch yet. The header says where HEAD stands, each row how its branch stands against its upstream and whether it is merged into the base. enter switches to it (a remote one gets its local tracking branch), ctrl-n creates a branch named after the query, ctrl-d deletes the highlighted local branch with \`git branch -d\`, which refuses one not merged yet, and ctrl-r fetches, prunes and lists again. Without a terminal it lists the branches instead.
2336
+ \`gb <branch>\` switches without the picker, a bare name finding the remote branch it would create. \`gb -\` goes back to the previous branch, \`gb -c <name>\` creates one and switches to it, \`gb -d <branch>\` deletes a local one.
2337
+ A branch checked out in another worktree cannot be switched to: gb prints that worktree's path on stdout and a hint on stderr, since a command cannot change its parent shell's folder.`;
2338
+ var EXITS = [[0, "it switched, created, deleted or listed"], ["git", "the code of the git command it ran, when that failed"], [1, "there is no branch by that name or nothing was picked"], [2, "outside a git repository or a usage error"]];
2339
+ var options = {
2340
+ create: { type: "boolean", short: "c", description: "create the branch named by the rest of the line and switch to it" },
2341
+ delete: { type: "boolean", short: "d", description: "delete the local branch with git branch -d" },
2342
+ json: jsonOption("[{ name, remote, worktree, when, subject, date, upstream, track, merged }]")
2343
+ };
2344
+ var FIELDS = ["%(refname)", "%(refname:short)", "%(committerdate:unix)", "%(subject)", "%(worktreepath)", "%(upstream:short)", "%(upstream:track,nobracket)"];
2345
+ var CHECKOUT = /^checkout: moving from (\S+) to (\S+)$/;
2346
+ var KEYS2 = "enter go, ctrl-n new from query, ctrl-d delete if merged, ctrl-r fetch";
2347
+ var TRACK_TINTS = { ahead: "green", behind: "red", gone: "yellow" };
2348
+ var TRACK_WORD = /^\w+/;
2349
+ var WHITESPACE = /\s+/;
2350
+ var colors = paint({ isTTY: true });
2351
+ function read(args) {
2352
+ const proc = Bun.spawnSync(["git", ...args], { stderr: "pipe" });
2353
+ return proc.success ? proc.stdout.toString().trim() : "";
2354
+ }
2355
+ function visited(reflog) {
2356
+ const order = new Set;
2357
+ for (const line of reflog) {
2358
+ const move = CHECKOUT.exec(line);
2359
+ if (move) {
2360
+ order.add(move[2]);
2361
+ order.add(move[1]);
2362
+ }
2363
+ }
2364
+ return [...order];
2365
+ }
2366
+ function ordered(branches, recent, current) {
2367
+ const rank = new Map(recent.map((name, index) => [name, index]));
2368
+ const locals = branches.filter((branch) => !branch.remote && branch.name !== current);
2369
+ const names = new Set(branches.filter((branch) => !branch.remote).map((branch) => branch.name));
2370
+ const remotes = branches.filter((branch) => branch.remote && !names.has(localName(branch.name)));
2371
+ const byDate = (a, b) => b.date - a.date;
2372
+ return [
2373
+ ...locals.filter((branch) => rank.has(branch.name)).sort((a, b) => rank.get(a.name) - rank.get(b.name)),
2374
+ ...locals.filter((branch) => !rank.has(branch.name)).sort(byDate),
2375
+ ...remotes.sort(byDate)
2376
+ ];
2377
+ }
2378
+ function localName(remote) {
2379
+ return remote.slice(remote.indexOf("/") + 1);
2380
+ }
2381
+ function branches(against) {
2382
+ const here = read(["rev-parse", "--show-toplevel"]);
2383
+ const lines = read(["for-each-ref", `--format=${FIELDS.join("%00")}`, "refs/heads", "refs/remotes"]).split(`
2384
+ `).filter(Boolean);
2385
+ const merged = new Set(against !== undefined ? read(["branch", "--merged", against, "--format=%(refname:short)"]).split(`
2386
+ `) : []);
2387
+ return lines.map((line) => line.split("\x00")).filter(([ref = ""]) => !ref.endsWith("/HEAD")).map(([ref = "", name = "", date = "0", subject = "", worktree = "", upstream = "", track = ""]) => {
2388
+ const remote = ref.startsWith("refs/remotes/");
2389
+ return {
2390
+ name,
2391
+ remote,
2392
+ worktree: worktree === here ? "" : worktree,
2393
+ when: formatAge(Number(date) * 1000),
2394
+ subject,
2395
+ date: Number(date),
2396
+ upstream,
2397
+ track,
2398
+ merged: !remote && merged.has(name) && name !== against && name !== localName(against ?? "")
2399
+ };
2400
+ });
2401
+ }
2402
+ function base() {
2403
+ const remote = read(["symbolic-ref", "--short", "-q", "refs/remotes/origin/HEAD"]);
2404
+ if (remote)
2405
+ return remote;
2406
+ return ["main", "master"].find((name) => read(["rev-parse", "--verify", "-q", `refs/heads/${name}`]) !== "");
2407
+ }
2408
+ function goTo(branch) {
2409
+ if (branch.worktree)
2410
+ return ["cd", branch.worktree];
2411
+ return branch.remote ? ["git", "switch", "--track", branch.name] : ["git", "switch", branch.name];
2412
+ }
2413
+ function remove(branch) {
2414
+ if (branch.remote)
2415
+ fail(`${branch.name} is a remote branch, deleting it is left to git push --delete`, 1);
2416
+ return ["git", "branch", "-d", branch.name];
2417
+ }
2418
+ function invalid(name) {
2419
+ if (!name)
2420
+ return "Type the name of the new branch first";
2421
+ return Bun.spawnSync(["git", "check-ref-format", "--branch", name], { stdout: "ignore", stderr: "ignore" }).success ? "" : `${name} is not a valid branch name`;
2422
+ }
2423
+ function track(text, tint = colors) {
2424
+ return text.split(", ").filter(Boolean).map((part) => tint[TRACK_TINTS[TRACK_WORD.exec(part)?.[0] ?? ""] ?? "dim"](part)).join(" ");
2425
+ }
2426
+ function tags(branch, tint = colors) {
2427
+ const away = branch.remote ? tint.magenta("remote") : "";
2428
+ const where = branch.worktree === "" ? away : tint.green(`wt ${basename(branch.worktree)}`);
2429
+ return [where, track(branch.track, tint), branch.merged ? tint.cyan("merged") : ""].filter(Boolean).join(" ");
2430
+ }
2431
+ function status(current, head, changed) {
2432
+ const parts = [current ? `on ${colors.bold(current.name)}` : `${colors.bold("HEAD")} detached at ${head}`];
2433
+ if (current?.upstream !== undefined && current.upstream !== "")
2434
+ parts.push(`${colors.dim(current.upstream)} ${track(current.track) || "up to date"}`);
2435
+ if (changed)
2436
+ parts.push(colors.yellow(`${changed} uncommitted`));
2437
+ return parts.join(colors.dim(" | "));
2438
+ }
2439
+ function row(branch) {
2440
+ const name = branch.remote ? `${colors.dim(branch.name.slice(0, branch.name.indexOf("/") + 1))}${colors.magenta(localName(branch.name))}` : branch.name;
2441
+ return { hidden: [branch.name], cells: [name, colors.dim(branch.when), tags(branch), colors.dim(branch.subject)] };
2442
+ }
2443
+ function preview(name) {
2444
+ const against = base();
2445
+ const lines = [];
2446
+ const compared = against !== undefined && against !== name;
2447
+ if (compared) {
2448
+ const [behind = "0", ahead = "0"] = read(["rev-list", "--left-right", "--count", `${against}...${name}`]).split(WHITESPACE);
2449
+ lines.push(`${colors.green(`${ahead} ahead`)}, ${colors.red(`${behind} behind`)} ${colors.dim(against)}
2450
+ `);
2451
+ }
2452
+ const own = compared ? [`${against}..${name}`] : [name];
2453
+ const log = ["log", "--color=always", "--format=%C(auto)%h %s %C(dim)%cr, %an", "-30"];
2454
+ lines.push(read([...log, ...own]) || read([...log, name]));
2455
+ return lines.join(`
2456
+ `);
2457
+ }
2458
+ function load() {
2459
+ const found = branches(base());
2460
+ const current = read(["branch", "--show-current"]);
2461
+ return { found, current, all: ordered(found, visited(read(["reflog", "-n", "2000", "--format=%gs"]).split(`
2462
+ `)), current) };
2463
+ }
2464
+ function isCurrent(named, current, found) {
2465
+ return current !== "" && (named === current || found.some((branch) => branch.remote && branch.name === named && localName(branch.name) === current));
2466
+ }
2467
+ function header(found, current, failure = "") {
2468
+ const changed = read(["status", "--porcelain", "--untracked-files=no"]).split(`
2469
+ `).filter(Boolean).length;
2470
+ const here = found.find((branch) => !branch.remote && branch.name === current) ?? (current ? { name: current, upstream: "", track: "" } : undefined);
2471
+ const line = status(here, here ? "" : read(["rev-parse", "--short", "HEAD"]), changed);
2472
+ return `${line}${failure ? colors.dim(" | ") + colors.red(failure) : ""}
2473
+ ${KEYS2}`;
2474
+ }
2475
+ async function fetched() {
2476
+ const proc = Bun.spawn(["git", "fetch", "--all", "--prune", "--quiet"], { stdout: "ignore", stderr: "ignore" });
2477
+ const success = await proc.exited === 0;
2478
+ return header(branches(base()), read(["branch", "--show-current"]), success ? "" : "fetch failed");
2479
+ }
2480
+ function listed2(all) {
2481
+ list([
2482
+ ...all.map((branch) => ({
2483
+ label: branch.name,
2484
+ hint: [branch.track, branch.when, branch.subject].filter(Boolean).join(" \xB7 "),
2485
+ typed: branch.name,
2486
+ preview: ["--show", branch.name],
2487
+ actions: [
2488
+ ...branch.remote ? [] : [{ label: "Delete", key: "ctrl-d", typed: `-d ${branch.name}` }],
2489
+ { label: "Fetch", key: "ctrl-r", reload: ["--fetch"] }
2490
+ ]
2491
+ })),
2492
+ { label: "New branch", hint: "git switch -c", typed: "-c", asks: "" }
2493
+ ]);
2494
+ }
2495
+ async function hidden(flag, rest) {
2496
+ if (flag === "--show") {
2497
+ console.log(preview(rest[0] ?? ""));
2498
+ return 0;
2499
+ }
2500
+ if (read(["rev-parse", "--git-dir"]) === "")
2501
+ fail("not a git repository", 2);
2502
+ if (flag === "--fetch") {
2503
+ console.log(await fetched());
2504
+ return 0;
2505
+ }
2506
+ if (flag === "--list") {
2507
+ listed2(load().all);
2508
+ return 0;
2509
+ }
2510
+ if (flag === "--names") {
2511
+ console.log(load().all.map((branch) => `${branch.name} ${branch.when}, ${branch.subject}`).join(`
2512
+ `));
2513
+ return 0;
2514
+ }
2515
+ return;
2516
+ }
2517
+ function create(name) {
2518
+ const problem = invalid(name);
2519
+ if (problem)
2520
+ fail(problem, 1);
2521
+ return ["git", "switch", "-c", name];
2522
+ }
2523
+ async function gb(args) {
2524
+ const [flag = ""] = args;
2525
+ if (["--show", "--fetch", "--list", "--names"].includes(flag))
2526
+ return await hidden(flag, args.slice(1)) ?? 0;
2527
+ const emitting = flag === "--emit";
2528
+ const parsed = parse(emitting ? args.slice(1) : args, usage2, options, { exits: EXITS, replaces: "git switch, git branch -d and git checkout typed per branch", examples: ["gb", ["gb feature", "switch to feature, or create it from origin/feature"], ["gb -", "back to the previous branch"], ["gb -c fix/login", "create a branch and switch to it"], ["gb -d old", "delete a merged local branch"]] });
2529
+ const [named] = parsed.positionals;
2530
+ if (read(["rev-parse", "--git-dir"]) === "")
2531
+ fail("not a git repository", 2);
2532
+ let typed;
2533
+ let command;
2534
+ if (parsed.values.create === true) {
2535
+ const name = parsed.positionals.join(" ");
2536
+ command = create(name);
2537
+ typed = `-c ${name}`;
2538
+ } else if (named === "-" && parsed.values.delete !== true) {
2539
+ command = ["git", "switch", "-"];
2540
+ typed = "-";
2541
+ } else {
2542
+ const { found, current, all } = load();
2543
+ const deleting = parsed.values.delete === true;
2544
+ let branch;
2545
+ let key = "";
2546
+ if (named === undefined) {
2547
+ const interactive = isInteractive() && parsed.values.json !== true;
2548
+ if (!interactive) {
2549
+ if (emitting)
2550
+ fail("the picker needs a terminal", 1);
2551
+ if (parsed.values.json === true)
2552
+ printJson(all);
2553
+ else
2554
+ console.log(table2(all.map(row)).map((line) => takesControlCodes(process22.stdout) ? line : Bun.stripANSI(line)).join(`
2555
+ `));
2556
+ return 0;
2557
+ }
2558
+ const picked = await pick(all.map(row), {
2559
+ prompt: "gb> ",
2560
+ header: header(found, current),
2561
+ expect: ["ctrl-d", "ctrl-n"],
2562
+ searched: 1,
2563
+ preview: (fields) => preview(fields[0]),
2564
+ reload: { key: "ctrl-r", run: async () => ({ header: await fetched(), rows: load().all.map(row) }) }
2565
+ });
2566
+ if (picked?.key === "ctrl-n") {
2567
+ const name = picked.query.trim();
2568
+ return finish(create(name), `-c ${name}`, emitting);
2569
+ }
2570
+ branch = picked && load().all.find((candidate) => candidate.name === picked.hidden[0]);
2571
+ if (!branch)
2572
+ return 1;
2573
+ key = picked.key;
2574
+ } else if (deleting && named === "-") {
2575
+ return fail("-d takes a branch name, not -", 1);
2576
+ } else if (!deleting && isCurrent(named, current, found)) {
2577
+ console.error(`already on ${current}`);
2578
+ return 0;
2579
+ } else {
2580
+ branch = all.find((candidate) => candidate.name === named) ?? all.find((candidate) => candidate.remote && localName(candidate.name) === named);
2581
+ if (!branch) {
2582
+ const nearest = closest(named, all.map((candidate) => candidate.name));
2583
+ return fail(`no branch named ${named}${nearest === undefined ? "" : `, did you mean ${nearest}?`}`, 1);
2584
+ }
2585
+ }
2586
+ if (deleting || key === "ctrl-d") {
2587
+ command = remove(branch);
2588
+ typed = `-d ${branch.name}`;
2589
+ } else {
2590
+ command = goTo(branch);
2591
+ typed = branch.name;
2592
+ }
2593
+ }
2594
+ return finish(command, typed, emitting);
2595
+ }
2596
+ async function finish(command, typed, emitting) {
2597
+ if (emitting) {
2598
+ emit("run", typed, "", command);
2599
+ return 0;
2600
+ }
2601
+ const words = command;
2602
+ if (words[0] === "cd") {
2603
+ console.log(words[1]);
2604
+ console.error(`checked out in another worktree: cd ${words[1]}`);
2605
+ return 0;
2606
+ }
2607
+ return Bun.spawn(words, { stdio: ["inherit", "inherit", "inherit"] }).exited;
2608
+ }
2609
+
2610
+ // src/conflicts.ts
2611
+ var OPENER = /^<{7}(?: |$)/;
2612
+ var CLOSER = /^>{7}(?: |$)/;
2613
+ var LINE_BREAK = /\r?\n/;
2614
+ function conflictHunks(text, context = 2) {
2615
+ const lines = text.split(LINE_BREAK);
2616
+ const spans = [];
2617
+ for (let i = 0;i < lines.length; i++) {
2618
+ if (!OPENER.test(lines[i] ?? ""))
2619
+ continue;
2620
+ const end = lines.findIndex((line, at) => at > i && CLOSER.test(line));
2621
+ if (end === -1)
2622
+ break;
2623
+ const from = Math.max(0, i - context);
2624
+ const to = Math.min(lines.length - 1, end + context);
2625
+ const last = spans.at(-1);
2626
+ if (last !== undefined && from <= last[1] + 1)
2627
+ last[1] = to;
2628
+ else
2629
+ spans.push([from, to]);
2630
+ i = end;
2631
+ }
2632
+ return spans.map(([from, to]) => ({ from: from + 1, to: to + 1, lines: lines.slice(from, to + 1).map((line, at) => ({ line: from + at + 1, text: line })) }));
2633
+ }
2634
+
2635
+ // src/git.ts
2636
+ async function git2(args, env) {
2637
+ const ran = await runCommand(["git", "--no-optional-locks", "-c", "core.quotePath=false", ...args], env === undefined ? {} : { env });
2638
+ const text = (stream) => Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === stream).map((chunk) => chunk.data)).toString();
2639
+ return { code: ran.code, stdout: text("stdout"), stderr: text("stderr") };
2640
+ }
2641
+
2642
+ // src/gm.ts
2643
+ var USAGE = `gm [branch]: merges the branch into the current one with git merge --no-edit, saying what came in
2644
+
2645
+ Without a branch, on a terminal, picks one: every branch but the current one with how far it is ahead of and behind it, a preview of what the merge would do (the commits coming in, the files they touch, whether it would conflict and where), enter to merge and ctrl-s to merge with --squash. Without a terminal it lists the branches with that verdict each, clean, conflicts with the files, or merged already. A merge in progress is refused here: gm --continue or gm --abort.
2646
+ --squash stages the changes of the branch without committing them or recording a merge, to commit with gc; a conflict then leaves the files to resolve and git reset --merge to give up.
2647
+
2648
+ A working tree with uncommitted changes is refused. The output names the outcome (fast-forward, merge commit or already up to date), the commits and the files that came in. On a conflict every conflicted file is listed with its conflict regions (the <<<<<<<, ======= and >>>>>>> lines and two lines around them, line numbers included) and the exit is 1.
2649
+ gm --dry-run <branch> says whether the merge would conflict and in which files, touching nothing (git merge-tree). gm --continue commits the merge once the markers are gone from the conflicted files, refusing while one remains; gm --abort gives the merge up.`;
2650
+ var EXITS2 = [[0, "it merged, the branch was already merged, or --dry-run found no conflict"], [1, "a conflict, a dirty tree, an unknown branch, a refused step or git failed"], [2, "outside a git repository or a usage error"]];
2651
+ var OPTIONS = {
2652
+ abort: { type: "boolean", description: "give up the merge in progress", conflicts: ["continue", "dry-run"] },
2653
+ continue: { type: "boolean", description: "commit the merge in progress once no conflict marker is left", conflicts: ["abort", "dry-run"] },
2654
+ squash: { type: "boolean", short: "s", description: "stage the branch's changes without committing or recording a merge", conflicts: ["abort", "continue", "dry-run"] },
2655
+ "dry-run": { type: "boolean", short: "n", description: "say whether the merge would conflict, and where, without touching the tree", conflicts: ["abort", "continue"] },
2656
+ json: jsonOption("{outcome, branch, into, sha?, commits?, files?: [{status, path, from?}], conflicts?: [{path, hunks: [{from, to, lines: [{line, text}]}]}]}, outcome being fast-forward, merge, squashed, up-to-date, conflict, clean (dry run), aborted or refused; with no branch an array of {name, remote, ahead, behind, outcome, conflicts: [path], when, subject}")
2657
+ };
2658
+ var NOT_A_REPOSITORY = /not a git repository/i;
2659
+ var RENAME = /^[RC]\d*$/;
2660
+ var EDITOR_OFF = { ...process23.env, GIT_EDITOR: "true", GIT_MERGE_AUTOEDIT: "no" };
2661
+ async function ran(args, env) {
2662
+ const { code, stdout, stderr } = await git2(args, env);
2663
+ if (code !== 0)
2664
+ fail(`git ${args[0]} failed:
2665
+ ${(stderr || stdout).trim()}`, NOT_A_REPOSITORY.test(stderr) ? 2 : 1);
2666
+ return stdout;
2667
+ }
2668
+ async function succeeds(args) {
2669
+ return (await git2(args)).code === 0;
2670
+ }
2671
+ async function currentBranch() {
2672
+ const name = (await ran(["rev-parse", "--abbrev-ref", "HEAD"])).trim();
2673
+ return name === "HEAD" ? "HEAD (detached)" : name;
2674
+ }
2675
+ async function merging() {
2676
+ return succeeds(["rev-parse", "-q", "--verify", "MERGE_HEAD"]);
2677
+ }
2678
+ async function conflicted() {
2679
+ const paths = (await ran(["diff", "--name-only", "--diff-filter=U", "--relative", "-z"])).split("\x00").filter(Boolean);
2680
+ return paths.map((path) => {
2681
+ try {
2682
+ return { path, hunks: conflictHunks(readFileSync5(path, "utf8")) };
2683
+ } catch {
2684
+ return { path, hunks: [] };
2685
+ }
2686
+ });
2687
+ }
2688
+ function conflictLines(conflicts) {
2689
+ return conflicts.flatMap(({ path, hunks }) => hunks.length === 0 ? [`${role("path", process23.stdout)(path)}: conflicted, no markers to show (deleted on a side, binary or a mode change)`] : hunks.flatMap((hunk) => [role("path", process23.stdout)(`${path}:${hunk.from}-${hunk.to}`), ...hunk.lines.map(({ line, text }) => `${line} ${text}`), ""]));
2690
+ }
2691
+ function fileLine(line) {
2692
+ const [letter = "", from = "", to] = line.split("\t");
2693
+ return RENAME.test(letter) ? ` ${letter[0]} ${from} -> ${to}` : ` ${letter} ${from}`;
2694
+ }
2695
+ function files(text) {
2696
+ return text.split(`
2697
+ `).filter(Boolean).map((line) => {
2698
+ const [letter = "", from = "", to] = line.split("\t");
2699
+ return RENAME.test(letter) ? { status: letter[0] ?? letter, path: to ?? from, from } : { status: letter, path: from };
2700
+ });
2701
+ }
2702
+ function conflictReport(branch, into, conflicts, json, squash = false) {
2703
+ if (json) {
2704
+ printJson({ outcome: "conflict", branch, into, conflicts });
2705
+ return 1;
2706
+ }
2707
+ console.log([marked("problem", `merging ${branch} into ${into} left ${conflicts.length} conflicted ${conflicts.length === 1 ? "file" : "files"}`, process23.stdout), ...conflictLines(conflicts)].join(`
2708
+ `).trimEnd());
2709
+ console.log(squash ? `
2710
+ resolve the files and commit them with gc, or git reset --merge to give up` : `
2711
+ resolve the files, then gm --continue, or gm --abort`);
2712
+ return 1;
2713
+ }
2714
+ async function mergedReport(before, branch, into, json) {
2715
+ const sha = (await ran(["rev-parse", "HEAD"])).trim();
2716
+ const parents = (await ran(["rev-list", "--parents", "-n", "1", "HEAD"])).trim().split(" ").length - 1;
2717
+ const outcome = parents > 1 ? "merge" : "fast-forward";
2718
+ const commits = Number((await ran(["rev-list", "--count", `${before}..HEAD`])).trim()) - (parents > 1 ? 1 : 0);
2719
+ const changed = await ran(["diff", "--name-status", "-M", before, "HEAD"]);
2720
+ if (json) {
2721
+ printJson({ outcome, branch, into, sha, commits, files: files(changed) });
2722
+ return 0;
2723
+ }
2724
+ const count = `${commits} ${commits === 1 ? "commit" : "commits"}`;
2725
+ const how = outcome === "merge" ? `merge commit ${sha.slice(0, 7)}` : "fast-forward";
2726
+ const list = changed.split(`
2727
+ `).filter(Boolean);
2728
+ console.log([marked("ok", `${into} <- ${branch}, ${how}, ${count}, ${list.length} ${list.length === 1 ? "file" : "files"} changed`, process23.stdout), ...list.map(fileLine)].join(`
2729
+ `));
2730
+ return 0;
2731
+ }
2732
+ async function verdictOf(branch) {
2733
+ if (await succeeds(["merge-base", "--is-ancestor", branch, "HEAD"]))
2734
+ return { outcome: "up-to-date", conflicts: [] };
2735
+ const { code, stdout, stderr } = await git2(["merge-tree", "--write-tree", "--name-only", "HEAD", branch]);
2736
+ if (code > 1)
2737
+ fail(`git merge-tree failed:
2738
+ ${(stderr || stdout).trim()}`);
2739
+ const [, ...rest] = stdout.split(`
2740
+ `);
2741
+ return { outcome: code === 0 ? "clean" : "conflict", conflicts: [...new Set(rest.slice(0, Math.max(0, rest.indexOf(""))))] };
2742
+ }
2743
+ function verdictText(verdict, tint = paint(process23.stdout)) {
2744
+ if (verdict.outcome === "up-to-date")
2745
+ return tint.dim("merged already");
2746
+ return verdict.outcome === "clean" ? tint.green("clean") : tint.red(`conflicts: ${verdict.conflicts.join(", ")}`);
2747
+ }
2748
+ async function squashedReport(before, branch, into, json) {
2749
+ const commits = Number((await ran(["rev-list", "--count", `${before}..${branch}`])).trim());
2750
+ const changed = await ran(["diff", "--cached", "--name-status", "-M"]);
2751
+ if (json) {
2752
+ printJson({ outcome: "squashed", branch, into, commits, files: files(changed) });
2753
+ return 0;
2754
+ }
2755
+ const list = changed.split(`
2756
+ `).filter(Boolean);
2757
+ console.log([marked("ok", `${branch} squashed into the index of ${into}: ${commits} ${commits === 1 ? "commit" : "commits"}, ${list.length} ${list.length === 1 ? "file" : "files"}, commit them with gc`, process23.stdout), ...list.map(fileLine)].join(`
2758
+ `));
2759
+ return 0;
2760
+ }
2761
+ async function dryRun(branch, into, json) {
2762
+ const verdict = await verdictOf(branch);
2763
+ const code = verdict.outcome === "conflict" ? 1 : 0;
2764
+ if (json) {
2765
+ printJson({ outcome: verdict.outcome, branch, into, conflicts: verdict.conflicts.map((path) => ({ path, hunks: [] })) });
2766
+ return code;
2767
+ }
2768
+ if (verdict.outcome === "up-to-date")
2769
+ console.log(`${branch} is already merged into ${into}`);
2770
+ else if (verdict.outcome === "clean")
2771
+ console.log(marked("ok", `merging ${branch} into ${into} would not conflict`, process23.stdout));
2772
+ else
2773
+ console.log([marked("problem", `merging ${branch} into ${into} would conflict in ${verdict.conflicts.length} ${verdict.conflicts.length === 1 ? "file" : "files"}`, process23.stdout), ...verdict.conflicts.map((path) => ` ${path}`)].join(`
2774
+ `));
2775
+ return code;
2776
+ }
2777
+ async function candidates() {
2778
+ return Promise.all(load().all.map(async (branch) => {
2779
+ const [behind = "0", ahead = "0"] = (await ran(["rev-list", "--left-right", "--count", `HEAD...${branch.name}`])).trim().split("\t");
2780
+ return { name: branch.name, remote: branch.remote, ahead: Number(ahead), behind: Number(behind), when: formatAge(branch.date * 1000), subject: branch.subject };
2781
+ }));
2782
+ }
2783
+ var PREVIEW_COMMITS = 30;
2784
+ async function preview2(branch) {
2785
+ const tint = paint({ isTTY: true });
2786
+ const [log, files, verdict] = await Promise.all([ran(["log", "--format=%h %s", `-${PREVIEW_COMMITS}`, `HEAD..${branch}`]), ran(["diff", "--name-status", "-M", `HEAD...${branch}`]), verdictOf(branch)]);
2787
+ return [verdictText(verdict, tint), "", tint.bold("commits coming in"), log.trim() || tint.dim("none"), "", tint.bold("files"), files.trim() || tint.dim("none")].join(`
2788
+ `);
2789
+ }
2790
+ async function listing(json) {
2791
+ const found = await candidates();
2792
+ const verdicts = await Promise.all(found.map(async (candidate) => candidate.ahead === 0 ? { outcome: "up-to-date", conflicts: [] } : verdictOf(candidate.name)));
2793
+ if (json) {
2794
+ printJson(found.map((candidate, at) => ({ ...candidate, outcome: verdicts[at]?.outcome, conflicts: verdicts[at]?.conflicts })));
2795
+ return 0;
2796
+ }
2797
+ console.log(table(found.map((candidate, at) => [candidate.name, `${candidate.ahead} ahead, ${candidate.behind} behind`, verdictText(verdicts[at])])));
2798
+ return 0;
2799
+ }
2800
+ async function choose2(into) {
2801
+ const tint = paint({ isTTY: true });
2802
+ const rows = (await candidates()).map((candidate) => ({ hidden: [candidate.name], cells: [candidate.name, tint.green(`${candidate.ahead} ahead`), tint.red(`${candidate.behind} behind`), tint.dim(candidate.when), tint.dim(candidate.subject)] }));
2803
+ const picked = await pick(rows, { prompt: "gm> ", header: `merge into ${tint.bold(into)}
2804
+ enter merge, ctrl-s merge --squash`, expect: ["ctrl-s"], searched: 1, preview: async (hidden) => preview2(hidden[0] ?? "") });
2805
+ return picked === undefined || picked.hidden[0] === undefined ? undefined : { branch: picked.hidden[0], squash: picked.key === "ctrl-s" };
2806
+ }
2807
+ async function main(argv) {
2808
+ const { values, positionals } = parse(argv, USAGE, OPTIONS, { positionals: ["[branch]"], exits: EXITS2, replaces: "git merge and then git diff --name-only --diff-filter=U and reading each file for markers", examples: ["gm feature", ["gm --dry-run feature", "whether it would conflict, and where"], ["gm --continue", "commit once the conflicts are resolved"], ["gm --abort", "give the merge up"]] });
2809
+ const json = values.json === true;
2810
+ const into = await currentBranch();
2811
+ if (values.abort === true || values.continue === true) {
2812
+ if (positionals.length > 0)
2813
+ badUsage("--abort and --continue take no branch");
2814
+ if (!await merging())
2815
+ fail("no merge in progress", 1);
2816
+ if (values.abort === true) {
2817
+ await ran(["merge", "--abort"]);
2818
+ if (json)
2819
+ printJson({ outcome: "aborted", into });
2820
+ else
2821
+ console.log(`merge into ${into} aborted`);
2822
+ return 0;
2823
+ }
2824
+ const left = (await conflicted()).filter((conflict) => conflict.hunks.length > 0);
2825
+ if (left.length > 0) {
2826
+ if (json)
2827
+ printJson({ outcome: "refused", into, conflicts: left });
2828
+ else
2829
+ console.log([marked("problem", `conflict markers remain in ${left.map((conflict) => conflict.path).join(", ")}`, process23.stdout), ...conflictLines(left)].join(`
2830
+ `).trimEnd());
2831
+ return 1;
2832
+ }
2833
+ const before = (await ran(["rev-parse", "HEAD"])).trim();
2834
+ const incoming = (await ran(["rev-parse", "MERGE_HEAD"])).trim();
2835
+ await ran(["add", "-A", "--", ...(await conflicted()).map((conflict) => conflict.path)]);
2836
+ await ran(["commit", "--no-edit"], EDITOR_OFF);
2837
+ return mergedReport(before, incoming.slice(0, 7), into, json);
2838
+ }
2839
+ const [named, ...extra] = positionals;
2840
+ if (extra.length > 0)
2841
+ badUsage(`give one branch to merge
2842
+
2843
+ ${USAGE}`);
2844
+ if (named === undefined && values["dry-run"] === true)
2845
+ badUsage("--dry-run needs the branch to try");
2846
+ let branch = named;
2847
+ let squash = values.squash === true;
2848
+ if (branch === undefined) {
2849
+ if (await merging())
2850
+ fail("a merge is in progress: gm --continue once the conflicts are resolved, or gm --abort", 1);
2851
+ if (!isInteractive() || json)
2852
+ return listing(json);
2853
+ const chosen = await choose2(into);
2854
+ if (chosen === undefined) {
2855
+ return 1;
2856
+ }
2857
+ ({ branch, squash } = chosen);
2858
+ }
2859
+ if (branch.startsWith("-"))
2860
+ badUsage(`${branch} is no branch name`);
2861
+ if (!await succeeds(["rev-parse", "--verify", "-q", `${branch}^{commit}`]))
2862
+ fail(`no branch or commit named ${branch}`, 1);
2863
+ if (values["dry-run"] === true)
2864
+ return dryRun(branch, into, json);
2865
+ if (await merging())
2866
+ fail("a merge is already in progress: gm --continue once the conflicts are resolved, or gm --abort", 1);
2867
+ if ((await ran(["status", "--porcelain", "--untracked-files=no"])).trim() !== "")
2868
+ fail("the working tree has uncommitted changes, commit or stash them first (gc, git stash)", 1);
2869
+ if (await succeeds(["merge-base", "--is-ancestor", branch, "HEAD"])) {
2870
+ if (json)
2871
+ printJson({ outcome: "up-to-date", branch, into });
2872
+ else
2873
+ console.log(`${into} already contains ${branch}`);
2874
+ return 0;
2875
+ }
2876
+ const before = (await ran(["rev-parse", "HEAD"])).trim();
2877
+ const merged = await git2(squash ? ["merge", "--squash", branch] : ["merge", "--no-edit", branch], EDITOR_OFF);
2878
+ if (merged.code === 0)
2879
+ return squash ? squashedReport(before, branch, into, json) : mergedReport(before, branch, into, json);
2880
+ if (squash ? (await conflicted()).length > 0 : await merging())
2881
+ return conflictReport(branch, into, await conflicted(), json, squash);
2882
+ return fail(`git merge failed:
2883
+ ${(merged.stderr || merged.stdout).trim()}`, NOT_A_REPOSITORY.test(merged.stderr) ? 2 : 1);
2884
+ }
2885
+ process23.exitCode = await runMain({ name: "gm", run: main });