@kaynooo/cli-probe 0.4.7 → 0.4.8

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.
Files changed (2) hide show
  1. package/dist/probe.js +38 -2022
  2. package/package.json +3 -6
package/dist/probe.js CHANGED
@@ -1,957 +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
- if (fn)
5
- try {
6
- res = fn(fn = 0);
7
- } catch (e) {
8
- err = [e];
9
- }
10
- if (err)
11
- throw err[0];
12
- return res;
13
- };
14
-
15
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
16
- function Ao(t, e, r = "...") {
17
- let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
18
- if (t.length <= e)
19
- return t;
20
- let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
21
- if (o && !Y.test(t[c.length] ?? " "))
22
- c = c.replace(Nt, "") || c;
23
- if (o)
24
- c = c.trimEnd();
25
- return s ? (c + n).slice(0, l) : c + n;
26
- }
27
- var N, Nt, Y, be, W;
28
- var init_chunk_rkhsft4a = __esm(() => {
29
- N = new Map;
30
- Nt = /\s+\S*$/;
31
- Y = /\s/;
32
- be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
33
- W = new Map;
34
- });
35
-
36
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
37
- var init_text = __esm(() => {
38
- init_chunk_rkhsft4a();
39
- });
40
-
41
- // ../kit/src/mode.ts
42
- import process2 from "process";
43
- function isSet(value) {
44
- return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
45
- }
46
- function outputMode(stream = process2.stdout, env = process2.env) {
47
- const chosen = env.KIT_MODE;
48
- if (chosen !== undefined && MODES.has(chosen))
49
- return chosen;
50
- if (AGENT_VARIABLES.some((name) => isSet(env[name])))
51
- return "agent";
52
- if (stream.isTTY === true)
53
- return "terminal";
54
- return isSet(env.CI) ? "ci" : "pipe";
55
- }
56
- var MODES, AGENT_VARIABLES;
57
- var init_mode = __esm(() => {
58
- MODES = new Set(["terminal", "ci", "agent", "pipe"]);
59
- AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
60
- });
61
-
62
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
63
- function b(r) {
64
- let e = r.startsWith("#") ? r.slice(1) : r;
65
- if (!G2.test(e))
66
- return [0, 0, 0];
67
- if (e.length === 3 || e.length === 4)
68
- return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
69
- if (e.length !== 6 && e.length !== 8)
70
- throw Error(`Invalid hex color length: ${e.length}`);
71
- return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
72
- }
73
- function C(r, e = globalThis.process?.env ?? {}) {
74
- if (e.FORCE_COLOR !== undefined)
75
- return h.has(e.FORCE_COLOR);
76
- if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
77
- return false;
78
- return r?.isTTY === true;
79
- }
80
- function f(r, e = []) {
81
- let l = "", n = "";
82
- for (let t = 0, i = e.length;t < i; t++)
83
- l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
84
- let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
85
- return new Proxy(c, { get(t, i) {
86
- let a = B[i];
87
- if (Array.isArray(a)) {
88
- let s = g.get(i);
89
- if (s === undefined)
90
- s = f(r, [...e, a]), g.set(i, s);
91
- return s;
92
- }
93
- if (typeof a === "function")
94
- return (...s) => {
95
- let y = `${i}:${s.join(",")}`, u = g.get(y);
96
- if (u === undefined) {
97
- if (g.size >= 64)
98
- g.clear();
99
- u = f(r, [...e, a(...s)]), g.set(y, u);
100
- }
101
- return u;
102
- };
103
- throw Error(`Unknown style: ${String(i)}`);
104
- } });
105
- }
106
- function Fe(r = {}) {
107
- return f(r);
108
- }
109
- var G2, B, h, o;
110
- var init_chunk_x450vn3m = __esm(() => {
111
- G2 = /^[a-f0-9]+$/i;
112
- 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") => {
113
- let [l, n, c] = b(r);
114
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
115
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
116
- h = new Set(["", "1", "2", "3", "true"]);
117
- o = Fe();
118
- });
119
-
120
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
121
- var init_colors = __esm(() => {
122
- init_chunk_x450vn3m();
123
- });
124
-
125
- // ../kit/src/config.ts
126
- import { existsSync } from "fs";
127
- import { dirname, join, resolve } from "path";
128
- import process3 from "process";
129
- function findUp(names, from = process3.cwd(), stop = () => false) {
130
- const wanted = typeof names === "string" ? [names] : names;
131
- for (let dir = resolve(from);; dir = dirname(dir)) {
132
- const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
133
- if (found !== undefined)
134
- return found;
135
- if (stop(dir) || dirname(dir) === dir)
136
- return;
137
- }
138
- }
139
- var init_config = __esm(() => {
140
- init_args();
141
- });
142
-
143
- // ../kit/src/user-config.ts
144
- import { homedir } from "os";
145
- import { isAbsolute, join as join2 } from "path";
146
- import process4 from "process";
147
- function xdgFolder(value, fallback) {
148
- return value !== undefined && isAbsolute(value) ? value : fallback;
149
- }
150
- function configBase(where = {}) {
151
- const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
152
- return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
153
- }
154
- function userConfigPath(bin, where = {}) {
155
- return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
156
- }
157
- var init_user_config = () => {};
158
-
159
- // ../kit/src/theme.ts
160
- import { existsSync as existsSync2, readFileSync, statSync } from "fs";
161
- import { homedir as homedir2 } from "os";
162
- import { join as join3, resolve as resolve2 } from "path";
163
- import process5 from "process";
164
- function isColorSpec(spec) {
165
- if (typeof spec === "number")
166
- return Number.isInteger(spec) && spec >= 0 && spec <= 255;
167
- return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
168
- }
169
- function cubeLevel(channel) {
170
- return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
171
- }
172
- function nearest256(hex) {
173
- const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
174
- const levels = rgb.map(cubeLevel);
175
- const cube = levels.map((level) => CUBE[level]);
176
- const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
177
- const greyValue = 8 + grey * 10;
178
- const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
179
- return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
180
- }
181
- function hasTrueColor(env) {
182
- return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
183
- }
184
- function tinted(colors, spec, env = process5.env) {
185
- if (typeof spec === "number")
186
- return colors.ansi256(spec);
187
- return spec.trim().split(SPACES).reduce((chain, token) => {
188
- if (HEX.test(token))
189
- return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
190
- return chain[token] ?? chain;
191
- }, colors);
192
- }
193
- function isRecord(value) {
194
- return typeof value === "object" && value !== null && !Array.isArray(value);
195
- }
196
- function readThemeFile(path, warn) {
197
- try {
198
- const stat = statSync(path, { throwIfNoEntry: false });
199
- if (stat === undefined)
200
- return;
201
- if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
202
- warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
203
- return;
204
- }
205
- const parsed = JSON.parse(readFileSync(path, "utf8"));
206
- if (isRecord(parsed))
207
- return parsed;
208
- warn(`${path} is not a JSON object, theme ignored`);
209
- } catch (error) {
210
- warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
211
- }
212
- return;
213
- }
214
- function applyPreset(theme, name, warn, where) {
215
- if (name === undefined)
216
- return;
217
- if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
218
- warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
219
- return;
220
- }
221
- const preset = PRESETS[name];
222
- Object.assign(theme.colors, preset.colors);
223
- Object.assign(theme.glyphs, preset.glyphs);
224
- if (preset.accents !== undefined)
225
- theme.accents = [...preset.accents];
226
- if (Object.hasOwn(preset, "gradient"))
227
- theme.gradient = preset.gradient;
228
- return name;
229
- }
230
- function applyFile(theme, file, where, warn) {
231
- if (isRecord(file.colors)) {
232
- for (const [key, value] of Object.entries(file.colors)) {
233
- if (!Object.hasOwn(DEFAULT.colors, key))
234
- warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
235
- else if (!isColorSpec(value))
236
- warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
237
- else
238
- theme.colors[key] = value;
239
- }
240
- }
241
- if (isRecord(file.glyphs)) {
242
- for (const [key, value] of Object.entries(file.glyphs)) {
243
- if (!Object.hasOwn(DEFAULT.glyphs, key))
244
- warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
245
- else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
246
- warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
247
- else
248
- theme.glyphs[key] = value;
249
- }
250
- }
251
- if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
252
- theme.accents = [...file.accents];
253
- else if (file.accents !== undefined)
254
- warn(`${where}: accents must be a non-empty list of colours`);
255
- if (file.gradient === null)
256
- theme.gradient = undefined;
257
- else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
258
- theme.gradient = [file.gradient[0], file.gradient[1]];
259
- else if (file.gradient !== undefined)
260
- warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
261
- if (isRecord(file.bins)) {
262
- for (const [bin, value] of Object.entries(file.bins)) {
263
- if (isColorSpec(value))
264
- theme.bins[bin] = value;
265
- else
266
- warn(`${where}: bin ${bin} has no valid colour`);
267
- }
268
- }
269
- }
270
- function endsWalk(home) {
271
- return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
272
- }
273
- function warnOnce(message) {
274
- if (warned.has(message))
275
- return;
276
- warned.add(message);
277
- console.error(`warning: theme ${message}`);
278
- }
279
- function isPath(chosen) {
280
- return chosen.includes("/") || chosen.endsWith(".json");
281
- }
282
- function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
283
- const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
284
- const sources = [];
285
- const chosen = env.KIT_THEME ?? "";
286
- const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
287
- if (isPath(chosen))
288
- wanted.push(resolve2(from, chosen));
289
- const files = [];
290
- for (const path of wanted) {
291
- const file = path === undefined ? undefined : readThemeFile(path, warn);
292
- if (path !== undefined && file !== undefined)
293
- files.push({ path, file });
294
- }
295
- let preset = "default";
296
- if (chosen !== "" && !isPath(chosen)) {
297
- preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
298
- } else {
299
- const named = files.findLast(({ file }) => file.preset !== undefined);
300
- if (named !== undefined)
301
- preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
302
- }
303
- for (const { path, file } of files) {
304
- applyFile(theme, file, path, warn);
305
- sources.push(path);
306
- }
307
- return { theme, sources, preset };
308
- }
309
- function activeTheme() {
310
- const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
311
- if (current === undefined || key !== currentKey) {
312
- current = loadTheme();
313
- currentKey = key;
314
- }
315
- return current;
316
- }
317
- var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
318
- var init_theme = __esm(() => {
319
- init_config();
320
- init_user_config();
321
- ENDS = new Map;
322
- DEFAULT = {
323
- 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" },
324
- 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" },
325
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
326
- bins: {},
327
- gradient: ["#c084fc", "#67e8f9"]
328
- };
329
- 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" };
330
- 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" };
331
- ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
332
- PRESETS = {
333
- default: {},
334
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
335
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
336
- ascii: { glyphs: ASCII }
337
- };
338
- 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"]);
339
- HEX = /^#[0-9a-f]{6}$/i;
340
- CONTROL = /\p{Cc}/u;
341
- MAX_FILE_BYTES = 64 * 1024;
342
- SPACES = /\s+/;
343
- CUBE = [0, 95, 135, 175, 215, 255];
344
- warned = new Set;
345
- });
346
-
347
- // ../kit/src/style.ts
348
- import process6 from "process";
349
- function takesControlCodes(stream, env = process6.env) {
350
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
351
- }
352
- function paint(stream, env = process6.env) {
353
- return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
354
- }
355
- function marked(mark, text, stream, detail, env = process6.env) {
356
- const colors = paint(stream, env);
357
- let head = MARK_WORDS[mark];
358
- if (takesControlCodes(stream, env)) {
359
- const { theme } = activeTheme();
360
- head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
361
- }
362
- return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
363
- }
364
- function role(name, stream, env = process6.env) {
365
- const colors = paint(stream, env);
366
- return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
367
- }
368
- var MARK_WORDS, STATUS_WORDS, STATUS_OF;
369
- var init_style = __esm(() => {
370
- init_colors();
371
- init_mode();
372
- init_theme();
373
- MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
374
- STATUS_WORDS = {
375
- passed: ["passed", "success", "succeeded", "ok"],
376
- failed: ["failed", "failure", "error", "errored"],
377
- running: ["running", "in_progress", "started", "holding"],
378
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
379
- skipped: ["skipped", "cancelled", "canceled", "manual"]
380
- };
381
- STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
382
- });
383
-
384
- // ../kit/src/format.ts
385
- import process7 from "process";
386
- function formatSeconds(total) {
387
- let rest = Math.max(0, Math.round(total));
388
- const amounts = UNITS.map(([unit, size]) => {
389
- const amount = Math.floor(rest / size);
390
- rest -= amount * size;
391
- return `${amount}${unit}`;
392
- });
393
- const first = amounts.findIndex((amount) => !amount.startsWith("0"));
394
- if (first === -1)
395
- return "0s";
396
- const next = amounts[first + 1];
397
- return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
398
- }
399
- function formatDuration(ms) {
400
- return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
401
- }
402
- function upTo(text, separator) {
403
- const end = text.indexOf(separator);
404
- return end === -1 ? text : text.slice(0, end);
405
- }
406
- function truncate(text, width) {
407
- return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
408
- }
409
- function textWidth(text) {
410
- return Bun.stringWidth(text);
411
- }
412
- function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
413
- const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
414
- if (outputMode(stream, env) === "agent")
415
- return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
416
- `);
417
- const widths = [];
418
- for (const row of cells) {
419
- for (const [index, cell] of row.entries())
420
- widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
421
- }
422
- const shown = fit === undefined ? cells : narrow(cells, widths, fit);
423
- const colors = paint(stream);
424
- const lines = shown.map((row) => row.map((cell, index) => {
425
- const width = widths[index] ?? 0;
426
- const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
427
- if (align[index] === "right")
428
- return `${gap}${cell}`;
429
- return index === row.length - 1 ? cell : `${cell}${gap}`;
430
- }).join(" ").trimEnd());
431
- const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
432
- return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
433
- `);
434
- }
435
- function narrow(rows, widths, limit) {
436
- const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
437
- const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
438
- const floor = 8;
439
- while (used() > limit) {
440
- let widest = -1;
441
- for (const [index, width] of widths.entries()) {
442
- if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
443
- widest = index;
444
- }
445
- if (widest === -1)
446
- break;
447
- widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
448
- }
449
- return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
450
- }
451
- function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
452
- return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
453
- }
454
- function printJson(value) {
455
- console.log(jsonText(value));
456
- }
457
- var UNITS, LINE_BREAKS, ESCAPE;
458
- var init_format = __esm(() => {
459
- init_text();
460
- init_mode();
461
- init_style();
462
- UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
463
- LINE_BREAKS = /\s*\n\s*/g;
464
- ESCAPE = String.fromCharCode(27);
465
- });
466
-
467
- // ../kit/src/help.ts
468
- import process8 from "process";
469
- function usageLine(usage, colors = paint(process8.stdout), { summary: withSummary = true } = {}) {
470
- const lines = usage.replace(USAGE_PREFIX, "").split(`
471
- `);
472
- const blank = lines.indexOf("");
473
- const synopses = blank === -1 ? lines : lines.slice(0, blank);
474
- const details = blank === -1 ? [] : lines.slice(blank + 1);
475
- const colon = synopses[0].indexOf(": ");
476
- const inline = synopses[0].slice(colon + 2);
477
- const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
478
- if (colon !== -1)
479
- synopses[0] = synopses[0].slice(0, colon);
480
- const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
481
- `)}`;
482
- const lead = summary === undefined || !withSummary ? [] : ["", colors.bold(prose(summary, colors))];
483
- const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
484
- return [head, ...lead, ...rest].join(`
485
- `);
486
- }
487
- function prose(line, colors) {
488
- if (colors.cyan("x") === "x")
489
- return line;
490
- return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
491
- }
492
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [], bin } = {}) {
493
- const { summary } = description(usage);
494
- const head = bin === undefined ? [usageLine(usage, colors)] : [`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary === "" ? "" : ` ${summary}`}`, "", usageLine(usage, colors, { summary: false })];
495
- return [...head, "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
496
- `);
497
- }
498
- function exitRows(exits, colors = paint(process8.stdout)) {
499
- if (exits.length === 0)
500
- return [];
501
- return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
502
- }
503
- function wantsHelpJson(env = process8.env) {
504
- return env.KIT_HELP === "json";
505
- }
506
- function description(usage, { examples = [], replaces, exits } = {}, options) {
507
- const lines = usage.replace(USAGE_PREFIX, "").split(`
508
- `);
509
- const first = lines[0];
510
- const colon = first.indexOf(": ");
511
- const prose = lines[lines.indexOf("") + 1] ?? "";
512
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
513
- return {
514
- synopsis: colon === -1 ? first : first.slice(0, colon),
515
- summary: colon === -1 ? fallback : first.slice(colon + 2),
516
- ...replaces === undefined ? {} : { replaces },
517
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
518
- ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
519
- ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
520
- };
521
- }
522
- function exampleRows(examples, colors = paint(process8.stdout)) {
523
- if (examples.length === 0 || outputMode() === "agent")
524
- return [];
525
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
526
- }
527
- function optionRows(options, colors = paint(process8.stdout)) {
528
- const rows = Object.entries(options).map(([name, option]) => {
529
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
530
- const choices = option.choices?.join("|");
531
- const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
532
- const named = inline ? `<${choices}>` : "<value>";
533
- const placeholder = option.optional === undefined ? named : `[${named}]`;
534
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
535
- const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
536
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
537
- });
538
- const width = Math.max(0, ...rows.map((row) => row.width));
539
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
540
- }
541
- var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
542
- var init_help = __esm(() => {
543
- init_mode();
544
- init_style();
545
- OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
546
- USAGE_PREFIX = /^usage:\s*/i;
547
- FULL_STOP = /\.$/;
548
- PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
549
- });
550
-
551
- // ../kit/src/text.ts
552
- function distance(a, b) {
553
- const left = [...a];
554
- const right = [...b];
555
- let before = [];
556
- let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
557
- for (const [i, x] of left.entries()) {
558
- const current = [i + 1];
559
- for (const [j, y] of right.entries()) {
560
- let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
561
- if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
562
- cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
563
- current.push(cost);
564
- }
565
- before = previous;
566
- previous = current;
567
- }
568
- return previous[right.length] ?? 0;
569
- }
570
- function closest(name, names) {
571
- const started = names.find((known) => known.startsWith(name));
572
- if (started !== undefined)
573
- return started;
574
- const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
575
- return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
576
- }
577
- var init_text2 = () => {};
578
-
579
- // ../kit/src/input.ts
580
- function durationMs(text, unit) {
581
- if (BARE_DURATION.test(text))
582
- return Number(text) * UNIT_MS[unit];
583
- if (!DURATION.test(text))
584
- return 0;
585
- let ms = 0;
586
- for (const [, amount, part] of text.matchAll(DURATION_PART))
587
- ms += Number(amount) * UNIT_MS[part];
588
- return ms;
589
- }
590
- function duration(value, name, fallback, unit = "s") {
591
- if (value === undefined)
592
- return fallback;
593
- const ms = durationMs(value.trim(), unit);
594
- if (ms < 1)
595
- badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
596
- return ms;
597
- }
598
- var BARE_DURATION, DURATION, DURATION_PART, UNIT_MS;
599
- var init_input = __esm(() => {
600
- init_args();
601
- BARE_DURATION = /^\d+(?:\.\d+)?$/;
602
- DURATION = /^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/;
603
- DURATION_PART = /(\d+(?:\.\d+)?)(ms|min|[smhd])/g;
604
- UNIT_MS = { ms: 1, s: 1000, m: 60000, min: 60000, h: 3600000, d: 86400000 };
605
- });
606
-
607
- // ../kit/src/args.ts
608
- import process9 from "process";
609
- import { parseArgs } from "util";
610
- function jsonOption(holds) {
611
- return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
612
- }
613
- function fail(message, code = 2, hint) {
614
- throw new Exit(message, code, hint);
615
- }
616
- function badUsage(message) {
617
- throw new UsageError(message);
618
- }
619
-
620
- class Completing {
621
- options;
622
- positionals;
623
- candidates;
624
- constructor(options, positionals = [], candidates = {}) {
625
- this.options = options;
626
- this.positionals = positionals;
627
- this.candidates = candidates;
628
- }
629
- }
630
- function applyOutput(color, plain, env = process9.env) {
631
- const when = plain === true ? "never" : color ?? "auto";
632
- if (when === "auto")
633
- return;
634
- if (when !== "always" && when !== "never")
635
- badUsage(`--color takes auto, always or never, not ${when}`);
636
- if (when === "always") {
637
- env.FORCE_COLOR = "1";
638
- delete env.NO_COLOR;
639
- } else {
640
- env.NO_COLOR = "1";
641
- delete env.FORCE_COLOR;
642
- }
643
- }
644
- function parse(args, usage, options, settings = {}) {
645
- const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
646
- const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
647
- const listing = listed(all, settings.allowNegative === true);
648
- if (completion.active)
649
- throw new Completing(listing, settings.positionals, settings.candidates);
650
- const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
651
- let parsed;
652
- try {
653
- parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
654
- } catch (error) {
655
- const message = parseError(error);
656
- throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
657
- }
658
- const values = parsed.values;
659
- applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
660
- if (values.help === true) {
661
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, { ...settings, bin: heading.bin }));
662
- throw new HelpShown;
663
- }
664
- checkChoices(parsed.values, all);
665
- checkConflicts(parsed.values, all);
666
- if (settings.positionals !== undefined)
667
- checkPositionals(parsed.positionals, settings.positionals);
668
- return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
669
- }
670
- function splitRest(args, passes) {
671
- const separator = passes ? args.indexOf("--") : -1;
672
- return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
673
- }
674
- function splitTrailing(args, options, count) {
675
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
676
- let seen = 0;
677
- if (count === 0)
678
- return { own: args, rest: undefined };
679
- for (let at = 0;at < args.length; at++) {
680
- const word = args[at];
681
- if (word === "--")
682
- break;
683
- if (word.startsWith("-")) {
684
- if (takesValue(word))
685
- at++;
686
- continue;
687
- }
688
- seen++;
689
- if (seen === count)
690
- return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
691
- }
692
- return { own: args, rest: undefined };
693
- }
694
- function listed(options, allowNegative) {
695
- if (!allowNegative)
696
- return options;
697
- return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
698
- if (option.type !== "boolean" || option.negative === undefined)
699
- return [[name, option]];
700
- return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
701
- }));
702
- }
703
- function withAliases(args, options) {
704
- const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
705
- if (named.size === 0)
706
- return args;
707
- const separator = args.indexOf("--");
708
- const own = separator === -1 ? args : args.slice(0, separator);
709
- return [...own.map((arg) => {
710
- const at = arg.indexOf("=");
711
- const current = named.get(at === -1 ? arg : arg.slice(0, at));
712
- return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
713
- }), ...separator === -1 ? [] : args.slice(separator)];
714
- }
715
- function withBare(args, options) {
716
- const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
717
- if (bare.size === 0)
718
- return args;
719
- const separator = args.indexOf("--");
720
- const own = separator === -1 ? args : args.slice(0, separator);
721
- return [...own.flatMap((arg, index) => {
722
- const optional = bare.get(arg);
723
- const next = own[index + 1];
724
- const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
725
- return optional === undefined || value ? [arg] : [arg, optional.bare];
726
- }), ...separator === -1 ? [] : args.slice(separator)];
727
- }
728
- function checkConflicts(values, options) {
729
- const given = (name) => values[name] !== undefined && values[name] !== false;
730
- for (const [name, { conflicts = [] }] of Object.entries(options)) {
731
- const other = given(name) ? conflicts.find(given) : undefined;
732
- if (other !== undefined)
733
- badUsage(`--${name} cannot be used with --${other}`);
734
- }
735
- }
736
- function checkChoices(values, options) {
737
- for (const [name, option] of Object.entries(options)) {
738
- if (option.choices === undefined)
739
- continue;
740
- const given = values[name];
741
- for (const value of Array.isArray(given) ? given : [given]) {
742
- if (typeof value === "string")
743
- oneOf(value, name, option.choices);
744
- }
745
- }
746
- }
747
- function oneOf(value, name, choices) {
748
- if (!choices.includes(value))
749
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
750
- return value;
751
- }
752
- function checkPositionals(given, names) {
753
- const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
754
- const required = names.filter((name) => !name.startsWith("[")).length;
755
- if (given.length < required)
756
- badUsage(`missing ${names[given.length]}`);
757
- if (!variadic && given.length > names.length)
758
- badUsage(`unexpected argument ${given[names.length]}`);
759
- }
760
- function joinDashValues(args, options) {
761
- const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
762
- const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
763
- const joined = [];
764
- for (let i = 0;i < args.length; i++) {
765
- const arg = args[i] ?? "";
766
- if (arg === "--")
767
- return [...joined, ...args.slice(i)];
768
- const name = longOf.get(arg);
769
- const next = args[i + 1];
770
- if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
771
- joined.push(`--${name}=${next}`);
772
- i++;
773
- } else {
774
- joined.push(arg);
775
- }
776
- }
777
- return joined;
778
- }
779
- function parseError(error) {
780
- const message = upTo(error instanceof Error ? error.message : String(error), ". ");
781
- return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
782
- }
783
- function nearestOption(message, options, allowNegative) {
784
- const typed = UNKNOWN_OPTION.exec(message)?.[1];
785
- if (typed === undefined)
786
- return;
787
- const word = typed.replace(DASHES, "");
788
- if (word.length < 2 && !typed.startsWith("--"))
789
- return;
790
- const known = Object.entries(options).flatMap(([name, option]) => [
791
- ...option.short === undefined ? [] : [`-${option.short}`],
792
- `--${name}`,
793
- ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
794
- ]);
795
- const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
796
- return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
797
- }
798
- var DASHES, EXIT, Exit, UsageError, HelpShown, completion, heading, OUTPUT_OPTIONS, UNKNOWN_OPTION;
799
- var init_args = __esm(() => {
800
- init_format();
801
- init_help();
802
- init_text2();
803
- init_help();
804
- init_input();
805
- DASHES = /^-+/;
806
- EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
807
- Exit = class Exit extends Error {
808
- code;
809
- hint;
810
- [EXIT] = true;
811
- constructor(message, code, hint) {
812
- super(message);
813
- this.code = code;
814
- this.hint = hint;
815
- }
816
- static [Symbol.hasInstance](value) {
817
- if (this !== Exit)
818
- return Function.prototype[Symbol.hasInstance].call(this, value);
819
- return typeof value === "object" && value !== null && value[EXIT] === true;
820
- }
821
- };
822
- UsageError = class UsageError extends Exit {
823
- constructor(message, hint) {
824
- super(message, 2, hint);
825
- }
826
- };
827
- HelpShown = class HelpShown extends Exit {
828
- constructor() {
829
- super("help shown", 0);
830
- }
831
- };
832
- completion = { active: false };
833
- heading = { bin: undefined };
834
- OUTPUT_OPTIONS = {
835
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
836
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
837
- };
838
- UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
839
- });
840
-
841
- // ../kit/src/folders.ts
842
- var SKIPPED_FOLDERS;
843
- var init_folders = __esm(() => {
844
- init_user_config();
845
- SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
846
- });
847
-
848
- // src/probe.ts
849
- import { isIP as isIP2 } from "net";
850
- import process16 from "process";
851
-
852
- // ../kit/src/index.ts
853
- init_args();
854
-
855
- // ../kit/src/argv.ts
856
- import { readFileSync as readFileSync2, realpathSync } from "fs";
857
- import { resolve as resolve3 } from "path";
858
- import process10 from "process";
859
- function commandLine() {
860
- try {
861
- return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
862
- } catch {
863
- return;
864
- }
865
- }
866
- function realPath(word) {
867
- try {
868
- return realpathSync(resolve3(word));
869
- } catch {
870
- return;
871
- }
872
- }
873
- function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
874
- const target = script === undefined ? undefined : realPath(script) ?? script;
875
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
876
- const after = at === -1 ? [] : cmdline.slice(at + 1);
877
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
878
- }
879
- // ../kit/src/chart.ts
880
- init_format();
881
- init_mode();
882
- init_style();
883
- init_theme();
884
- // ../kit/src/ci.ts
885
- init_args();
886
- init_format();
887
-
888
- // ../kit/src/progress.ts
889
- init_format();
890
-
891
- // ../kit/src/process.ts
892
- var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
893
-
894
- // ../kit/src/progress.ts
895
- init_style();
896
- init_theme();
897
- var ESC = String.fromCharCode(27);
898
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
899
- var RESET_STYLE = `${ESC}[0m`;
900
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
901
-
902
- // ../kit/src/ci.ts
903
- init_style();
904
-
905
- // ../kit/src/tool.ts
906
- init_format();
907
- // ../kit/src/cli.ts
908
- init_args();
909
- import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
910
- import { dirname as dirname3, join as join5 } from "path";
911
- import process14 from "process";
912
-
913
- // ../kit/src/askpass.ts
914
- import process11 from "process";
915
- var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
916
- async function askpassClient(argv) {
917
- const socketPath = process11.env[SOCKET_VARIABLE];
918
- if (socketPath === undefined)
919
- return;
920
- const request = { prompt: argv[0] ?? "", ...process11.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
921
- const { promise, resolve } = Promise.withResolvers();
922
- let received = "";
923
- try {
924
- await Bun.connect({
925
- unix: socketPath,
926
- socket: {
927
- open: (socket) => void socket.write(`${JSON.stringify(request)}
928
- `),
929
- data: (_, chunk) => {
930
- received += chunk.toString();
931
- },
932
- close: () => resolve(received),
933
- error: () => resolve("")
934
- }
935
- });
936
- } catch {
937
- return 1;
938
- }
939
- const reply = await promise;
940
- if (reply === "")
941
- return 1;
942
- const { answer } = JSON.parse(reply);
943
- if (request.notice === true)
944
- return 0;
945
- if (answer === undefined)
946
- return 1;
947
- process11.stdout.write(`${answer}
948
- `);
949
- return 0;
950
- }
951
-
952
- // ../kit/src/completions.ts
953
- var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
954
- var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
3
+ var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};function Ao(t,e,r="..."){let{suffix:n="...",includeSuffix:s=!1,wordBoundary:o=!1}=typeof r==="string"?{suffix:r}:r;if(t.length<=e)return t;let l=Math.max(0,e),c=t.substring(0,Math.max(0,s?l-n.length:l));if(o&&!Y.test(t[c.length]??" "))c=c.replace(Nt,"")||c;if(o)c=c.trimEnd();return s?(c+n).slice(0,l):c+n}var Nt,Y,be;var init_chunk_rkhsft4a=__esm(()=>{Nt=/\s+\S*$/,Y=/\s/;be=new Map(["\u20AC","","\u201A","\u0192","\u201E","\u2026","\u2020","\u2021","\u02C6","\u2030","\u0160","\u2039","\u0152","","\u017D","","","\u2018","\u2019","\u201C","\u201D","\u2022","\u2013","\u2014","\u02DC","\u2122","\u0161","\u203A","\u0153","","\u017E","\u0178"].map((t,e)=>[t,128+e]).filter(([t])=>t))});var init_text=__esm(()=>{init_chunk_rkhsft4a()});import process2 from"process";function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process2.stdout,env=process2.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}var MODES,AGENT_VARIABLES;var init_mode=__esm(()=>{MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"]});function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var G2,B,h,o;var init_chunk_x450vn3m=__esm(()=>{G2=/^[a-f0-9]+$/i;B={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49],rgb:(r,e,l,n="fg")=>[`${n==="fg"?38:48};2;${r};${e};${l}`,n==="fg"?39:49],hex:(r,e="fg")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);o=Fe()});var init_colors=__esm(()=>{init_chunk_x450vn3m()});import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process3 from"process";function findUp(names,from=process3.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}var init_config=__esm(()=>{init_args()});import{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 marked(mark,text,stream,detail,env=process6.env){let colors=paint(stream,env),head=MARK_WORDS[mark];if(takesControlCodes(stream,env)){let{theme}=activeTheme();head=tinted(colors.bold,theme.colors[mark],env)(theme.glyphs[mark])}return`${head} ${text}${detail===void 0?"":` ${colors.dim(detail)}`}`}function role(name,stream,env=process6.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}var MARK_WORDS,STATUS_WORDS,STATUS_OF;var init_style=__esm(()=>{init_colors();init_mode();init_theme();MARK_WORDS={ok:"ok:",warn:"warning:",problem:"error:",note:"note:",plan:"would:"};STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])))});function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}function cutToWidth(line,width,suffix=""){if(Bun.stringWidth(line)<=width)return line;let suffixWidth=suffix===""?0:Bun.stringWidth(suffix),room=Math.max(0,width-suffixWidth),kept="",index=0,styled=!1,linked=!1;while(index<line.length){ESCAPE_CODE.lastIndex=index;let escape=ESCAPE_CODE.exec(line);if(escape!==null){if(kept+=escape[0],escape[0].startsWith(`${ESC}]`))linked=!0;else styled=!0;index=ESCAPE_CODE.lastIndex;continue}let char=String.fromCodePoint(line.codePointAt(index)),columns=Bun.stringWidth(char);if(columns>room)break;kept+=char,room-=columns,index+=char.length}return`${kept}${styled?RESET_STYLE:""}${linked?CLOSE_LINK:""}${suffix}`}var ESC,ESCAPE_CODE,RESET_STYLE,CLOSE_LINK;var init_text2=__esm(()=>{ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`});import process7 from"process";function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function truncate(text,width){return Ao(text,width,{suffix:"\u2026",includeSuffix:!0})}function textWidth(text){return Bun.stringWidth(text)}function table(rows,{cellWidth,header=!1,align=[],fit,stream=process7.stdout,env=process7.env}={}){let cells=cellWidth===void 0?rows:rows.map((row)=>row.map((cell)=>truncate(cell.replaceAll(LINE_BREAKS," "),cellWidth)));if(outputMode(stream,env)==="agent")return cells.map((row)=>row.map((cell)=>Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g," ")).join("\t")).join(`
4
+ `);let widths=[];for(let row of cells)for(let[index,cell]of row.entries())widths[index]=Math.max(widths[index]??0,textWidth(cell));let shown=fit===void 0?cells:narrow(cells,widths,fit),colors=paint(stream,env),lines=shown.map((row)=>row.map((cell,index)=>{let width=widths[index]??0,gap=" ".repeat(Math.max(0,width-textWidth(cell)));if(align[index]==="right")return`${gap}${cell}`;return index===row.length-1?cell:`${cell}${gap}`}).join(" ").trimEnd()),rule=header&&takesControlCodes(stream,env)&&lines.length>1?[colors.dim(activeTheme().theme.glyphs.rule.repeat(Math.max(...lines.map(textWidth))))]:[];return lines.flatMap((line,index)=>header&&index===0?[colors.bold(line),...rule]:[line]).join(`
5
+ `)}function narrow(rows,widths,limit){let used=()=>widths.reduce((sum,width)=>sum+width,0)+2*Math.max(0,widths.length-1),floor=8;while(used()>limit){let widest=-1;for(let[index,width]of widths.entries())if(width>8&&width>(widths[widest]??0))widest=index;if(widest===-1)break;widths[widest]=Math.max(8,(widths[widest]??0)-(used()-limit))}return rows.map((row)=>row.map((cell,index)=>textWidth(cell)>(widths[index]??0)?cutToWidth(cell,widths[index]??0,"\u2026"):cell))}function jsonText(value,replacer,{stream=process7.stdout,env=process7.env}={}){return JSON.stringify(value,replacer,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}var UNITS,LINE_BREAKS;var init_format=__esm(()=>{init_text();init_mode();init_style();init_text2();init_theme();UNITS=[["d",86400],["h",3600],["m",60],["s",1]];LINE_BREAKS=/\s*\n\s*/g});import process8 from"process";function usageLine(usage,colors=paint(process8.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
6
+ `),blank=lines.indexOf(""),synopses=blank===-1?lines:lines.slice(0,blank),details=blank===-1?[]:lines.slice(blank+1),colon=synopses[0].indexOf(": "),inline=synopses[0].slice(colon+2),summary=colon===-1?details.shift():`${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;if(colon!==-1)synopses[0]=synopses[0].slice(0,colon);let head=`${colors.bold("Usage:")} ${synopses.map((line)=>line.replaceAll(OPTIONAL,(part)=>colors.dim(part))).join(`
7
+ `)}`,lead=summary===void 0||!withSummary?[]:["",colors.bold(prose(summary,colors))],rest=details.length===0?[]:["",...details.map((line)=>prose(line,colors))];return[head,...lead,...rest].join(`
8
+ `)}function prose(line,colors){if(colors.cyan("x")==="x")return line;return line.replaceAll(PROSE_MARKS,(match,code,flag)=>code===void 0?colors.cyan(flag??match):colors.bold(code))}function helpText(usage,options,colors=paint(process8.stdout),{examples=[],exits=[],bin,columns}={}){let{summary}=description(usage);return[...bin===void 0?[usageLine(usage,colors)]:[`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary===""?"":` ${summary}`}`,"",usageLine(usage,colors,{summary:!1})],"",colors.bold("Options:"),...optionRows(options,colors,columns),...exitRows(exits,colors),...exampleRows(examples,colors)].join(`
9
+ `)}function exitRows(exits,colors=paint(process8.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process8.env){return env.KIT_HELP==="json"}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
10
+ `),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}function exampleRows(examples,colors=paint(process8.stdout)){if(examples.length===0||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});function durationMs(text,unit){if(BARE_DURATION.test(text))return Number(text)*UNIT_MS[unit];if(!DURATION.test(text))return 0;let ms=0;for(let[,amount,part]of text.matchAll(DURATION_PART))ms+=Number(amount)*UNIT_MS[part];return ms}function duration(value,name,fallback,unit="s"){if(value===void 0)return fallback;let ms=durationMs(value.trim(),unit);if(ms<1)badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);return ms}var BARE_DURATION,DURATION,DURATION_PART,UNIT_MS;var init_input=__esm(()=>{init_args();BARE_DURATION=/^\d+(?:\.\d+)?$/,DURATION=/^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/,DURATION_PART=/(\d+(?:\.\d+)?)(ms|min|[smhd])/g,UNIT_MS={ms:1,s:1000,m:60000,min:60000,h:3600000,d:86400000}});import process9 from"process";import{parseArgs}from"util";function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}function badUsage(message){throw new UsageError(message)}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}function applyOutput(color,plain,env=process9.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),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_text2();init_help();init_input();DASHES=/^-+/;EXIT=Symbol.for("@kaynooo/cli-kit/Exit");Exit=class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}};UsageError=class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}};HelpShown=class HelpShown extends Exit{constructor(){super("help shown",0)}};completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};UNKNOWN_OPTION=/^unknown option '(-[^']+)'/});var init_folders=__esm(()=>{init_user_config()});import{isIP as isIP2}from"net";import process16 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_text2();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'
955
14
  set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
956
15
  set -l current (commandline -ct)
957
16
  for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
@@ -961,8 +20,10 @@ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_
961
20
  echo $line
962
21
  end
963
22
  end
964
- end`;
965
- var BASH_FUNCTION = `__kaynooo_cli_complete() {
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() {
966
27
  local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
967
28
  local -a lines
968
29
  COMPREPLY=()
@@ -975,8 +36,10 @@ var BASH_FUNCTION = `__kaynooo_cli_complete() {
975
36
  fi
976
37
  done
977
38
  COMPREPLY+=($(compgen -W "$words" -- "$cur"))
978
- }`;
979
- var ZSH_FUNCTION = `__kaynooo_cli_complete() {
39
+ }
40
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
41
+ `;return`${header}
42
+ __kaynooo_cli_complete() {
980
43
  local line
981
44
  local -a described plain
982
45
  for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
@@ -991,1075 +54,28 @@ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
991
54
  (( \${#described} )) && _describe -V value described
992
55
  (( \${#plain} )) && compadd -- "\${plain[@]}"
993
56
  return 0
994
- }`;
995
- function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
996
- if (shell === "fish")
997
- return `${header}
998
- ${FISH_FUNCTION}
999
- ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1000
- `).join("")}`;
1001
- if (shell === "bash")
1002
- return `${header}
1003
- ${BASH_FUNCTION}
1004
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
1005
- `;
1006
- return `${header}
1007
- ${ZSH_FUNCTION}
1008
- compdef __kaynooo_cli_complete ${bins.join(" ")}
1009
- `;
1010
- }
1011
-
1012
- // ../kit/src/notify.ts
1013
- init_format();
1014
- init_mode();
1015
- import process12 from "process";
1016
- var NOTIFY_AFTER_MS = 1e4;
1017
- var CANCELLED = 130;
1018
- function base64(text) {
1019
- return Buffer.from(text).toString("base64");
1020
- }
1021
- function notification(title, body, env = process12.env) {
1022
- const id = `kit${process12.pid}`;
1023
- 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\\`];
1024
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1025
- }
1026
- function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
1027
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1028
- return;
1029
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1030
- }
1031
-
1032
- // ../kit/src/cli.ts
1033
- init_style();
1034
- init_text2();
1035
-
1036
- // ../kit/src/usage.ts
1037
- import { appendFileSync, mkdirSync } from "fs";
1038
- import { homedir as homedir3 } from "os";
1039
- import { dirname as dirname2, join as join4 } from "path";
1040
- import process13 from "process";
1041
-
1042
- // ../kit/src/logs.ts
1043
- init_user_config();
1044
- var DAY_MS = 24 * 60 * 60 * 1000;
1045
- var CLI_FOLDER = "kaynooo-cli";
1046
-
1047
- // ../kit/src/usage.ts
1048
- init_user_config();
1049
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1050
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1051
- var LONGEST_NAME = 40;
1052
- var usageError;
1053
- function noteUsageError(message) {
1054
- usageError = message;
1055
- }
1056
- function stateHome(env = process13.env) {
1057
- return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
1058
- }
1059
- function usagePath(env = process13.env) {
1060
- return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1061
- }
1062
- function usageRecorded(env = process13.env) {
1063
- const off = env.KAYNOOO_CLI_NO_USAGE;
1064
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1065
- }
1066
- function flagNames(argv) {
1067
- const end = argv.indexOf("--");
1068
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1069
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1070
- }
1071
- function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1072
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1073
- usageError = undefined;
1074
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1075
- }
1076
- function recordUsage(entry, env = process13.env) {
1077
- if (!usageRecorded(env))
1078
- return;
1079
- try {
1080
- const path = usagePath(env);
1081
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1082
- appendFileSync(path, `${JSON.stringify(entry)}
1083
- `, { mode: 384 });
1084
- } catch {}
1085
- }
1086
-
1087
- // ../kit/src/cli.ts
1088
- var LEVEL_OPTIONS = {
1089
- ...OUTPUT_OPTIONS,
1090
- help: { type: "boolean", short: "h", description: "show this help" }
1091
- };
1092
- var TOP_OPTIONS = {
1093
- ...LEVEL_OPTIONS,
1094
- version: { type: "boolean", short: "v", description: "print the version" },
1095
- completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1096
- };
1097
- function printError(prefix, message, hint, cause) {
1098
- const colors = paint(process14.stderr);
1099
- const styled = takesControlCodes(process14.stderr);
1100
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1101
- const under = (label, text, tint) => text === undefined ? "" : `
1102
- ${styled ? tint(label) : `${label}:`} ${text}`;
1103
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1104
- }
1105
- function printJsonError(message, hint, cause) {
1106
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1107
- }
1108
- function wantsJson(argv) {
1109
- const end = argv.indexOf("--");
1110
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1111
- }
1112
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
1113
- if (error instanceof HelpShown)
1114
- return 0;
1115
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1116
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1117
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1118
- if (error instanceof Exit && error.code === 2)
1119
- noteUsageError(error.message);
1120
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1121
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1122
- return error instanceof Exit ? error.code : 1;
1123
- }
1124
- var COMPLETE = "__complete";
1125
- var FILES = "__files__";
1126
- async function completingOf(run) {
1127
- completion.active = true;
1128
- try {
1129
- await run([]);
1130
- } catch (error) {
1131
- if (error instanceof Completing)
1132
- return error;
1133
- } finally {
1134
- completion.active = false;
1135
- }
1136
- return new Completing({});
1137
- }
1138
- function candidateLine(candidate) {
1139
- return typeof candidate === "string" ? candidate : candidate.join("\t");
1140
- }
1141
- function positionalBeingTyped(before, { options, positionals }) {
1142
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1143
- const typed = [];
1144
- let at = 0;
1145
- while (at < before.length) {
1146
- const word = before[at];
1147
- if (word === "--") {
1148
- typed.push(...before.slice(at + 1));
1149
- break;
1150
- }
1151
- if (!word.startsWith("-"))
1152
- typed.push(word);
1153
- else if (takesValue(word))
1154
- at++;
1155
- at++;
1156
- }
1157
- const last = positionals.at(-1);
1158
- if (typed.length < positionals.length)
1159
- return { name: positionals[typed.length], typed };
1160
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1161
- }
1162
- async function leafCandidates(run, words) {
1163
- const completing = await completingOf(run);
1164
- if ((words.at(-1) ?? "").startsWith("-"))
1165
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1166
- const flag = words.at(-2);
1167
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1168
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1169
- if (option?.type === "string") {
1170
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1171
- return values === undefined ? [FILES] : values.map(candidateLine);
1172
- }
1173
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1174
- return values === undefined ? [FILES] : values.map(candidateLine);
1175
57
  }
1176
- var COMPLETIONS = "--completions";
1177
- function flagValue([flag = "", ...rest]) {
1178
- return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1179
- }
1180
- function printCompletionScript(name, args) {
1181
- const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1182
- if (shell === undefined || args.length !== 1) {
1183
- printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1184
- return 2;
1185
- }
1186
- console.log(completionScript(shell, [name]).trimEnd());
1187
- return 0;
1188
- }
1189
- async function printCandidates(found) {
1190
- for (const line of await found)
1191
- console.log(line);
1192
- return 0;
1193
- }
1194
- function packageVersion(entry = Bun.main) {
1195
- let resolved = entry;
1196
- try {
1197
- resolved = realpathSync2(entry);
1198
- } catch {}
1199
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1200
- try {
1201
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1202
- if (typeof version === "string")
1203
- return version;
1204
- } catch {}
1205
- if (dirname3(dir) === dir)
1206
- return "0.0.0";
1207
- }
1208
- }
1209
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1210
- const answered = await askpassClient(argv);
1211
- if (answered !== undefined)
1212
- return answered;
1213
- if (argv[0] === COMPLETE)
1214
- return printCandidates(leafCandidates(run, argv.slice(1)));
1215
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1216
- return printCompletionScript(name, flagValue(argv));
1217
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1218
- console.log(version ?? packageVersion());
1219
- return 0;
1220
- }
1221
- let code;
1222
- const started = performance.now();
1223
- heading.bin = { name, version: () => version ?? packageVersion() };
1224
- try {
1225
- code = await run(argv);
1226
- } catch (error) {
1227
- code = reportThrown(name, error, redact, wantsJson(argv));
1228
- } finally {
1229
- heading.bin = undefined;
1230
- }
1231
- notifyEnd(name, code, performance.now() - started);
1232
- if (usage !== false) {
1233
- try {
1234
- recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
1235
- } catch {}
1236
- }
1237
- return code;
1238
- }
1239
-
1240
- // ../kit/src/index.ts
1241
- init_config();
1242
-
1243
- // ../kit/src/excerpt.ts
1244
- init_text2();
1245
-
1246
- // ../kit/src/index.ts
1247
- init_folders();
1248
- init_format();
1249
-
1250
- // ../kit/src/git.ts
1251
- init_args();
1252
- // ../kit/src/limit.ts
1253
- init_args();
1254
-
1255
- // ../kit/src/index.ts
1256
- init_mode();
1257
-
1258
- // ../kit/src/report.ts
1259
- init_style();
1260
- init_text2();
1261
- // ../kit/src/secrets.ts
1262
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1263
- var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1264
- // ../kit/src/sessions.ts
1265
- var {Glob } = globalThis.Bun;
1266
- var SESSION_FILES = new Glob("*.json");
1267
- var ACCOUNT_DIRS = new Glob("*/sessions");
1268
-
1269
- // ../kit/src/index.ts
1270
- init_style();
1271
- init_text2();
1272
- init_theme();
1273
- init_user_config();
1274
-
1275
- // ../kit/src/watch.ts
1276
- init_args();
1277
- init_input();
1278
- init_style();
1279
- // ../kit/src/workspace-root.ts
1280
- init_user_config();
1281
- // src/analyze.ts
1282
- var SOON_DAYS = 14;
1283
- var MAX_HOPS = 10;
1284
- var SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
1285
- var SEPARATOR = `
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_text2();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_text2();init_folders();init_format();init_args();init_args();init_mode();init_style();init_text2();var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");init_style();init_text2();init_theme();init_user_config();init_args();init_input();init_style();init_user_config();var MAX_HOPS=10,SCHEME=/^[a-z][a-z0-9+.-]*:\/\//i;var CERT_PREFIX=/^(?:DNS|IP Address|IP|email|URI):/,CACHE_NODE=/^cache-/i,ALT_VALUE=/=.*$/;function parseTarget(input){let bare=!SCHEME.test(input);try{let url=new URL(bare?`https://${input}`:input);return url.protocol!=="http:"&&url.protocol!=="https:"||url.hostname===""?void 0:{url,bare}}catch{return}}var WRITE_OUT=`%{json}
1286
73
  ---HEADERS---
1287
- `;
1288
- var CERT_PREFIX = /^(?:DNS|IP Address|IP|email|URI):/;
1289
- var CACHE_NODE = /^cache-/i;
1290
- var ALT_VALUE = /=.*$/;
1291
- function parseTarget(input) {
1292
- const bare = !SCHEME.test(input);
1293
- try {
1294
- const url = new URL(bare ? `https://${input}` : input);
1295
- return url.protocol !== "http:" && url.protocol !== "https:" || url.hostname === "" ? undefined : { url, bare };
1296
- } catch {
1297
- return;
1298
- }
1299
- }
1300
- var WRITE_OUT = `%{json}${SEPARATOR}%{header_json}`;
1301
- function seconds(value) {
1302
- return typeof value === "number" ? value : 0;
1303
- }
1304
- function ms(value) {
1305
- return Math.round(value * 1000);
1306
- }
1307
- function timingsOf(info) {
1308
- const lookup = seconds(info.time_namelookup);
1309
- const connect = seconds(info.time_connect);
1310
- const secure = seconds(info.time_appconnect);
1311
- const ready = secure > 0 ? secure : connect;
1312
- const first = seconds(info.time_starttransfer);
1313
- return {
1314
- dns: ms(lookup),
1315
- connect: ms(Math.max(0, connect - lookup)),
1316
- tls: secure > 0 ? ms(Math.max(0, secure - connect)) : 0,
1317
- firstByte: ms(Math.max(0, first - ready)),
1318
- total: ms(seconds(info.time_total))
1319
- };
1320
- }
1321
- function headersOf(json) {
1322
- const headers = {};
1323
- try {
1324
- const parsed = JSON.parse(json);
1325
- if (typeof parsed !== "object" || parsed === null)
1326
- return headers;
1327
- for (const [name, value] of Object.entries(parsed)) {
1328
- const values = Array.isArray(value) ? value.map(String) : [String(value)];
1329
- headers[name.toLowerCase()] = values.join(", ");
1330
- }
1331
- } catch {}
1332
- return headers;
1333
- }
1334
- function parseCurl(stdout) {
1335
- const at = stdout.indexOf(SEPARATOR);
1336
- const infoText = at === -1 ? stdout : stdout.slice(0, at);
1337
- let info;
1338
- try {
1339
- info = JSON.parse(infoText);
1340
- } catch {
1341
- return { exitcode: 1, errormsg: "curl printed no result" };
1342
- }
1343
- const exitcode = typeof info.exitcode === "number" ? info.exitcode : 1;
1344
- const errormsg = typeof info.errormsg === "string" ? info.errormsg : null;
1345
- const status = typeof info.response_code === "number" ? info.response_code : 0;
1346
- if (exitcode !== 0 || status === 0)
1347
- return { exitcode: exitcode === 0 ? 1 : exitcode, errormsg: errormsg ?? "no response" };
1348
- const headers = headersOf(at === -1 ? "" : stdout.slice(at + SEPARATOR.length));
1349
- const hop = {
1350
- url: String(info.url_effective ?? info.url ?? ""),
1351
- status,
1352
- version: String(info.http_version ?? ""),
1353
- timings: timingsOf(info),
1354
- headers
1355
- };
1356
- if (typeof info.redirect_url === "string" && info.redirect_url !== "")
1357
- hop.location = info.redirect_url;
1358
- else if (headers.location !== undefined)
1359
- hop.location = headers.location;
1360
- if (typeof info.remote_ip === "string" && info.remote_ip !== "")
1361
- hop.remoteIp = info.remote_ip;
1362
- return { exitcode, errormsg, hop };
1363
- }
1364
- function isRedirect(status) {
1365
- return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
1366
- }
1367
- function nextUrl(current, location) {
1368
- try {
1369
- const next = new URL(location, current);
1370
- return next.protocol === "http:" || next.protocol === "https:" ? next.href : undefined;
1371
- } catch {
1372
- return;
1373
- }
1374
- }
1375
- function versionLabel(version) {
1376
- return version === "" ? "unknown" : `HTTP/${version}`;
1377
- }
1378
- function altSvcProtocols(altSvc) {
1379
- if (altSvc === undefined || altSvc.trim() === "clear")
1380
- return [];
1381
- const ids = altSvc.split(",").map((entry) => entry.trim().replace(ALT_VALUE, "")).filter((id) => id !== "");
1382
- return [...new Set(ids)];
1383
- }
1384
- function offersOf(options) {
1385
- const altSvc = altSvcProtocols(options.altSvc);
1386
- return {
1387
- h2: options.alpn === "h2" || options.version === "2" || options.version === "3",
1388
- h3: options.version === "3" || altSvc.some((id) => id === "h3" || id.startsWith("h3-")),
1389
- altSvc
1390
- };
1391
- }
1392
- var KNOWN_SERVERS = [
1393
- [/cloudflare/i, "Cloudflare"],
1394
- [/cloudfront/i, "CloudFront"],
1395
- [/akamai/i, "Akamai"],
1396
- [/fastly/i, "Fastly"],
1397
- [/vercel/i, "Vercel"],
1398
- [/netlify/i, "Netlify"],
1399
- [/bunnycdn/i, "BunnyCDN"],
1400
- [/^(?:gws|esf|gse)$|google frontend/i, "Google"]
1401
- ];
1402
- function cdnHint(headers) {
1403
- const served = headers["x-served-by"];
1404
- if (headers["cf-ray"] !== undefined)
1405
- return "Cloudflare (cf-ray)";
1406
- if (served !== undefined)
1407
- return `${CACHE_NODE.test(served) ? "Fastly" : served} (x-served-by)`;
1408
- if (headers["x-amz-cf-id"] !== undefined)
1409
- return "CloudFront (x-amz-cf-id)";
1410
- if (headers["x-vercel-id"] !== undefined)
1411
- return "Vercel (x-vercel-id)";
1412
- if (headers.via !== undefined)
1413
- return `${headers.via} (via)`;
1414
- if (headers["x-cache"] !== undefined)
1415
- return `${headers["x-cache"]} (x-cache)`;
1416
- const server = headers.server;
1417
- if (server !== undefined) {
1418
- const known = KNOWN_SERVERS.find(([pattern]) => pattern.test(server));
1419
- if (known !== undefined)
1420
- return `${known[1]} (server)`;
1421
- }
1422
- return;
1423
- }
1424
- var WORTH_KNOWING = ["server", "content-type", "content-encoding", "cache-control", "strict-transport-security"];
1425
- function worthKnowing(headers) {
1426
- const kept = {};
1427
- for (const name of WORTH_KNOWING) {
1428
- const value = headers[name];
1429
- if (value !== undefined)
1430
- kept[name] = value;
1431
- }
1432
- return kept;
1433
- }
1434
- function field(value) {
1435
- if (typeof value === "string")
1436
- return value;
1437
- return Array.isArray(value) ? value.join(", ") : "";
1438
- }
1439
- function nameOf(entry) {
1440
- if (entry === undefined)
1441
- return "";
1442
- const common = field(entry.CN);
1443
- const organization = field(entry.O);
1444
- if (common !== "" && organization !== "" && common !== organization)
1445
- return `${common} (${organization})`;
1446
- return common === "" ? organization : common;
1447
- }
1448
- function namesOf(subjectaltname) {
1449
- if (subjectaltname === undefined)
1450
- return [];
1451
- return subjectaltname.split(",").map((entry) => entry.trim().replace(CERT_PREFIX, "")).filter((name) => name !== "");
1452
- }
1453
- function daysLeftLabel(days) {
1454
- return `${days} ${days === 1 ? "day" : "days"} left`;
1455
- }
1456
- function certInfo(raw, now = Date.now()) {
1457
- if (raw.valid_to === undefined || raw.valid_from === undefined)
1458
- return;
1459
- const end = Date.parse(raw.valid_to);
1460
- const start = Date.parse(raw.valid_from);
1461
- if (Number.isNaN(end) || Number.isNaN(start))
1462
- return;
1463
- return {
1464
- subject: nameOf(raw.subject),
1465
- issuer: nameOf(raw.issuer),
1466
- names: namesOf(raw.subjectaltname),
1467
- validFrom: new Date(start).toISOString(),
1468
- validTo: new Date(end).toISOString(),
1469
- daysLeft: Math.floor((end - now) / 86400000)
1470
- };
1471
- }
1472
- function httpRedirectOf(hop) {
1473
- if (hop === undefined)
1474
- return;
1475
- const next = hop.location === undefined ? undefined : nextUrl(hop.url, hop.location);
1476
- const redirect = { status: hop.status, toHttps: isRedirect(hop.status) && next !== undefined && new URL(next).protocol === "https:" };
1477
- if (hop.location !== undefined)
1478
- redirect.location = hop.location;
1479
- return redirect;
1480
- }
1481
- function wantsHttpCheck(target) {
1482
- return target.url.protocol === "https:" && target.url.port === "";
1483
- }
1484
- function warningsOf(input) {
1485
- const warnings = [];
1486
- const { cert, httpRedirect } = input;
1487
- if (cert !== undefined) {
1488
- if (cert.daysLeft === -1)
1489
- warnings.push("certificate expired within the last day");
1490
- else if (cert.daysLeft < 0)
1491
- warnings.push(`certificate expired ${-cert.daysLeft} days ago`);
1492
- else if (cert.daysLeft < SOON_DAYS)
1493
- warnings.push(`certificate expires in ${cert.daysLeft} ${cert.daysLeft === 1 ? "day" : "days"}`);
1494
- }
1495
- if (input.authorizationError !== undefined)
1496
- warnings.push(`certificate not trusted: ${input.authorizationError}`);
1497
- if (httpRedirect !== undefined && !httpRedirect.toHttps)
1498
- warnings.push(`http:// answers ${httpRedirect.status} and does not redirect to https`);
1499
- if (input.tooManyRedirects)
1500
- warnings.push(`more than ${MAX_HOPS} redirects`);
1501
- return warnings;
1502
- }
1503
-
1504
- // src/cors.ts
1505
- var SIMPLE_METHODS = new Set(["GET", "HEAD", "POST"]);
1506
- var NORMALIZED_METHODS = new Set(["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]);
1507
- var SAFELISTED_HEADERS = new Set(["accept", "accept-language", "content-language"]);
1508
- var LIST = /\s*,\s*/;
1509
- var HOSTED_SCHEME = /^[a-z][a-z0-9+.-]*:\/\/[^/]/i;
1510
- function listOf(value) {
1511
- return value === undefined ? [] : value.trim().split(LIST).filter((item) => item !== "");
1512
- }
1513
- function methodOf(input) {
1514
- return NORMALIZED_METHODS.has(input.toUpperCase()) ? input.toUpperCase() : input;
1515
- }
1516
- function requestedHeaders(value) {
1517
- return listOf(value).map((name) => name.toLowerCase()).filter((name) => !SAFELISTED_HEADERS.has(name));
1518
- }
1519
- function originOf(input) {
1520
- if (input === "null")
1521
- return input;
1522
- if (!HOSTED_SCHEME.test(input) || !URL.canParse(input))
1523
- return;
1524
- const url = new URL(input);
1525
- return url.origin === "null" ? `${url.protocol}//${url.host}` : url.origin;
1526
- }
1527
- function corsVerdict(status, headers, request) {
1528
- const reasons = [];
1529
- const warnings = [];
1530
- const origin = headers["access-control-allow-origin"];
1531
- const credentials = headers["access-control-allow-credentials"] === "true";
1532
- const methods = listOf(headers["access-control-allow-methods"]);
1533
- const allowedHeaders = new Set(listOf(headers["access-control-allow-headers"]).map((name) => name.toLowerCase()));
1534
- if (status < 200 || status > 299)
1535
- reasons.push(`the preflight answered ${status}, a browser wants a 2xx`);
1536
- if (origin === undefined)
1537
- reasons.push("no access-control-allow-origin");
1538
- else if (origin !== "*" && origin !== request.origin)
1539
- reasons.push(`access-control-allow-origin is ${origin}, not ${request.origin}`);
1540
- const { method } = request;
1541
- if (!SIMPLE_METHODS.has(method) && !methods.includes("*") && !methods.includes(method))
1542
- reasons.push(methods.length === 0 ? `no access-control-allow-methods, which ${method} needs` : `access-control-allow-methods (${methods.join(", ")}) does not list ${method}`);
1543
- const missing = request.headers.map((name) => name.toLowerCase()).filter((name) => !allowedHeaders.has(name) && (name === "authorization" || !allowedHeaders.has("*")));
1544
- if (missing.length > 0)
1545
- reasons.push(`access-control-allow-headers does not cover ${missing.join(", ")}`);
1546
- if (credentials && (origin === "*" || methods.includes("*") || allowedHeaders.has("*")))
1547
- warnings.push("access-control-allow-credentials comes with a * wildcard, which a request with cookies or auth does not get");
1548
- if (origin === request.origin && !listOf(headers.vary).some((name) => name.toLowerCase() === "origin" || name === "*"))
1549
- warnings.push("if the origin is echoed back from the request, vary lacks origin: a cache may hand this answer to another origin");
1550
- const shown = Object.fromEntries(Object.entries(headers).filter(([name]) => name.startsWith("access-control-") || name === "vary"));
1551
- return { allowed: reasons.length === 0, reasons, warnings, headers: shown };
1552
- }
1553
-
1554
- // src/dns.ts
1555
- import { Resolver } from "dns/promises";
1556
- var TIMEOUT_MS = 3000;
1557
- var PUBLIC_RESOLVERS = [
1558
- { name: "cloudflare", address: "1.1.1.1" },
1559
- { name: "google", address: "8.8.8.8" },
1560
- { name: "quad9", address: "9.9.9.9" }
1561
- ];
1562
- function resolverFor(server, timeoutMs) {
1563
- const resolver = new Resolver({ timeout: timeoutMs, tries: 1 });
1564
- if (server.address !== undefined)
1565
- resolver.setServers([server.address]);
1566
- return resolver;
1567
- }
1568
- function failureOf(error) {
1569
- const code = error.code;
1570
- return code === "ETIMEOUT" || code === "ECONNREFUSED" ? "no answer" : String(error.message ?? error);
1571
- }
1572
- async function settled(query) {
1573
- try {
1574
- return await query;
1575
- } catch (error) {
1576
- const code = error.code;
1577
- if (code === "ENOTFOUND" || code === "ENODATA")
1578
- return [];
1579
- throw error;
1580
- }
1581
- }
1582
- function network(timeoutMs = TIMEOUT_MS, upstream = PUBLIC_RESOLVERS[0]) {
1583
- return {
1584
- servers: (server) => server.address ?? resolverFor(server, timeoutMs).getServers().join(", "),
1585
- async records(server, host) {
1586
- const resolver = resolverFor(server, timeoutMs);
1587
- try {
1588
- const [a, aaaa, cname] = await Promise.all([settled(resolver.resolve4(host, { ttl: true })), settled(resolver.resolve6(host, { ttl: true })), settled(resolver.resolveCname(host))]);
1589
- const ttls = [...a, ...aaaa].map((record) => record.ttl);
1590
- return { a: a.map((record) => record.address).sort(), aaaa: aaaa.map((record) => record.address).sort(), cname: cname.map((target) => target.toLowerCase()), ttl: ttls.length === 0 ? null : Math.min(...ttls) };
1591
- } catch (error) {
1592
- return { a: [], aaaa: [], cname: [], ttl: null, error: failureOf(error) };
1593
- }
1594
- },
1595
- async nameservers(zone) {
1596
- const resolver = resolverFor(upstream, timeoutMs);
1597
- const [nameservers, alias] = await Promise.all([settled(resolver.resolveNs(zone)), settled(resolver.resolveCname(zone))]);
1598
- return alias.length > 0 ? [] : nameservers;
1599
- },
1600
- async addressOf(host) {
1601
- return (await settled(resolverFor(upstream, timeoutMs).resolve4(host)))[0];
1602
- }
1603
- };
1604
- }
1605
- var NO_ZONE = "no zone with nameservers was found for this name";
1606
- var ZONE_LOOKUP_FAILED = "the zone of this name could not be looked up, so no nameserver was asked";
1607
- async function zoneOf(host, client) {
1608
- const labels = host.split(".");
1609
- for (let at = 0;at < labels.length - 1; at++) {
1610
- const zone = labels.slice(at).join(".");
1611
- const nameservers = await failingToNothing(client.nameservers(zone));
1612
- if (nameservers === undefined)
1613
- return { problem: ZONE_LOOKUP_FAILED };
1614
- if (nameservers.length > 0)
1615
- return { zone, nameservers: nameservers.sort() };
1616
- }
1617
- return { problem: NO_ZONE };
1618
- }
1619
- async function failingToNothing(query) {
1620
- try {
1621
- return await query;
1622
- } catch {
1623
- return;
1624
- }
1625
- }
1626
- function sameFamily(mine, theirs) {
1627
- if (mine.length === 0 || theirs.length === 0)
1628
- return mine.length === theirs.length;
1629
- const other = new Set(theirs);
1630
- return mine.some((address) => other.has(address));
1631
- }
1632
- function sameAnswer(one, other) {
1633
- if (one.error !== undefined || other.error !== undefined)
1634
- return one.error === other.error;
1635
- if (one.cname.length > 0 || other.cname.length > 0)
1636
- return one.cname.join().toLowerCase() === other.cname.join().toLowerCase();
1637
- return sameFamily(one.a, other.a) && sameFamily(one.aaaa, other.aaaa);
1638
- }
1639
- var TRAILING_DOT = /\.$/;
1640
- async function dnsReport(target, host, client = network()) {
1641
- const name = host.replace(TRAILING_DOT, "").toLowerCase();
1642
- const found = await zoneOf(name, client);
1643
- const authoritative = await Promise.all(("nameservers" in found ? found.nameservers : []).map(async (nameserver) => {
1644
- const address = await failingToNothing(client.addressOf(nameserver));
1645
- return address === undefined ? undefined : { name: nameserver, address };
1646
- }));
1647
- const asked = [
1648
- ...[{ name: "system" }, ...PUBLIC_RESOLVERS].map((server) => ({ server, authoritative: false })),
1649
- ...authoritative.filter((server) => server !== undefined).map((server) => ({ server, authoritative: true }))
1650
- ];
1651
- const answers = await Promise.all(asked.map(async ({ server, authoritative }) => ({ resolver: server.name, server: client.servers(server), authoritative, ...await client.records(server, name) })));
1652
- return { target, zone: "zone" in found ? found.zone : null, answers, ...verdictOf(answers, "problem" in found ? found.problem : undefined) };
1653
- }
1654
- function verdictOf(answers, zoneProblem) {
1655
- const warnings = zoneProblem === undefined ? [] : [zoneProblem];
1656
- const answered = answers.filter((answer) => answer.error !== "no answer");
1657
- const reference = answered.filter((answer) => answer.authoritative);
1658
- const truth = reference[0] ?? answered[0];
1659
- const agree = truth === undefined || answered.every((answer) => sameAnswer(answer, truth));
1660
- if (reference.some((answer) => !sameAnswer(answer, reference[0])))
1661
- warnings.push("the zone's own nameservers disagree: one of them has not taken the last change yet");
1662
- for (const answer of answers) {
1663
- if (answer.error === "no answer")
1664
- warnings.push(`${answer.resolver} did not answer`);
1665
- }
1666
- if (agree)
1667
- return { agree, warnings };
1668
- if (reference.length === 0) {
1669
- warnings.push(`the resolvers disagree, with no nameserver of the zone to tell which is right: ${answered.filter((answer) => !sameAnswer(answer, truth)).map((answer) => answer.resolver).join(", ")} differ from ${truth.resolver}`);
1670
- return { agree, warnings };
1671
- }
1672
- const stale = answered.filter((answer) => !answer.authoritative && !reference.some((ns) => sameAnswer(answer, ns)));
1673
- for (const answer of stale) {
1674
- const until = answer.ttl === null || answer.cname.length > 0 ? "" : `, cached for up to ${answer.ttl}s more`;
1675
- warnings.push(answer.resolver === "system" ? `the system resolver answers differently from the zone's nameservers${until}: \`sudo resolvectl flush-caches\` drops its copy` : `${answer.resolver} answers differently from the zone's nameservers${until}: the change has not reached it yet`);
1676
- }
1677
- return { agree, warnings };
1678
- }
1679
- function known(report) {
1680
- return report.answers.some((answer) => answer.error === undefined && answer.a.length + answer.aaaa.length + answer.cname.length > 0);
1681
- }
1682
-
1683
- // src/net.ts
1684
- import { lookup } from "dns/promises";
1685
- import { isIP } from "net";
1686
- import { connect } from "tls";
1687
- var CONNECT_TIMEOUT = 10;
1688
- var MAX_TIME = 20;
1689
- var HTTP3_FEATURE = /^Features:.*\bHTTP3\b/m;
1690
- var BRACKETS = /^\[|\]$/g;
1691
- var http3;
1692
- async function curlHasHttp3() {
1693
- if (http3 !== undefined)
1694
- return http3;
1695
- try {
1696
- const result = Bun.spawn(["curl", "--version"], { stdout: "pipe", stderr: "ignore" });
1697
- const text = await new Response(result.stdout).text();
1698
- http3 = HTTP3_FEATURE.test(text);
1699
- } catch {
1700
- http3 = false;
1701
- }
1702
- return http3;
1703
- }
1704
- function portOf(url) {
1705
- if (url.port !== "")
1706
- return Number(url.port);
1707
- return url.protocol === "https:" ? 443 : 80;
1708
- }
1709
- function curlResolve(url, resolve) {
1710
- const parsed = URL.canParse(url) ? new URL(url) : undefined;
1711
- const address = parsed === undefined ? undefined : resolve?.get(parsed.hostname);
1712
- if (parsed === undefined || address === undefined)
1713
- return [];
1714
- return ["--resolve", `${parsed.hostname}:${portOf(parsed)}:${isIP(address) === 6 ? `[${address}]` : address}`];
1715
- }
1716
- async function runCurl(url, { http3: wantsH3, insecure, get, method, headers = [], resolve, timeoutS = MAX_TIME }) {
1717
- const args = ["-sS", "-o", "/dev/null", "--connect-timeout", String(Math.min(CONNECT_TIMEOUT, timeoutS)), "--max-time", String(timeoutS), "--write-out", WRITE_OUT, ...curlResolve(url, resolve)];
1718
- for (const header of headers)
1719
- args.push("-H", header);
1720
- if (method !== undefined)
1721
- args.push("-X", method);
1722
- else if (!get)
1723
- args.push("-I");
1724
- if (wantsH3)
1725
- args.push("--http3");
1726
- if (insecure)
1727
- args.push("--insecure");
1728
- try {
1729
- const result = Bun.spawn(["curl", ...args, url], { stdout: "pipe", stderr: "pipe" });
1730
- const [stdout] = await Promise.all([new Response(result.stdout).text(), new Response(result.stderr).text(), result.exited]);
1731
- return parseCurl(stdout);
1732
- } catch {
1733
- return { exitcode: 127, errormsg: "curl is not installed" };
1734
- }
1735
- }
1736
- async function curlHop(url, options) {
1737
- let result = await runCurl(url, options);
1738
- if (result.hop === undefined && options.http3)
1739
- result = await runCurl(url, { ...options, http3: false });
1740
- if (result.hop !== undefined && !options.get && options.method === undefined && result.hop.status >= 400)
1741
- result = await runCurl(url, { ...options, get: true });
1742
- return result;
1743
- }
1744
- async function curlPreflight(url, request, options) {
1745
- const asked = [`Origin: ${request.origin}`, `Access-Control-Request-Method: ${request.method}`, ...request.headers.length > 0 ? [`Access-Control-Request-Headers: ${request.headers.join(", ")}`] : []];
1746
- return runCurl(url, { ...options, headers: [...options.headers ?? [], ...asked], http3: false, get: true, method: "OPTIONS" });
1747
- }
1748
- async function addressesOf(host, resolve) {
1749
- const bare = resolve?.get(host) ?? host.replace(BRACKETS, "");
1750
- const family = isIP(bare);
1751
- if (family !== 0)
1752
- return family === 4 ? { a: [bare], aaaa: [] } : { a: [], aaaa: [bare] };
1753
- try {
1754
- const found = await lookup(bare, { all: true });
1755
- return { a: found.filter((entry) => entry.family === 4).map((entry) => entry.address), aaaa: found.filter((entry) => entry.family === 6).map((entry) => entry.address) };
1756
- } catch {
1757
- return { a: [], aaaa: [] };
1758
- }
1759
- }
1760
- async function tlsInfo(host, port, { address, timeoutS = CONNECT_TIMEOUT } = {}) {
1761
- const bare = host.replace(BRACKETS, "");
1762
- return new Promise((resolve) => {
1763
- const socket = connect({ host: address ?? bare, port, servername: isIP(bare) === 0 ? bare : "", ALPNProtocols: ["h2", "http/1.1"], rejectUnauthorized: false, timeout: Math.min(CONNECT_TIMEOUT, timeoutS) * 1000 });
1764
- socket.on("secureConnect", () => {
1765
- const error = socket.authorizationError;
1766
- resolve({
1767
- protocol: socket.getProtocol() ?? "",
1768
- cipher: socket.getCipher().name,
1769
- alpn: typeof socket.alpnProtocol === "string" ? socket.alpnProtocol : undefined,
1770
- authorizationError: error === null || error === undefined || error === false ? undefined : String(error),
1771
- cert: certInfo(socket.getPeerCertificate())
1772
- });
1773
- socket.end();
1774
- });
1775
- socket.on("error", () => resolve(undefined));
1776
- socket.on("timeout", () => {
1777
- socket.destroy();
1778
- resolve(undefined);
1779
- });
1780
- });
1781
- }
1782
-
1783
- // src/probe.ts
1784
- var LABEL_WIDTH = 13;
1785
- var USAGE = `probe [options] <url|domain>...: reports each site's negotiated HTTP version, redirect chain, timings, addresses, TLS and certificate, the headers worth knowing and what warrants a warning
74
+ %{header_json}`;function seconds(value){return typeof value==="number"?value:0}function ms(value){return Math.round(value*1000)}function timingsOf(info){let lookup=seconds(info.time_namelookup),connect=seconds(info.time_connect),secure=seconds(info.time_appconnect),ready=secure>0?secure:connect,first=seconds(info.time_starttransfer);return{dns:ms(lookup),connect:ms(Math.max(0,connect-lookup)),tls:secure>0?ms(Math.max(0,secure-connect)):0,firstByte:ms(Math.max(0,first-ready)),total:ms(seconds(info.time_total))}}function headersOf(json){let headers={};try{let parsed=JSON.parse(json);if(typeof parsed!=="object"||parsed===null)return headers;for(let[name,value]of Object.entries(parsed)){let values=Array.isArray(value)?value.map(String):[String(value)];headers[name.toLowerCase()]=values.join(", ")}}catch{}return headers}function parseCurl(stdout){let at=stdout.indexOf(`
75
+ ---HEADERS---
76
+ `),infoText=at===-1?stdout:stdout.slice(0,at),info;try{info=JSON.parse(infoText)}catch{return{exitcode:1,errormsg:"curl printed no result"}}let exitcode=typeof info.exitcode==="number"?info.exitcode:1,errormsg=typeof info.errormsg==="string"?info.errormsg:null,status=typeof info.response_code==="number"?info.response_code:0;if(exitcode!==0||status===0)return{exitcode:exitcode===0?1:exitcode,errormsg:errormsg??"no response"};let headers=headersOf(at===-1?"":stdout.slice(at+15)),hop={url:String(info.url_effective??info.url??""),status,version:String(info.http_version??""),timings:timingsOf(info),headers};if(typeof info.redirect_url==="string"&&info.redirect_url!=="")hop.location=info.redirect_url;else if(headers.location!==void 0)hop.location=headers.location;if(typeof info.remote_ip==="string"&&info.remote_ip!=="")hop.remoteIp=info.remote_ip;return{exitcode,errormsg,hop}}function isRedirect(status){return status===301||status===302||status===303||status===307||status===308}function nextUrl(current,location){try{let next=new URL(location,current);return next.protocol==="http:"||next.protocol==="https:"?next.href:void 0}catch{return}}function versionLabel(version){return version===""?"unknown":`HTTP/${version}`}function altSvcProtocols(altSvc){if(altSvc===void 0||altSvc.trim()==="clear")return[];let ids=altSvc.split(",").map((entry)=>entry.trim().replace(ALT_VALUE,"")).filter((id)=>id!=="");return[...new Set(ids)]}function offersOf(options){let altSvc=altSvcProtocols(options.altSvc);return{h2:options.alpn==="h2"||options.version==="2"||options.version==="3",h3:options.version==="3"||altSvc.some((id)=>id==="h3"||id.startsWith("h3-")),altSvc}}var KNOWN_SERVERS=[[/cloudflare/i,"Cloudflare"],[/cloudfront/i,"CloudFront"],[/akamai/i,"Akamai"],[/fastly/i,"Fastly"],[/vercel/i,"Vercel"],[/netlify/i,"Netlify"],[/bunnycdn/i,"BunnyCDN"],[/^(?:gws|esf|gse)$|google frontend/i,"Google"]];function cdnHint(headers){let served=headers["x-served-by"];if(headers["cf-ray"]!==void 0)return"Cloudflare (cf-ray)";if(served!==void 0)return`${CACHE_NODE.test(served)?"Fastly":served} (x-served-by)`;if(headers["x-amz-cf-id"]!==void 0)return"CloudFront (x-amz-cf-id)";if(headers["x-vercel-id"]!==void 0)return"Vercel (x-vercel-id)";if(headers.via!==void 0)return`${headers.via} (via)`;if(headers["x-cache"]!==void 0)return`${headers["x-cache"]} (x-cache)`;let server=headers.server;if(server!==void 0){let known=KNOWN_SERVERS.find(([pattern])=>pattern.test(server));if(known!==void 0)return`${known[1]} (server)`}return}var WORTH_KNOWING=["server","content-type","content-encoding","cache-control","strict-transport-security"];function worthKnowing(headers){let kept={};for(let name of WORTH_KNOWING){let value=headers[name];if(value!==void 0)kept[name]=value}return kept}function field(value){if(typeof value==="string")return value;return Array.isArray(value)?value.join(", "):""}function nameOf(entry){if(entry===void 0)return"";let common=field(entry.CN),organization=field(entry.O);if(common!==""&&organization!==""&&common!==organization)return`${common} (${organization})`;return common===""?organization:common}function namesOf(subjectaltname){if(subjectaltname===void 0)return[];return subjectaltname.split(",").map((entry)=>entry.trim().replace(CERT_PREFIX,"")).filter((name)=>name!=="")}function daysLeftLabel(days){return`${days} ${days===1?"day":"days"} left`}function certInfo(raw,now=Date.now()){if(raw.valid_to===void 0||raw.valid_from===void 0)return;let end=Date.parse(raw.valid_to),start=Date.parse(raw.valid_from);if(Number.isNaN(end)||Number.isNaN(start))return;return{subject:nameOf(raw.subject),issuer:nameOf(raw.issuer),names:namesOf(raw.subjectaltname),validFrom:new Date(start).toISOString(),validTo:new Date(end).toISOString(),daysLeft:Math.floor((end-now)/86400000)}}function httpRedirectOf(hop){if(hop===void 0)return;let next=hop.location===void 0?void 0:nextUrl(hop.url,hop.location),redirect={status:hop.status,toHttps:isRedirect(hop.status)&&next!==void 0&&new URL(next).protocol==="https:"};if(hop.location!==void 0)redirect.location=hop.location;return redirect}function wantsHttpCheck(target){return target.url.protocol==="https:"&&target.url.port===""}function warningsOf(input){let warnings=[],{cert,httpRedirect}=input;if(cert!==void 0){if(cert.daysLeft===-1)warnings.push("certificate expired within the last day");else if(cert.daysLeft<0)warnings.push(`certificate expired ${-cert.daysLeft} days ago`);else if(cert.daysLeft<14)warnings.push(`certificate expires in ${cert.daysLeft} ${cert.daysLeft===1?"day":"days"}`)}if(input.authorizationError!==void 0)warnings.push(`certificate not trusted: ${input.authorizationError}`);if(httpRedirect!==void 0&&!httpRedirect.toHttps)warnings.push(`http:// answers ${httpRedirect.status} and does not redirect to https`);if(input.tooManyRedirects)warnings.push("more than 10 redirects");return warnings}var SIMPLE_METHODS=new Set(["GET","HEAD","POST"]),NORMALIZED_METHODS=new Set(["DELETE","GET","HEAD","OPTIONS","POST","PUT"]),SAFELISTED_HEADERS=new Set(["accept","accept-language","content-language"]),LIST=/\s*,\s*/,HOSTED_SCHEME=/^[a-z][a-z0-9+.-]*:\/\/[^/]/i;function listOf(value){return value===void 0?[]:value.trim().split(LIST).filter((item)=>item!=="")}function methodOf(input){return NORMALIZED_METHODS.has(input.toUpperCase())?input.toUpperCase():input}function requestedHeaders(value){return listOf(value).map((name)=>name.toLowerCase()).filter((name)=>!SAFELISTED_HEADERS.has(name))}function originOf(input){if(input==="null")return input;if(!HOSTED_SCHEME.test(input)||!URL.canParse(input))return;let url=new URL(input);return url.origin==="null"?`${url.protocol}//${url.host}`:url.origin}function corsVerdict(status,headers,request){let reasons=[],warnings=[],origin=headers["access-control-allow-origin"],credentials=headers["access-control-allow-credentials"]==="true",methods=listOf(headers["access-control-allow-methods"]),allowedHeaders=new Set(listOf(headers["access-control-allow-headers"]).map((name)=>name.toLowerCase()));if(status<200||status>299)reasons.push(`the preflight answered ${status}, a browser wants a 2xx`);if(origin===void 0)reasons.push("no access-control-allow-origin");else if(origin!=="*"&&origin!==request.origin)reasons.push(`access-control-allow-origin is ${origin}, not ${request.origin}`);let{method}=request;if(!SIMPLE_METHODS.has(method)&&!methods.includes("*")&&!methods.includes(method))reasons.push(methods.length===0?`no access-control-allow-methods, which ${method} needs`:`access-control-allow-methods (${methods.join(", ")}) does not list ${method}`);let missing=request.headers.map((name)=>name.toLowerCase()).filter((name)=>!allowedHeaders.has(name)&&(name==="authorization"||!allowedHeaders.has("*")));if(missing.length>0)reasons.push(`access-control-allow-headers does not cover ${missing.join(", ")}`);if(credentials&&(origin==="*"||methods.includes("*")||allowedHeaders.has("*")))warnings.push("access-control-allow-credentials comes with a * wildcard, which a request with cookies or auth does not get");if(origin===request.origin&&!listOf(headers.vary).some((name)=>name.toLowerCase()==="origin"||name==="*"))warnings.push("if the origin is echoed back from the request, vary lacks origin: a cache may hand this answer to another origin");let shown=Object.fromEntries(Object.entries(headers).filter(([name])=>name.startsWith("access-control-")||name==="vary"));return{allowed:reasons.length===0,reasons,warnings,headers:shown}}import{Resolver}from"dns/promises";var TIMEOUT_MS=3000,PUBLIC_RESOLVERS=[{name:"cloudflare",address:"1.1.1.1"},{name:"google",address:"8.8.8.8"},{name:"quad9",address:"9.9.9.9"}];function resolverFor(server,timeoutMs){let resolver=new Resolver({timeout:timeoutMs,tries:1});if(server.address!==void 0)resolver.setServers([server.address]);return resolver}function failureOf(error){let code=error.code;return code==="ETIMEOUT"||code==="ECONNREFUSED"?"no answer":String(error.message??error)}async function settled(query){try{return await query}catch(error){let code=error.code;if(code==="ENOTFOUND"||code==="ENODATA")return[];throw error}}function network(timeoutMs=TIMEOUT_MS,upstream=PUBLIC_RESOLVERS[0]){return{servers:(server)=>server.address??resolverFor(server,timeoutMs).getServers().join(", "),async records(server,host){let resolver=resolverFor(server,timeoutMs);try{let[a,aaaa,cname]=await Promise.all([settled(resolver.resolve4(host,{ttl:!0})),settled(resolver.resolve6(host,{ttl:!0})),settled(resolver.resolveCname(host))]),ttls=[...a,...aaaa].map((record)=>record.ttl);return{a:a.map((record)=>record.address).sort(),aaaa:aaaa.map((record)=>record.address).sort(),cname:cname.map((target)=>target.toLowerCase()),ttl:ttls.length===0?null:Math.min(...ttls)}}catch(error){return{a:[],aaaa:[],cname:[],ttl:null,error:failureOf(error)}}},async nameservers(zone){let resolver=resolverFor(upstream,timeoutMs),[nameservers,alias]=await Promise.all([settled(resolver.resolveNs(zone)),settled(resolver.resolveCname(zone))]);return alias.length>0?[]:nameservers},async addressOf(host){return(await settled(resolverFor(upstream,timeoutMs).resolve4(host)))[0]}}}var NO_ZONE="no zone with nameservers was found for this name",ZONE_LOOKUP_FAILED="the zone of this name could not be looked up, so no nameserver was asked";async function zoneOf(host,client){let labels=host.split(".");for(let at=0;at<labels.length-1;at++){let zone=labels.slice(at).join("."),nameservers=await failingToNothing(client.nameservers(zone));if(nameservers===void 0)return{problem:ZONE_LOOKUP_FAILED};if(nameservers.length>0)return{zone,nameservers:nameservers.sort()}}return{problem:NO_ZONE}}async function failingToNothing(query){try{return await query}catch{return}}function sameFamily(mine,theirs){if(mine.length===0||theirs.length===0)return mine.length===theirs.length;let other=new Set(theirs);return mine.some((address)=>other.has(address))}function sameAnswer(one,other){if(one.error!==void 0||other.error!==void 0)return one.error===other.error;if(one.cname.length>0||other.cname.length>0)return one.cname.join().toLowerCase()===other.cname.join().toLowerCase();return sameFamily(one.a,other.a)&&sameFamily(one.aaaa,other.aaaa)}var TRAILING_DOT=/\.$/;async function dnsReport(target,host,client=network()){let name=host.replace(TRAILING_DOT,"").toLowerCase(),found=await zoneOf(name,client),authoritative=await Promise.all(("nameservers"in found?found.nameservers:[]).map(async(nameserver)=>{let address=await failingToNothing(client.addressOf(nameserver));return address===void 0?void 0:{name:nameserver,address}})),asked=[...[{name:"system"},...PUBLIC_RESOLVERS].map((server)=>({server,authoritative:!1})),...authoritative.filter((server)=>server!==void 0).map((server)=>({server,authoritative:!0}))],answers=await Promise.all(asked.map(async({server,authoritative})=>({resolver:server.name,server:client.servers(server),authoritative,...await client.records(server,name)})));return{target,zone:"zone"in found?found.zone:null,answers,...verdictOf(answers,"problem"in found?found.problem:void 0)}}function verdictOf(answers,zoneProblem){let warnings=zoneProblem===void 0?[]:[zoneProblem],answered=answers.filter((answer)=>answer.error!=="no answer"),reference=answered.filter((answer)=>answer.authoritative),truth=reference[0]??answered[0],agree=truth===void 0||answered.every((answer)=>sameAnswer(answer,truth));if(reference.some((answer)=>!sameAnswer(answer,reference[0])))warnings.push("the zone's own nameservers disagree: one of them has not taken the last change yet");for(let answer of answers)if(answer.error==="no answer")warnings.push(`${answer.resolver} did not answer`);if(agree)return{agree,warnings};if(reference.length===0)return warnings.push(`the resolvers disagree, with no nameserver of the zone to tell which is right: ${answered.filter((answer)=>!sameAnswer(answer,truth)).map((answer)=>answer.resolver).join(", ")} differ from ${truth.resolver}`),{agree,warnings};let stale=answered.filter((answer)=>!answer.authoritative&&!reference.some((ns)=>sameAnswer(answer,ns)));for(let answer of stale){let until=answer.ttl===null||answer.cname.length>0?"":`, cached for up to ${answer.ttl}s more`;warnings.push(answer.resolver==="system"?`the system resolver answers differently from the zone's nameservers${until}: \`sudo resolvectl flush-caches\` drops its copy`:`${answer.resolver} answers differently from the zone's nameservers${until}: the change has not reached it yet`)}return{agree,warnings}}function known(report){return report.answers.some((answer)=>answer.error===void 0&&answer.a.length+answer.aaaa.length+answer.cname.length>0)}import{lookup}from"dns/promises";import{isIP}from"net";import{connect}from"tls";var CONNECT_TIMEOUT=10,MAX_TIME=20,HTTP3_FEATURE=/^Features:.*\bHTTP3\b/m,BRACKETS=/^\[|\]$/g,http3;async function curlHasHttp3(){if(http3!==void 0)return http3;try{let result=Bun.spawn(["curl","--version"],{stdout:"pipe",stderr:"ignore"}),text=await new Response(result.stdout).text();http3=HTTP3_FEATURE.test(text)}catch{http3=!1}return http3}function portOf(url){if(url.port!=="")return Number(url.port);return url.protocol==="https:"?443:80}function curlResolve(url,resolve){let parsed=URL.canParse(url)?new URL(url):void 0,address=parsed===void 0?void 0:resolve?.get(parsed.hostname);if(parsed===void 0||address===void 0)return[];return["--resolve",`${parsed.hostname}:${portOf(parsed)}:${isIP(address)===6?`[${address}]`:address}`]}async function runCurl(url,{http3:wantsH3,insecure,get,method,headers=[],resolve,timeoutS=MAX_TIME}){let args=["-sS","-o","/dev/null","--connect-timeout",String(Math.min(CONNECT_TIMEOUT,timeoutS)),"--max-time",String(timeoutS),"--write-out",WRITE_OUT,...curlResolve(url,resolve)];for(let header of headers)args.push("-H",header);if(method!==void 0)args.push("-X",method);else if(!get)args.push("-I");if(wantsH3)args.push("--http3");if(insecure)args.push("--insecure");try{let result=Bun.spawn(["curl",...args,url],{stdout:"pipe",stderr:"pipe"}),[stdout]=await Promise.all([new Response(result.stdout).text(),new Response(result.stderr).text(),result.exited]);return parseCurl(stdout)}catch{return{exitcode:127,errormsg:"curl is not installed"}}}async function curlHop(url,options){let result=await runCurl(url,options);if(result.hop===void 0&&options.http3)result=await runCurl(url,{...options,http3:!1});if(result.hop!==void 0&&!options.get&&options.method===void 0&&result.hop.status>=400)result=await runCurl(url,{...options,get:!0});return result}async function curlPreflight(url,request,options){let asked=[`Origin: ${request.origin}`,`Access-Control-Request-Method: ${request.method}`,...request.headers.length>0?[`Access-Control-Request-Headers: ${request.headers.join(", ")}`]:[]];return runCurl(url,{...options,headers:[...options.headers??[],...asked],http3:!1,get:!0,method:"OPTIONS"})}async function addressesOf(host,resolve){let bare=resolve?.get(host)??host.replace(BRACKETS,""),family=isIP(bare);if(family!==0)return family===4?{a:[bare],aaaa:[]}:{a:[],aaaa:[bare]};try{let found=await lookup(bare,{all:!0});return{a:found.filter((entry)=>entry.family===4).map((entry)=>entry.address),aaaa:found.filter((entry)=>entry.family===6).map((entry)=>entry.address)}}catch{return{a:[],aaaa:[]}}}async function tlsInfo(host,port,{address,timeoutS=CONNECT_TIMEOUT}={}){let bare=host.replace(BRACKETS,"");return new Promise((resolve)=>{let socket=connect({host:address??bare,port,servername:isIP(bare)===0?bare:"",ALPNProtocols:["h2","http/1.1"],rejectUnauthorized:!1,timeout:Math.min(CONNECT_TIMEOUT,timeoutS)*1000});socket.on("secureConnect",()=>{let error=socket.authorizationError;resolve({protocol:socket.getProtocol()??"",cipher:socket.getCipher().name,alpn:typeof socket.alpnProtocol==="string"?socket.alpnProtocol:void 0,authorizationError:error===null||error===void 0||error===!1?void 0:String(error),cert:certInfo(socket.getPeerCertificate())}),socket.end()}),socket.on("error",()=>resolve(void 0)),socket.on("timeout",()=>{socket.destroy(),resolve(void 0)})})}var LABEL_WIDTH=13,USAGE=`probe [options] <url|domain>...: reports each site's negotiated HTTP version, redirect chain, timings, addresses, TLS and certificate, the headers worth knowing and what warrants a warning
1786
77
 
1787
78
  A bare domain is tried over https first, then http, and redirects are followed hop by hop (at most ${MAX_HOPS}).
1788
79
  Warns on a certificate with fewer than 14 days left or not trusted, and on an http:// twin that does not redirect to https.
1789
80
  --dns makes no HTTP request and compares the records the system resolver, public resolvers and the zone's nameservers give.
1790
- --cors <origin> sends the preflight a browser on that origin would send and says whether it would go on, with each reason when not.`;
1791
- var EXITS = [[0, "every site answered, warnings or not"], [1, "a site could not be reached or redirects where nothing answers, a CORS preflight was refused, or no resolver knows a name"], [2, "a usage error"]];
1792
- var OPTIONS = {
1793
- insecure: { type: "boolean", short: "k", description: "let curl go on with a certificate it does not trust" },
1794
- header: { type: "string", short: "H", multiple: true, description: "a `Name: value` header sent with every request, repeatable" },
1795
- resolve: { type: "string", multiple: true, description: "host:ip, reach the host at that address instead of the DNS answer, repeatable" },
1796
- timeout: { type: "string", short: "t", description: "longest one request may take (20s, 3s for a DNS query): 5s, 1m, a bare number in seconds" },
1797
- verbose: { type: "boolean", description: "the whole table for each target instead of one line" },
1798
- dns: { type: "boolean", description: "compare what each resolver and the zone's nameservers answer for the host, no HTTP request", conflicts: ["cors", "header", "resolve", "insecure", "verbose"] },
1799
- cors: { type: "string", description: "the origin a browser would call from: whether its CORS preflight lets the request through", conflicts: ["dns", "verbose"] },
1800
- method: { type: "string", description: "with --cors, the method of the request the preflight asks for (POST)" },
1801
- "cors-headers": { type: "string", description: "with --cors, the headers it carries, comma separated, empty for none (content-type)" },
1802
- json: jsonOption("one object per target {target, url, version, status, chain, timings, addresses, tls, certificate, headers, cdn, offers, httpRedirect, failedHop: {url, error} or null, warnings}, an array of them for several targets (an unreachable one is {target, error}); with --dns {target, zone, answers, agree, warnings}, with --cors {target, url, status, request, allowed, reasons, warnings, headers}")
1803
- };
1804
- var BRACKETS2 = /^\[|\]$/g;
1805
- var HEADER_LINE = /^[\w!#$%&'*+.^`|~-]+:/;
1806
- async function follow(start, { insecure, wire }, http3) {
1807
- const chain = [];
1808
- let url = start;
1809
- while (chain.length <= MAX_HOPS) {
1810
- const { hop, errormsg } = await curlHop(url, { ...wire, http3: http3 && url.startsWith("https:"), insecure, get: false });
1811
- if (hop === undefined)
1812
- return { chain, failed: { url, error: errormsg ?? "no response" }, tooMany: false };
1813
- chain.push(hop);
1814
- const next = hop.location === undefined ? undefined : nextUrl(hop.url, hop.location);
1815
- if (!isRedirect(hop.status) || next === undefined)
1816
- return { chain, tooMany: false };
1817
- url = next;
1818
- }
1819
- return { chain, tooMany: true };
1820
- }
1821
- async function probe(target, input, settings) {
1822
- const { wire } = settings;
1823
- const http3 = await curlHasHttp3();
1824
- let followed = await follow(target.url.href, settings, http3);
1825
- let httpsError;
1826
- if (followed.chain.length === 0 && target.bare) {
1827
- const plain = new URL(target.url.href);
1828
- plain.protocol = "http:";
1829
- const second = await follow(plain.href, settings, http3);
1830
- if (second.chain.length > 0) {
1831
- httpsError = followed.failed?.error;
1832
- followed = second;
1833
- }
1834
- }
1835
- const final = followed.chain.at(-1);
1836
- if (final === undefined)
1837
- return { target: input, error: `could not reach ${target.url.host}: ${followed.failed?.error ?? "no response"}` };
1838
- const finalUrl = new URL(final.url);
1839
- const secure = finalUrl.protocol === "https:";
1840
- const [addresses, tls, twin] = await Promise.all([
1841
- addressesOf(target.url.hostname, wire.resolve),
1842
- secure ? tlsInfo(finalUrl.hostname, portOf(finalUrl), { address: wire.resolve?.get(finalUrl.hostname), ...wire.timeoutS === undefined ? {} : { timeoutS: wire.timeoutS } }) : Promise.resolve(undefined),
1843
- wantsHttpCheck(target) && secure ? twinOf(target.url, settings) : Promise.resolve(undefined)
1844
- ]);
1845
- const httpRedirect = httpRedirectOf(twin);
1846
- const offers = offersOf({ alpn: tls?.alpn, version: final.version, altSvc: final.headers["alt-svc"] });
1847
- const warnings = warningsOf({ cert: tls?.cert, authorizationError: tls?.authorizationError, httpRedirect, tooManyRedirects: followed.tooMany });
1848
- if (followed.failed !== undefined)
1849
- warnings.unshift(`the redirect to ${followed.failed.url} got no answer: ${followed.failed.error}`);
1850
- if (!secure)
1851
- warnings.push(httpsError === undefined ? "the site is not served over https" : `the site is not served over https: ${httpsError}`);
1852
- return {
1853
- target: input,
1854
- url: final.url,
1855
- version: final.version,
1856
- status: final.status,
1857
- chain: followed.chain.map((hop) => ({ url: hop.url, status: hop.status, version: hop.version, ...hop.location === undefined ? {} : { location: hop.location }, ms: hop.timings.total })),
1858
- timings: final.timings,
1859
- addresses,
1860
- tls: tls === undefined ? null : { protocol: tls.protocol, cipher: tls.cipher, ...tls.alpn === undefined ? {} : { alpn: tls.alpn } },
1861
- certificate: tls?.cert ?? null,
1862
- headers: worthKnowing(final.headers),
1863
- cdn: cdnHint(final.headers) ?? null,
1864
- offers,
1865
- httpRedirect: httpRedirect ?? null,
1866
- failedHop: followed.failed ?? null,
1867
- warnings
1868
- };
1869
- }
1870
- var unreached = (report) => ("error" in report) || report.failedHop !== null;
1871
- async function twinOf(url, { insecure, wire }) {
1872
- const plain = new URL(url.href);
1873
- plain.protocol = "http:";
1874
- return (await curlHop(plain.href, { ...wire, http3: false, insecure, get: false })).hop;
1875
- }
1876
- function resolvesOf(entries) {
1877
- const resolve = new Map;
1878
- for (const entry of entries) {
1879
- const at = entry.indexOf(":");
1880
- const address = entry.slice(at + 1).replace(BRACKETS2, "");
1881
- if (at < 1 || isIP2(address) === 0)
1882
- badUsage(`--resolve takes host:ip, not ${entry}`);
1883
- resolve.set(entry.slice(0, at).toLowerCase(), address);
1884
- }
1885
- return resolve;
1886
- }
1887
- function ms2(value) {
1888
- return `${value}ms`;
1889
- }
1890
- function compact(report) {
1891
- const { dim } = paint(process16.stdout);
1892
- const redirects = report.chain.length - 1;
1893
- const parts = [`${role("accent", process16.stdout)(versionLabel(report.version))} ${role("value", process16.stdout)(String(report.status))} ${role("path", process16.stdout)(report.url)}`, ms2(report.timings.total)];
1894
- const address = report.addresses.a[0] ?? report.addresses.aaaa[0];
1895
- if (redirects > 0)
1896
- parts.push(`${redirects} ${redirects === 1 ? "redirect" : "redirects"}`);
1897
- if (report.certificate !== null)
1898
- parts.push(`cert ${daysLeftLabel(report.certificate.daysLeft)}`);
1899
- if (address !== undefined)
1900
- parts.push(address);
1901
- const line = parts.join(dim(" "));
1902
- return report.warnings.length === 0 ? line : `${line} ${marked("warn", report.warnings.join("; "), process16.stdout)}`;
1903
- }
1904
- function print(report) {
1905
- const label = role("label", process16.stdout);
1906
- const value = role("value", process16.stdout);
1907
- const accent = role("accent", process16.stdout);
1908
- const row = (name, text) => console.log(`${label(name.padEnd(LABEL_WIDTH))} ${text}`);
1909
- console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path", process16.stdout)(report.url)}`);
1910
- console.log("");
1911
- if (report.chain.length > 1) {
1912
- console.log(table(report.chain.map((hop) => [String(hop.status), versionLabel(hop.version), ms2(hop.ms), hop.url]), { align: ["right", "left", "right", "left"] }));
1913
- console.log("");
1914
- }
1915
- const { timings } = report;
1916
- row("timings", `dns ${ms2(timings.dns)}, connect ${ms2(timings.connect)}, tls ${ms2(timings.tls)}, first byte ${ms2(timings.firstByte)}, total ${ms2(timings.total)}`);
1917
- row("addresses", [...report.addresses.a, ...report.addresses.aaaa].join(", ") || "none found");
1918
- if (report.tls !== null)
1919
- row("tls", `${report.tls.protocol} ${report.tls.cipher}`);
1920
- const cert = report.certificate;
1921
- if (cert !== null) {
1922
- row("issuer", cert.issuer);
1923
- row("expires", `${cert.validTo.slice(0, 10)} (${daysLeftLabel(cert.daysLeft)})`);
1924
- row("names", cert.names.join(", "));
1925
- }
1926
- row("offers", `h2 ${report.offers.h2 ? "yes" : "no"}, h3 ${report.offers.h3 ? "yes" : "no"}${report.offers.altSvc.length === 0 ? "" : ` (alt-svc ${report.offers.altSvc.join(" ")})`}`);
1927
- for (const [name, text] of Object.entries(report.headers))
1928
- row(name === "strict-transport-security" ? "hsts" : name, text);
1929
- if (report.cdn !== null)
1930
- row("cdn", report.cdn);
1931
- if (report.httpRedirect !== null)
1932
- row("http://", report.httpRedirect.toHttps ? `redirects to https (${report.httpRedirect.status})` : `answers ${report.httpRedirect.status}`);
1933
- for (const warning of report.warnings)
1934
- console.log(marked("warn", warning, process16.stdout));
1935
- }
1936
- function printDns(report) {
1937
- const label = role("label", process16.stdout);
1938
- const listed = (values) => values.length === 0 ? "-" : values.join(" ");
1939
- console.log(`${role("path", process16.stdout)(report.target)} ${label(report.zone === null ? "no zone found" : `zone ${report.zone}`)}`);
1940
- console.log(table([
1941
- ["RESOLVER", "SERVER", "A", "AAAA", "CNAME", "TTL"],
1942
- ...report.answers.map((answer) => [
1943
- answer.authoritative ? `${answer.resolver} (ns)` : answer.resolver,
1944
- answer.server,
1945
- ...answer.error === undefined ? [listed(answer.a), listed(answer.aaaa), listed(answer.cname)] : [answer.error, "", ""],
1946
- answer.ttl === null ? "-" : `${answer.ttl}s`
1947
- ])
1948
- ], { header: true }));
1949
- if (report.agree)
1950
- console.log(marked("ok", "every resolver gives the same answer", process16.stdout));
1951
- for (const warning of report.warnings)
1952
- console.log(marked("warn", warning, process16.stdout));
1953
- }
1954
- async function dnsMain(inputs, timeoutMs, json) {
1955
- const hosts = inputs.map((input) => {
1956
- const host = parseTarget(input)?.url.hostname;
1957
- if (host === undefined)
1958
- badUsage(`not a URL or domain: ${input}`);
1959
- if (isIP2(host.replace(BRACKETS2, "")) !== 0)
1960
- badUsage(`--dns takes a name, not the address ${input}`);
1961
- return { input, host };
1962
- });
1963
- const client = network(timeoutMs);
1964
- const reports = await Promise.all(hosts.map(async ({ input, host }) => dnsReport(input, host, client)));
1965
- if (json) {
1966
- printJson(reports.length === 1 ? reports[0] : reports);
1967
- } else {
1968
- for (const [at, report] of reports.entries()) {
1969
- if (at > 0)
1970
- console.log("");
1971
- printDns(report);
1972
- }
1973
- }
1974
- return reports.every(known) ? 0 : 1;
1975
- }
1976
- function printCors(report) {
1977
- const label = role("label", process16.stdout);
1978
- const { request } = report;
1979
- const asked = `from ${request.origin}, ${request.method}${request.headers.length === 0 ? "" : ` with ${request.headers.join(", ")}`}`;
1980
- console.log(`${marked(report.allowed ? "ok" : "problem", report.allowed ? "allowed" : "refused", process16.stdout)} ${role("value", process16.stdout)(String(report.status))} ${role("path", process16.stdout)(report.url)} ${label(asked)}`);
1981
- for (const [name, value] of Object.entries(report.headers))
1982
- console.log(` ${label(name)} ${value}`);
1983
- for (const reason of report.reasons)
1984
- console.log(marked("problem", reason, process16.stdout));
1985
- for (const warning of report.warnings)
1986
- console.log(marked("warn", warning, process16.stdout));
1987
- }
1988
- async function corsMain(targets, request, { insecure, wire }, json) {
1989
- const reports = await Promise.all(targets.map(async ({ input, target }) => {
1990
- const { hop, errormsg } = await curlPreflight(target.url.href, request, { ...wire, insecure });
1991
- if (hop === undefined)
1992
- return { target: input, error: `could not reach ${target.url.host}: ${errormsg ?? "no response"}` };
1993
- return { target: input, url: hop.url, status: hop.status, request, ...corsVerdict(hop.status, hop.headers, request) };
1994
- }));
1995
- const [only] = reports;
1996
- if (reports.length === 1 && only !== undefined && "error" in only)
1997
- fail(only.error, 1);
1998
- if (json) {
1999
- printJson(reports.length === 1 ? only : reports);
2000
- } else {
2001
- for (const report of reports) {
2002
- if ("error" in report)
2003
- console.error(marked("problem", report.error, process16.stderr));
2004
- else
2005
- printCors(report);
2006
- }
2007
- }
2008
- return reports.every((report) => ("allowed" in report) && report.allowed) ? 0 : 1;
2009
- }
2010
- async function main(args) {
2011
- const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["<url|domain>..."], exits: EXITS, replaces: "the httpversion fish function, curl -sI chains, openssl s_client and dig @server one-liners", examples: ["probe example.com", "probe https://example.com/path --json", ["probe a.test b.test", "one line each"], ['probe https://example.com --resolve example.com:203.0.113.7 -H "Host: example.com" --verbose', "a server before its DNS points at it"], ["probe --dns example.com", "whether a DNS change has reached every resolver"], ["probe --cors https://app.example.com --method PUT --cors-headers content-type,authorization https://api.example.com/items", "whether the browser would let the call through"]] });
2012
- if (values.cors === undefined) {
2013
- if (values.method !== undefined)
2014
- badUsage("--method goes with --cors");
2015
- if (values["cors-headers"] !== undefined)
2016
- badUsage("--cors-headers goes with --cors");
2017
- }
2018
- const headers = values.header ?? [];
2019
- for (const header of headers) {
2020
- if (!HEADER_LINE.test(header))
2021
- badUsage(`-H takes "Name: value", not ${header}`);
2022
- }
2023
- const timeoutMs = values.timeout === undefined ? undefined : duration(values.timeout, "timeout", 0, "s");
2024
- if (values.dns === true)
2025
- return dnsMain(positionals, timeoutMs, values.json === true);
2026
- const wire = { headers, resolve: resolvesOf(values.resolve ?? []), ...timeoutMs === undefined ? {} : { timeoutS: timeoutMs / 1000 } };
2027
- const targets = positionals.map((input) => {
2028
- const target = parseTarget(input);
2029
- if (target === undefined)
2030
- badUsage(`not a URL or domain: ${input}`);
2031
- return { input, target };
2032
- });
2033
- if (values.cors !== undefined) {
2034
- const origin = originOf(values.cors);
2035
- if (origin === undefined)
2036
- badUsage(`--cors takes an origin such as https://app.example.com, not ${values.cors}`);
2037
- const request = { origin, method: methodOf(values.method ?? "POST"), headers: requestedHeaders(values["cors-headers"] ?? "content-type") };
2038
- return corsMain(targets, request, { insecure: values.insecure === true, wire }, values.json === true);
2039
- }
2040
- const reports = await Promise.all(targets.map(async ({ input, target }) => probe(target, input, { insecure: values.insecure === true, wire })));
2041
- const [only] = reports;
2042
- if (reports.length === 1 && only !== undefined && "error" in only)
2043
- fail(only.error, 1);
2044
- if (values.json === true) {
2045
- printJson(reports.length === 1 ? only : reports);
2046
- return reports.some(unreached) ? 1 : 0;
2047
- }
2048
- let first = true;
2049
- for (const report of reports) {
2050
- if ("error" in report) {
2051
- console.error(marked("problem", report.error, process16.stderr));
2052
- } else if (values.verbose === true) {
2053
- if (!first)
2054
- console.log("");
2055
- if (reports.length > 1)
2056
- console.log(role("label", process16.stdout)(report.target));
2057
- print(report);
2058
- } else {
2059
- console.log(compact(report));
2060
- }
2061
- first = false;
2062
- }
2063
- return reports.some(unreached) ? 1 : 0;
2064
- }
2065
- process16.exitCode = await runMain({ name: "probe", run: main });
81
+ --cors <origin> sends the preflight a browser on that origin would send and says whether it would go on, with each reason when not.`,EXITS=[[0,"every site answered, warnings or not"],[1,"a site could not be reached or redirects where nothing answers, a CORS preflight was refused, or no resolver knows a name"],[2,"a usage error"]],OPTIONS={insecure:{type:"boolean",short:"k",description:"let curl go on with a certificate it does not trust"},header:{type:"string",short:"H",multiple:!0,description:"a `Name: value` header sent with every request, repeatable"},resolve:{type:"string",multiple:!0,description:"host:ip, reach the host at that address instead of the DNS answer, repeatable"},timeout:{type:"string",short:"t",description:"longest one request may take (20s, 3s for a DNS query): 5s, 1m, a bare number in seconds"},verbose:{type:"boolean",description:"the whole table for each target instead of one line"},dns:{type:"boolean",description:"compare what each resolver and the zone's nameservers answer for the host, no HTTP request",conflicts:["cors","header","resolve","insecure","verbose"]},cors:{type:"string",description:"the origin a browser would call from: whether its CORS preflight lets the request through",conflicts:["dns","verbose"]},method:{type:"string",description:"with --cors, the method of the request the preflight asks for (POST)"},"cors-headers":{type:"string",description:"with --cors, the headers it carries, comma separated, empty for none (content-type)"},json:jsonOption("one object per target {target, url, version, status, chain, timings, addresses, tls, certificate, headers, cdn, offers, httpRedirect, failedHop: {url, error} or null, warnings}, an array of them for several targets (an unreachable one is {target, error}); with --dns {target, zone, answers, agree, warnings}, with --cors {target, url, status, request, allowed, reasons, warnings, headers}")},BRACKETS2=/^\[|\]$/g,HEADER_LINE=/^[\w!#$%&'*+.^`|~-]+:/;async function follow(start,{insecure,wire},http3){let chain=[],url=start;while(chain.length<=MAX_HOPS){let{hop,errormsg}=await curlHop(url,{...wire,http3:http3&&url.startsWith("https:"),insecure,get:!1});if(hop===void 0)return{chain,failed:{url,error:errormsg??"no response"},tooMany:!1};chain.push(hop);let next=hop.location===void 0?void 0:nextUrl(hop.url,hop.location);if(!isRedirect(hop.status)||next===void 0)return{chain,tooMany:!1};url=next}return{chain,tooMany:!0}}async function probe(target,input,settings){let{wire}=settings,http3=await curlHasHttp3(),followed=await follow(target.url.href,settings,http3),httpsError;if(followed.chain.length===0&&target.bare){let plain=new URL(target.url.href);plain.protocol="http:";let second=await follow(plain.href,settings,http3);if(second.chain.length>0)httpsError=followed.failed?.error,followed=second}let final=followed.chain.at(-1);if(final===void 0)return{target:input,error:`could not reach ${target.url.host}: ${followed.failed?.error??"no response"}`};let finalUrl=new URL(final.url),secure=finalUrl.protocol==="https:",[addresses,tls,twin]=await Promise.all([addressesOf(target.url.hostname,wire.resolve),secure?tlsInfo(finalUrl.hostname,portOf(finalUrl),{address:wire.resolve?.get(finalUrl.hostname),...wire.timeoutS===void 0?{}:{timeoutS:wire.timeoutS}}):Promise.resolve(void 0),wantsHttpCheck(target)&&secure?twinOf(target.url,settings):Promise.resolve(void 0)]),httpRedirect=httpRedirectOf(twin),offers=offersOf({alpn:tls?.alpn,version:final.version,altSvc:final.headers["alt-svc"]}),warnings=warningsOf({cert:tls?.cert,authorizationError:tls?.authorizationError,httpRedirect,tooManyRedirects:followed.tooMany});if(followed.failed!==void 0)warnings.unshift(`the redirect to ${followed.failed.url} got no answer: ${followed.failed.error}`);if(!secure)warnings.push(httpsError===void 0?"the site is not served over https":`the site is not served over https: ${httpsError}`);return{target:input,url:final.url,version:final.version,status:final.status,chain:followed.chain.map((hop)=>({url:hop.url,status:hop.status,version:hop.version,...hop.location===void 0?{}:{location:hop.location},ms:hop.timings.total})),timings:final.timings,addresses,tls:tls===void 0?null:{protocol:tls.protocol,cipher:tls.cipher,...tls.alpn===void 0?{}:{alpn:tls.alpn}},certificate:tls?.cert??null,headers:worthKnowing(final.headers),cdn:cdnHint(final.headers)??null,offers,httpRedirect:httpRedirect??null,failedHop:followed.failed??null,warnings}}var unreached=(report)=>("error"in report)||report.failedHop!==null;async function twinOf(url,{insecure,wire}){let plain=new URL(url.href);return plain.protocol="http:",(await curlHop(plain.href,{...wire,http3:!1,insecure,get:!1})).hop}function resolvesOf(entries){let resolve=new Map;for(let entry of entries){let at=entry.indexOf(":"),address=entry.slice(at+1).replace(BRACKETS2,"");if(at<1||isIP2(address)===0)badUsage(`--resolve takes host:ip, not ${entry}`);resolve.set(entry.slice(0,at).toLowerCase(),address)}return resolve}function ms2(value){return`${value}ms`}function compact(report){let{dim}=paint(process16.stdout),redirects=report.chain.length-1,parts=[`${role("accent",process16.stdout)(versionLabel(report.version))} ${role("value",process16.stdout)(String(report.status))} ${role("path",process16.stdout)(report.url)}`,ms2(report.timings.total)],address=report.addresses.a[0]??report.addresses.aaaa[0];if(redirects>0)parts.push(`${redirects} ${redirects===1?"redirect":"redirects"}`);if(report.certificate!==null)parts.push(`cert ${daysLeftLabel(report.certificate.daysLeft)}`);if(address!==void 0)parts.push(address);let line=parts.join(dim(" "));return report.warnings.length===0?line:`${line} ${marked("warn",report.warnings.join("; "),process16.stdout)}`}function print(report){let label=role("label",process16.stdout),value=role("value",process16.stdout),accent=role("accent",process16.stdout),row=(name,text)=>console.log(`${label(name.padEnd(LABEL_WIDTH))} ${text}`);if(console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path",process16.stdout)(report.url)}`),console.log(""),report.chain.length>1)console.log(table(report.chain.map((hop)=>[String(hop.status),versionLabel(hop.version),ms2(hop.ms),hop.url]),{align:["right","left","right","left"]})),console.log("");let{timings}=report;if(row("timings",`dns ${ms2(timings.dns)}, connect ${ms2(timings.connect)}, tls ${ms2(timings.tls)}, first byte ${ms2(timings.firstByte)}, total ${ms2(timings.total)}`),row("addresses",[...report.addresses.a,...report.addresses.aaaa].join(", ")||"none found"),report.tls!==null)row("tls",`${report.tls.protocol} ${report.tls.cipher}`);let cert=report.certificate;if(cert!==null)row("issuer",cert.issuer),row("expires",`${cert.validTo.slice(0,10)} (${daysLeftLabel(cert.daysLeft)})`),row("names",cert.names.join(", "));row("offers",`h2 ${report.offers.h2?"yes":"no"}, h3 ${report.offers.h3?"yes":"no"}${report.offers.altSvc.length===0?"":` (alt-svc ${report.offers.altSvc.join(" ")})`}`);for(let[name,text]of Object.entries(report.headers))row(name==="strict-transport-security"?"hsts":name,text);if(report.cdn!==null)row("cdn",report.cdn);if(report.httpRedirect!==null)row("http://",report.httpRedirect.toHttps?`redirects to https (${report.httpRedirect.status})`:`answers ${report.httpRedirect.status}`);for(let warning of report.warnings)console.log(marked("warn",warning,process16.stdout))}function printDns(report){let label=role("label",process16.stdout),listed=(values)=>values.length===0?"-":values.join(" ");if(console.log(`${role("path",process16.stdout)(report.target)} ${label(report.zone===null?"no zone found":`zone ${report.zone}`)}`),console.log(table([["RESOLVER","SERVER","A","AAAA","CNAME","TTL"],...report.answers.map((answer)=>[answer.authoritative?`${answer.resolver} (ns)`:answer.resolver,answer.server,...answer.error===void 0?[listed(answer.a),listed(answer.aaaa),listed(answer.cname)]:[answer.error,"",""],answer.ttl===null?"-":`${answer.ttl}s`])],{header:!0})),report.agree)console.log(marked("ok","every resolver gives the same answer",process16.stdout));for(let warning of report.warnings)console.log(marked("warn",warning,process16.stdout))}async function dnsMain(inputs,timeoutMs,json){let hosts=inputs.map((input)=>{let host=parseTarget(input)?.url.hostname;if(host===void 0)badUsage(`not a URL or domain: ${input}`);if(isIP2(host.replace(BRACKETS2,""))!==0)badUsage(`--dns takes a name, not the address ${input}`);return{input,host}}),client=network(timeoutMs),reports=await Promise.all(hosts.map(async({input,host})=>dnsReport(input,host,client)));if(json)printJson(reports.length===1?reports[0]:reports);else for(let[at,report]of reports.entries()){if(at>0)console.log("");printDns(report)}return reports.every(known)?0:1}function printCors(report){let label=role("label",process16.stdout),{request}=report,asked=`from ${request.origin}, ${request.method}${request.headers.length===0?"":` with ${request.headers.join(", ")}`}`;console.log(`${marked(report.allowed?"ok":"problem",report.allowed?"allowed":"refused",process16.stdout)} ${role("value",process16.stdout)(String(report.status))} ${role("path",process16.stdout)(report.url)} ${label(asked)}`);for(let[name,value]of Object.entries(report.headers))console.log(` ${label(name)} ${value}`);for(let reason of report.reasons)console.log(marked("problem",reason,process16.stdout));for(let warning of report.warnings)console.log(marked("warn",warning,process16.stdout))}async function corsMain(targets,request,{insecure,wire},json){let reports=await Promise.all(targets.map(async({input,target})=>{let{hop,errormsg}=await curlPreflight(target.url.href,request,{...wire,insecure});if(hop===void 0)return{target:input,error:`could not reach ${target.url.host}: ${errormsg??"no response"}`};return{target:input,url:hop.url,status:hop.status,request,...corsVerdict(hop.status,hop.headers,request)}})),[only]=reports;if(reports.length===1&&only!==void 0&&"error"in only)fail(only.error,1);if(json)printJson(reports.length===1?only:reports);else for(let report of reports)if("error"in report)console.error(marked("problem",report.error,process16.stderr));else printCors(report);return reports.every((report)=>("allowed"in report)&&report.allowed)?0:1}async function main(args){let{values,positionals}=parse(args,USAGE,OPTIONS,{positionals:["<url|domain>..."],exits:EXITS,replaces:"the httpversion fish function, curl -sI chains, openssl s_client and dig @server one-liners",examples:["probe example.com","probe https://example.com/path --json",["probe a.test b.test","one line each"],['probe https://example.com --resolve example.com:203.0.113.7 -H "Host: example.com" --verbose',"a server before its DNS points at it"],["probe --dns example.com","whether a DNS change has reached every resolver"],["probe --cors https://app.example.com --method PUT --cors-headers content-type,authorization https://api.example.com/items","whether the browser would let the call through"]]});if(values.cors===void 0){if(values.method!==void 0)badUsage("--method goes with --cors");if(values["cors-headers"]!==void 0)badUsage("--cors-headers goes with --cors")}let headers=values.header??[];for(let header of headers)if(!HEADER_LINE.test(header))badUsage(`-H takes "Name: value", not ${header}`);let timeoutMs=values.timeout===void 0?void 0:duration(values.timeout,"timeout",0,"s");if(values.dns===!0)return dnsMain(positionals,timeoutMs,values.json===!0);let wire={headers,resolve:resolvesOf(values.resolve??[]),...timeoutMs===void 0?{}:{timeoutS:timeoutMs/1000}},targets=positionals.map((input)=>{let target=parseTarget(input);if(target===void 0)badUsage(`not a URL or domain: ${input}`);return{input,target}});if(values.cors!==void 0){let origin=originOf(values.cors);if(origin===void 0)badUsage(`--cors takes an origin such as https://app.example.com, not ${values.cors}`);let request={origin,method:methodOf(values.method??"POST"),headers:requestedHeaders(values["cors-headers"]??"content-type")};return corsMain(targets,request,{insecure:values.insecure===!0,wire},values.json===!0)}let reports=await Promise.all(targets.map(async({input,target})=>probe(target,input,{insecure:values.insecure===!0,wire}))),[only]=reports;if(reports.length===1&&only!==void 0&&"error"in only)fail(only.error,1);if(values.json===!0)return printJson(reports.length===1?only:reports),reports.some(unreached)?1:0;let first=!0;for(let report of reports){if("error"in report)console.error(marked("problem",report.error,process16.stderr));else if(values.verbose===!0){if(!first)console.log("");if(reports.length>1)console.log(role("label",process16.stdout)(report.target));print(report)}else console.log(compact(report));first=!1}return reports.some(unreached)?1:0}process16.exitCode=await runMain({name:"probe",run:main});