@kaynooo/cli-pick 0.11.6 → 0.11.7
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/pick.js +41 -2171
- package/package.json +3 -6
package/dist/pick.js
CHANGED
|
@@ -1,1273 +1,16 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
var __esm = (fn, res, err) => () => {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
err = [e];
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
// ../kit/src/mode.ts
|
|
16
|
-
import process2 from "process";
|
|
17
|
-
function isSet(value) {
|
|
18
|
-
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
19
|
-
}
|
|
20
|
-
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
21
|
-
const chosen = env.KIT_MODE;
|
|
22
|
-
if (chosen !== undefined && MODES.has(chosen))
|
|
23
|
-
return chosen;
|
|
24
|
-
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
25
|
-
return "agent";
|
|
26
|
-
if (stream.isTTY === true)
|
|
27
|
-
return "terminal";
|
|
28
|
-
return isSet(env.CI) ? "ci" : "pipe";
|
|
29
|
-
}
|
|
30
|
-
var MODES, AGENT_VARIABLES;
|
|
31
|
-
var init_mode = __esm(() => {
|
|
32
|
-
MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
33
|
-
AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
34
|
-
});
|
|
35
|
-
|
|
36
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
37
|
-
function b(r) {
|
|
38
|
-
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
39
|
-
if (!G.test(e))
|
|
40
|
-
return [0, 0, 0];
|
|
41
|
-
if (e.length === 3 || e.length === 4)
|
|
42
|
-
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
43
|
-
if (e.length !== 6 && e.length !== 8)
|
|
44
|
-
throw Error(`Invalid hex color length: ${e.length}`);
|
|
45
|
-
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
46
|
-
}
|
|
47
|
-
function C(r, e = globalThis.process?.env ?? {}) {
|
|
48
|
-
if (e.FORCE_COLOR !== undefined)
|
|
49
|
-
return h.has(e.FORCE_COLOR);
|
|
50
|
-
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
51
|
-
return false;
|
|
52
|
-
return r?.isTTY === true;
|
|
53
|
-
}
|
|
54
|
-
function f(r, e = []) {
|
|
55
|
-
let l = "", n = "";
|
|
56
|
-
for (let t = 0, i = e.length;t < i; t++)
|
|
57
|
-
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
58
|
-
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
59
|
-
return new Proxy(c, { get(t, i) {
|
|
60
|
-
let a = B[i];
|
|
61
|
-
if (Array.isArray(a)) {
|
|
62
|
-
let s = g.get(i);
|
|
63
|
-
if (s === undefined)
|
|
64
|
-
s = f(r, [...e, a]), g.set(i, s);
|
|
65
|
-
return s;
|
|
66
|
-
}
|
|
67
|
-
if (typeof a === "function")
|
|
68
|
-
return (...s) => {
|
|
69
|
-
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
70
|
-
if (u === undefined) {
|
|
71
|
-
if (g.size >= 64)
|
|
72
|
-
g.clear();
|
|
73
|
-
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
74
|
-
}
|
|
75
|
-
return u;
|
|
76
|
-
};
|
|
77
|
-
throw Error(`Unknown style: ${String(i)}`);
|
|
78
|
-
} });
|
|
79
|
-
}
|
|
80
|
-
function Fe(r = {}) {
|
|
81
|
-
return f(r);
|
|
82
|
-
}
|
|
83
|
-
var G, B, h, o;
|
|
84
|
-
var init_chunk_x450vn3m = __esm(() => {
|
|
85
|
-
G = /^[a-f0-9]+$/i;
|
|
86
|
-
B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
|
|
87
|
-
let [l, n, c] = b(r);
|
|
88
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
89
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
90
|
-
h = new Set(["", "1", "2", "3", "true"]);
|
|
91
|
-
o = Fe();
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
|
|
95
|
-
var init_colors = __esm(() => {
|
|
96
|
-
init_chunk_x450vn3m();
|
|
97
|
-
});
|
|
98
|
-
|
|
99
|
-
// ../kit/src/config.ts
|
|
100
|
-
import { existsSync } from "fs";
|
|
101
|
-
import { dirname, join, resolve } from "path";
|
|
102
|
-
import process3 from "process";
|
|
103
|
-
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
104
|
-
const wanted = typeof names === "string" ? [names] : names;
|
|
105
|
-
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
106
|
-
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
107
|
-
if (found !== undefined)
|
|
108
|
-
return found;
|
|
109
|
-
if (stop(dir) || dirname(dir) === dir)
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
var init_config = __esm(() => {
|
|
114
|
-
init_args();
|
|
115
|
-
});
|
|
116
|
-
|
|
117
|
-
// ../kit/src/user-config.ts
|
|
118
|
-
import { homedir } from "os";
|
|
119
|
-
import { isAbsolute, join as join2 } from "path";
|
|
120
|
-
import process4 from "process";
|
|
121
|
-
function xdgFolder(value, fallback) {
|
|
122
|
-
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
123
|
-
}
|
|
124
|
-
function configBase(where = {}) {
|
|
125
|
-
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
126
|
-
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
127
|
-
}
|
|
128
|
-
function userConfigPath(bin, where = {}) {
|
|
129
|
-
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
130
|
-
}
|
|
131
|
-
var init_user_config = () => {};
|
|
132
|
-
|
|
133
|
-
// ../kit/src/theme.ts
|
|
134
|
-
import { existsSync as existsSync2, readFileSync, statSync } from "fs";
|
|
135
|
-
import { homedir as homedir2 } from "os";
|
|
136
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
137
|
-
import process5 from "process";
|
|
138
|
-
function isColorSpec(spec) {
|
|
139
|
-
if (typeof spec === "number")
|
|
140
|
-
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
141
|
-
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
142
|
-
}
|
|
143
|
-
function cubeLevel(channel) {
|
|
144
|
-
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
145
|
-
}
|
|
146
|
-
function nearest256(hex) {
|
|
147
|
-
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
148
|
-
const levels = rgb.map(cubeLevel);
|
|
149
|
-
const cube = levels.map((level) => CUBE[level]);
|
|
150
|
-
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
151
|
-
const greyValue = 8 + grey * 10;
|
|
152
|
-
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
153
|
-
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
154
|
-
}
|
|
155
|
-
function hasTrueColor(env) {
|
|
156
|
-
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
157
|
-
}
|
|
158
|
-
function tinted(colors, spec, env = process5.env) {
|
|
159
|
-
if (typeof spec === "number")
|
|
160
|
-
return colors.ansi256(spec);
|
|
161
|
-
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
162
|
-
if (HEX.test(token))
|
|
163
|
-
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
164
|
-
return chain[token] ?? chain;
|
|
165
|
-
}, colors);
|
|
166
|
-
}
|
|
167
|
-
function isRecord(value) {
|
|
168
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
169
|
-
}
|
|
170
|
-
function readThemeFile(path, warn) {
|
|
171
|
-
try {
|
|
172
|
-
const stat = statSync(path, { throwIfNoEntry: false });
|
|
173
|
-
if (stat === undefined)
|
|
174
|
-
return;
|
|
175
|
-
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
176
|
-
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
|
-
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
180
|
-
if (isRecord(parsed))
|
|
181
|
-
return parsed;
|
|
182
|
-
warn(`${path} is not a JSON object, theme ignored`);
|
|
183
|
-
} catch (error) {
|
|
184
|
-
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
185
|
-
}
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
function applyPreset(theme, name, warn, where) {
|
|
189
|
-
if (name === undefined)
|
|
190
|
-
return;
|
|
191
|
-
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
192
|
-
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
193
|
-
return;
|
|
194
|
-
}
|
|
195
|
-
const preset = PRESETS[name];
|
|
196
|
-
Object.assign(theme.colors, preset.colors);
|
|
197
|
-
Object.assign(theme.glyphs, preset.glyphs);
|
|
198
|
-
if (preset.accents !== undefined)
|
|
199
|
-
theme.accents = [...preset.accents];
|
|
200
|
-
if (Object.hasOwn(preset, "gradient"))
|
|
201
|
-
theme.gradient = preset.gradient;
|
|
202
|
-
return name;
|
|
203
|
-
}
|
|
204
|
-
function applyFile(theme, file, where, warn) {
|
|
205
|
-
if (isRecord(file.colors)) {
|
|
206
|
-
for (const [key, value] of Object.entries(file.colors)) {
|
|
207
|
-
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
208
|
-
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
209
|
-
else if (!isColorSpec(value))
|
|
210
|
-
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
211
|
-
else
|
|
212
|
-
theme.colors[key] = value;
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
if (isRecord(file.glyphs)) {
|
|
216
|
-
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
217
|
-
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
218
|
-
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
219
|
-
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
220
|
-
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
221
|
-
else
|
|
222
|
-
theme.glyphs[key] = value;
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
226
|
-
theme.accents = [...file.accents];
|
|
227
|
-
else if (file.accents !== undefined)
|
|
228
|
-
warn(`${where}: accents must be a non-empty list of colours`);
|
|
229
|
-
if (file.gradient === null)
|
|
230
|
-
theme.gradient = undefined;
|
|
231
|
-
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
232
|
-
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
233
|
-
else if (file.gradient !== undefined)
|
|
234
|
-
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
235
|
-
if (isRecord(file.bins)) {
|
|
236
|
-
for (const [bin, value] of Object.entries(file.bins)) {
|
|
237
|
-
if (isColorSpec(value))
|
|
238
|
-
theme.bins[bin] = value;
|
|
239
|
-
else
|
|
240
|
-
warn(`${where}: bin ${bin} has no valid colour`);
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
function endsWalk(home) {
|
|
245
|
-
return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
|
|
246
|
-
}
|
|
247
|
-
function warnOnce(message) {
|
|
248
|
-
if (warned.has(message))
|
|
249
|
-
return;
|
|
250
|
-
warned.add(message);
|
|
251
|
-
console.error(`warning: theme ${message}`);
|
|
252
|
-
}
|
|
253
|
-
function isPath(chosen) {
|
|
254
|
-
return chosen.includes("/") || chosen.endsWith(".json");
|
|
255
|
-
}
|
|
256
|
-
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
257
|
-
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
258
|
-
const sources = [];
|
|
259
|
-
const chosen = env.KIT_THEME ?? "";
|
|
260
|
-
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
261
|
-
if (isPath(chosen))
|
|
262
|
-
wanted.push(resolve2(from, chosen));
|
|
263
|
-
const files = [];
|
|
264
|
-
for (const path of wanted) {
|
|
265
|
-
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
266
|
-
if (path !== undefined && file !== undefined)
|
|
267
|
-
files.push({ path, file });
|
|
268
|
-
}
|
|
269
|
-
let preset = "default";
|
|
270
|
-
if (chosen !== "" && !isPath(chosen)) {
|
|
271
|
-
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
272
|
-
} else {
|
|
273
|
-
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
274
|
-
if (named !== undefined)
|
|
275
|
-
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
276
|
-
}
|
|
277
|
-
for (const { path, file } of files) {
|
|
278
|
-
applyFile(theme, file, path, warn);
|
|
279
|
-
sources.push(path);
|
|
280
|
-
}
|
|
281
|
-
return { theme, sources, preset };
|
|
282
|
-
}
|
|
283
|
-
function activeTheme() {
|
|
284
|
-
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
285
|
-
if (current === undefined || key !== currentKey) {
|
|
286
|
-
current = loadTheme();
|
|
287
|
-
currentKey = key;
|
|
288
|
-
}
|
|
289
|
-
return current;
|
|
290
|
-
}
|
|
291
|
-
var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
|
|
292
|
-
var init_theme = __esm(() => {
|
|
293
|
-
init_config();
|
|
294
|
-
init_user_config();
|
|
295
|
-
ENDS = new Map;
|
|
296
|
-
DEFAULT = {
|
|
297
|
-
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" },
|
|
298
|
-
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" },
|
|
299
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
300
|
-
bins: {},
|
|
301
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
302
|
-
};
|
|
303
|
-
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" };
|
|
304
|
-
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" };
|
|
305
|
-
ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
306
|
-
PRESETS = {
|
|
307
|
-
default: {},
|
|
308
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
309
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
310
|
-
ascii: { glyphs: ASCII }
|
|
311
|
-
};
|
|
312
|
-
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"]);
|
|
313
|
-
HEX = /^#[0-9a-f]{6}$/i;
|
|
314
|
-
CONTROL = /\p{Cc}/u;
|
|
315
|
-
MAX_FILE_BYTES = 64 * 1024;
|
|
316
|
-
SPACES = /\s+/;
|
|
317
|
-
CUBE = [0, 95, 135, 175, 215, 255];
|
|
318
|
-
warned = new Set;
|
|
319
|
-
});
|
|
320
|
-
|
|
321
|
-
// ../kit/src/style.ts
|
|
322
|
-
import process6 from "process";
|
|
323
|
-
function takesControlCodes(stream, env = process6.env) {
|
|
324
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
325
|
-
}
|
|
326
|
-
function paint(stream, env = process6.env) {
|
|
327
|
-
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
328
|
-
}
|
|
329
|
-
function role(name, stream, env = process6.env) {
|
|
330
|
-
const colors = paint(stream, env);
|
|
331
|
-
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
332
|
-
}
|
|
333
|
-
var STATUS_WORDS, STATUS_OF;
|
|
334
|
-
var init_style = __esm(() => {
|
|
335
|
-
init_colors();
|
|
336
|
-
init_mode();
|
|
337
|
-
init_theme();
|
|
338
|
-
STATUS_WORDS = {
|
|
339
|
-
passed: ["passed", "success", "succeeded", "ok"],
|
|
340
|
-
failed: ["failed", "failure", "error", "errored"],
|
|
341
|
-
running: ["running", "in_progress", "started", "holding"],
|
|
342
|
-
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
343
|
-
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
344
|
-
};
|
|
345
|
-
STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
346
|
-
});
|
|
347
|
-
|
|
348
|
-
// ../kit/src/format.ts
|
|
349
|
-
import process7 from "process";
|
|
350
|
-
function formatSeconds(total) {
|
|
351
|
-
let rest = Math.max(0, Math.round(total));
|
|
352
|
-
const amounts = UNITS.map(([unit, size]) => {
|
|
353
|
-
const amount = Math.floor(rest / size);
|
|
354
|
-
rest -= amount * size;
|
|
355
|
-
return `${amount}${unit}`;
|
|
356
|
-
});
|
|
357
|
-
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
358
|
-
if (first === -1)
|
|
359
|
-
return "0s";
|
|
360
|
-
const next = amounts[first + 1];
|
|
361
|
-
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
362
|
-
}
|
|
363
|
-
function formatDuration(ms) {
|
|
364
|
-
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
365
|
-
}
|
|
366
|
-
function upTo(text, separator) {
|
|
367
|
-
const end = text.indexOf(separator);
|
|
368
|
-
return end === -1 ? text : text.slice(0, end);
|
|
369
|
-
}
|
|
370
|
-
function textWidth(text) {
|
|
371
|
-
return Bun.stringWidth(text);
|
|
372
|
-
}
|
|
373
|
-
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
374
|
-
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
375
|
-
}
|
|
376
|
-
function printJson(value) {
|
|
377
|
-
console.log(jsonText(value));
|
|
378
|
-
}
|
|
379
|
-
var UNITS, ESCAPE;
|
|
380
|
-
var init_format = __esm(() => {
|
|
381
|
-
init_mode();
|
|
382
|
-
init_style();
|
|
383
|
-
UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
384
|
-
ESCAPE = String.fromCharCode(27);
|
|
385
|
-
});
|
|
386
|
-
|
|
387
|
-
// ../kit/src/help.ts
|
|
388
|
-
import process8 from "process";
|
|
389
|
-
function usageLine(usage, colors = paint(process8.stdout), { summary: withSummary = true } = {}) {
|
|
390
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
391
|
-
`);
|
|
392
|
-
const blank = lines.indexOf("");
|
|
393
|
-
const synopses = blank === -1 ? lines : lines.slice(0, blank);
|
|
394
|
-
const details = blank === -1 ? [] : lines.slice(blank + 1);
|
|
395
|
-
const colon = synopses[0].indexOf(": ");
|
|
396
|
-
const inline = synopses[0].slice(colon + 2);
|
|
397
|
-
const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
|
|
398
|
-
if (colon !== -1)
|
|
399
|
-
synopses[0] = synopses[0].slice(0, colon);
|
|
400
|
-
const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
|
|
401
|
-
`)}`;
|
|
402
|
-
const lead = summary === undefined || !withSummary ? [] : ["", colors.bold(prose(summary, colors))];
|
|
403
|
-
const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
|
|
404
|
-
return [head, ...lead, ...rest].join(`
|
|
405
|
-
`);
|
|
406
|
-
}
|
|
407
|
-
function prose(line, colors) {
|
|
408
|
-
if (colors.cyan("x") === "x")
|
|
409
|
-
return line;
|
|
410
|
-
return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
|
|
411
|
-
}
|
|
412
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [], bin } = {}) {
|
|
413
|
-
const { summary } = description(usage);
|
|
414
|
-
const head = bin === undefined ? [usageLine(usage, colors)] : [`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary === "" ? "" : ` ${summary}`}`, "", usageLine(usage, colors, { summary: false })];
|
|
415
|
-
return [...head, "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
416
|
-
`);
|
|
417
|
-
}
|
|
418
|
-
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
419
|
-
if (exits.length === 0)
|
|
420
|
-
return [];
|
|
421
|
-
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
422
|
-
}
|
|
423
|
-
function wantsHelpJson(env = process8.env) {
|
|
424
|
-
return env.KIT_HELP === "json";
|
|
425
|
-
}
|
|
426
|
-
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
427
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
428
|
-
`);
|
|
429
|
-
const first = lines[0];
|
|
430
|
-
const colon = first.indexOf(": ");
|
|
431
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
432
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
433
|
-
return {
|
|
434
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
435
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
436
|
-
...replaces === undefined ? {} : { replaces },
|
|
437
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
438
|
-
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
439
|
-
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
440
|
-
};
|
|
441
|
-
}
|
|
442
|
-
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
443
|
-
if (examples.length === 0 || outputMode() === "agent")
|
|
444
|
-
return [];
|
|
445
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
446
|
-
}
|
|
447
|
-
function optionRows(options, colors = paint(process8.stdout)) {
|
|
448
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
449
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
450
|
-
const choices = option.choices?.join("|");
|
|
451
|
-
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
452
|
-
const named = inline ? `<${choices}>` : "<value>";
|
|
453
|
-
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
454
|
-
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
455
|
-
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
456
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
457
|
-
});
|
|
458
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
459
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
460
|
-
}
|
|
461
|
-
var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
|
|
462
|
-
var init_help = __esm(() => {
|
|
463
|
-
init_mode();
|
|
464
|
-
init_style();
|
|
465
|
-
OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
466
|
-
USAGE_PREFIX = /^usage:\s*/i;
|
|
467
|
-
FULL_STOP = /\.$/;
|
|
468
|
-
PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
|
|
469
|
-
});
|
|
470
|
-
|
|
471
|
-
// ../kit/src/text.ts
|
|
472
|
-
function distance(a, b) {
|
|
473
|
-
const left = [...a];
|
|
474
|
-
const right = [...b];
|
|
475
|
-
let before = [];
|
|
476
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
477
|
-
for (const [i, x] of left.entries()) {
|
|
478
|
-
const current = [i + 1];
|
|
479
|
-
for (const [j, y] of right.entries()) {
|
|
480
|
-
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
481
|
-
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
482
|
-
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
483
|
-
current.push(cost);
|
|
484
|
-
}
|
|
485
|
-
before = previous;
|
|
486
|
-
previous = current;
|
|
487
|
-
}
|
|
488
|
-
return previous[right.length] ?? 0;
|
|
489
|
-
}
|
|
490
|
-
function closest(name, names) {
|
|
491
|
-
const started = names.find((known) => known.startsWith(name));
|
|
492
|
-
if (started !== undefined)
|
|
493
|
-
return started;
|
|
494
|
-
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
495
|
-
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
496
|
-
}
|
|
497
|
-
var ANSI;
|
|
498
|
-
var init_text = __esm(() => {
|
|
499
|
-
ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
|
|
500
|
-
});
|
|
501
|
-
|
|
502
|
-
// ../kit/src/input.ts
|
|
503
|
-
var init_input = __esm(() => {
|
|
504
|
-
init_args();
|
|
505
|
-
});
|
|
506
|
-
|
|
507
|
-
// ../kit/src/args.ts
|
|
508
|
-
import process9 from "process";
|
|
509
|
-
import { parseArgs } from "util";
|
|
510
|
-
function jsonOption(holds) {
|
|
511
|
-
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
512
|
-
}
|
|
513
|
-
function fail(message, code = 2, hint) {
|
|
514
|
-
throw new Exit(message, code, hint);
|
|
515
|
-
}
|
|
516
|
-
function badUsage(message) {
|
|
517
|
-
throw new UsageError(message);
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
class Completing {
|
|
521
|
-
options;
|
|
522
|
-
positionals;
|
|
523
|
-
candidates;
|
|
524
|
-
constructor(options, positionals = [], candidates = {}) {
|
|
525
|
-
this.options = options;
|
|
526
|
-
this.positionals = positionals;
|
|
527
|
-
this.candidates = candidates;
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
function applyOutput(color, plain, env = process9.env) {
|
|
531
|
-
const when = plain === true ? "never" : color ?? "auto";
|
|
532
|
-
if (when === "auto")
|
|
533
|
-
return;
|
|
534
|
-
if (when !== "always" && when !== "never")
|
|
535
|
-
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
536
|
-
if (when === "always") {
|
|
537
|
-
env.FORCE_COLOR = "1";
|
|
538
|
-
delete env.NO_COLOR;
|
|
539
|
-
} else {
|
|
540
|
-
env.NO_COLOR = "1";
|
|
541
|
-
delete env.FORCE_COLOR;
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
function parse(args, usage, options, settings = {}) {
|
|
545
|
-
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
546
|
-
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
547
|
-
const listing = listed(all, settings.allowNegative === true);
|
|
548
|
-
if (completion.active)
|
|
549
|
-
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
550
|
-
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
551
|
-
let parsed;
|
|
552
|
-
try {
|
|
553
|
-
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
554
|
-
} catch (error) {
|
|
555
|
-
const message = parseError(error);
|
|
556
|
-
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
557
|
-
}
|
|
558
|
-
const values = parsed.values;
|
|
559
|
-
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
560
|
-
if (values.help === true) {
|
|
561
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, { ...settings, bin: heading.bin }));
|
|
562
|
-
throw new HelpShown;
|
|
563
|
-
}
|
|
564
|
-
checkChoices(parsed.values, all);
|
|
565
|
-
checkConflicts(parsed.values, all);
|
|
566
|
-
if (settings.positionals !== undefined)
|
|
567
|
-
checkPositionals(parsed.positionals, settings.positionals);
|
|
568
|
-
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
569
|
-
}
|
|
570
|
-
function splitRest(args, passes) {
|
|
571
|
-
const separator = passes ? args.indexOf("--") : -1;
|
|
572
|
-
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
573
|
-
}
|
|
574
|
-
function splitTrailing(args, options, count) {
|
|
575
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
576
|
-
let seen = 0;
|
|
577
|
-
if (count === 0)
|
|
578
|
-
return { own: args, rest: undefined };
|
|
579
|
-
for (let at = 0;at < args.length; at++) {
|
|
580
|
-
const word = args[at];
|
|
581
|
-
if (word === "--")
|
|
582
|
-
break;
|
|
583
|
-
if (word.startsWith("-")) {
|
|
584
|
-
if (takesValue(word))
|
|
585
|
-
at++;
|
|
586
|
-
continue;
|
|
587
|
-
}
|
|
588
|
-
seen++;
|
|
589
|
-
if (seen === count)
|
|
590
|
-
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
591
|
-
}
|
|
592
|
-
return { own: args, rest: undefined };
|
|
593
|
-
}
|
|
594
|
-
function listed(options, allowNegative) {
|
|
595
|
-
if (!allowNegative)
|
|
596
|
-
return options;
|
|
597
|
-
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
598
|
-
if (option.type !== "boolean" || option.negative === undefined)
|
|
599
|
-
return [[name, option]];
|
|
600
|
-
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
601
|
-
}));
|
|
602
|
-
}
|
|
603
|
-
function withAliases(args, options) {
|
|
604
|
-
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
605
|
-
if (named.size === 0)
|
|
606
|
-
return args;
|
|
607
|
-
const separator = args.indexOf("--");
|
|
608
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
609
|
-
return [...own.map((arg) => {
|
|
610
|
-
const at = arg.indexOf("=");
|
|
611
|
-
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
612
|
-
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
613
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
614
|
-
}
|
|
615
|
-
function withBare(args, options) {
|
|
616
|
-
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
617
|
-
if (bare.size === 0)
|
|
618
|
-
return args;
|
|
619
|
-
const separator = args.indexOf("--");
|
|
620
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
621
|
-
return [...own.flatMap((arg, index) => {
|
|
622
|
-
const optional = bare.get(arg);
|
|
623
|
-
const next = own[index + 1];
|
|
624
|
-
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
625
|
-
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
626
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
627
|
-
}
|
|
628
|
-
function checkConflicts(values, options) {
|
|
629
|
-
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
630
|
-
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
631
|
-
const other = given(name) ? conflicts.find(given) : undefined;
|
|
632
|
-
if (other !== undefined)
|
|
633
|
-
badUsage(`--${name} cannot be used with --${other}`);
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
function checkChoices(values, options) {
|
|
637
|
-
for (const [name, option] of Object.entries(options)) {
|
|
638
|
-
if (option.choices === undefined)
|
|
639
|
-
continue;
|
|
640
|
-
const given = values[name];
|
|
641
|
-
for (const value of Array.isArray(given) ? given : [given]) {
|
|
642
|
-
if (typeof value === "string")
|
|
643
|
-
oneOf(value, name, option.choices);
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
function oneOf(value, name, choices) {
|
|
648
|
-
if (!choices.includes(value))
|
|
649
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
650
|
-
return value;
|
|
651
|
-
}
|
|
652
|
-
function checkPositionals(given, names) {
|
|
653
|
-
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
654
|
-
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
655
|
-
if (given.length < required)
|
|
656
|
-
badUsage(`missing ${names[given.length]}`);
|
|
657
|
-
if (!variadic && given.length > names.length)
|
|
658
|
-
badUsage(`unexpected argument ${given[names.length]}`);
|
|
659
|
-
}
|
|
660
|
-
function joinDashValues(args, options) {
|
|
661
|
-
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
662
|
-
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
663
|
-
const joined = [];
|
|
664
|
-
for (let i = 0;i < args.length; i++) {
|
|
665
|
-
const arg = args[i] ?? "";
|
|
666
|
-
if (arg === "--")
|
|
667
|
-
return [...joined, ...args.slice(i)];
|
|
668
|
-
const name = longOf.get(arg);
|
|
669
|
-
const next = args[i + 1];
|
|
670
|
-
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
671
|
-
joined.push(`--${name}=${next}`);
|
|
672
|
-
i++;
|
|
673
|
-
} else {
|
|
674
|
-
joined.push(arg);
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
return joined;
|
|
678
|
-
}
|
|
679
|
-
function parseError(error) {
|
|
680
|
-
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
681
|
-
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
682
|
-
}
|
|
683
|
-
function nearestOption(message, options, allowNegative) {
|
|
684
|
-
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
685
|
-
if (typed === undefined)
|
|
686
|
-
return;
|
|
687
|
-
const word = typed.replace(DASHES, "");
|
|
688
|
-
if (word.length < 2 && !typed.startsWith("--"))
|
|
689
|
-
return;
|
|
690
|
-
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
691
|
-
...option.short === undefined ? [] : [`-${option.short}`],
|
|
692
|
-
`--${name}`,
|
|
693
|
-
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
694
|
-
]);
|
|
695
|
-
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
696
|
-
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
697
|
-
}
|
|
698
|
-
var DASHES, EXIT, Exit, UsageError, HelpShown, completion, heading, OUTPUT_OPTIONS, UNKNOWN_OPTION;
|
|
699
|
-
var init_args = __esm(() => {
|
|
700
|
-
init_format();
|
|
701
|
-
init_help();
|
|
702
|
-
init_text();
|
|
703
|
-
init_help();
|
|
704
|
-
init_input();
|
|
705
|
-
DASHES = /^-+/;
|
|
706
|
-
EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
|
|
707
|
-
Exit = class Exit extends Error {
|
|
708
|
-
code;
|
|
709
|
-
hint;
|
|
710
|
-
[EXIT] = true;
|
|
711
|
-
constructor(message, code, hint) {
|
|
712
|
-
super(message);
|
|
713
|
-
this.code = code;
|
|
714
|
-
this.hint = hint;
|
|
715
|
-
}
|
|
716
|
-
static [Symbol.hasInstance](value) {
|
|
717
|
-
if (this !== Exit)
|
|
718
|
-
return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
719
|
-
return typeof value === "object" && value !== null && value[EXIT] === true;
|
|
720
|
-
}
|
|
721
|
-
};
|
|
722
|
-
UsageError = class UsageError extends Exit {
|
|
723
|
-
constructor(message, hint) {
|
|
724
|
-
super(message, 2, hint);
|
|
725
|
-
}
|
|
726
|
-
};
|
|
727
|
-
HelpShown = class HelpShown extends Exit {
|
|
728
|
-
constructor() {
|
|
729
|
-
super("help shown", 0);
|
|
730
|
-
}
|
|
731
|
-
};
|
|
732
|
-
completion = { active: false };
|
|
733
|
-
heading = { bin: undefined };
|
|
734
|
-
OUTPUT_OPTIONS = {
|
|
735
|
-
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
736
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
737
|
-
};
|
|
738
|
-
UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
739
|
-
});
|
|
740
|
-
|
|
741
|
-
// ../kit/src/folders.ts
|
|
742
|
-
var SKIPPED_FOLDERS;
|
|
743
|
-
var init_folders = __esm(() => {
|
|
744
|
-
init_user_config();
|
|
745
|
-
SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
746
|
-
});
|
|
747
|
-
|
|
748
|
-
// ../kit/src/picker/line.ts
|
|
749
|
-
function isEditKey(key) {
|
|
750
|
-
return EDIT_KEYS.has(key);
|
|
751
|
-
}
|
|
752
|
-
function endsKills(key) {
|
|
753
|
-
return typeof key !== "object" && !isEditKey(key);
|
|
754
|
-
}
|
|
755
|
-
function isWord(char) {
|
|
756
|
-
return char !== undefined && WORD_CHARACTER.test(char);
|
|
757
|
-
}
|
|
758
|
-
function wordStart(chars, from) {
|
|
759
|
-
let at = from;
|
|
760
|
-
while (at > 0 && !isWord(chars[at - 1]))
|
|
761
|
-
at--;
|
|
762
|
-
while (at > 0 && isWord(chars[at - 1]))
|
|
763
|
-
at--;
|
|
764
|
-
return at;
|
|
765
|
-
}
|
|
766
|
-
function wordEnd(chars, from) {
|
|
767
|
-
let at = from;
|
|
768
|
-
while (at < chars.length && !isWord(chars[at]))
|
|
769
|
-
at++;
|
|
770
|
-
while (at < chars.length && isWord(chars[at]))
|
|
771
|
-
at++;
|
|
772
|
-
return at;
|
|
773
|
-
}
|
|
774
|
-
function spacedStart(chars, from) {
|
|
775
|
-
let at = from;
|
|
776
|
-
while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
|
|
777
|
-
at--;
|
|
778
|
-
while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
|
|
779
|
-
at--;
|
|
780
|
-
return at;
|
|
781
|
-
}
|
|
782
|
-
function cut(chars, from, to) {
|
|
783
|
-
return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
|
|
784
|
-
}
|
|
785
|
-
function insert(chars, at, text) {
|
|
786
|
-
const typed = [...text];
|
|
787
|
-
return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
|
|
788
|
-
}
|
|
789
|
-
function editLine(line, key) {
|
|
790
|
-
const { killed = "", chained = false } = line;
|
|
791
|
-
const chars = [...line.text];
|
|
792
|
-
const at = Math.min(Math.max(line.caret, 0), chars.length);
|
|
793
|
-
const edited = edit(chars, at, key, killed);
|
|
794
|
-
if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
|
|
795
|
-
return line.killed === undefined ? edited : { ...edited, killed };
|
|
796
|
-
const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
|
|
797
|
-
if (taken === "")
|
|
798
|
-
return { ...edited, killed, chained };
|
|
799
|
-
if (!chained)
|
|
800
|
-
return { ...edited, killed: taken, chained: true };
|
|
801
|
-
return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
|
|
802
|
-
}
|
|
803
|
-
function edit(chars, at, key, killed) {
|
|
804
|
-
const text = chars.join("");
|
|
805
|
-
if (typeof key === "object")
|
|
806
|
-
return insert(chars, at, key.text);
|
|
807
|
-
switch (key) {
|
|
808
|
-
case "left":
|
|
809
|
-
return { text, caret: Math.max(at - 1, 0) };
|
|
810
|
-
case "right":
|
|
811
|
-
return { text, caret: Math.min(at + 1, chars.length) };
|
|
812
|
-
case "wordleft":
|
|
813
|
-
return { text, caret: wordStart(chars, at) };
|
|
814
|
-
case "wordright":
|
|
815
|
-
return { text, caret: wordEnd(chars, at) };
|
|
816
|
-
case "linestart":
|
|
817
|
-
return { text, caret: 0 };
|
|
818
|
-
case "lineend":
|
|
819
|
-
return { text, caret: chars.length };
|
|
820
|
-
case "erase":
|
|
821
|
-
return cut(chars, Math.max(at - 1, 0), at);
|
|
822
|
-
case "delete":
|
|
823
|
-
return cut(chars, at, Math.min(at + 1, chars.length));
|
|
824
|
-
case "word":
|
|
825
|
-
return cut(chars, spacedStart(chars, at), at);
|
|
826
|
-
case "killword":
|
|
827
|
-
return cut(chars, wordStart(chars, at), at);
|
|
828
|
-
case "killnext":
|
|
829
|
-
return cut(chars, at, wordEnd(chars, at));
|
|
830
|
-
case "clear":
|
|
831
|
-
return cut(chars, 0, at);
|
|
832
|
-
case "killend":
|
|
833
|
-
return cut(chars, at, chars.length);
|
|
834
|
-
case "yank":
|
|
835
|
-
return insert(chars, at, killed);
|
|
836
|
-
}
|
|
837
|
-
}
|
|
838
|
-
function visible({ text, caret }, room) {
|
|
839
|
-
const chars = [...text];
|
|
840
|
-
const at = Math.min(Math.max(caret, 0), chars.length);
|
|
841
|
-
const cells = at === chars.length ? [...chars, " "] : chars;
|
|
842
|
-
const widths = cells.map((char) => Bun.stringWidth(char));
|
|
843
|
-
const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
|
|
844
|
-
const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
|
|
845
|
-
let start = at;
|
|
846
|
-
let end = at + 1;
|
|
847
|
-
while (start > 0 && fits(start - 1, end))
|
|
848
|
-
start--;
|
|
849
|
-
while (end < cells.length && fits(start, end + 1))
|
|
850
|
-
end++;
|
|
851
|
-
const left = start > 0 ? "\u2026" : "";
|
|
852
|
-
const right = end < cells.length ? "\u2026" : "";
|
|
853
|
-
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) };
|
|
854
|
-
}
|
|
855
|
-
var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
|
|
856
|
-
var init_line = __esm(() => {
|
|
857
|
-
EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
|
|
858
|
-
BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
|
|
859
|
-
FORWARD_KILLS = new Set(["killnext", "killend"]);
|
|
860
|
-
WORD_CHARACTER = /[\p{L}\p{N}_]/u;
|
|
861
|
-
SPACE = /\s/;
|
|
862
|
-
});
|
|
863
|
-
|
|
864
|
-
// ../kit/src/picker/score.ts
|
|
865
|
-
function startsWord(text, index) {
|
|
866
|
-
if (index === 0)
|
|
867
|
-
return true;
|
|
868
|
-
const before = text[index - 1];
|
|
869
|
-
return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
|
|
870
|
-
}
|
|
871
|
-
function fuzzy(query, text) {
|
|
872
|
-
if (query === "")
|
|
873
|
-
return { score: 0, positions: [] };
|
|
874
|
-
const exact = query !== query.toLowerCase();
|
|
875
|
-
const needle = exact ? query : query.toLowerCase();
|
|
876
|
-
const haystack = exact ? text : text.toLowerCase();
|
|
877
|
-
if (haystack.length !== text.length || needle.length > haystack.length)
|
|
878
|
-
return;
|
|
879
|
-
const width = haystack.length;
|
|
880
|
-
const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
|
|
881
|
-
const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
|
|
882
|
-
for (let j = 0;j < needle.length; j++) {
|
|
883
|
-
let run = NONE;
|
|
884
|
-
let runAt = -1;
|
|
885
|
-
for (let i = j;i < width; i++) {
|
|
886
|
-
if (j > 0 && i - 2 >= j - 1) {
|
|
887
|
-
const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
|
|
888
|
-
if (candidate > run) {
|
|
889
|
-
run = candidate;
|
|
890
|
-
runAt = i - 2;
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
if (haystack[i] !== needle[j])
|
|
894
|
-
continue;
|
|
895
|
-
const here = MATCH + (startsWord(text, i) ? BOUNDARY : 0) + (i === 0 ? PREFIX : 0);
|
|
896
|
-
if (j === 0) {
|
|
897
|
-
best[0][i] = here - i * GAP;
|
|
898
|
-
continue;
|
|
899
|
-
}
|
|
900
|
-
const joined = best[j - 1][i - 1] + CONSECUTIVE;
|
|
901
|
-
const skipped = run - (i - 1) * GAP;
|
|
902
|
-
if (joined > NONE && joined >= skipped) {
|
|
903
|
-
best[j][i] = joined + here;
|
|
904
|
-
from[j][i] = i - 1;
|
|
905
|
-
} else if (skipped > NONE) {
|
|
906
|
-
best[j][i] = skipped + here;
|
|
907
|
-
from[j][i] = runAt;
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
}
|
|
911
|
-
const last = best[needle.length - 1];
|
|
912
|
-
let end = -1;
|
|
913
|
-
for (let i = 0;i < width; i++) {
|
|
914
|
-
if (last[i] > NONE && (end === -1 || last[i] > last[end]))
|
|
915
|
-
end = i;
|
|
916
|
-
}
|
|
917
|
-
if (end === -1)
|
|
918
|
-
return;
|
|
919
|
-
const positions = [];
|
|
920
|
-
for (let j = needle.length - 1, i = end;j >= 0; j--) {
|
|
921
|
-
positions.unshift(i);
|
|
922
|
-
i = from[j][i];
|
|
923
|
-
}
|
|
924
|
-
return { score: last[end], positions };
|
|
925
|
-
}
|
|
926
|
-
function rank(query, lines) {
|
|
927
|
-
if (query === "")
|
|
928
|
-
return lines.map((_, index) => ({ index, positions: [] }));
|
|
929
|
-
const found = [];
|
|
930
|
-
for (const [index, line] of lines.entries()) {
|
|
931
|
-
const match = fuzzy(query, line);
|
|
932
|
-
if (match !== undefined)
|
|
933
|
-
found.push({ index, positions: match.positions, score: match.score });
|
|
934
|
-
}
|
|
935
|
-
return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
|
|
936
|
-
}
|
|
937
|
-
var MATCH = 16, CONSECUTIVE = 12, BOUNDARY = 10, PREFIX = 8, GAP = 1, BOUNDARY_AFTER, UPPER, LOWER, NONE;
|
|
938
|
-
var init_score = __esm(() => {
|
|
939
|
-
BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
940
|
-
UPPER = /\p{Lu}/u;
|
|
941
|
-
LOWER = /\p{Ll}/u;
|
|
942
|
-
NONE = Number.NEGATIVE_INFINITY;
|
|
943
|
-
});
|
|
944
|
-
|
|
945
|
-
// ../kit/src/picker/state.ts
|
|
946
|
-
function repeat(value, count) {
|
|
947
|
-
return Array.from({ length: count }).fill(value);
|
|
948
|
-
}
|
|
949
|
-
function styled(line) {
|
|
950
|
-
let text = "";
|
|
951
|
-
const styles = [];
|
|
952
|
-
let active = "";
|
|
953
|
-
let colored = false;
|
|
954
|
-
let last = 0;
|
|
955
|
-
function add(chunk) {
|
|
956
|
-
const flat = chunk.replace(CONTROL2, " ");
|
|
957
|
-
text += flat;
|
|
958
|
-
colored ||= active !== "" && flat !== "";
|
|
959
|
-
styles.push(...repeat(active, flat.length));
|
|
960
|
-
}
|
|
961
|
-
for (const found of line.matchAll(ANSI)) {
|
|
962
|
-
add(line.slice(last, found.index));
|
|
963
|
-
last = found.index + found[0].length;
|
|
964
|
-
if (SGR.test(found[0]))
|
|
965
|
-
active = RESET.test(found[0]) ? "" : active + found[0];
|
|
966
|
-
}
|
|
967
|
-
add(line.slice(last));
|
|
968
|
-
return { text, styles: colored ? styles : undefined };
|
|
969
|
-
}
|
|
970
|
-
function lay(rows, searched) {
|
|
971
|
-
const parsed = rows.map((row) => row.cells.map(styled));
|
|
972
|
-
const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
|
|
973
|
-
return parsed.map((cells, at) => {
|
|
974
|
-
let text = "";
|
|
975
|
-
const styles = [];
|
|
976
|
-
let colored = false;
|
|
977
|
-
let searchEnd = 0;
|
|
978
|
-
for (const [column, cell] of cells.entries()) {
|
|
979
|
-
const last = column === cells.length - 1;
|
|
980
|
-
const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
|
|
981
|
-
text += shown;
|
|
982
|
-
colored ||= cell.styles !== undefined;
|
|
983
|
-
styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
|
|
984
|
-
if (column < searched)
|
|
985
|
-
searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
|
|
986
|
-
if (!last) {
|
|
987
|
-
const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
|
|
988
|
-
text += " ".repeat(pad);
|
|
989
|
-
styles.push(...repeat("", pad));
|
|
990
|
-
}
|
|
991
|
-
}
|
|
992
|
-
return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
|
|
993
|
-
});
|
|
994
|
-
}
|
|
995
|
-
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
996
|
-
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
997
|
-
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
998
|
-
const wheel = MOUSE.exec(sequence)?.[1];
|
|
999
|
-
if (wheel !== undefined)
|
|
1000
|
-
return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
|
|
1001
|
-
const named = codes.get(sequence);
|
|
1002
|
-
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
1003
|
-
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
1004
|
-
paste.active = sequence === PASTE_START;
|
|
1005
|
-
return [];
|
|
1006
|
-
}
|
|
1007
|
-
if (paste.active && (sequence === "\r" || sequence === `
|
|
1008
|
-
`))
|
|
1009
|
-
return [];
|
|
1010
|
-
if (key !== undefined)
|
|
1011
|
-
return [key];
|
|
1012
|
-
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
1013
|
-
});
|
|
1014
|
-
}
|
|
1015
|
-
function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
|
|
1016
|
-
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 };
|
|
1017
|
-
return withRows(state, rows);
|
|
1018
|
-
}
|
|
1019
|
-
function withRows(state, rows, header = state.header) {
|
|
1020
|
-
const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
|
|
1021
|
-
const laid = lay(cells, state.searched);
|
|
1022
|
-
const searchable = laid.map((row) => row.searchable);
|
|
1023
|
-
const matches = rank(state.query, searchable);
|
|
1024
|
-
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 };
|
|
1025
|
-
}
|
|
1026
|
-
function withQuery(state, key) {
|
|
1027
|
-
const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
|
|
1028
|
-
return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
|
|
1029
|
-
}
|
|
1030
|
-
function move(state, by) {
|
|
1031
|
-
return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
|
|
1032
|
-
}
|
|
1033
|
-
function highlighted(state) {
|
|
1034
|
-
return state.matches[state.cursor]?.index;
|
|
1035
|
-
}
|
|
1036
|
-
function press(state, key) {
|
|
1037
|
-
if (state.done !== undefined)
|
|
1038
|
-
return state;
|
|
1039
|
-
if (state.chained && endsKills(key))
|
|
1040
|
-
state = { ...state, chained: false };
|
|
1041
|
-
if (state.help)
|
|
1042
|
-
return { ...state, help: false };
|
|
1043
|
-
if (typeof key === "object") {
|
|
1044
|
-
if ("text" in key)
|
|
1045
|
-
return withQuery(state, key);
|
|
1046
|
-
return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
|
|
1047
|
-
}
|
|
1048
|
-
if (isEditKey(key))
|
|
1049
|
-
return withQuery(state, key);
|
|
1050
|
-
switch (key) {
|
|
1051
|
-
case "up":
|
|
1052
|
-
return move(state, -1);
|
|
1053
|
-
case "down":
|
|
1054
|
-
return move(state, 1);
|
|
1055
|
-
case "pageup":
|
|
1056
|
-
return move(state, -state.page);
|
|
1057
|
-
case "pagedown":
|
|
1058
|
-
return move(state, state.page);
|
|
1059
|
-
case "home":
|
|
1060
|
-
return move(state, -state.matches.length);
|
|
1061
|
-
case "end":
|
|
1062
|
-
return move(state, state.matches.length);
|
|
1063
|
-
case "cancel":
|
|
1064
|
-
return { ...state, done: "cancel" };
|
|
1065
|
-
case "help":
|
|
1066
|
-
return { ...state, help: true };
|
|
1067
|
-
case "suspend":
|
|
1068
|
-
return state;
|
|
1069
|
-
case "enter":
|
|
1070
|
-
return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
|
|
1071
|
-
case "tab": {
|
|
1072
|
-
const at = highlighted(state);
|
|
1073
|
-
if (!state.multi || at === undefined)
|
|
1074
|
-
return state;
|
|
1075
|
-
const marked = new Set(state.marked);
|
|
1076
|
-
if (!marked.delete(at))
|
|
1077
|
-
marked.add(at);
|
|
1078
|
-
return move({ ...state, marked }, 1);
|
|
1079
|
-
}
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
function chosen(state) {
|
|
1083
|
-
if (state.marked.size > 0)
|
|
1084
|
-
return state.rows.filter((_, index) => state.marked.has(index));
|
|
1085
|
-
const at = highlighted(state);
|
|
1086
|
-
return at === undefined ? [] : [state.rows[at]];
|
|
1087
|
-
}
|
|
1088
|
-
var CONTROL2, IS_CONTROL, SGR, RESET, COLUMN_GAP = 2, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
|
|
1089
|
-
var init_state = __esm(() => {
|
|
1090
|
-
init_text();
|
|
1091
|
-
init_line();
|
|
1092
|
-
init_score();
|
|
1093
|
-
CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
|
|
1094
|
-
IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
1095
|
-
SGR = /^\x1B\[[0-9;]*m$/;
|
|
1096
|
-
RESET = /^\x1B\[0?m$/;
|
|
1097
|
-
KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
|
|
1098
|
-
MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
|
|
1099
|
-
KEYS = {
|
|
1100
|
-
"\x1B[A": "up",
|
|
1101
|
-
"\x1BOA": "up",
|
|
1102
|
-
"\x10": "up",
|
|
1103
|
-
"\x1B[B": "down",
|
|
1104
|
-
"\x1BOB": "down",
|
|
1105
|
-
"\x0E": "down",
|
|
1106
|
-
"\x1B[5~": "pageup",
|
|
1107
|
-
"\x1B[6~": "pagedown",
|
|
1108
|
-
"\x1B[H": "home",
|
|
1109
|
-
"\x1B[1~": "home",
|
|
1110
|
-
"\x1BOH": "home",
|
|
1111
|
-
"\x1B[F": "end",
|
|
1112
|
-
"\x1B[4~": "end",
|
|
1113
|
-
"\x1BOF": "end",
|
|
1114
|
-
"\r": "enter",
|
|
1115
|
-
"\n": "enter",
|
|
1116
|
-
"\x03": "cancel",
|
|
1117
|
-
"\x1B": "cancel",
|
|
1118
|
-
"\x1B[D": "left",
|
|
1119
|
-
"\x1BOD": "left",
|
|
1120
|
-
"\x1B[C": "right",
|
|
1121
|
-
"\x1BOC": "right",
|
|
1122
|
-
"\x1B[1;5D": "wordleft",
|
|
1123
|
-
"\x1B[1;3D": "wordleft",
|
|
1124
|
-
"\x1Bb": "wordleft",
|
|
1125
|
-
"\x1B[1;5C": "wordright",
|
|
1126
|
-
"\x1B[1;3C": "wordright",
|
|
1127
|
-
"\x1Bf": "wordright",
|
|
1128
|
-
"\x01": "linestart",
|
|
1129
|
-
"\x05": "lineend",
|
|
1130
|
-
"\x7F": "erase",
|
|
1131
|
-
"\x1B[3~": "delete",
|
|
1132
|
-
"\b": "killword",
|
|
1133
|
-
"\x1B\x7F": "killword",
|
|
1134
|
-
"\x1B[3;5~": "killnext",
|
|
1135
|
-
"\x1Bd": "killnext",
|
|
1136
|
-
"\x15": "clear",
|
|
1137
|
-
"\v": "killend",
|
|
1138
|
-
"\x17": "word",
|
|
1139
|
-
"\x19": "yank",
|
|
1140
|
-
"\x1A": "suspend",
|
|
1141
|
-
"\t": "tab",
|
|
1142
|
-
"\x1F": "help",
|
|
1143
|
-
"\x1BOP": "help",
|
|
1144
|
-
"\x1B[11~": "help"
|
|
1145
|
-
};
|
|
1146
|
-
});
|
|
1147
|
-
|
|
1148
|
-
// ../kit/src/job.ts
|
|
1149
|
-
import process16 from "process";
|
|
1150
|
-
function stopJob() {
|
|
1151
|
-
process16.kill(0, "SIGTSTP");
|
|
1152
|
-
}
|
|
1153
|
-
var init_job = () => {};
|
|
1154
|
-
|
|
1155
|
-
// ../kit/src/redraw.ts
|
|
1156
|
-
function overwrite(lines, columns) {
|
|
1157
|
-
return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
|
|
1158
|
-
`);
|
|
1159
|
-
}
|
|
1160
|
-
var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
|
|
1161
|
-
var init_redraw = __esm(() => {
|
|
1162
|
-
init_format();
|
|
1163
|
-
});
|
|
1164
|
-
|
|
1165
|
-
// src/pick.ts
|
|
1166
|
-
import process19 from "process";
|
|
1167
|
-
|
|
1168
|
-
// ../kit/src/index.ts
|
|
1169
|
-
init_args();
|
|
1170
|
-
|
|
1171
|
-
// ../kit/src/argv.ts
|
|
1172
|
-
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
1173
|
-
import { resolve as resolve3 } from "path";
|
|
1174
|
-
import process10 from "process";
|
|
1175
|
-
function commandLine() {
|
|
1176
|
-
try {
|
|
1177
|
-
return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
1178
|
-
} catch {
|
|
1179
|
-
return;
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
function realPath(word) {
|
|
1183
|
-
try {
|
|
1184
|
-
return realpathSync(resolve3(word));
|
|
1185
|
-
} catch {
|
|
1186
|
-
return;
|
|
1187
|
-
}
|
|
1188
|
-
}
|
|
1189
|
-
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
1190
|
-
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
1191
|
-
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
1192
|
-
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
1193
|
-
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
1194
|
-
}
|
|
1195
|
-
// ../kit/src/chart.ts
|
|
1196
|
-
init_format();
|
|
1197
|
-
init_mode();
|
|
1198
|
-
init_style();
|
|
1199
|
-
init_theme();
|
|
1200
|
-
// ../kit/src/ci.ts
|
|
1201
|
-
init_args();
|
|
1202
|
-
init_format();
|
|
1203
|
-
|
|
1204
|
-
// ../kit/src/progress.ts
|
|
1205
|
-
init_format();
|
|
1206
|
-
|
|
1207
|
-
// ../kit/src/process.ts
|
|
1208
|
-
var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
1209
|
-
|
|
1210
|
-
// ../kit/src/progress.ts
|
|
1211
|
-
init_style();
|
|
1212
|
-
init_theme();
|
|
1213
|
-
var ESC = String.fromCharCode(27);
|
|
1214
|
-
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
1215
|
-
var RESET_STYLE = `${ESC}[0m`;
|
|
1216
|
-
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
1217
|
-
|
|
1218
|
-
// ../kit/src/ci.ts
|
|
1219
|
-
init_style();
|
|
1220
|
-
|
|
1221
|
-
// ../kit/src/tool.ts
|
|
1222
|
-
init_format();
|
|
1223
|
-
// ../kit/src/cli.ts
|
|
1224
|
-
init_args();
|
|
1225
|
-
import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
|
|
1226
|
-
import { dirname as dirname3, join as join5 } from "path";
|
|
1227
|
-
import process14 from "process";
|
|
1228
|
-
|
|
1229
|
-
// ../kit/src/askpass.ts
|
|
1230
|
-
import process11 from "process";
|
|
1231
|
-
var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
|
|
1232
|
-
async function askpassClient(argv) {
|
|
1233
|
-
const socketPath = process11.env[SOCKET_VARIABLE];
|
|
1234
|
-
if (socketPath === undefined)
|
|
1235
|
-
return;
|
|
1236
|
-
const request = { prompt: argv[0] ?? "", ...process11.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
1237
|
-
const { promise, resolve } = Promise.withResolvers();
|
|
1238
|
-
let received = "";
|
|
1239
|
-
try {
|
|
1240
|
-
await Bun.connect({
|
|
1241
|
-
unix: socketPath,
|
|
1242
|
-
socket: {
|
|
1243
|
-
open: (socket) => void socket.write(`${JSON.stringify(request)}
|
|
1244
|
-
`),
|
|
1245
|
-
data: (_, chunk) => {
|
|
1246
|
-
received += chunk.toString();
|
|
1247
|
-
},
|
|
1248
|
-
close: () => resolve(received),
|
|
1249
|
-
error: () => resolve("")
|
|
1250
|
-
}
|
|
1251
|
-
});
|
|
1252
|
-
} catch {
|
|
1253
|
-
return 1;
|
|
1254
|
-
}
|
|
1255
|
-
const reply = await promise;
|
|
1256
|
-
if (reply === "")
|
|
1257
|
-
return 1;
|
|
1258
|
-
const { answer } = JSON.parse(reply);
|
|
1259
|
-
if (request.notice === true)
|
|
1260
|
-
return 0;
|
|
1261
|
-
if (answer === undefined)
|
|
1262
|
-
return 1;
|
|
1263
|
-
process11.stdout.write(`${answer}
|
|
1264
|
-
`);
|
|
1265
|
-
return 0;
|
|
1266
|
-
}
|
|
1267
|
-
|
|
1268
|
-
// ../kit/src/completions.ts
|
|
1269
|
-
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
1270
|
-
var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
|
|
3
|
+
var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};import process2 from"process";function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process2.stdout,env=process2.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}var MODES,AGENT_VARIABLES;var init_mode=__esm(()=>{MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"]});function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var G,B,h,o;var init_chunk_x450vn3m=__esm(()=>{G=/^[a-f0-9]+$/i;B={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49],rgb:(r,e,l,n="fg")=>[`${n==="fg"?38:48};2;${r};${e};${l}`,n==="fg"?39:49],hex:(r,e="fg")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);o=Fe()});var init_colors=__esm(()=>{init_chunk_x450vn3m()});import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process3 from"process";function findUp(names,from=process3.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}var init_config=__esm(()=>{init_args()});import{homedir}from"os";import{isAbsolute,join as join2}from"path";import process4 from"process";function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process4.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}var init_user_config=()=>{};import{existsSync as existsSync2,readFileSync,statSync}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process5 from"process";function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process5.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=JSON.parse(readFileSync(path,"utf8"));if(isRecord(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync2(join3(dir,".git"))}function warnOnce(message){if(warned.has(message))return;warned.add(message),console.error(`warning: theme ${message}`)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process5.env,from=process5.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}function activeTheme(){let key=`${process5.cwd()}\x00${process5.env.KIT_THEME??""}\x00${process5.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var DEFAULT,BRIGHT,LIGHT,MONO,ASCII,PRESETS,STYLES,HEX,CONTROL,MAX_FILE_BYTES=65536,SPACES,CUBE,warned,current,currentKey="";var init_theme=__esm(()=>{init_config();init_user_config();DEFAULT={colors:{accent:"cyan",id:"yellow",path:"blue",label:"dim",value:"bold",ok:"green",warn:"yellow",problem:"red",note:"dim",plan:"magenta",passed:"green",failed:"red",running:"cyan",queued:"yellow",skipped:"dim"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",rule:"\u2500",corner:"\u256D",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",ok:"greenBright",warn:"yellowBright",problem:"redBright",note:"white",plan:"magentaBright",passed:"greenBright",failed:"redBright",running:"cyanBright",queued:"yellowBright",skipped:"white"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},MONO={accent:"bold",id:"bold",path:"underline",label:"dim",value:"bold",ok:"bold",warn:"bold",problem:"bold",note:"dim",plan:"dim",passed:"bold",failed:"bold",running:"bold",queued:"dim",skipped:"dim"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",rule:"-",corner:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},STYLES=new Set(["bold","dim","italic","underline","inverse","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,SPACES=/\s+/;CUBE=[0,95,135,175,215,255];warned=new Set});import process6 from"process";function takesControlCodes(stream,env=process6.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process6.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function role(name,stream,env=process6.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}var STATUS_WORDS,STATUS_OF;var init_style=__esm(()=>{init_colors();init_mode();init_theme();STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])))});function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}var ANSI,ESC,ESCAPE_CODE,RESET_STYLE,CLOSE_LINK;var init_text=__esm(()=>{ANSI=/\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`});import process7 from"process";function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function textWidth(text){return Bun.stringWidth(text)}function jsonText(value,replacer,{stream=process7.stdout,env=process7.env}={}){return JSON.stringify(value,replacer,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}var UNITS;var init_format=__esm(()=>{init_mode();init_style();init_text();init_theme();UNITS=[["d",86400],["h",3600],["m",60],["s",1]]});import process8 from"process";function usageLine(usage,colors=paint(process8.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
4
|
+
`),blank=lines.indexOf(""),synopses=blank===-1?lines:lines.slice(0,blank),details=blank===-1?[]:lines.slice(blank+1),colon=synopses[0].indexOf(": "),inline=synopses[0].slice(colon+2),summary=colon===-1?details.shift():`${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;if(colon!==-1)synopses[0]=synopses[0].slice(0,colon);let head=`${colors.bold("Usage:")} ${synopses.map((line)=>line.replaceAll(OPTIONAL,(part)=>colors.dim(part))).join(`
|
|
5
|
+
`)}`,lead=summary===void 0||!withSummary?[]:["",colors.bold(prose(summary,colors))],rest=details.length===0?[]:["",...details.map((line)=>prose(line,colors))];return[head,...lead,...rest].join(`
|
|
6
|
+
`)}function prose(line,colors){if(colors.cyan("x")==="x")return line;return line.replaceAll(PROSE_MARKS,(match,code,flag)=>code===void 0?colors.cyan(flag??match):colors.bold(code))}function helpText(usage,options,colors=paint(process8.stdout),{examples=[],exits=[],bin,columns}={}){let{summary}=description(usage);return[...bin===void 0?[usageLine(usage,colors)]:[`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary===""?"":` ${summary}`}`,"",usageLine(usage,colors,{summary:!1})],"",colors.bold("Options:"),...optionRows(options,colors,columns),...exitRows(exits,colors),...exampleRows(examples,colors)].join(`
|
|
7
|
+
`)}function exitRows(exits,colors=paint(process8.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process8.env){return env.KIT_HELP==="json"}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
8
|
+
`),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}function exampleRows(examples,colors=paint(process8.stdout)){if(examples.length===0||outputMode()==="agent")return[];return["",colors.bold("Examples:"),...examples.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}function wrapText(text,limit){if(text.length<=limit)return[text];let lines=[],current="";for(let word of text.split(" "))if(current==="")current=word;else if(current.length+1+word.length<=limit)current=`${current} ${word}`;else lines.push(current),current=word;if(current!=="")lines.push(current);return lines}function optionRows(options,colors=paint(process8.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapText(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}var OPTIONAL,USAGE_PREFIX,FULL_STOP,PROSE_MARKS,MAX_INLINE_CHOICES=24;var init_help=__esm(()=>{init_mode();init_style();OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi});var init_input=__esm(()=>{init_args()});import process9 from"process";import{parseArgs}from"util";function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}function badUsage(message){throw new UsageError(message)}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}function applyOutput(color,plain,env=process9.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(own,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process9.stdout)?process9.stdout.columns:void 0;throw console.log(wantsHelpJson()?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}var DASHES,EXIT,Exit,UsageError,HelpShown,completion,heading,OUTPUT_OPTIONS,UNKNOWN_OPTION;var init_args=__esm(()=>{init_format();init_help();init_style();init_text();init_help();init_input();DASHES=/^-+/;EXIT=Symbol.for("@kaynooo/cli-kit/Exit");Exit=class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}};UsageError=class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}};HelpShown=class HelpShown extends Exit{constructor(){super("help shown",0)}};completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};UNKNOWN_OPTION=/^unknown option '(-[^']+)'/});var init_folders=__esm(()=>{init_user_config()});function isEditKey(key){return EDIT_KEYS.has(key)}function endsKills(key){return typeof key!=="object"&&!isEditKey(key)}function isWord(char){return char!==void 0&&WORD_CHARACTER.test(char)}function wordStart(chars,from){let at=from;while(at>0&&!isWord(chars[at-1]))at--;while(at>0&&isWord(chars[at-1]))at--;return at}function wordEnd(chars,from){let at=from;while(at<chars.length&&!isWord(chars[at]))at++;while(at<chars.length&&isWord(chars[at]))at++;return at}function spacedStart(chars,from){let at=from;while(at>0&&SPACE.test(chars[at-1]??""))at--;while(at>0&&!SPACE.test(chars[at-1]??""))at--;return at}function cut(chars,from,to){return{text:[...chars.slice(0,from),...chars.slice(to)].join(""),caret:from}}function insert(chars,at,text){let typed=[...text];return{text:[...chars.slice(0,at),...typed,...chars.slice(at)].join(""),caret:at+typed.length}}function editLine(line,key){let{killed="",chained=!1}=line,chars=[...line.text],at=Math.min(Math.max(line.caret,0),chars.length),edited=edit(chars,at,key,killed);if(typeof key==="object"||!BACKWARD_KILLS.has(key)&&!FORWARD_KILLS.has(key))return line.killed===void 0?edited:{...edited,killed};let taken=chars.slice(edited.caret,edited.caret+chars.length-[...edited.text].length).join("");if(taken==="")return{...edited,killed,chained};if(!chained)return{...edited,killed:taken,chained:!0};return{...edited,killed:BACKWARD_KILLS.has(key)?taken+killed:killed+taken,chained:!0}}function edit(chars,at,key,killed){let text=chars.join("");if(typeof key==="object")return insert(chars,at,key.text);switch(key){case"left":return{text,caret:Math.max(at-1,0)};case"right":return{text,caret:Math.min(at+1,chars.length)};case"wordleft":return{text,caret:wordStart(chars,at)};case"wordright":return{text,caret:wordEnd(chars,at)};case"linestart":return{text,caret:0};case"lineend":return{text,caret:chars.length};case"erase":return cut(chars,Math.max(at-1,0),at);case"delete":return cut(chars,at,Math.min(at+1,chars.length));case"word":return cut(chars,spacedStart(chars,at),at);case"killword":return cut(chars,wordStart(chars,at),at);case"killnext":return cut(chars,at,wordEnd(chars,at));case"clear":return cut(chars,0,at);case"killend":return cut(chars,at,chars.length);case"yank":return insert(chars,at,killed)}}function visible({text,caret},room){let chars=[...text],at=Math.min(Math.max(caret,0),chars.length),cells=at===chars.length?[...chars," "]:chars,widths=cells.map((char)=>Bun.stringWidth(char)),width=(from,to)=>widths.slice(from,to).reduce((sum,size)=>sum+size,0),fits=(from,to)=>(from>0?1:0)+width(from,to)+(to<cells.length?1:0)<=room,start=at,end=at+1;while(start>0&&fits(start-1,end))start--;while(end<cells.length&&fits(start,end+1))end++;let left=start>0?"\u2026":"",right=end<cells.length?"\u2026":"";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)}}var EDIT_KEYS,BACKWARD_KILLS,FORWARD_KILLS,WORD_CHARACTER,SPACE;var init_line=__esm(()=>{EDIT_KEYS=new Set(["left","right","wordleft","wordright","linestart","lineend","erase","delete","word","killword","killnext","clear","killend","yank"]),BACKWARD_KILLS=new Set(["word","killword","clear"]),FORWARD_KILLS=new Set(["killnext","killend"]);WORD_CHARACTER=/[\p{L}\p{N}_]/u,SPACE=/\s/});function startsWord(text,index){if(index===0)return!0;let before=text[index-1];return BOUNDARY_AFTER.has(before)||LOWER.test(before)&&UPPER.test(text[index])}function fuzzy(query,text){if(query==="")return{score:0,positions:[]};let exact=query!==query.toLowerCase(),needle=exact?query:query.toLowerCase(),haystack=exact?text:text.toLowerCase();if(haystack.length!==text.length||needle.length>haystack.length)return;let width=haystack.length,best=Array.from({length:needle.length},()=>Array(width).fill(NONE)),from=Array.from({length:needle.length},()=>Array(width).fill(-1));for(let j=0;j<needle.length;j++){let run=NONE,runAt=-1;for(let i=j;i<width;i++){if(j>0&&i-2>=j-1){let candidate=best[j-1][i-2]+(i-2)*1;if(candidate>run)run=candidate,runAt=i-2}if(haystack[i]!==needle[j])continue;let here=16+(startsWord(text,i)?10:0)+(i===0?8:0);if(j===0){best[0][i]=here-i*1;continue}let joined=best[j-1][i-1]+12,skipped=run-(i-1)*1;if(joined>NONE&&joined>=skipped)best[j][i]=joined+here,from[j][i]=i-1;else if(skipped>NONE)best[j][i]=skipped+here,from[j][i]=runAt}}let last=best[needle.length-1],end=-1;for(let i=0;i<width;i++)if(last[i]>NONE&&(end===-1||last[i]>last[end]))end=i;if(end===-1)return;let positions=[];for(let j=needle.length-1,i=end;j>=0;j--)positions.unshift(i),i=from[j][i];return{score:last[end],positions}}function rank(query,lines){if(query==="")return lines.map((_,index)=>({index,positions:[]}));let found=[];for(let[index,line]of lines.entries()){let match=fuzzy(query,line);if(match!==void 0)found.push({index,positions:match.positions,score:match.score})}return found.sort((a,b)=>b.score-a.score||lines[a.index].length-lines[b.index].length||a.index-b.index)}var BOUNDARY_AFTER,UPPER,LOWER,NONE;var init_score=__esm(()=>{BOUNDARY_AFTER=new Set([" ","/","-","_",".",":","\\","(","[",",","\t"]),UPPER=/\p{Lu}/u,LOWER=/\p{Ll}/u,NONE=Number.NEGATIVE_INFINITY});function repeat(value,count){return Array.from({length:count}).fill(value)}function styled(line){let text="",styles=[],active="",colored=!1,last=0;function add(chunk){let flat=chunk.replace(CONTROL2," ");text+=flat,colored||=active!==""&&flat!=="",styles.push(...repeat(active,flat.length))}for(let found of line.matchAll(ANSI))if(add(line.slice(last,found.index)),last=found.index+found[0].length,SGR.test(found[0]))active=RESET.test(found[0])?"":active+found[0];return add(line.slice(last)),{text,styles:colored?styles:void 0}}function lay(rows,searched){let parsed=rows.map((row)=>row.cells.map(styled)),widths=(parsed[0]??[]).map((_,column)=>Math.max(...parsed.map((cells)=>Bun.stringWidth(cells[column]?.text??""))));return parsed.map((cells,at)=>{let text="",styles=[],colored=!1,searchEnd=0;for(let[column,cell]of cells.entries()){let last=column===cells.length-1,shown=cells.length>1&&last?cell.text.trimEnd():cell.text;if(text+=shown,colored||=cell.styles!==void 0,styles.push(...cell.styles?.slice(0,shown.length)??repeat("",shown.length)),column<searched)searchEnd=cells.length>1?text.trimEnd().length:text.length;if(!last){let pad=widths[column]-Bun.stringWidth(cell.text)+COLUMN_GAP;text+=" ".repeat(pad),styles.push(...repeat("",pad))}}return{text,styles:colored?styles:void 0,searchable:rows[at].search??text.slice(0,searchEnd)}})}function parseKeys(input,paste={active:!1},ctrls=[]){let codes=new Map(ctrls.map((name)=>[String.fromCharCode(name.codePointAt(name.length-1)-96),name]));return(input.match(KEY_SEQUENCES)??[]).flatMap((sequence)=>{let wheel=MOUSE.exec(sequence)?.[1];if(wheel!==void 0)return repeat(wheel==="64"?"up":"down",wheel==="64"||wheel==="65"?WHEEL_LINES:0);let named=codes.get(sequence),key=named===void 0?KEYS[sequence]:{ctrl:named};if(sequence===PASTE_START||sequence===PASTE_END)return paste.active=sequence===PASTE_START,[];if(paste.active&&(sequence==="\r"||sequence===`
|
|
9
|
+
`))return[];if(key!==void 0)return[key];return IS_CONTROL.test(sequence)||sequence.startsWith("\x1B")?[]:[{text:sequence}]})}function createState(rows,{multi=!1,prompt="> ",query="",header="",expect=[],searched=Number.POSITIVE_INFINITY}={}){let state={rows:[],items:[],styles:[],searchable:[],searched,header,expect,key:"",status:"",query,caret:[...query].length,killed:"",chained:!1,matches:[],cursor:0,help:!1,page:10,marked:new Set,multi,prompt,done:void 0};return withRows(state,rows)}function withRows(state,rows,header=state.header){let cells=rows.map((row)=>typeof row==="string"?{hidden:[],cells:[row]}:row),laid=lay(cells,state.searched),searchable=laid.map((row)=>row.searchable),matches=rank(state.query,searchable);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}}function withQuery(state,key){let{text,caret,killed="",chained=!1}=editLine({text:state.query,caret:state.caret,killed:state.killed,chained:state.chained},key);return text===state.query?{...state,caret,killed,chained}:{...state,query:text,caret,killed,chained,matches:rank(text,state.searchable),cursor:0}}function move(state,by){return{...state,cursor:Math.max(0,Math.min(state.matches.length-1,state.cursor+by))}}function highlighted(state){return state.matches[state.cursor]?.index}function press(state,key){if(state.done!==void 0)return state;if(state.chained&&endsKills(key))state={...state,chained:!1};if(state.help)return{...state,help:!1};if(typeof key==="object"){if("text"in key)return withQuery(state,key);return state.expect.includes(key.ctrl)?{...state,done:"accept",key:key.ctrl}:state}if(isEditKey(key))return withQuery(state,key);switch(key){case"up":return move(state,-1);case"down":return move(state,1);case"pageup":return move(state,-state.page);case"pagedown":return move(state,state.page);case"home":return move(state,-state.matches.length);case"end":return move(state,state.matches.length);case"cancel":return{...state,done:"cancel"};case"help":return{...state,help:!0};case"suspend":return state;case"enter":return state.matches.length===0&&state.marked.size===0?state:{...state,done:"accept"};case"tab":{let at=highlighted(state);if(!state.multi||at===void 0)return state;let marked=new Set(state.marked);if(!marked.delete(at))marked.add(at);return move({...state,marked},1)}}}function chosen(state){if(state.marked.size>0)return state.rows.filter((_,index)=>state.marked.has(index));let at=highlighted(state);return at===void 0?[]:[state.rows[at]]}var CONTROL2,IS_CONTROL,SGR,RESET,COLUMN_GAP=2,PASTE_START="\x1B[200~",PASTE_END="\x1B[201~",KEY_SEQUENCES,MOUSE,WHEEL_LINES=3,KEYS;var init_state=__esm(()=>{init_text();init_line();init_score();CONTROL2=/[\x00-\x1F\x7F-\x9F]/g,IS_CONTROL=/[\x00-\x1F\x7F-\x9F]/,SGR=/^\x1B\[[0-9;]*m$/,RESET=/^\x1B\[0?m$/,KEY_SEQUENCES=/\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu,MOUSE=/^\x1B\[<(\d+);\d+;\d+[a-z]$/i,KEYS={"\x1B[A":"up","\x1BOA":"up","\x10":"up","\x1B[B":"down","\x1BOB":"down","\x0E":"down","\x1B[5~":"pageup","\x1B[6~":"pagedown","\x1B[H":"home","\x1B[1~":"home","\x1BOH":"home","\x1B[F":"end","\x1B[4~":"end","\x1BOF":"end","\r":"enter","\n":"enter","\x03":"cancel","\x1B":"cancel","\x1B[D":"left","\x1BOD":"left","\x1B[C":"right","\x1BOC":"right","\x1B[1;5D":"wordleft","\x1B[1;3D":"wordleft","\x1Bb":"wordleft","\x1B[1;5C":"wordright","\x1B[1;3C":"wordright","\x1Bf":"wordright","\x01":"linestart","\x05":"lineend","\x7F":"erase","\x1B[3~":"delete","\b":"killword","\x1B\x7F":"killword","\x1B[3;5~":"killnext","\x1Bd":"killnext","\x15":"clear","\v":"killend","\x17":"word","\x19":"yank","\x1A":"suspend","\t":"tab","\x1F":"help","\x1BOP":"help","\x1B[11~":"help"}});import process16 from"process";function stopJob(){process16.kill(0,"SIGTSTP")}var init_job=()=>{};function overwrite(lines,columns){return lines.map((line)=>textWidth(line)%columns===0?`\x1B[2K${line}`:`${line}\x1B[K`).join(`
|
|
10
|
+
`)}var SYNC_START="\x1B[?2026h",SYNC_END="\x1B[?2026l";var init_redraw=__esm(()=>{init_format()});import process19 from"process";init_args();import{readFileSync as readFileSync2,realpathSync}from"fs";import{resolve as resolve3}from"path";import process10 from"process";function commandLine(){try{return readFileSync2("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve3(word))}catch{return}}function scriptArgs(argv=process10.argv.slice(2),cmdline=commandLine(),script=process10.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve3(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}init_format();init_mode();init_style();init_theme();init_args();init_format();init_format();init_style();init_text();init_theme();init_style();init_format();init_args();import{readFileSync as readFileSync4,realpathSync as realpathSync2}from"fs";import{dirname as dirname3,join as join5}from"path";import process14 from"process";import process11 from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process11.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process11.env.SSH_ASKPASS_PROMPT==="none"?{notice:!0}:{}},{promise,resolve}=Promise.withResolvers(),received="";try{await Bun.connect({unix:socketPath,socket:{open:(socket)=>void socket.write(`${JSON.stringify(request)}
|
|
11
|
+
`),data:(_,chunk)=>{received+=chunk.toString()},close:()=>resolve(received),error:()=>resolve("")}})}catch{return 1}let reply=await promise;if(reply==="")return 1;let{answer}=JSON.parse(reply);if(request.notice===!0)return 0;if(answer===void 0)return 1;return process11.stdout.write(`${answer}
|
|
12
|
+
`),0}var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
|
|
13
|
+
functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
|
|
1271
14
|
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
1272
15
|
set -l current (commandline -ct)
|
|
1273
16
|
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
@@ -1277,8 +20,10 @@ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_
|
|
|
1277
20
|
echo $line
|
|
1278
21
|
end
|
|
1279
22
|
end
|
|
1280
|
-
end
|
|
1281
|
-
|
|
23
|
+
end
|
|
24
|
+
${bins.map((bin)=>`complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
25
|
+
`).join("")}`;if(shell==="bash")return`${header}
|
|
26
|
+
__kaynooo_cli_complete() {
|
|
1282
27
|
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
1283
28
|
local -a lines
|
|
1284
29
|
COMPREPLY=()
|
|
@@ -1291,8 +36,10 @@ var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
|
1291
36
|
fi
|
|
1292
37
|
done
|
|
1293
38
|
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1294
|
-
}
|
|
1295
|
-
|
|
39
|
+
}
|
|
40
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
41
|
+
`;return`${header}
|
|
42
|
+
__kaynooo_cli_complete() {
|
|
1296
43
|
local line
|
|
1297
44
|
local -a described plain
|
|
1298
45
|
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
@@ -1307,907 +54,30 @@ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
|
1307
54
|
(( \${#described} )) && _describe -V value described
|
|
1308
55
|
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
1309
56
|
return 0
|
|
1310
|
-
}`;
|
|
1311
|
-
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1312
|
-
if (shell === "fish")
|
|
1313
|
-
return `${header}
|
|
1314
|
-
${FISH_FUNCTION}
|
|
1315
|
-
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1316
|
-
`).join("")}`;
|
|
1317
|
-
if (shell === "bash")
|
|
1318
|
-
return `${header}
|
|
1319
|
-
${BASH_FUNCTION}
|
|
1320
|
-
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1321
|
-
`;
|
|
1322
|
-
return `${header}
|
|
1323
|
-
${ZSH_FUNCTION}
|
|
1324
|
-
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
1325
|
-
`;
|
|
1326
|
-
}
|
|
1327
|
-
|
|
1328
|
-
// ../kit/src/notify.ts
|
|
1329
|
-
init_format();
|
|
1330
|
-
init_mode();
|
|
1331
|
-
import process12 from "process";
|
|
1332
|
-
var NOTIFY_AFTER_MS = 1e4;
|
|
1333
|
-
var CANCELLED = 130;
|
|
1334
|
-
function base64(text) {
|
|
1335
|
-
return Buffer.from(text).toString("base64");
|
|
1336
|
-
}
|
|
1337
|
-
function notification(title, body, env = process12.env) {
|
|
1338
|
-
const id = `kit${process12.pid}`;
|
|
1339
|
-
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\\`];
|
|
1340
|
-
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1341
|
-
}
|
|
1342
|
-
function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
|
|
1343
|
-
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1344
|
-
return;
|
|
1345
|
-
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1346
|
-
}
|
|
1347
|
-
|
|
1348
|
-
// ../kit/src/cli.ts
|
|
1349
|
-
init_style();
|
|
1350
|
-
init_text();
|
|
1351
|
-
|
|
1352
|
-
// ../kit/src/usage.ts
|
|
1353
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
1354
|
-
import { homedir as homedir3 } from "os";
|
|
1355
|
-
import { dirname as dirname2, join as join4 } from "path";
|
|
1356
|
-
import process13 from "process";
|
|
1357
|
-
|
|
1358
|
-
// ../kit/src/logs.ts
|
|
1359
|
-
init_user_config();
|
|
1360
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1361
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
1362
|
-
|
|
1363
|
-
// ../kit/src/usage.ts
|
|
1364
|
-
init_user_config();
|
|
1365
|
-
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1366
|
-
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1367
|
-
var LONGEST_NAME = 40;
|
|
1368
|
-
var usageError;
|
|
1369
|
-
function noteUsageError(message) {
|
|
1370
|
-
usageError = message;
|
|
1371
|
-
}
|
|
1372
|
-
function stateHome(env = process13.env) {
|
|
1373
|
-
return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
|
|
1374
|
-
}
|
|
1375
|
-
function usagePath(env = process13.env) {
|
|
1376
|
-
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1377
|
-
}
|
|
1378
|
-
function usageRecorded(env = process13.env) {
|
|
1379
|
-
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1380
|
-
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1381
|
-
}
|
|
1382
|
-
function flagNames(argv) {
|
|
1383
|
-
const end = argv.indexOf("--");
|
|
1384
|
-
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1385
|
-
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1386
|
-
}
|
|
1387
|
-
function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
1388
|
-
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1389
|
-
usageError = undefined;
|
|
1390
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
1391
|
-
}
|
|
1392
|
-
function recordUsage(entry, env = process13.env) {
|
|
1393
|
-
if (!usageRecorded(env))
|
|
1394
|
-
return;
|
|
1395
|
-
try {
|
|
1396
|
-
const path = usagePath(env);
|
|
1397
|
-
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1398
|
-
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1399
|
-
`, { mode: 384 });
|
|
1400
|
-
} catch {}
|
|
1401
|
-
}
|
|
1402
|
-
|
|
1403
|
-
// ../kit/src/cli.ts
|
|
1404
|
-
var LEVEL_OPTIONS = {
|
|
1405
|
-
...OUTPUT_OPTIONS,
|
|
1406
|
-
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1407
|
-
};
|
|
1408
|
-
var TOP_OPTIONS = {
|
|
1409
|
-
...LEVEL_OPTIONS,
|
|
1410
|
-
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1411
|
-
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1412
|
-
};
|
|
1413
|
-
function printError(prefix, message, hint, cause) {
|
|
1414
|
-
const colors = paint(process14.stderr);
|
|
1415
|
-
const styled = takesControlCodes(process14.stderr);
|
|
1416
|
-
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1417
|
-
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1418
|
-
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1419
|
-
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1420
|
-
}
|
|
1421
|
-
function printJsonError(message, hint, cause) {
|
|
1422
|
-
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1423
|
-
}
|
|
1424
|
-
function wantsJson(argv) {
|
|
1425
|
-
const end = argv.indexOf("--");
|
|
1426
|
-
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1427
|
-
}
|
|
1428
|
-
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1429
|
-
if (error instanceof HelpShown)
|
|
1430
|
-
return 0;
|
|
1431
|
-
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1432
|
-
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1433
|
-
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1434
|
-
if (error instanceof Exit && error.code === 2)
|
|
1435
|
-
noteUsageError(error.message);
|
|
1436
|
-
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1437
|
-
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1438
|
-
return error instanceof Exit ? error.code : 1;
|
|
1439
|
-
}
|
|
1440
|
-
var COMPLETE = "__complete";
|
|
1441
|
-
var FILES = "__files__";
|
|
1442
|
-
async function completingOf(run) {
|
|
1443
|
-
completion.active = true;
|
|
1444
|
-
try {
|
|
1445
|
-
await run([]);
|
|
1446
|
-
} catch (error) {
|
|
1447
|
-
if (error instanceof Completing)
|
|
1448
|
-
return error;
|
|
1449
|
-
} finally {
|
|
1450
|
-
completion.active = false;
|
|
1451
|
-
}
|
|
1452
|
-
return new Completing({});
|
|
1453
|
-
}
|
|
1454
|
-
function candidateLine(candidate) {
|
|
1455
|
-
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1456
|
-
}
|
|
1457
|
-
function positionalBeingTyped(before, { options, positionals }) {
|
|
1458
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1459
|
-
const typed = [];
|
|
1460
|
-
let at = 0;
|
|
1461
|
-
while (at < before.length) {
|
|
1462
|
-
const word = before[at];
|
|
1463
|
-
if (word === "--") {
|
|
1464
|
-
typed.push(...before.slice(at + 1));
|
|
1465
|
-
break;
|
|
1466
|
-
}
|
|
1467
|
-
if (!word.startsWith("-"))
|
|
1468
|
-
typed.push(word);
|
|
1469
|
-
else if (takesValue(word))
|
|
1470
|
-
at++;
|
|
1471
|
-
at++;
|
|
1472
|
-
}
|
|
1473
|
-
const last = positionals.at(-1);
|
|
1474
|
-
if (typed.length < positionals.length)
|
|
1475
|
-
return { name: positionals[typed.length], typed };
|
|
1476
|
-
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1477
57
|
}
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
}
|
|
1492
|
-
var
|
|
1493
|
-
function
|
|
1494
|
-
|
|
1495
|
-
}
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
if (shell === undefined || args.length !== 1) {
|
|
1499
|
-
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1500
|
-
return 2;
|
|
1501
|
-
}
|
|
1502
|
-
console.log(completionScript(shell, [name]).trimEnd());
|
|
1503
|
-
return 0;
|
|
1504
|
-
}
|
|
1505
|
-
async function printCandidates(found) {
|
|
1506
|
-
for (const line of await found)
|
|
1507
|
-
console.log(line);
|
|
1508
|
-
return 0;
|
|
1509
|
-
}
|
|
1510
|
-
function packageVersion(entry = Bun.main) {
|
|
1511
|
-
let resolved = entry;
|
|
1512
|
-
try {
|
|
1513
|
-
resolved = realpathSync2(entry);
|
|
1514
|
-
} catch {}
|
|
1515
|
-
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1516
|
-
try {
|
|
1517
|
-
const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
|
|
1518
|
-
if (typeof version === "string")
|
|
1519
|
-
return version;
|
|
1520
|
-
} catch {}
|
|
1521
|
-
if (dirname3(dir) === dir)
|
|
1522
|
-
return "0.0.0";
|
|
1523
|
-
}
|
|
1524
|
-
}
|
|
1525
|
-
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1526
|
-
const answered = await askpassClient(argv);
|
|
1527
|
-
if (answered !== undefined)
|
|
1528
|
-
return answered;
|
|
1529
|
-
if (argv[0] === COMPLETE)
|
|
1530
|
-
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1531
|
-
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1532
|
-
return printCompletionScript(name, flagValue(argv));
|
|
1533
|
-
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1534
|
-
console.log(version ?? packageVersion());
|
|
1535
|
-
return 0;
|
|
1536
|
-
}
|
|
1537
|
-
let code;
|
|
1538
|
-
const started = performance.now();
|
|
1539
|
-
heading.bin = { name, version: () => version ?? packageVersion() };
|
|
1540
|
-
try {
|
|
1541
|
-
code = await run(argv);
|
|
1542
|
-
} catch (error) {
|
|
1543
|
-
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1544
|
-
} finally {
|
|
1545
|
-
heading.bin = undefined;
|
|
1546
|
-
}
|
|
1547
|
-
notifyEnd(name, code, performance.now() - started);
|
|
1548
|
-
if (usage !== false) {
|
|
1549
|
-
try {
|
|
1550
|
-
recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
|
|
1551
|
-
} catch {}
|
|
1552
|
-
}
|
|
1553
|
-
return code;
|
|
1554
|
-
}
|
|
1555
|
-
|
|
1556
|
-
// ../kit/src/index.ts
|
|
1557
|
-
init_config();
|
|
1558
|
-
|
|
1559
|
-
// ../kit/src/excerpt.ts
|
|
1560
|
-
init_text();
|
|
1561
|
-
|
|
1562
|
-
// ../kit/src/index.ts
|
|
1563
|
-
init_folders();
|
|
1564
|
-
init_format();
|
|
1565
|
-
|
|
1566
|
-
// ../kit/src/git.ts
|
|
1567
|
-
init_args();
|
|
1568
|
-
// ../kit/src/limit.ts
|
|
1569
|
-
init_args();
|
|
1570
|
-
|
|
1571
|
-
// ../kit/src/index.ts
|
|
1572
|
-
init_mode();
|
|
1573
|
-
|
|
1574
|
-
// ../kit/src/report.ts
|
|
1575
|
-
init_style();
|
|
1576
|
-
init_text();
|
|
1577
|
-
// ../kit/src/secrets.ts
|
|
1578
|
-
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1579
|
-
var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
|
|
1580
|
-
// ../kit/src/sessions.ts
|
|
1581
|
-
var {Glob } = globalThis.Bun;
|
|
1582
|
-
var SESSION_FILES = new Glob("*.json");
|
|
1583
|
-
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1584
|
-
|
|
1585
|
-
// ../kit/src/index.ts
|
|
1586
|
-
init_style();
|
|
1587
|
-
init_text();
|
|
1588
|
-
init_theme();
|
|
1589
|
-
init_user_config();
|
|
1590
|
-
|
|
1591
|
-
// ../kit/src/watch.ts
|
|
1592
|
-
init_args();
|
|
1593
|
-
init_input();
|
|
1594
|
-
init_style();
|
|
1595
|
-
// ../kit/src/workspace-root.ts
|
|
1596
|
-
init_user_config();
|
|
1597
|
-
// ../kit/src/picker.ts
|
|
1598
|
-
init_folders();
|
|
1599
|
-
init_state();
|
|
1600
|
-
|
|
1601
|
-
// ../kit/src/picker/terminal.ts
|
|
1602
|
-
init_args();
|
|
1603
|
-
init_job();
|
|
1604
|
-
init_redraw();
|
|
1605
|
-
init_style();
|
|
1606
|
-
import { openSync } from "fs";
|
|
1607
|
-
import process18 from "process";
|
|
1608
|
-
import tty from "tty";
|
|
1609
|
-
|
|
1610
|
-
// ../kit/src/picker/preview.ts
|
|
1611
|
-
import process17 from "process";
|
|
1612
|
-
|
|
1613
|
-
// ../kit/src/shell.ts
|
|
1614
|
-
var SEPARATORS = new Set([`
|
|
1615
|
-
`, ";", "|"]);
|
|
1616
|
-
var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
|
|
1617
|
-
var GLOB_CHARS = new Set(["*", "?", "["]);
|
|
1618
|
-
var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
|
|
1619
|
-
var SAFE_WORD = /^[\w@%+=:,./-]+$/;
|
|
1620
|
-
var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
|
|
1621
|
-
var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
|
|
1622
|
-
var FISH_COMBINERS = new Set(["and", "or", "not"]);
|
|
1623
|
-
var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
|
|
1624
|
-
var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
|
|
1625
|
-
var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
|
|
1626
|
-
var POWERSHELL = new Set(["pwsh", "powershell"]);
|
|
1627
|
-
var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
|
|
1628
|
-
var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
|
|
1629
|
-
var PRINTERS = new Set(["echo", "printf"]);
|
|
1630
|
-
var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
1631
|
-
function wrapper(short = "", long = [], operands = 0, runsString = false) {
|
|
1632
|
-
return { short, long, operands, runsString };
|
|
1633
|
-
}
|
|
1634
|
-
var RUNNER = { ...wrapper(), afterDashes: true };
|
|
1635
|
-
var WRAPPERS = new Map([
|
|
1636
|
-
["command", wrapper()],
|
|
1637
|
-
["builtin", wrapper()],
|
|
1638
|
-
["nohup", wrapper()],
|
|
1639
|
-
["setsid", wrapper()],
|
|
1640
|
-
["busybox", wrapper()],
|
|
1641
|
-
["exec", wrapper("a")],
|
|
1642
|
-
["time", wrapper("fo", ["--format", "--output"])],
|
|
1643
|
-
["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
|
|
1644
|
-
["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
|
|
1645
|
-
["doas", wrapper("uC")],
|
|
1646
|
-
["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
|
|
1647
|
-
["nice", wrapper("n", ["--adjustment"])],
|
|
1648
|
-
["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
|
|
1649
|
-
["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
|
|
1650
|
-
["chroot", wrapper("", ["--userspec", "--groups"], 1)],
|
|
1651
|
-
["watch", wrapper("n", ["--interval"], 0, true)],
|
|
1652
|
-
["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
|
|
1653
|
-
["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
|
|
1654
|
-
["unbuffer", wrapper()],
|
|
1655
|
-
["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
|
|
1656
|
-
["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])],
|
|
1657
|
-
["strace", wrapper("abeEIoOpPsSuUX", ["--trace", "--output", "--attach", "--string-limit", "--user", "--env", "--columns", "--trace-path", "--signal", "--status", "--summary-sort-by", "--summary-columns", "--const-print-style", "--interruptible", "--detach-on"])],
|
|
1658
|
-
["ltrace", wrapper("aeFlnopsuxX", ["--output", "--user", "--library", "--config", "--align", "--indent"])],
|
|
1659
|
-
["taskset", wrapper("", [], 1)],
|
|
1660
|
-
["fakeroot", wrapper("lsib", ["--lib", "--faked"])],
|
|
1661
|
-
["sshpass", wrapper("pfdP")],
|
|
1662
|
-
["coproc", wrapper()],
|
|
1663
|
-
["proxychains", wrapper("f")],
|
|
1664
|
-
["proxychains4", wrapper("f")],
|
|
1665
|
-
["torsocks", wrapper("upaP", ["--user", "--pass", "--address", "--port"])],
|
|
1666
|
-
["chrt", wrapper("TPD", ["--sched-runtime", "--sched-period", "--sched-deadline"], 1)],
|
|
1667
|
-
["unshare", wrapper("SGRw", ["--setuid", "--setgid", "--root", "--wd", "--map-user", "--map-group", "--map-users", "--map-groups", "--propagation", "--setgroups"])],
|
|
1668
|
-
["nsenter", wrapper("tSG", ["--target", "--setuid", "--setgid"])],
|
|
1669
|
-
["out", RUNNER],
|
|
1670
|
-
["slot", RUNNER],
|
|
1671
|
-
["waitfor", RUNNER],
|
|
1672
|
-
["base", RUNNER]
|
|
1673
|
-
]);
|
|
1674
|
-
function shellQuote(word) {
|
|
1675
|
-
return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
1676
|
-
}
|
|
1677
|
-
|
|
1678
|
-
// ../kit/src/picker/preview.ts
|
|
1679
|
-
var PREVIEW_BYTES = 64 * 1024;
|
|
1680
|
-
var PREVIEW_LINES = 200;
|
|
1681
|
-
var PREVIEW_TIMEOUT_MS = 3000;
|
|
1682
|
-
var PLACEHOLDER = /\{([1-9]\d*)?\}/g;
|
|
1683
|
-
function previewCommand(template, line, hidden = []) {
|
|
1684
|
-
return template.replace(PLACEHOLDER, (_, field) => shellQuote(field === undefined ? line : hidden[Number(field) - 1] ?? ""));
|
|
1685
|
-
}
|
|
1686
|
-
function previewLines(output) {
|
|
1687
|
-
const lines = output.split(`
|
|
1688
|
-
`);
|
|
1689
|
-
if (lines.at(-1) === "")
|
|
1690
|
-
lines.pop();
|
|
1691
|
-
return lines.slice(0, PREVIEW_LINES);
|
|
1692
|
-
}
|
|
1693
|
-
async function runPreview(template, line, signal, hidden = []) {
|
|
1694
|
-
const proc = Bun.spawn(["sh", "-c", `exec 2>&1
|
|
1695
|
-
${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
|
|
1696
|
-
const stop = () => {
|
|
1697
|
-
try {
|
|
1698
|
-
process17.kill(-proc.pid, "SIGKILL");
|
|
1699
|
-
} catch {
|
|
1700
|
-
proc.kill();
|
|
1701
|
-
}
|
|
1702
|
-
};
|
|
1703
|
-
const timer = setTimeout(stop, PREVIEW_TIMEOUT_MS);
|
|
1704
|
-
const chunks = [];
|
|
1705
|
-
let size = 0;
|
|
1706
|
-
signal.addEventListener("abort", stop);
|
|
1707
|
-
try {
|
|
1708
|
-
for await (const chunk of proc.stdout) {
|
|
1709
|
-
chunks.push(chunk);
|
|
1710
|
-
size += chunk.length;
|
|
1711
|
-
if (size >= PREVIEW_BYTES) {
|
|
1712
|
-
stop();
|
|
1713
|
-
break;
|
|
1714
|
-
}
|
|
1715
|
-
}
|
|
1716
|
-
} finally {
|
|
1717
|
-
clearTimeout(timer);
|
|
1718
|
-
signal.removeEventListener("abort", stop);
|
|
1719
|
-
}
|
|
1720
|
-
return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
|
|
1721
|
-
}
|
|
1722
|
-
|
|
1723
|
-
// ../kit/src/picker/terminal.ts
|
|
1724
|
-
init_state();
|
|
1725
|
-
|
|
1726
|
-
// ../kit/src/picker/view.ts
|
|
1727
|
-
init_line();
|
|
1728
|
-
init_state();
|
|
1729
|
-
var MIN_HEIGHT = 4;
|
|
1730
|
-
var PREVIEW_MIN_COLUMNS = 80;
|
|
1731
|
-
var PREVIEW_MIN_ROWS = 10;
|
|
1732
|
-
var PREVIEW_SHARE = 0.4;
|
|
1733
|
-
var RESET2 = "\x1B[0m";
|
|
1734
|
-
var SEPARATOR = " \u2502 ";
|
|
1735
|
-
var HEIGHT = /^(\d+)(%?)$/;
|
|
1736
|
-
var DEFAULT_HEIGHT = { percent: 100 };
|
|
1737
|
-
function parseHeight(text) {
|
|
1738
|
-
const found = HEIGHT.exec(text);
|
|
1739
|
-
if (found === null || Number(found[1]) < 1)
|
|
1740
|
-
return;
|
|
1741
|
-
return found[2] === "%" ? { percent: Math.min(100, Number(found[1])) } : { lines: Number(found[1]) };
|
|
1742
|
-
}
|
|
1743
|
-
function layoutFor(size, height, previewing, position = "right") {
|
|
1744
|
-
const wanted = "lines" in height ? height.lines : Math.round(size.rows * height.percent / 100);
|
|
1745
|
-
const rows = Math.min(size.rows, Math.max(MIN_HEIGHT, wanted));
|
|
1746
|
-
if (position === "down") {
|
|
1747
|
-
const previewHeight = previewing && rows >= PREVIEW_MIN_ROWS ? Math.round(rows * PREVIEW_SHARE) : 0;
|
|
1748
|
-
return { height: rows, listHeight: rows - previewHeight, listWidth: size.columns, previewWidth: 0, previewHeight };
|
|
1749
|
-
}
|
|
1750
|
-
const split = previewing && size.columns >= PREVIEW_MIN_COLUMNS;
|
|
1751
|
-
const listWidth = split ? Math.floor(size.columns / 2) : size.columns;
|
|
1752
|
-
return { height: rows, listHeight: rows, listWidth, previewWidth: split ? size.columns - listWidth - SEPARATOR.length : 0, previewHeight: 0 };
|
|
1753
|
-
}
|
|
1754
|
-
function fit(text, width, plain, mark = plain, marked = new Set, styles) {
|
|
1755
|
-
const room = Bun.stringWidth(text) > width ? width - 1 : width;
|
|
1756
|
-
let out = "";
|
|
1757
|
-
let used = 0;
|
|
1758
|
-
let at = 0;
|
|
1759
|
-
for (const char of text) {
|
|
1760
|
-
const size = Bun.stringWidth(char);
|
|
1761
|
-
if (used + size > room)
|
|
1762
|
-
break;
|
|
1763
|
-
const style = marked.has(at) ? "" : styles?.[at] ?? "";
|
|
1764
|
-
out += style === "" ? (marked.has(at) ? mark : plain)(char) : `${style}${char}${RESET2}`;
|
|
1765
|
-
used += size;
|
|
1766
|
-
at += char.length;
|
|
1767
|
-
}
|
|
1768
|
-
if (room < width) {
|
|
1769
|
-
out += plain("\u2026");
|
|
1770
|
-
used += 1;
|
|
1771
|
-
}
|
|
1772
|
-
return { text: out, width: used };
|
|
1773
|
-
}
|
|
1774
|
-
var identity = (text) => text;
|
|
1775
|
-
function fitStyled(line, width, plain = identity) {
|
|
1776
|
-
const { text, styles } = styled(line);
|
|
1777
|
-
return fit(text, width, plain, plain, new Set, styles);
|
|
1778
|
-
}
|
|
1779
|
-
function queryShown(state, layout) {
|
|
1780
|
-
return visible({ text: state.query, caret: state.caret }, Math.max(1, layout.listWidth - Bun.stringWidth(state.prompt)));
|
|
1781
|
-
}
|
|
1782
|
-
function caretCell(state, layout) {
|
|
1783
|
-
const shown = queryShown(state, layout);
|
|
1784
|
-
return { column: Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + shown.column + 1), char: shown.at ?? " " };
|
|
1785
|
-
}
|
|
1786
|
-
function helpLines(state, layout, theme) {
|
|
1787
|
-
const lines = [
|
|
1788
|
-
"type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end, the wheel move",
|
|
1789
|
-
"left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word",
|
|
1790
|
-
"ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead",
|
|
1791
|
-
"ctrl-y puts back what they erased, ctrl-z suspends to the shell",
|
|
1792
|
-
`enter picks${state.multi ? ", tab marks" : ""}, esc or ctrl-c cancels`,
|
|
1793
|
-
...state.expect.length > 0 ? [`${state.expect.join(", ")} end the pick as this command asks`] : []
|
|
1794
|
-
];
|
|
1795
|
-
const title = "keys, any key closes this help";
|
|
1796
|
-
return [{ text: theme.accent(title), width: title.length }, ...lines.map((line) => fit(` ${line}`, layout.listWidth, theme.label))];
|
|
1797
|
-
}
|
|
1798
|
-
function listLines(state, layout, theme) {
|
|
1799
|
-
if (state.help)
|
|
1800
|
-
return helpLines(state, layout, theme);
|
|
1801
|
-
const header = state.header === "" ? [] : state.header.split(`
|
|
1802
|
-
`).map((line) => fitStyled(line, layout.listWidth, theme.label));
|
|
1803
|
-
const rows = Math.max(1, layout.listHeight - 2 - header.length);
|
|
1804
|
-
const prefixWidth = state.multi ? 4 : 2;
|
|
1805
|
-
const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
|
|
1806
|
-
const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
|
|
1807
|
-
const promptWidth = Bun.stringWidth(state.prompt);
|
|
1808
|
-
const shown = queryShown(state, layout);
|
|
1809
|
-
const text = `${shown.before}${shown.at ?? ""}${shown.after}`;
|
|
1810
|
-
const query = { text, width: Bun.stringWidth(text) };
|
|
1811
|
-
const place = state.matches.length > rows ? ` (${state.cursor + 1} of ${state.matches.length})` : "";
|
|
1812
|
-
const count = fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`, layout.listWidth, theme.label);
|
|
1813
|
-
const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
|
|
1814
|
-
if (state.matches.length === 0)
|
|
1815
|
-
lines.push(fit(" no match", layout.listWidth, theme.label));
|
|
1816
|
-
for (const [offset, match] of state.matches.slice(top, top + rows).entries()) {
|
|
1817
|
-
const current = top + offset === state.cursor;
|
|
1818
|
-
const pointer = current ? theme.accent("\u276F") : " ";
|
|
1819
|
-
const mark = state.multi ? `${state.marked.has(match.index) ? theme.id("\u25CF") : " "} ` : "";
|
|
1820
|
-
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]);
|
|
1821
|
-
lines.push({ text: `${pointer} ${mark}${text.text}`, width: prefixWidth + text.width });
|
|
1822
|
-
}
|
|
1823
|
-
return lines;
|
|
1824
|
-
}
|
|
1825
|
-
function render(state, layout, theme, preview = []) {
|
|
1826
|
-
const left = listLines(state, layout, theme);
|
|
1827
|
-
return Array.from({ length: layout.height }, (_, row) => {
|
|
1828
|
-
if (row >= layout.listHeight)
|
|
1829
|
-
return row === layout.listHeight ? theme.label("\u2500".repeat(layout.listWidth)) : fitStyled(preview[row - layout.listHeight - 1] ?? "", layout.listWidth).text;
|
|
1830
|
-
const list = left[row] ?? { text: "", width: 0 };
|
|
1831
|
-
if (layout.previewWidth === 0)
|
|
1832
|
-
return list.text;
|
|
1833
|
-
return `${list.text}${" ".repeat(Math.max(0, layout.listWidth - list.width))}${theme.label(SEPARATOR)}${fitStyled(preview[row] ?? "", layout.previewWidth).text}`;
|
|
1834
|
-
});
|
|
1835
|
-
}
|
|
1836
|
-
|
|
1837
|
-
// ../kit/src/picker/terminal.ts
|
|
1838
|
-
var PREVIEW_DELAY_MS = 120;
|
|
1839
|
-
var ESCAPE_WAIT_MS = 30;
|
|
1840
|
-
var OPEN = { ctrl: "open" };
|
|
1841
|
-
var HIDE_CURSOR = "\x1B[?25l";
|
|
1842
|
-
var SHOW_CURSOR = "\x1B[?25h";
|
|
1843
|
-
var REVERSE = "\x1B[7m";
|
|
1844
|
-
var REVERSE_END = "\x1B[27m";
|
|
1845
|
-
var PASTE_ON = "\x1B[?2004h";
|
|
1846
|
-
var PASTE_OFF = "\x1B[?2004l";
|
|
1847
|
-
var MOUSE_ON = "\x1B[?1000h\x1B[?1006h";
|
|
1848
|
-
var MOUSE_OFF = "\x1B[?1006l\x1B[?1000l";
|
|
1849
|
-
var CLEAR_BELOW = "\r\x1B[J";
|
|
1850
|
-
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
1851
|
-
function up(lines) {
|
|
1852
|
-
return lines > 0 ? `\x1B[${lines}A` : "";
|
|
1853
|
-
}
|
|
1854
|
-
function openTerminal() {
|
|
1855
|
-
let mode;
|
|
1856
|
-
try {
|
|
1857
|
-
mode = new tty.ReadStream(openSync("/dev/tty", "r"));
|
|
1858
|
-
} catch {
|
|
1859
|
-
return fail("no terminal to read keys from (/dev/tty)");
|
|
1860
|
-
}
|
|
1861
|
-
const keys = Bun.file("/dev/tty").stream().getReader();
|
|
1862
|
-
const out = process18.stderr;
|
|
1863
|
-
let resize;
|
|
1864
|
-
async function read(onChunk) {
|
|
1865
|
-
const decoder = new TextDecoder;
|
|
1866
|
-
try {
|
|
1867
|
-
for (let chunk = await keys.read();!chunk.done; chunk = await keys.read())
|
|
1868
|
-
onChunk(decoder.decode(chunk.value, { stream: true }));
|
|
1869
|
-
} catch {
|
|
1870
|
-
onChunk("\x03");
|
|
1871
|
-
}
|
|
1872
|
-
}
|
|
1873
|
-
return {
|
|
1874
|
-
get columns() {
|
|
1875
|
-
return out.columns || 80;
|
|
1876
|
-
},
|
|
1877
|
-
get rows() {
|
|
1878
|
-
return out.rows || 24;
|
|
1879
|
-
},
|
|
1880
|
-
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)) },
|
|
1881
|
-
write: (text) => void out.write(text),
|
|
1882
|
-
listen(onChunk, onResize) {
|
|
1883
|
-
resize = onResize;
|
|
1884
|
-
mode.setRawMode(true);
|
|
1885
|
-
out.on("resize", onResize);
|
|
1886
|
-
read(onChunk);
|
|
1887
|
-
},
|
|
1888
|
-
suspend() {
|
|
1889
|
-
mode.setRawMode(false);
|
|
1890
|
-
stopJob();
|
|
1891
|
-
mode.setRawMode(true);
|
|
1892
|
-
},
|
|
1893
|
-
close() {
|
|
1894
|
-
if (resize !== undefined)
|
|
1895
|
-
out.off("resize", resize);
|
|
1896
|
-
try {
|
|
1897
|
-
mode.setRawMode(false);
|
|
1898
|
-
} finally {
|
|
1899
|
-
mode.destroy();
|
|
1900
|
-
keys.cancel();
|
|
1901
|
-
}
|
|
1902
|
-
}
|
|
1903
|
-
};
|
|
1904
|
-
}
|
|
1905
|
-
async function select(rows, settings, terminal = openTerminal()) {
|
|
1906
|
-
const { theme } = terminal;
|
|
1907
|
-
let state = createState(rows, settings);
|
|
1908
|
-
let preview = [];
|
|
1909
|
-
let reserved = 0;
|
|
1910
|
-
let previewTimer;
|
|
1911
|
-
let previewing = new AbortController;
|
|
1912
|
-
let shownLine;
|
|
1913
|
-
let finish;
|
|
1914
|
-
let restored = false;
|
|
1915
|
-
let escape;
|
|
1916
|
-
function draw(clear = false) {
|
|
1917
|
-
if (restored)
|
|
1918
|
-
return;
|
|
1919
|
-
const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
|
|
1920
|
-
let frame = SYNC_START + HIDE_CURSOR;
|
|
1921
|
-
if (reserved !== layout.height || clear) {
|
|
1922
|
-
frame += CLEAR_BELOW + `
|
|
1923
|
-
`.repeat(layout.height - 1) + up(layout.height - 1);
|
|
1924
|
-
reserved = layout.height;
|
|
1925
|
-
}
|
|
1926
|
-
const caret = caretCell(state, layout);
|
|
1927
|
-
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}`;
|
|
1928
|
-
terminal.write(frame);
|
|
1929
|
-
}
|
|
1930
|
-
function pageSize() {
|
|
1931
|
-
const headerLines = state.header === "" ? 0 : state.header.split(`
|
|
1932
|
-
`).length;
|
|
1933
|
-
return Math.max(1, layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition).listHeight - 2 - headerLines);
|
|
1934
|
-
}
|
|
1935
|
-
function refreshPreview() {
|
|
1936
|
-
const at = highlighted(state);
|
|
1937
|
-
if (settings.preview === undefined || at === shownLine)
|
|
1938
|
-
return;
|
|
1939
|
-
shownLine = at;
|
|
1940
|
-
clearTimeout(previewTimer);
|
|
1941
|
-
previewing.abort();
|
|
1942
|
-
previewing = new AbortController;
|
|
1943
|
-
if (at === undefined) {
|
|
1944
|
-
preview = [];
|
|
1945
|
-
return;
|
|
1946
|
-
}
|
|
1947
|
-
const { signal } = previewing;
|
|
1948
|
-
const template = settings.preview;
|
|
1949
|
-
const row = state.rows[at];
|
|
1950
|
-
async function show() {
|
|
1951
|
-
const shown = typeof template === "string" ? await runPreview(template, row.cells.join(" "), signal, row.hidden) : await previewOf(template, row.hidden, signal);
|
|
1952
|
-
if (!signal.aborted) {
|
|
1953
|
-
preview = shown;
|
|
1954
|
-
draw();
|
|
1955
|
-
}
|
|
1956
|
-
}
|
|
1957
|
-
previewTimer = setTimeout(() => void show(), PREVIEW_DELAY_MS);
|
|
1958
|
-
}
|
|
1959
|
-
function restore() {
|
|
1960
|
-
if (restored)
|
|
1961
|
-
return;
|
|
1962
|
-
restored = true;
|
|
1963
|
-
clearTimeout(previewTimer);
|
|
1964
|
-
clearTimeout(escape);
|
|
1965
|
-
previewing.abort();
|
|
1966
|
-
terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
|
|
1967
|
-
terminal.close();
|
|
1968
|
-
}
|
|
1969
|
-
function suspend() {
|
|
1970
|
-
if (terminal.suspend === undefined)
|
|
1971
|
-
return;
|
|
1972
|
-
terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
|
|
1973
|
-
terminal.suspend();
|
|
1974
|
-
terminal.write(`${PASTE_ON}${MOUSE_ON}`);
|
|
1975
|
-
draw(true);
|
|
1976
|
-
}
|
|
1977
|
-
const stop = () => {
|
|
1978
|
-
state = { ...state, done: "cancel" };
|
|
1979
|
-
finish?.();
|
|
1980
|
-
};
|
|
1981
|
-
const paste = { active: false };
|
|
1982
|
-
const { reload } = settings;
|
|
1983
|
-
const pending = [];
|
|
1984
|
-
let busy = false;
|
|
1985
|
-
let draining = false;
|
|
1986
|
-
async function reloadRows() {
|
|
1987
|
-
if (reload === undefined)
|
|
1988
|
-
return;
|
|
1989
|
-
busy = true;
|
|
1990
|
-
state = { ...state, status: "reloading" };
|
|
1991
|
-
draw();
|
|
1992
|
-
try {
|
|
1993
|
-
const next = await reload.run();
|
|
1994
|
-
state = { ...withRows(state, next.rows, next.header), status: "" };
|
|
1995
|
-
shownLine = undefined;
|
|
1996
|
-
} catch (error) {
|
|
1997
|
-
state = { ...state, status: `reload failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
1998
|
-
} finally {
|
|
1999
|
-
busy = false;
|
|
2000
|
-
}
|
|
2001
|
-
}
|
|
2002
|
-
async function drain() {
|
|
2003
|
-
if (draining)
|
|
2004
|
-
return;
|
|
2005
|
-
draining = true;
|
|
2006
|
-
try {
|
|
2007
|
-
for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
|
|
2008
|
-
if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
|
|
2009
|
-
await reloadRows();
|
|
2010
|
-
else if (key === "suspend")
|
|
2011
|
-
suspend();
|
|
2012
|
-
else
|
|
2013
|
-
state = press({ ...state, page: pageSize() }, key);
|
|
2014
|
-
}
|
|
2015
|
-
} finally {
|
|
2016
|
-
draining = false;
|
|
2017
|
-
}
|
|
2018
|
-
if (state.done !== undefined) {
|
|
2019
|
-
finish?.();
|
|
2020
|
-
return;
|
|
2021
|
-
}
|
|
2022
|
-
refreshPreview();
|
|
2023
|
-
draw();
|
|
2024
|
-
}
|
|
2025
|
-
function onChunk(chunk) {
|
|
2026
|
-
if (escape !== undefined) {
|
|
2027
|
-
clearTimeout(escape);
|
|
2028
|
-
escape = undefined;
|
|
2029
|
-
chunk = `\x1B${chunk}`;
|
|
2030
|
-
} else if (chunk === "\x1B") {
|
|
2031
|
-
escape = setTimeout(() => {
|
|
2032
|
-
escape = undefined;
|
|
2033
|
-
takeKeys("\x1B");
|
|
2034
|
-
}, ESCAPE_WAIT_MS);
|
|
2035
|
-
return;
|
|
2036
|
-
}
|
|
2037
|
-
takeKeys(chunk);
|
|
2038
|
-
}
|
|
2039
|
-
function takeKeys(chunk) {
|
|
2040
|
-
const keys = parseKeys(chunk, paste, [...settings.expect ?? [], ...reload?.key === undefined ? [] : [reload.key]]);
|
|
2041
|
-
if (busy && keys.includes("cancel")) {
|
|
2042
|
-
stop();
|
|
2043
|
-
return;
|
|
2044
|
-
}
|
|
2045
|
-
pending.push(...keys);
|
|
2046
|
-
drain();
|
|
2047
|
-
}
|
|
2048
|
-
const ended = new Promise((resolve) => {
|
|
2049
|
-
finish = resolve;
|
|
2050
|
-
});
|
|
2051
|
-
process18.once("exit", restore);
|
|
2052
|
-
for (const signal of SIGNALS)
|
|
2053
|
-
process18.once(signal, stop);
|
|
2054
|
-
try {
|
|
2055
|
-
terminal.write(`${PASTE_ON}${MOUSE_ON}`);
|
|
2056
|
-
terminal.listen(onChunk, () => draw(true));
|
|
2057
|
-
refreshPreview();
|
|
2058
|
-
draw(true);
|
|
2059
|
-
if (reload?.onOpen === true) {
|
|
2060
|
-
pending.push(OPEN);
|
|
2061
|
-
drain();
|
|
2062
|
-
}
|
|
2063
|
-
await ended;
|
|
2064
|
-
} finally {
|
|
2065
|
-
for (const signal of SIGNALS)
|
|
2066
|
-
process18.off(signal, stop);
|
|
2067
|
-
process18.off("exit", restore);
|
|
2068
|
-
restore();
|
|
2069
|
-
}
|
|
2070
|
-
return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
|
|
2071
|
-
}
|
|
2072
|
-
async function previewOf(preview, hidden, signal) {
|
|
2073
|
-
try {
|
|
2074
|
-
return previewLines(await preview(hidden, signal));
|
|
2075
|
-
} catch (error) {
|
|
2076
|
-
return [error instanceof Error ? error.message : String(error)];
|
|
2077
|
-
}
|
|
2078
|
-
}
|
|
2079
|
-
|
|
2080
|
-
// ../kit/src/picker.ts
|
|
2081
|
-
init_score();
|
|
2082
|
-
|
|
2083
|
-
// src/fields.ts
|
|
2084
|
-
var INDEX = /^-?\d+$/;
|
|
2085
|
-
function splitFields(line, delimiter) {
|
|
2086
|
-
if (delimiter === undefined)
|
|
2087
|
-
return line.match(/\s*\S+\s*/g) ?? [];
|
|
2088
|
-
const fields = [];
|
|
2089
|
-
let from = 0;
|
|
2090
|
-
for (const match of line.matchAll(new RegExp(delimiter, `${delimiter.flags}g`))) {
|
|
2091
|
-
if (match[0] === "")
|
|
2092
|
-
continue;
|
|
2093
|
-
fields.push(line.slice(from, match.index + match[0].length));
|
|
2094
|
-
from = match.index + match[0].length;
|
|
2095
|
-
}
|
|
2096
|
-
fields.push(line.slice(from));
|
|
2097
|
-
return fields;
|
|
2098
|
-
}
|
|
2099
|
-
function parseFields(expression) {
|
|
2100
|
-
const spans = [];
|
|
2101
|
-
for (const part of expression.split(",")) {
|
|
2102
|
-
const dots = part.indexOf("..");
|
|
2103
|
-
const from = dots === -1 ? part : part.slice(0, dots);
|
|
2104
|
-
const to = dots === -1 ? from : part.slice(dots + 2);
|
|
2105
|
-
if (part === "0" || part === "" || from !== "" && !INDEX.test(from) || to !== "" && !INDEX.test(to))
|
|
2106
|
-
return;
|
|
2107
|
-
const resolve = (n, count) => n < 0 ? count + n : n - 1;
|
|
2108
|
-
spans.push((count) => {
|
|
2109
|
-
const first = from === "" ? 0 : resolve(Number(from), count);
|
|
2110
|
-
const last = to === "" ? count - 1 : resolve(Number(to), count);
|
|
2111
|
-
return Array.from({ length: Math.max(0, last - first + 1) }, (_, i) => first + i).filter((i) => i >= 0 && i < count);
|
|
2112
|
-
});
|
|
2113
|
-
}
|
|
2114
|
-
return (count) => spans.flatMap((span) => span(count));
|
|
2115
|
-
}
|
|
2116
|
-
function pickFields(line, select, delimiter) {
|
|
2117
|
-
const fields = splitFields(line, delimiter);
|
|
2118
|
-
return select(fields.length).map((i) => fields[i]).join("");
|
|
2119
|
-
}
|
|
2120
|
-
|
|
2121
|
-
// src/pick.ts
|
|
2122
|
-
var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
|
|
58
|
+
__kaynooo_cli_register() {
|
|
59
|
+
add-zsh-hook -d precmd __kaynooo_cli_register
|
|
60
|
+
(( $+functions[compdef] )) || { autoload -Uz compinit && compinit }
|
|
61
|
+
compdef __kaynooo_cli_complete $__kaynooo_cli_bins
|
|
62
|
+
}
|
|
63
|
+
autoload -Uz add-zsh-hook
|
|
64
|
+
add-zsh-hook precmd __kaynooo_cli_register
|
|
65
|
+
typeset -gaU __kaynooo_cli_bins
|
|
66
|
+
__kaynooo_cli_bins+=(${bins.join(" ")})
|
|
67
|
+
`}init_format();init_mode();import process12 from"process";var NOTIFY_AFTER_MS=1e4,CANCELLED=130;function base64(text){return Buffer.from(text).toString("base64")}function sanitizeOsc(text){return text.replaceAll(/[\x00-\x1F\x7F;]/g," ")}function wrapTmux(codes,env){return codes.map((code)=>env.TMUX===void 0||env.TMUX===""?code:`\x1BPtmux;${code.replaceAll("\x1B","\x1B\x1B")}\x1B\\`).join("")}function notification(title,body,env=process12.env){let program=env.TERM_PROGRAM??"",term=env.TERM??"";if(program==="WezTerm"||term.startsWith("foot")||term.startsWith("rxvt"))return wrapTmux([`\x1B]777;notify;${sanitizeOsc(title)};${sanitizeOsc(body)}\x1B\\`],env);if(program==="iTerm.app"||env.WT_SESSION!==void 0&&env.WT_SESSION!=="")return wrapTmux([`\x1B]9;${sanitizeOsc(title)}: ${sanitizeOsc(body)}\x1B\\`],env);let id=`kit${process12.pid}`,codes=[`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`,`\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];return wrapTmux(codes,env)}function notifyEnd(command,code,ms,{stream=process12.stderr,env=process12.env}={}){if(ms<NOTIFY_AFTER_MS||code===CANCELLED||outputMode(stream,env)!=="terminal")return;stream.write(notification(command,code===0?`done in ${formatDuration(ms)}`:`failed with exit ${code} after ${formatDuration(ms)}`,env))}init_style();init_text();import{appendFileSync,mkdirSync,readFileSync as readFileSync3,renameSync,statSync as statSync2,writeFileSync}from"fs";import{homedir as homedir3}from"os";import{dirname as dirname2,join as join4}from"path";import process13 from"process";init_user_config();var CLI_FOLDER="kaynooo-cli";init_user_config();var MAX_USAGE_BYTES=2097152,UNKNOWN_OPTION2=/unknown option '(--[a-z][a-z0-9-]*)[=']/,FLAG_NAME=/^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/,LONGEST_NAME=40,usageError;function noteUsageError(message){usageError=message}function stateHome(env=process13.env){return xdgFolder(env.XDG_STATE_HOME,join4(homedir3(),".local","state"))}function usagePath(env=process13.env){return join4(stateHome(env),CLI_FOLDER,"usage.jsonl")}function usageRecorded(env=process13.env){let off=env.KAYNOOO_CLI_NO_USAGE;return env.NODE_ENV!=="test"&&(off===void 0||off===""||off==="0")}function flagNames(argv){let end=argv.indexOf("--"),names=(end===-1?argv:argv.slice(0,end)).filter((word)=>word.startsWith("-")&&word!=="-").map((word)=>word.includes("=")?word.slice(0,word.indexOf("=")):word);return[...new Set(names)].filter((name)=>name.length<=LONGEST_NAME&&FLAG_NAME.test(name))}function usageEntry(bin,command,argv,code,{ms,now=new Date}={}){let unknown=code===2&&usageError!==void 0?UNKNOWN_OPTION2.exec(usageError)?.[1]:void 0;return usageError=void 0,{at:now.toISOString(),bin,...command===void 0?{}:{command},flags:flagNames(argv),code,...unknown===void 0?{}:{unknown},...ms===void 0?{}:{ms:Math.round(ms)}}}function trimUsage(path,maxBytes){let info=statSync2(path,{throwIfNoEntry:!1});if(info===void 0||info.size<=maxBytes)return;let lines=readFileSync3(path,"utf8").split(`
|
|
68
|
+
`).filter(Boolean),kept=`${lines.slice(Math.floor(lines.length/2)).join(`
|
|
69
|
+
`)}
|
|
70
|
+
`,temp=`${path}.${process13.pid}.tmp`;writeFileSync(temp,kept,{mode:384}),renameSync(temp,path)}function recordUsage(entry,env=process13.env,maxBytes=MAX_USAGE_BYTES){if(!usageRecorded(env))return;try{let path=usagePath(env);mkdirSync(dirname2(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
|
|
71
|
+
`,{mode:384}),trimUsage(path,maxBytes)}catch{}}var LEVEL_OPTIONS={...OUTPUT_OPTIONS,help:{type:"boolean",short:"h",description:"show this help"}},TOP_OPTIONS={...LEVEL_OPTIONS,version:{type:"boolean",short:"v",description:"print the version"},completions:{type:"string",choices:COMPLETION_SHELLS,description:"print the shell completion script"}};function printError(prefix,message,hint,cause){let colors=paint(process14.stderr),styled=takesControlCodes(process14.stderr),head=styled?`${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}`:`error: ${prefix}:`,under=(label,text,tint)=>text===void 0?"":`
|
|
72
|
+
${styled?tint(label):`${label}:`} ${text}`;console.error(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause){console.error(JSON.stringify({error:message,...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}function wantsJson(argv){let end=argv.indexOf("--");return(end===-1?argv:argv.slice(0,end)).includes("--json")}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let help=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?printJsonError:(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??help:void 0,cause),error instanceof Exit?error.code:1}var COMPLETE="__complete",FILES="__files__";async function completingOf(run){completion.active=!0;try{await run([])}catch(error){if(error instanceof Completing)return error}finally{completion.active=!1}return new Completing({})}function candidateLine(candidate){return typeof candidate==="string"?candidate:candidate.join("\t")}function positionalBeingTyped(before,{options,positionals}){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),typed=[],at=0;while(at<before.length){let word=before[at];if(word==="--"){typed.push(...before.slice(at+1));break}if(!word.startsWith("-"))typed.push(word);else if(takesValue(word))at++;at++}let last=positionals.at(-1);if(typed.length<positionals.length)return{name:positionals[typed.length],typed};return{name:last?.replace("]","").endsWith("...")===!0?last:void 0,typed}}async function leafCandidates(run,words){let completing=await completingOf(run);if((words.at(-1)??"").startsWith("-"))return Object.entries(completing.options).map(([name,option])=>option.description===void 0?`--${name}`:`--${name} ${option.description}`);let flag=words.at(-2),option=flag?.startsWith("-")===!0?Object.entries(completing.options).find(([name,{short}])=>flag===`--${name}`||flag===`-${short}`)?.[1]:void 0,{name,typed}=positionalBeingTyped(words.slice(0,-1),completing);if(option?.type==="string"){let values=option.choices===void 0?await option.candidates?.(typed):option.choices;return values===void 0?[FILES]:values.map(candidateLine)}let values=name===void 0?void 0:await completing.candidates[name]?.(typed);return values===void 0?[FILES]:values.map(candidateLine)}var COMPLETIONS="--completions";function flagValue([flag="",...rest]){return flag.includes("=")?[flag.slice(flag.indexOf("=")+1),...rest]:rest}function printCompletionScript(name,args){let shell=COMPLETION_SHELLS.find((each)=>each===args[0]);if(shell===void 0||args.length!==1)return printError(name,`${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`,`${name} ${COMPLETIONS} fish`),2;return console.log(completionScript(shell,[name]).trimEnd()),0}async function printCandidates(found){for(let line of await found)console.log(line);return 0}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname3(resolved);;dir=dirname3(dir)){try{let{version}=JSON.parse(readFileSync4(join5(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname3(dir)===dir)return"0.0.0"}}async function runMain({name,version,run,redact,usage},argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(leafCandidates(run,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(name,flagValue(argv));if(argv.length===1&&(argv[0]==="--version"||argv[0]==="-v"))return console.log(version??packageVersion()),0;let code,meta=!1,started=performance.now();heading.bin={name,version:()=>version??packageVersion()};try{code=await run(argv)}catch(error){meta=error instanceof HelpShown,code=reportThrown(name,error,redact,wantsJson(argv))}finally{heading.bin=void 0}if(notifyEnd(name,code,performance.now()-started),usage!==!1&&!meta)try{recordUsage(usageEntry(name,void 0,argv,code,{ms:performance.now()-started}))}catch{}return code}init_config();init_text();init_folders();init_format();init_args();init_args();init_mode();init_style();init_text();var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");init_style();init_text();init_theme();init_user_config();init_args();init_input();init_style();init_user_config();init_folders();init_state();init_args();init_job();init_redraw();init_style();import{openSync}from"fs";import process18 from"process";import tty from"tty";import process17 from"process";var SAFE_WORD=/^[\w@%+=:,./-]+$/;var SHELLS=new Set(["sh","bash","zsh","dash","ash","ksh","fish","csh","tcsh","nu","xonsh","elvish","pwsh","powershell"]),SCANNED_PROGRAMS=new Set(["su","runuser","flock"]),COMMAND_STRING_PROGRAMS=new Set([...SHELLS,...SCANNED_PROGRAMS]);function wrapper(short="",long=[],operands=0,runsString=!1){return{short,long,operands,runsString}}var RUNNER={...wrapper(),afterDashes:!0},WRAPPERS=new Map([["command",wrapper()],["builtin",wrapper()],["nohup",wrapper()],["setsid",wrapper()],["busybox",wrapper()],["exec",wrapper("a")],["time",wrapper("fo",["--format","--output"])],["env",wrapper("uCS",["--unset","--chdir","--split-string","--argv0"])],["sudo",wrapper("ughpCTrtUDR",["--user","--group","--host","--prompt","--close-from","--command-timeout","--role","--type","--other-user","--chdir","--chroot"])],["doas",wrapper("uC")],["timeout",wrapper("sk",["--signal","--kill-after"],1)],["nice",wrapper("n",["--adjustment"])],["ionice",wrapper("cnpPu",["--class","--classdata","--pid","--pgid","--uid"])],["stdbuf",wrapper("ioe",["--input","--output","--error"])],["chroot",wrapper("",["--userspec","--groups"],1)],["watch",wrapper("n",["--interval"],0,!0)],["flock",wrapper("wE",["--timeout","--conflict-exit-code"],1)],["parallel",wrapper("jnNSaIPlLdTsC",["--jobs","--max-args","--max-replace-args","--sshlogin","--arg-file","--delimiter","--colsep"],0,!0)],["unbuffer",wrapper()],["systemd-run",wrapper("puEMH",["--property","--unit","--description","--slice","--setenv","--machine","--host","--uid","--gid","--working-directory","--nice","--service-type"])],["xargs",wrapper("IndsEaPL",["--max-args","--max-procs","--max-chars","--delimiter","--arg-file","--eof","--max-lines","--process-slot-var"])],["strace",wrapper("abeEIoOpPsSuUX",["--trace","--output","--attach","--string-limit","--user","--env","--columns","--trace-path","--signal","--status","--summary-sort-by","--summary-columns","--const-print-style","--interruptible","--detach-on"])],["ltrace",wrapper("aeFlnopsuxX",["--output","--user","--library","--config","--align","--indent"])],["taskset",wrapper("",[],1)],["fakeroot",wrapper("lsib",["--lib","--faked"])],["sshpass",wrapper("pfdP")],["coproc",wrapper()],["proxychains",wrapper("f")],["proxychains4",wrapper("f")],["torsocks",wrapper("upaP",["--user","--pass","--address","--port"])],["chrt",wrapper("TPD",["--sched-runtime","--sched-period","--sched-deadline"],1)],["unshare",wrapper("SGRw",["--setuid","--setgid","--root","--wd","--map-user","--map-group","--map-users","--map-groups","--propagation","--setgroups"])],["nsenter",wrapper("tSG",["--target","--setuid","--setgid"])],["out",RUNNER],["slot",RUNNER],["waitfor",RUNNER],["base",RUNNER]]);function shellQuote(word){return SAFE_WORD.test(word)&&!word.startsWith("=")?word:`'${word.replaceAll("'","'\\''")}'`}var PREVIEW_BYTES=65536,PREVIEW_LINES=200,PREVIEW_TIMEOUT_MS=3000,PLACEHOLDER=/\{([1-9]\d*)?\}/g;function previewCommand(template,line,hidden=[]){return template.replace(PLACEHOLDER,(_,field)=>shellQuote(field===void 0?line:hidden[Number(field)-1]??""))}function previewLines(output){let lines=output.split(`
|
|
73
|
+
`);if(lines.at(-1)==="")lines.pop();return lines.slice(0,PREVIEW_LINES)}async function runPreview(template,line,signal,hidden=[]){let proc=Bun.spawn(["sh","-c",`exec 2>&1
|
|
74
|
+
${previewCommand(template,line,hidden)}`],{stdin:"ignore",stdout:"pipe",stderr:"ignore",detached:!0}),stop=()=>{try{process17.kill(-proc.pid,"SIGKILL")}catch{proc.kill()}},timer=setTimeout(stop,PREVIEW_TIMEOUT_MS),chunks=[],size=0;signal.addEventListener("abort",stop);try{for await(let chunk of proc.stdout)if(chunks.push(chunk),size+=chunk.length,size>=PREVIEW_BYTES){stop();break}}finally{clearTimeout(timer),signal.removeEventListener("abort",stop)}return signal.aborted?[]:previewLines(Buffer.concat(chunks).subarray(0,PREVIEW_BYTES).toString())}init_state();init_line();init_state();var MIN_HEIGHT=4,PREVIEW_MIN_COLUMNS=80,PREVIEW_MIN_ROWS=10,PREVIEW_SHARE=0.4,RESET2="\x1B[0m",SEPARATOR=" \u2502 ",HEIGHT=/^(\d+)(%?)$/,DEFAULT_HEIGHT={percent:100};function parseHeight(text){let found=HEIGHT.exec(text);if(found===null||Number(found[1])<1)return;return found[2]==="%"?{percent:Math.min(100,Number(found[1]))}:{lines:Number(found[1])}}function layoutFor(size,height,previewing,position="right"){let wanted="lines"in height?height.lines:Math.round(size.rows*height.percent/100),rows=Math.min(size.rows,Math.max(MIN_HEIGHT,wanted));if(position==="down"){let previewHeight=previewing&&rows>=PREVIEW_MIN_ROWS?Math.round(rows*PREVIEW_SHARE):0;return{height:rows,listHeight:rows-previewHeight,listWidth:size.columns,previewWidth:0,previewHeight}}let split=previewing&&size.columns>=PREVIEW_MIN_COLUMNS,listWidth=split?Math.floor(size.columns/2):size.columns;return{height:rows,listHeight:rows,listWidth,previewWidth:split?size.columns-listWidth-SEPARATOR.length:0,previewHeight:0}}function fit(text,width,plain,mark=plain,marked=new Set,styles){let room=Bun.stringWidth(text)>width?width-1:width,out="",used=0,at=0;for(let char of text){let size=Bun.stringWidth(char);if(used+size>room)break;let style=marked.has(at)?"":styles?.[at]??"";out+=style===""?(marked.has(at)?mark:plain)(char):`${style}${char}${RESET2}`,used+=size,at+=char.length}if(room<width)out+=plain("\u2026"),used+=1;return{text:out,width:used}}var identity=(text)=>text;function fitStyled(line,width,plain=identity){let{text,styles}=styled(line);return fit(text,width,plain,plain,new Set,styles)}function queryShown(state,layout){return visible({text:state.query,caret:state.caret},Math.max(1,layout.listWidth-Bun.stringWidth(state.prompt)))}function caretCell(state,layout){let shown=queryShown(state,layout);return{column:Math.min(layout.listWidth,Bun.stringWidth(state.prompt)+shown.column+1),char:shown.at??" "}}function helpLines(state,layout,theme){let lines=["type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end, the wheel move","left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word","ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead","ctrl-y puts back what they erased, ctrl-z suspends to the shell",`enter picks${state.multi?", tab marks":""}, esc or ctrl-c cancels`,...state.expect.length>0?[`${state.expect.join(", ")} end the pick as this command asks`]:[]],title="keys, any key closes this help";return[{text:theme.accent("keys, any key closes this help"),width:30},...lines.map((line)=>fit(` ${line}`,layout.listWidth,theme.label))]}function listLines(state,layout,theme){if(state.help)return helpLines(state,layout,theme);let header=state.header===""?[]:state.header.split(`
|
|
75
|
+
`).map((line)=>fitStyled(line,layout.listWidth,theme.label)),rows=Math.max(1,layout.listHeight-2-header.length),prefixWidth=state.multi?4:2,top=Math.max(0,Math.min(state.cursor-Math.floor(rows/2),state.matches.length-rows)),marks=(state.marked.size>0?` (${state.marked.size} marked)`:"")+(state.status===""?"":` ${state.status}`),promptWidth=Bun.stringWidth(state.prompt),shown=queryShown(state,layout),text=`${shown.before}${shown.at??""}${shown.after}`,query={text,width:Bun.stringWidth(text)},place=state.matches.length>rows?` (${state.cursor+1} of ${state.matches.length})`:"",count=fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`,layout.listWidth,theme.label),lines=[{text:theme.accent(state.prompt)+query.text,width:promptWidth+query.width},count,...header];if(state.matches.length===0)lines.push(fit(" no match",layout.listWidth,theme.label));for(let[offset,match]of state.matches.slice(top,top+rows).entries()){let current=top+offset===state.cursor,pointer=current?theme.accent("\u276F"):" ",mark=state.multi?`${state.marked.has(match.index)?theme.id("\u25CF"):" "} `:"",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]);lines.push({text:`${pointer} ${mark}${text.text}`,width:prefixWidth+text.width})}return lines}function render(state,layout,theme,preview=[]){let left=listLines(state,layout,theme);return Array.from({length:layout.height},(_,row)=>{if(row>=layout.listHeight)return row===layout.listHeight?theme.label("\u2500".repeat(layout.listWidth)):fitStyled(preview[row-layout.listHeight-1]??"",layout.listWidth).text;let list=left[row]??{text:"",width:0};if(layout.previewWidth===0)return list.text;return`${list.text}${" ".repeat(Math.max(0,layout.listWidth-list.width))}${theme.label(SEPARATOR)}${fitStyled(preview[row]??"",layout.previewWidth).text}`})}var PREVIEW_DELAY_MS=120,ESCAPE_WAIT_MS=30,OPEN={ctrl:"open"},HIDE_CURSOR="\x1B[?25l",SHOW_CURSOR="\x1B[?25h",REVERSE="\x1B[7m",REVERSE_END="\x1B[27m",PASTE_ON="\x1B[?2004h",PASTE_OFF="\x1B[?2004l",MOUSE_ON="\x1B[?1000h\x1B[?1006h",MOUSE_OFF="\x1B[?1006l\x1B[?1000l",CLEAR_BELOW="\r\x1B[J",SIGNALS=["SIGINT","SIGTERM","SIGHUP"];function up(lines){return lines>0?`\x1B[${lines}A`:""}function openTerminal(){let mode;try{mode=new tty.ReadStream(openSync("/dev/tty","r"))}catch{return fail("no terminal to read keys from (/dev/tty)")}let keys=Bun.file("/dev/tty").stream().getReader(),out=process18.stderr,resize;async function read(onChunk){let decoder=new TextDecoder;try{for(let chunk=await keys.read();!chunk.done;chunk=await keys.read())onChunk(decoder.decode(chunk.value,{stream:!0}))}catch{onChunk("\x03")}}return{get columns(){return out.columns||80},get rows(){return out.rows||24},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))},write:(text)=>void out.write(text),listen(onChunk,onResize){resize=onResize,mode.setRawMode(!0),out.on("resize",onResize),read(onChunk)},suspend(){mode.setRawMode(!1),stopJob(),mode.setRawMode(!0)},close(){if(resize!==void 0)out.off("resize",resize);try{mode.setRawMode(!1)}finally{mode.destroy(),keys.cancel()}}}}async function select(rows,settings,terminal=openTerminal()){let{theme}=terminal,state=createState(rows,settings),preview=[],reserved=0,previewTimer,previewing=new AbortController,shownLine,finish,restored=!1,escape;function draw(clear=!1){if(restored)return;let layout=layoutFor({columns:terminal.columns,rows:terminal.rows},settings.height,settings.preview!==void 0,settings.previewPosition),frame=SYNC_START+HIDE_CURSOR;if(reserved!==layout.height||clear)frame+=CLEAR_BELOW+`
|
|
76
|
+
`.repeat(layout.height-1)+up(layout.height-1),reserved=layout.height;let caret=caretCell(state,layout);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}`,terminal.write(frame)}function pageSize(){let headerLines=state.header===""?0:state.header.split(`
|
|
77
|
+
`).length;return Math.max(1,layoutFor({columns:terminal.columns,rows:terminal.rows},settings.height,settings.preview!==void 0,settings.previewPosition).listHeight-2-headerLines)}function refreshPreview(){let at=highlighted(state);if(settings.preview===void 0||at===shownLine)return;if(shownLine=at,clearTimeout(previewTimer),previewing.abort(),previewing=new AbortController,at===void 0){preview=[];return}let{signal}=previewing,template=settings.preview,row=state.rows[at];async function show(){let shown=typeof template==="string"?await runPreview(template,row.cells.join(" "),signal,row.hidden):await previewOf(template,row.hidden,signal);if(!signal.aborted)preview=shown,draw()}previewTimer=setTimeout(()=>void show(),PREVIEW_DELAY_MS)}function restore(){if(restored)return;restored=!0,clearTimeout(previewTimer),clearTimeout(escape),previewing.abort(),terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`),terminal.close()}function suspend(){if(terminal.suspend===void 0)return;terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`),terminal.suspend(),terminal.write(`${PASTE_ON}${MOUSE_ON}`),draw(!0)}let stop=()=>{state={...state,done:"cancel"},finish?.()},paste={active:!1},{reload}=settings,pending=[],busy=!1,draining=!1;async function reloadRows(){if(reload===void 0)return;busy=!0,state={...state,status:"reloading"},draw();try{let next=await reload.run();state={...withRows(state,next.rows,next.header),status:""},shownLine=void 0}catch(error){state={...state,status:`reload failed: ${error instanceof Error?error.message:String(error)}`}}finally{busy=!1}}async function drain(){if(draining)return;draining=!0;try{for(let key=pending.shift();key!==void 0&&state.done===void 0;key=pending.shift())if(key===OPEN||typeof key==="object"&&"ctrl"in key&&key.ctrl===reload?.key)await reloadRows();else if(key==="suspend")suspend();else state=press({...state,page:pageSize()},key)}finally{draining=!1}if(state.done!==void 0){finish?.();return}refreshPreview(),draw()}function onChunk(chunk){if(escape!==void 0)clearTimeout(escape),escape=void 0,chunk=`\x1B${chunk}`;else if(chunk==="\x1B"){escape=setTimeout(()=>{escape=void 0,takeKeys("\x1B")},ESCAPE_WAIT_MS);return}takeKeys(chunk)}function takeKeys(chunk){let keys=parseKeys(chunk,paste,[...settings.expect??[],...reload?.key===void 0?[]:[reload.key]]);if(busy&&keys.includes("cancel")){stop();return}pending.push(...keys),drain()}let ended=new Promise((resolve)=>{finish=resolve});process18.once("exit",restore);for(let signal of SIGNALS)process18.once(signal,stop);try{if(terminal.write(`${PASTE_ON}${MOUSE_ON}`),terminal.listen(onChunk,()=>draw(!0)),refreshPreview(),draw(!0),reload?.onOpen===!0)pending.push(OPEN),drain();await ended}finally{for(let signal of SIGNALS)process18.off(signal,stop);process18.off("exit",restore),restore()}return state.done==="accept"?{rows:chosen(state),key:state.key,query:state.query}:void 0}async function previewOf(preview,hidden,signal){try{return previewLines(await preview(hidden,signal))}catch(error){return[error instanceof Error?error.message:String(error)]}}init_score();var INDEX=/^-?\d+$/;function splitFields(line,delimiter){if(delimiter===void 0)return line.match(/\s*\S+\s*/g)??[];let fields=[],from=0;for(let match of line.matchAll(new RegExp(delimiter,`${delimiter.flags}g`))){if(match[0]==="")continue;fields.push(line.slice(from,match.index+match[0].length)),from=match.index+match[0].length}return fields.push(line.slice(from)),fields}function parseFields(expression){let spans=[];for(let part of expression.split(",")){let dots=part.indexOf(".."),from=dots===-1?part:part.slice(0,dots),to=dots===-1?from:part.slice(dots+2);if(part==="0"||part===""||from!==""&&!INDEX.test(from)||to!==""&&!INDEX.test(to))return;let resolve=(n,count)=>n<0?count+n:n-1;spans.push((count)=>{let first=from===""?0:resolve(Number(from),count),last=to===""?count-1:resolve(Number(to),count);return Array.from({length:Math.max(0,last-first+1)},(_,i)=>first+i).filter((i)=>i>=0&&i<count)})}return(count)=>spans.flatMap((span)=>span(count))}function pickFields(line,select,delimiter){let fields=splitFields(line,delimiter);return select(fields.length).map((i)=>fields[i]).join("")}var USAGE=`pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
|
|
2123
78
|
|
|
2124
79
|
Type to filter: the query matches as a subsequence, best matches first, and ctrl-/ or f1 shows the keys; enter picks, esc and ctrl-c cancel.
|
|
2125
80
|
The keys are read from the terminal and the selector is drawn on stderr, so \`pick\` in a pipe or a command substitution prints only the choice. With --multi, tab marks lines and enter prints them in input order.
|
|
2126
81
|
--delimiter, --nth and --with-nth split lines into fields in fzf's syntax, and the printed line is always the whole input line.
|
|
2127
|
-
Without a terminal on stderr it prints the best match, or every match with --multi
|
|
2128
|
-
|
|
2129
|
-
var OPTIONS = {
|
|
2130
|
-
multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
|
|
2131
|
-
prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
|
|
2132
|
-
query: { type: "string", short: "q", description: "the query to start with" },
|
|
2133
|
-
preview: { type: "string", description: "a command shown for the highlighted line, {} standing for it" },
|
|
2134
|
-
header: { type: "string", description: "a line of text shown above the list" },
|
|
2135
|
-
filter: { type: "string", short: "f", description: "print every line the query matches, best first, with no terminal" },
|
|
2136
|
-
"select-1": { type: "boolean", short: "1", description: "print the only match without opening the selector" },
|
|
2137
|
-
"exit-0": { type: "boolean", short: "0", description: "exit 1 at once when nothing matches" },
|
|
2138
|
-
delimiter: { type: "string", short: "d", description: "a regex splitting a line into fields (whitespace)" },
|
|
2139
|
-
nth: { type: "string", description: "the fields the query is matched against, 2, -1, 2.., 1..3, 1,3" },
|
|
2140
|
-
"with-nth": { type: "string", description: "the fields shown, the printed line stays whole" },
|
|
2141
|
-
read0: { type: "boolean", description: "lines on stdin end with NUL" },
|
|
2142
|
-
print0: { type: "boolean", description: "end each printed line with NUL" },
|
|
2143
|
-
height: { type: "string", description: "lines or a percentage of the terminal to draw in (100%)" },
|
|
2144
|
-
json: jsonOption("{picked: [lines]}, the choice or the marked lines in input order")
|
|
2145
|
-
};
|
|
2146
|
-
function print(chosen, lines, raw, json, end) {
|
|
2147
|
-
if (json)
|
|
2148
|
-
printJson({ picked: chosen.map((index) => lines[index]) });
|
|
2149
|
-
else
|
|
2150
|
-
process19.stdout.write(Buffer.concat(chosen.flatMap((index) => [raw[index], Buffer.from(end)])));
|
|
2151
|
-
}
|
|
2152
|
-
function splitBytes(bytes, separator) {
|
|
2153
|
-
const parts = [];
|
|
2154
|
-
let start = 0;
|
|
2155
|
-
for (let at = bytes.indexOf(separator);at !== -1; at = bytes.indexOf(separator, start)) {
|
|
2156
|
-
parts.push(bytes.subarray(start, at));
|
|
2157
|
-
start = at + 1;
|
|
2158
|
-
}
|
|
2159
|
-
parts.push(bytes.subarray(start));
|
|
2160
|
-
return parts.filter((part) => part.length > 0);
|
|
2161
|
-
}
|
|
2162
|
-
async function main(args) {
|
|
2163
|
-
const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, replaces: "fzf for a quick choice in a pipe, select in a shell script", examples: ["git branch --format='%(refname:short)' | pick", "ls | pick --multi --preview 'head -20 {}'", "git branch | pick --filter main # every match, best first, no terminal", "ps aux | pick --with-nth 2,11.. --nth 11.. # show some fields, search others"] });
|
|
2164
|
-
if (positionals.length > 0)
|
|
2165
|
-
badUsage("pick takes its lines on stdin, not as arguments");
|
|
2166
|
-
const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
|
|
2167
|
-
if (height === undefined)
|
|
2168
|
-
badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
|
|
2169
|
-
if (process19.stdin.isTTY)
|
|
2170
|
-
badUsage("pipe the lines to pick on stdin");
|
|
2171
|
-
const fieldsOf = (name) => {
|
|
2172
|
-
const text = values[name];
|
|
2173
|
-
if (text === undefined)
|
|
2174
|
-
return;
|
|
2175
|
-
return parseFields(text) ?? badUsage(`--${name} takes fields such as 2, -1, 2.., 1..3 or 1,3, not ${text}`);
|
|
2176
|
-
};
|
|
2177
|
-
const nth = fieldsOf("nth");
|
|
2178
|
-
const withNth = fieldsOf("with-nth");
|
|
2179
|
-
let delimiter;
|
|
2180
|
-
try {
|
|
2181
|
-
delimiter = values.delimiter === undefined ? undefined : new RegExp(values.delimiter);
|
|
2182
|
-
} catch {
|
|
2183
|
-
badUsage(`--delimiter is a regex, not ${values.delimiter}`);
|
|
2184
|
-
}
|
|
2185
|
-
const raw = splitBytes(await Bun.stdin.bytes(), values.read0 === true ? 0 : 10);
|
|
2186
|
-
const decoder = new TextDecoder;
|
|
2187
|
-
const lines = raw.map((bytes) => decoder.decode(bytes));
|
|
2188
|
-
if (lines.length === 0)
|
|
2189
|
-
fail("nothing to pick from", 1);
|
|
2190
|
-
const query = values.filter ?? values.query ?? "";
|
|
2191
|
-
const end = values.print0 === true ? "\x00" : `
|
|
2192
|
-
`;
|
|
2193
|
-
const json = values.json === true;
|
|
2194
|
-
const searched = lines.map((line) => nth === undefined ? line : pickFields(line, nth, delimiter));
|
|
2195
|
-
const matching = rank(query, searched).map(({ index }) => index);
|
|
2196
|
-
if (matching.length === 0 && (values["exit-0"] === true || values.filter !== undefined || !process19.stderr.isTTY))
|
|
2197
|
-
return 1;
|
|
2198
|
-
if (values.filter !== undefined || !process19.stderr.isTTY) {
|
|
2199
|
-
print(values.multi === true || values.filter !== undefined ? matching : matching.slice(0, 1), lines, raw, json, end);
|
|
2200
|
-
return 0;
|
|
2201
|
-
}
|
|
2202
|
-
if (values["select-1"] === true && matching.length === 1) {
|
|
2203
|
-
print(matching, lines, raw, json, end);
|
|
2204
|
-
return 0;
|
|
2205
|
-
}
|
|
2206
|
-
const rows = lines.map((line, index) => ({ hidden: [line], cells: [withNth === undefined ? line : pickFields(line, withNth, delimiter).trimEnd()], ...nth === undefined ? {} : { search: searched[index] } }));
|
|
2207
|
-
const picked = await select(rows, { multi: values.multi === true, prompt: values.prompt ?? "> ", query, height, preview: values.preview, header: values.header });
|
|
2208
|
-
if (picked === undefined)
|
|
2209
|
-
return 130;
|
|
2210
|
-
print(picked.rows.map((row) => rows.indexOf(row)), lines, raw, json, end);
|
|
2211
|
-
return 0;
|
|
2212
|
-
}
|
|
2213
|
-
process19.exitCode = await runMain({ name: "pick", run: main });
|
|
82
|
+
Without a terminal on stderr it prints the best match, or every match with --multi.`,EXITS=[[0,"it printed a choice"],[1,"nothing matches or there are no lines"],[2,"a usage error"],[130,"cancelled"]],OPTIONS={multi:{type:"boolean",short:"m",description:"tab marks several lines, enter prints them"},prompt:{type:"string",short:"p",description:"the prompt before the query (> )"},query:{type:"string",short:"q",description:"the query to start with"},preview:{type:"string",description:"a command shown for the highlighted line, {} standing for it"},header:{type:"string",description:"a line of text shown above the list"},filter:{type:"string",short:"f",description:"print every line the query matches, best first, with no terminal"},"select-1":{type:"boolean",short:"1",description:"print the only match without opening the selector"},"exit-0":{type:"boolean",short:"0",description:"exit 1 at once when nothing matches"},delimiter:{type:"string",short:"d",description:"a regex splitting a line into fields (whitespace)"},nth:{type:"string",description:"the fields the query is matched against, 2, -1, 2.., 1..3, 1,3"},"with-nth":{type:"string",description:"the fields shown, the printed line stays whole"},read0:{type:"boolean",description:"lines on stdin end with NUL"},print0:{type:"boolean",description:"end each printed line with NUL"},height:{type:"string",description:"lines or a percentage of the terminal to draw in (100%)"},json:jsonOption("{picked: [lines]}, the choice or the marked lines in input order")};function print(chosen,lines,raw,json,end){if(json)printJson({picked:chosen.map((index)=>lines[index])});else process19.stdout.write(Buffer.concat(chosen.flatMap((index)=>[raw[index],Buffer.from(end)])))}function splitBytes(bytes,separator){let parts=[],start=0;for(let at=bytes.indexOf(separator);at!==-1;at=bytes.indexOf(separator,start))parts.push(bytes.subarray(start,at)),start=at+1;return parts.push(bytes.subarray(start)),parts.filter((part)=>part.length>0)}async function main(args){let{values,positionals}=parse(args,USAGE,OPTIONS,{exits:EXITS,replaces:"fzf for a quick choice in a pipe, select in a shell script",examples:["git branch --format='%(refname:short)' | pick","ls | pick --multi --preview 'head -20 {}'","git branch | pick --filter main # every match, best first, no terminal","ps aux | pick --with-nth 2,11.. --nth 11.. # show some fields, search others"]});if(positionals.length>0)badUsage("pick takes its lines on stdin, not as arguments");let height=values.height===void 0?DEFAULT_HEIGHT:parseHeight(values.height);if(height===void 0)badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);if(process19.stdin.isTTY)badUsage("pipe the lines to pick on stdin");let fieldsOf=(name)=>{let text=values[name];if(text===void 0)return;return parseFields(text)??badUsage(`--${name} takes fields such as 2, -1, 2.., 1..3 or 1,3, not ${text}`)},nth=fieldsOf("nth"),withNth=fieldsOf("with-nth"),delimiter;try{delimiter=values.delimiter===void 0?void 0:new RegExp(values.delimiter)}catch{badUsage(`--delimiter is a regex, not ${values.delimiter}`)}let raw=splitBytes(await Bun.stdin.bytes(),values.read0===!0?0:10),decoder=new TextDecoder,lines=raw.map((bytes)=>decoder.decode(bytes));if(lines.length===0)fail("nothing to pick from",1);let query=values.filter??values.query??"",end=values.print0===!0?"\x00":`
|
|
83
|
+
`,json=values.json===!0,searched=lines.map((line)=>nth===void 0?line:pickFields(line,nth,delimiter)),matching=rank(query,searched).map(({index})=>index);if(matching.length===0&&(values["exit-0"]===!0||values.filter!==void 0||!process19.stderr.isTTY))return 1;if(values.filter!==void 0||!process19.stderr.isTTY)return print(values.multi===!0||values.filter!==void 0?matching:matching.slice(0,1),lines,raw,json,end),0;if(values["select-1"]===!0&&matching.length===1)return print(matching,lines,raw,json,end),0;let rows=lines.map((line,index)=>({hidden:[line],cells:[withNth===void 0?line:pickFields(line,withNth,delimiter).trimEnd()],...nth===void 0?{}:{search:searched[index]}})),picked=await select(rows,{multi:values.multi===!0,prompt:values.prompt??"> ",query,height,preview:values.preview,header:values.header});if(picked===void 0)return 130;return print(picked.rows.map((row)=>rows.indexOf(row)),lines,raw,json,end),0}process19.exitCode=await runMain({name:"pick",run:main});
|