@kaynooo/cli-probe 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +27 -2
- package/dist/probe.js +1362 -0
- package/package.json +38 -4
package/dist/probe.js
ADDED
|
@@ -0,0 +1,1362 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// src/probe.ts
|
|
5
|
+
import { isIP as isIP2 } from "net";
|
|
6
|
+
import process9 from "process";
|
|
7
|
+
// ../kit/src/args.ts
|
|
8
|
+
import process5 from "process";
|
|
9
|
+
import { parseArgs } from "util";
|
|
10
|
+
|
|
11
|
+
// ../kit/src/format.ts
|
|
12
|
+
import process3 from "process";
|
|
13
|
+
|
|
14
|
+
// ../kit/src/style.ts
|
|
15
|
+
import process2 from "process";
|
|
16
|
+
|
|
17
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
18
|
+
function x(s) {
|
|
19
|
+
let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
|
|
20
|
+
if (!/^[a-f0-9]+$/.test(r))
|
|
21
|
+
return [0, 0, 0];
|
|
22
|
+
let t = r.length, n = (c) => Number.parseInt(c, 16);
|
|
23
|
+
if (t === 3 || t === 4) {
|
|
24
|
+
let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
|
|
25
|
+
return g !== undefined ? [c, u, h, g] : [c, u, h];
|
|
26
|
+
}
|
|
27
|
+
if (t !== 6 && t !== 8)
|
|
28
|
+
throw Error(`Invalid hex color length: ${t}`);
|
|
29
|
+
let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
|
|
30
|
+
if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
|
|
31
|
+
throw Error(`Invalid hex color value: ${s}`);
|
|
32
|
+
return y !== undefined ? [a, b, o, y] : [a, b, o];
|
|
33
|
+
}
|
|
34
|
+
function A(s) {
|
|
35
|
+
let [r, t, n, a] = s;
|
|
36
|
+
if (a)
|
|
37
|
+
return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
|
|
38
|
+
return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
|
|
39
|
+
}
|
|
40
|
+
function R(s, r, t) {
|
|
41
|
+
s = (s % 360 + 360) % 360, t /= 100;
|
|
42
|
+
let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
|
|
43
|
+
let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
|
|
44
|
+
return Math.round(255 * y);
|
|
45
|
+
};
|
|
46
|
+
return [a(0), a(8), a(4)];
|
|
47
|
+
}
|
|
48
|
+
function k(s) {
|
|
49
|
+
let [r, t, n] = s;
|
|
50
|
+
r /= 255, t /= 255, n /= 255;
|
|
51
|
+
let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
|
|
52
|
+
if (a !== b) {
|
|
53
|
+
let u = a - b;
|
|
54
|
+
if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
|
|
55
|
+
o = (t - n) / u + (t < n ? 6 : 0);
|
|
56
|
+
else if (a === t)
|
|
57
|
+
o = (n - r) / u + 2;
|
|
58
|
+
else
|
|
59
|
+
o = (r - t) / u + 4;
|
|
60
|
+
o /= 6;
|
|
61
|
+
}
|
|
62
|
+
return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
|
|
63
|
+
}
|
|
64
|
+
function H(s, r, t) {
|
|
65
|
+
s = (s % 360 + 360) % 360, r /= 100, t /= 100;
|
|
66
|
+
let n = (a) => {
|
|
67
|
+
let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
|
|
68
|
+
return Math.round(255 * o);
|
|
69
|
+
};
|
|
70
|
+
return [n(5), n(3), n(1)];
|
|
71
|
+
}
|
|
72
|
+
function f(s) {
|
|
73
|
+
let [r, t, n] = s;
|
|
74
|
+
r /= 255, t /= 255, n /= 255;
|
|
75
|
+
let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
|
|
76
|
+
if (o !== 0) {
|
|
77
|
+
if (a === r)
|
|
78
|
+
y = (t - n) / o + (t < n ? 6 : 0);
|
|
79
|
+
else if (a === t)
|
|
80
|
+
y = (n - r) / o + 2;
|
|
81
|
+
else
|
|
82
|
+
y = (r - t) / o + 4;
|
|
83
|
+
y /= 6;
|
|
84
|
+
}
|
|
85
|
+
return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
|
|
86
|
+
}
|
|
87
|
+
function O(s) {
|
|
88
|
+
let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
|
|
89
|
+
if (a === 1)
|
|
90
|
+
return [0, 0, 0, 100];
|
|
91
|
+
let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
|
|
92
|
+
return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
|
|
93
|
+
}
|
|
94
|
+
function v(s, r, t, n) {
|
|
95
|
+
return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
|
|
96
|
+
}
|
|
97
|
+
var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
98
|
+
var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
|
|
99
|
+
var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
|
|
100
|
+
function T(s) {
|
|
101
|
+
let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
|
|
102
|
+
return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
|
|
103
|
+
}
|
|
104
|
+
function M(s, r, t) {
|
|
105
|
+
let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
|
|
106
|
+
return [u(o), u(y), u(c)];
|
|
107
|
+
}
|
|
108
|
+
function d(s) {
|
|
109
|
+
let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
|
|
110
|
+
return [i(r, 4), i(a, 4), i(b, 2)];
|
|
111
|
+
}
|
|
112
|
+
function C(s, r, t) {
|
|
113
|
+
let n = t * Math.PI / 180;
|
|
114
|
+
return M(s, r * Math.cos(n), r * Math.sin(n));
|
|
115
|
+
}
|
|
116
|
+
function l(s) {
|
|
117
|
+
let r = s / 255;
|
|
118
|
+
return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
class e {
|
|
122
|
+
r;
|
|
123
|
+
g;
|
|
124
|
+
b;
|
|
125
|
+
a;
|
|
126
|
+
constructor(s, r, t, n = 1) {
|
|
127
|
+
this.r = s, this.g = r, this.b = t, this.a = n;
|
|
128
|
+
}
|
|
129
|
+
static from(s, r) {
|
|
130
|
+
if (s === "hex") {
|
|
131
|
+
let [t, n, a, b] = x(r);
|
|
132
|
+
return new e(t, n, a, b);
|
|
133
|
+
}
|
|
134
|
+
if (s === "rgb") {
|
|
135
|
+
if (Array.isArray(r)) {
|
|
136
|
+
let [o, y, c, u] = r;
|
|
137
|
+
return new e(o, y, c, u);
|
|
138
|
+
}
|
|
139
|
+
let { r: t, g: n, b: a, a: b } = r;
|
|
140
|
+
return new e(t, n, a, b);
|
|
141
|
+
}
|
|
142
|
+
if (s === "hsl") {
|
|
143
|
+
let t, n, a, b;
|
|
144
|
+
if (Array.isArray(r))
|
|
145
|
+
[t, n, a, b] = r;
|
|
146
|
+
else
|
|
147
|
+
({ h: t, s: n, l: a, a: b } = r);
|
|
148
|
+
let [o, y, c] = R(t, n, a);
|
|
149
|
+
return new e(o, y, c, b);
|
|
150
|
+
}
|
|
151
|
+
if (s === "hsv") {
|
|
152
|
+
let t, n, a, b;
|
|
153
|
+
if (Array.isArray(r))
|
|
154
|
+
[t, n, a, b] = r;
|
|
155
|
+
else
|
|
156
|
+
({ h: t, s: n, v: a, a: b } = r);
|
|
157
|
+
let [o, y, c] = H(t, n, a);
|
|
158
|
+
return new e(o, y, c, b);
|
|
159
|
+
}
|
|
160
|
+
if (s === "cmyk") {
|
|
161
|
+
let t, n, a, b, o;
|
|
162
|
+
if (Array.isArray(r))
|
|
163
|
+
[t, n, a, b, o] = r;
|
|
164
|
+
else
|
|
165
|
+
({ c: t, m: n, y: a, k: b, a: o } = r);
|
|
166
|
+
let [y, c, u] = v(t, n, a, b);
|
|
167
|
+
return new e(y, c, u, o);
|
|
168
|
+
}
|
|
169
|
+
if (s === "oklch") {
|
|
170
|
+
let t, n, a, b;
|
|
171
|
+
if (Array.isArray(r))
|
|
172
|
+
[t, n, a, b] = r;
|
|
173
|
+
else
|
|
174
|
+
({ l: t, c: n, h: a, a: b } = r);
|
|
175
|
+
let [o, y, c] = C(t, n, a);
|
|
176
|
+
return new e(o, y, c, b);
|
|
177
|
+
}
|
|
178
|
+
if (s === "oklab") {
|
|
179
|
+
let t, n, a, b;
|
|
180
|
+
if (Array.isArray(r))
|
|
181
|
+
[t, n, a, b] = r;
|
|
182
|
+
else
|
|
183
|
+
({ l: t, a: n, b: a, alpha: b } = r);
|
|
184
|
+
let [o, y, c] = M(t, n, a);
|
|
185
|
+
return new e(o, y, c, b);
|
|
186
|
+
}
|
|
187
|
+
throw Error("Invalid input");
|
|
188
|
+
}
|
|
189
|
+
to(s) {
|
|
190
|
+
switch (s) {
|
|
191
|
+
case "rgb":
|
|
192
|
+
return [this.r, this.g, this.b];
|
|
193
|
+
case "rgba":
|
|
194
|
+
return [this.r, this.g, this.b, this.a];
|
|
195
|
+
case "hex":
|
|
196
|
+
return A([this.r, this.g, this.b]);
|
|
197
|
+
case "hexa":
|
|
198
|
+
return A([this.r, this.g, this.b, this.a]);
|
|
199
|
+
case "hsl":
|
|
200
|
+
return k([this.r, this.g, this.b]);
|
|
201
|
+
case "hsla":
|
|
202
|
+
return [...k([this.r, this.g, this.b]), this.a];
|
|
203
|
+
case "hsv":
|
|
204
|
+
return f([this.r, this.g, this.b]);
|
|
205
|
+
case "hsva":
|
|
206
|
+
return [...f([this.r, this.g, this.b]), this.a];
|
|
207
|
+
case "cmyk":
|
|
208
|
+
return O([this.r, this.g, this.b]);
|
|
209
|
+
case "cmyka":
|
|
210
|
+
return [...O([this.r, this.g, this.b]), this.a];
|
|
211
|
+
case "oklch":
|
|
212
|
+
return d([this.r, this.g, this.b]);
|
|
213
|
+
case "oklcha":
|
|
214
|
+
return [...d([this.r, this.g, this.b]), this.a];
|
|
215
|
+
case "oklab":
|
|
216
|
+
return T([this.r, this.g, this.b]);
|
|
217
|
+
case "oklaba":
|
|
218
|
+
return [...T([this.r, this.g, this.b]), this.a];
|
|
219
|
+
default:
|
|
220
|
+
return [this.r, this.g, this.b];
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
getLuminance() {
|
|
224
|
+
let s = l(this.r), r = l(this.g), t = l(this.b);
|
|
225
|
+
return 0.2126 * s + 0.7152 * r + 0.0722 * t;
|
|
226
|
+
}
|
|
227
|
+
contrastRatio(s) {
|
|
228
|
+
let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
|
|
229
|
+
return (n + 0.05) / (a + 0.05);
|
|
230
|
+
}
|
|
231
|
+
bestContrastForeground() {
|
|
232
|
+
let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
|
|
233
|
+
return t >= n ? s : r;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
|
|
238
|
+
var r = 39;
|
|
239
|
+
var o = 49;
|
|
240
|
+
var f2 = "\x1B[";
|
|
241
|
+
var C2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
|
|
242
|
+
let [a, l, s] = e.from("hex", i).to("rgb");
|
|
243
|
+
return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
|
|
244
|
+
}, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
|
|
245
|
+
var b = new Set(["", "1", "2", "3", "true"]);
|
|
246
|
+
function h(i, n = globalThis.process?.env ?? {}) {
|
|
247
|
+
if (n.FORCE_COLOR !== undefined)
|
|
248
|
+
return b.has(n.FORCE_COLOR);
|
|
249
|
+
if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
|
|
250
|
+
return false;
|
|
251
|
+
return i?.isTTY === true;
|
|
252
|
+
}
|
|
253
|
+
function d2(i, n, a) {
|
|
254
|
+
if (!h(a.stream ?? globalThis.process?.stdout, a.env))
|
|
255
|
+
return n;
|
|
256
|
+
let l = "", s = "";
|
|
257
|
+
for (let g = 0, y = i.length;g < y; g++) {
|
|
258
|
+
let [c, p] = i[g];
|
|
259
|
+
l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
|
|
260
|
+
}
|
|
261
|
+
return l + n + s;
|
|
262
|
+
}
|
|
263
|
+
function u(i, n = []) {
|
|
264
|
+
return new Proxy((l) => d2(n, l, i), { get(l, s) {
|
|
265
|
+
let g = C2[s];
|
|
266
|
+
if (Array.isArray(g))
|
|
267
|
+
return u(i, [...n, g]);
|
|
268
|
+
if (typeof g === "function")
|
|
269
|
+
return (...y) => u(i, [...n, g(...y)]);
|
|
270
|
+
throw Error(`Unknown style: ${String(s)}`);
|
|
271
|
+
} });
|
|
272
|
+
}
|
|
273
|
+
function le(i = {}) {
|
|
274
|
+
return u(i);
|
|
275
|
+
}
|
|
276
|
+
var t = le();
|
|
277
|
+
|
|
278
|
+
// ../kit/src/style.ts
|
|
279
|
+
var MARKS = {
|
|
280
|
+
ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
|
|
281
|
+
warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
|
|
282
|
+
problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
|
|
283
|
+
note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
|
|
284
|
+
};
|
|
285
|
+
function takesControlCodes(stream, env = process2.env) {
|
|
286
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
287
|
+
}
|
|
288
|
+
function paint(stream, env = process2.env) {
|
|
289
|
+
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
290
|
+
}
|
|
291
|
+
function marked(mark, text, stream, detail, env = process2.env) {
|
|
292
|
+
const colors = paint(stream, env);
|
|
293
|
+
const { symbol, word, paint: tint } = MARKS[mark];
|
|
294
|
+
const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
|
|
295
|
+
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
296
|
+
}
|
|
297
|
+
var ROLES = {
|
|
298
|
+
accent: (colors) => colors.cyan,
|
|
299
|
+
id: (colors) => colors.yellow,
|
|
300
|
+
path: (colors) => colors.blue,
|
|
301
|
+
label: (colors) => colors.dim,
|
|
302
|
+
value: (colors) => colors.bold
|
|
303
|
+
};
|
|
304
|
+
function role(name, stream, env = process2.env) {
|
|
305
|
+
return ROLES[name](paint(stream, env));
|
|
306
|
+
}
|
|
307
|
+
var STATUSES = {
|
|
308
|
+
passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
|
|
309
|
+
failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
|
|
310
|
+
running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
|
|
311
|
+
queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
|
|
312
|
+
skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
|
|
313
|
+
};
|
|
314
|
+
var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
|
|
315
|
+
|
|
316
|
+
// ../kit/src/format.ts
|
|
317
|
+
function upTo(text, separator) {
|
|
318
|
+
const end = text.indexOf(separator);
|
|
319
|
+
return end === -1 ? text : text.slice(0, end);
|
|
320
|
+
}
|
|
321
|
+
function truncate(text, width) {
|
|
322
|
+
return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
|
|
323
|
+
}
|
|
324
|
+
var LINE_BREAKS = /\s*\n\s*/g;
|
|
325
|
+
var ESCAPE = String.fromCharCode(27);
|
|
326
|
+
function textWidth(text) {
|
|
327
|
+
return Bun.stringWidth(text);
|
|
328
|
+
}
|
|
329
|
+
function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
|
|
330
|
+
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
331
|
+
const widths = [];
|
|
332
|
+
for (const row of cells) {
|
|
333
|
+
for (const [index, cell] of row.entries())
|
|
334
|
+
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
335
|
+
}
|
|
336
|
+
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
337
|
+
const colors = paint(process3.stdout);
|
|
338
|
+
const lines = shown.map((row) => row.map((cell, index) => {
|
|
339
|
+
const width = widths[index] ?? 0;
|
|
340
|
+
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
341
|
+
if (align[index] === "right")
|
|
342
|
+
return `${gap}${cell}`;
|
|
343
|
+
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
344
|
+
}).join(" ").trimEnd());
|
|
345
|
+
return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
|
|
346
|
+
`);
|
|
347
|
+
}
|
|
348
|
+
function narrow(rows, widths, limit) {
|
|
349
|
+
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
350
|
+
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
351
|
+
const floor = 8;
|
|
352
|
+
while (used() > limit) {
|
|
353
|
+
let widest = -1;
|
|
354
|
+
for (const [index, width] of widths.entries()) {
|
|
355
|
+
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
356
|
+
widest = index;
|
|
357
|
+
}
|
|
358
|
+
if (widest === -1)
|
|
359
|
+
break;
|
|
360
|
+
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
361
|
+
}
|
|
362
|
+
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
363
|
+
}
|
|
364
|
+
function printJson(value) {
|
|
365
|
+
console.log(JSON.stringify(value, undefined, 2));
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// ../kit/src/help.ts
|
|
369
|
+
import process4 from "process";
|
|
370
|
+
var OPTIONAL = /\[[^\]]+\]/g;
|
|
371
|
+
var USAGE_PREFIX = /^usage:\s*/i;
|
|
372
|
+
var FULL_STOP = /\.$/;
|
|
373
|
+
function usageLine(usage, colors = paint(process4.stdout)) {
|
|
374
|
+
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
375
|
+
}
|
|
376
|
+
function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
377
|
+
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
378
|
+
`);
|
|
379
|
+
}
|
|
380
|
+
function exitRows(exits, colors = paint(process4.stdout)) {
|
|
381
|
+
if (exits.length === 0)
|
|
382
|
+
return [];
|
|
383
|
+
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
384
|
+
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
385
|
+
}
|
|
386
|
+
function replacesRows(replaces, colors = paint(process4.stdout)) {
|
|
387
|
+
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
388
|
+
}
|
|
389
|
+
function wantsHelpJson(env = process4.env) {
|
|
390
|
+
return env.KIT_HELP === "json";
|
|
391
|
+
}
|
|
392
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
393
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
394
|
+
`);
|
|
395
|
+
const first = lines[0];
|
|
396
|
+
const colon = first.indexOf(": ");
|
|
397
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
398
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
399
|
+
return {
|
|
400
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
401
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
402
|
+
...replaces === undefined ? {} : { replaces },
|
|
403
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
404
|
+
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
405
|
+
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
function exampleRows(examples, colors = paint(process4.stdout)) {
|
|
409
|
+
if (examples.length === 0)
|
|
410
|
+
return [];
|
|
411
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
412
|
+
}
|
|
413
|
+
function optionRows(options, colors = paint(process4.stdout)) {
|
|
414
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
415
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
416
|
+
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
417
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
418
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
419
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
|
|
420
|
+
});
|
|
421
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
422
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// ../kit/src/text.ts
|
|
426
|
+
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
427
|
+
function distance(a, b) {
|
|
428
|
+
let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
429
|
+
for (const [i, left] of [...a].entries()) {
|
|
430
|
+
const current = [i + 1];
|
|
431
|
+
for (const [j, right] of [...b].entries())
|
|
432
|
+
current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
|
|
433
|
+
previous = current;
|
|
434
|
+
}
|
|
435
|
+
return previous[b.length] ?? 0;
|
|
436
|
+
}
|
|
437
|
+
function closest(name, names) {
|
|
438
|
+
const started = names.find((known) => known.startsWith(name));
|
|
439
|
+
if (started !== undefined)
|
|
440
|
+
return started;
|
|
441
|
+
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
442
|
+
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
443
|
+
}
|
|
444
|
+
// ../kit/src/input.ts
|
|
445
|
+
var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
|
|
446
|
+
var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
447
|
+
function duration(value, name, fallback, unit = "s") {
|
|
448
|
+
if (value === undefined)
|
|
449
|
+
return fallback;
|
|
450
|
+
const match = DURATION.exec(value.trim());
|
|
451
|
+
const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
|
|
452
|
+
if (ms < 1)
|
|
453
|
+
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
454
|
+
return ms;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// ../kit/src/args.ts
|
|
458
|
+
var DASHES = /^-+/;
|
|
459
|
+
function jsonOption(holds) {
|
|
460
|
+
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
class Exit extends Error {
|
|
464
|
+
code;
|
|
465
|
+
hint;
|
|
466
|
+
constructor(message, code, hint) {
|
|
467
|
+
super(message);
|
|
468
|
+
this.code = code;
|
|
469
|
+
this.hint = hint;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
function fail(message, code = 2, hint) {
|
|
473
|
+
throw new Exit(message, code, hint);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
class UsageError extends Exit {
|
|
477
|
+
constructor(message, hint) {
|
|
478
|
+
super(message, 2, hint);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
function badUsage(message) {
|
|
482
|
+
throw new UsageError(message);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
class HelpShown extends Exit {
|
|
486
|
+
constructor() {
|
|
487
|
+
super("help shown", 0);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
class Completing {
|
|
492
|
+
options;
|
|
493
|
+
positionals;
|
|
494
|
+
candidates;
|
|
495
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
496
|
+
this.options = options;
|
|
497
|
+
this.positionals = positionals;
|
|
498
|
+
this.candidates = candidates;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
var completion = { active: false };
|
|
502
|
+
var OUTPUT_OPTIONS = {
|
|
503
|
+
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
504
|
+
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
505
|
+
};
|
|
506
|
+
function applyOutput(color, plain, env = process5.env) {
|
|
507
|
+
const when = plain === true ? "never" : color ?? "auto";
|
|
508
|
+
if (when === "auto")
|
|
509
|
+
return;
|
|
510
|
+
if (when !== "always" && when !== "never")
|
|
511
|
+
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
512
|
+
if (when === "always") {
|
|
513
|
+
env.FORCE_COLOR = "1";
|
|
514
|
+
delete env.NO_COLOR;
|
|
515
|
+
} else {
|
|
516
|
+
env.NO_COLOR = "1";
|
|
517
|
+
delete env.FORCE_COLOR;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
function parse(args, usage, options, settings = {}) {
|
|
521
|
+
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
522
|
+
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
523
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
524
|
+
if (completion.active)
|
|
525
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
526
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
527
|
+
let parsed;
|
|
528
|
+
try {
|
|
529
|
+
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
530
|
+
} catch (error) {
|
|
531
|
+
const message = parseError(error);
|
|
532
|
+
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
533
|
+
}
|
|
534
|
+
const values = parsed.values;
|
|
535
|
+
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
536
|
+
if (values.help === true) {
|
|
537
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
538
|
+
throw new HelpShown;
|
|
539
|
+
}
|
|
540
|
+
checkChoices(parsed.values, all);
|
|
541
|
+
checkConflicts(parsed.values, all);
|
|
542
|
+
if (settings.positionals !== undefined)
|
|
543
|
+
checkPositionals(parsed.positionals, settings.positionals);
|
|
544
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
545
|
+
}
|
|
546
|
+
function splitRest(args, passes) {
|
|
547
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
548
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
549
|
+
}
|
|
550
|
+
function splitTrailing(args, options, count) {
|
|
551
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
552
|
+
let seen = 0;
|
|
553
|
+
if (count === 0)
|
|
554
|
+
return { own: args, rest: undefined };
|
|
555
|
+
for (let at = 0;at < args.length; at++) {
|
|
556
|
+
const word = args[at];
|
|
557
|
+
if (word === "--")
|
|
558
|
+
break;
|
|
559
|
+
if (word.startsWith("-")) {
|
|
560
|
+
if (takesValue(word))
|
|
561
|
+
at++;
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
seen++;
|
|
565
|
+
if (seen === count)
|
|
566
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
567
|
+
}
|
|
568
|
+
return { own: args, rest: undefined };
|
|
569
|
+
}
|
|
570
|
+
function listed(options, allowNegative) {
|
|
571
|
+
if (!allowNegative)
|
|
572
|
+
return options;
|
|
573
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
574
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
575
|
+
return [[name, option]];
|
|
576
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
577
|
+
}));
|
|
578
|
+
}
|
|
579
|
+
function withAliases(args, options) {
|
|
580
|
+
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
581
|
+
if (named.size === 0)
|
|
582
|
+
return args;
|
|
583
|
+
const separator = args.indexOf("--");
|
|
584
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
585
|
+
return [...own.map((arg) => {
|
|
586
|
+
const at = arg.indexOf("=");
|
|
587
|
+
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
588
|
+
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
589
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
590
|
+
}
|
|
591
|
+
function withBare(args, options) {
|
|
592
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
593
|
+
if (bare.size === 0)
|
|
594
|
+
return args;
|
|
595
|
+
const separator = args.indexOf("--");
|
|
596
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
597
|
+
return [...own.flatMap((arg, index) => {
|
|
598
|
+
const optional = bare.get(arg);
|
|
599
|
+
const next = own[index + 1];
|
|
600
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
601
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
602
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
603
|
+
}
|
|
604
|
+
function checkConflicts(values, options) {
|
|
605
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
606
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
607
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
608
|
+
if (other !== undefined)
|
|
609
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
function checkChoices(values, options) {
|
|
613
|
+
for (const [name, option] of Object.entries(options)) {
|
|
614
|
+
if (option.choices === undefined)
|
|
615
|
+
continue;
|
|
616
|
+
const given = values[name];
|
|
617
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
618
|
+
if (typeof value === "string")
|
|
619
|
+
oneOf(value, name, option.choices);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
function oneOf(value, name, choices) {
|
|
624
|
+
if (!choices.includes(value))
|
|
625
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
626
|
+
return value;
|
|
627
|
+
}
|
|
628
|
+
function checkPositionals(given, names) {
|
|
629
|
+
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
630
|
+
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
631
|
+
if (given.length < required)
|
|
632
|
+
badUsage(`missing ${names[given.length]}`);
|
|
633
|
+
if (!variadic && given.length > names.length)
|
|
634
|
+
badUsage(`unexpected argument ${given[names.length]}`);
|
|
635
|
+
}
|
|
636
|
+
function joinDashValues(args, options) {
|
|
637
|
+
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
638
|
+
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
639
|
+
const joined = [];
|
|
640
|
+
for (let i = 0;i < args.length; i++) {
|
|
641
|
+
const arg = args[i] ?? "";
|
|
642
|
+
if (arg === "--")
|
|
643
|
+
return [...joined, ...args.slice(i)];
|
|
644
|
+
const name = longOf.get(arg);
|
|
645
|
+
const next = args[i + 1];
|
|
646
|
+
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
647
|
+
joined.push(`--${name}=${next}`);
|
|
648
|
+
i++;
|
|
649
|
+
} else {
|
|
650
|
+
joined.push(arg);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
return joined;
|
|
654
|
+
}
|
|
655
|
+
function parseError(error) {
|
|
656
|
+
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
657
|
+
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
658
|
+
}
|
|
659
|
+
var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
660
|
+
function nearestOption(message, options, allowNegative) {
|
|
661
|
+
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
662
|
+
if (typed === undefined)
|
|
663
|
+
return;
|
|
664
|
+
const word = typed.replace(DASHES, "");
|
|
665
|
+
if (word.length < 2 && !typed.startsWith("--"))
|
|
666
|
+
return;
|
|
667
|
+
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
668
|
+
...option.short === undefined ? [] : [`-${option.short}`],
|
|
669
|
+
`--${name}`,
|
|
670
|
+
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
671
|
+
]);
|
|
672
|
+
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
673
|
+
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
674
|
+
}
|
|
675
|
+
// ../kit/src/progress.ts
|
|
676
|
+
var ESC = String.fromCharCode(27);
|
|
677
|
+
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
678
|
+
var RESET_STYLE = `${ESC}[0m`;
|
|
679
|
+
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
680
|
+
// ../kit/src/cli.ts
|
|
681
|
+
import { readFileSync, realpathSync } from "fs";
|
|
682
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
683
|
+
import process7 from "process";
|
|
684
|
+
|
|
685
|
+
// ../kit/src/usage.ts
|
|
686
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
687
|
+
import { homedir } from "os";
|
|
688
|
+
import { dirname, isAbsolute, join } from "path";
|
|
689
|
+
import process6 from "process";
|
|
690
|
+
|
|
691
|
+
// ../kit/src/logs.ts
|
|
692
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
693
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
694
|
+
|
|
695
|
+
// ../kit/src/usage.ts
|
|
696
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
697
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
698
|
+
var LONGEST_NAME = 40;
|
|
699
|
+
var usageError;
|
|
700
|
+
function noteUsageError(message) {
|
|
701
|
+
usageError = message;
|
|
702
|
+
}
|
|
703
|
+
function stateHome(env = process6.env) {
|
|
704
|
+
const dir = env.XDG_STATE_HOME;
|
|
705
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
706
|
+
}
|
|
707
|
+
function usagePath(env = process6.env) {
|
|
708
|
+
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
709
|
+
}
|
|
710
|
+
function usageRecorded(env = process6.env) {
|
|
711
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
712
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
713
|
+
}
|
|
714
|
+
function flagNames(argv) {
|
|
715
|
+
const end = argv.indexOf("--");
|
|
716
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
717
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
718
|
+
}
|
|
719
|
+
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
720
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
721
|
+
usageError = undefined;
|
|
722
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
723
|
+
}
|
|
724
|
+
function recordUsage(entry, env = process6.env) {
|
|
725
|
+
if (!usageRecorded(env))
|
|
726
|
+
return;
|
|
727
|
+
try {
|
|
728
|
+
const path = usagePath(env);
|
|
729
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
730
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
731
|
+
`, { mode: 384 });
|
|
732
|
+
} catch {}
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// ../kit/src/cli.ts
|
|
736
|
+
var LEVEL_OPTIONS = {
|
|
737
|
+
...OUTPUT_OPTIONS,
|
|
738
|
+
help: { type: "boolean", short: "h", description: "show this help" }
|
|
739
|
+
};
|
|
740
|
+
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
741
|
+
function printError(prefix, message, hint, cause) {
|
|
742
|
+
const colors = paint(process7.stderr);
|
|
743
|
+
const styled = takesControlCodes(process7.stderr);
|
|
744
|
+
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
745
|
+
const under = (label, text, tint) => text === undefined ? "" : `
|
|
746
|
+
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
747
|
+
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
748
|
+
}
|
|
749
|
+
function printJsonError(message, hint, cause) {
|
|
750
|
+
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
751
|
+
}
|
|
752
|
+
function wantsJson(argv) {
|
|
753
|
+
const end = argv.indexOf("--");
|
|
754
|
+
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
755
|
+
}
|
|
756
|
+
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
757
|
+
if (error instanceof HelpShown)
|
|
758
|
+
return 0;
|
|
759
|
+
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
760
|
+
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
761
|
+
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
762
|
+
if (error instanceof UsageError)
|
|
763
|
+
noteUsageError(error.message);
|
|
764
|
+
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
765
|
+
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
766
|
+
return error instanceof Exit ? error.code : 1;
|
|
767
|
+
}
|
|
768
|
+
var COMPLETE = "__complete";
|
|
769
|
+
var FILES = "__files__";
|
|
770
|
+
async function completingOf(run) {
|
|
771
|
+
completion.active = true;
|
|
772
|
+
try {
|
|
773
|
+
await run([]);
|
|
774
|
+
} catch (error) {
|
|
775
|
+
if (error instanceof Completing)
|
|
776
|
+
return error;
|
|
777
|
+
} finally {
|
|
778
|
+
completion.active = false;
|
|
779
|
+
}
|
|
780
|
+
return new Completing({});
|
|
781
|
+
}
|
|
782
|
+
function candidateLine(candidate) {
|
|
783
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
784
|
+
}
|
|
785
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
786
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
787
|
+
let index = 0;
|
|
788
|
+
let at = 0;
|
|
789
|
+
while (at < before.length) {
|
|
790
|
+
const word = before[at];
|
|
791
|
+
if (word === "--") {
|
|
792
|
+
index += before.length - at - 1;
|
|
793
|
+
break;
|
|
794
|
+
}
|
|
795
|
+
if (!word.startsWith("-"))
|
|
796
|
+
index++;
|
|
797
|
+
else if (takesValue(word))
|
|
798
|
+
at++;
|
|
799
|
+
at++;
|
|
800
|
+
}
|
|
801
|
+
const last = positionals.at(-1);
|
|
802
|
+
if (index < positionals.length)
|
|
803
|
+
return positionals[index];
|
|
804
|
+
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
805
|
+
}
|
|
806
|
+
async function leafCandidates(run, words) {
|
|
807
|
+
const completing = await completingOf(run);
|
|
808
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
809
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
810
|
+
const flag = words.at(-2);
|
|
811
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
812
|
+
if (option?.type === "string") {
|
|
813
|
+
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
814
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
815
|
+
}
|
|
816
|
+
const name = positionalBeingTyped(words.slice(0, -1), completing);
|
|
817
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
818
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
819
|
+
}
|
|
820
|
+
async function printCandidates(found) {
|
|
821
|
+
for (const line of await found)
|
|
822
|
+
console.log(line);
|
|
823
|
+
return 0;
|
|
824
|
+
}
|
|
825
|
+
function packageVersion(entry = Bun.main) {
|
|
826
|
+
for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
|
|
827
|
+
try {
|
|
828
|
+
const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
|
|
829
|
+
if (typeof version === "string")
|
|
830
|
+
return version;
|
|
831
|
+
} catch {}
|
|
832
|
+
if (dirname2(dir) === dir)
|
|
833
|
+
return "0.0.0";
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
|
|
837
|
+
if (argv[0] === COMPLETE)
|
|
838
|
+
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
839
|
+
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
840
|
+
console.log(version ?? packageVersion());
|
|
841
|
+
return 0;
|
|
842
|
+
}
|
|
843
|
+
let code;
|
|
844
|
+
try {
|
|
845
|
+
code = await run(argv);
|
|
846
|
+
} catch (error) {
|
|
847
|
+
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
848
|
+
}
|
|
849
|
+
if (usage !== false) {
|
|
850
|
+
try {
|
|
851
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
852
|
+
} catch {}
|
|
853
|
+
}
|
|
854
|
+
return code;
|
|
855
|
+
}
|
|
856
|
+
// ../kit/src/secrets.ts
|
|
857
|
+
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
858
|
+
// ../kit/src/sessions.ts
|
|
859
|
+
var {Glob } = globalThis.Bun;
|
|
860
|
+
var SESSION_FILES = new Glob("*.json");
|
|
861
|
+
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
862
|
+
// src/analyze.ts
|
|
863
|
+
var SOON_DAYS = 14;
|
|
864
|
+
var MAX_HOPS = 10;
|
|
865
|
+
var SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
866
|
+
var SEPARATOR = `
|
|
867
|
+
---HEADERS---
|
|
868
|
+
`;
|
|
869
|
+
var CERT_PREFIX = /^(?:DNS|IP Address|IP|email|URI):/;
|
|
870
|
+
var CACHE_NODE = /^cache-/i;
|
|
871
|
+
var ALT_VALUE = /=.*$/;
|
|
872
|
+
function parseTarget(input) {
|
|
873
|
+
const bare = !SCHEME.test(input);
|
|
874
|
+
try {
|
|
875
|
+
const url = new URL(bare ? `https://${input}` : input);
|
|
876
|
+
return url.protocol !== "http:" && url.protocol !== "https:" || url.hostname === "" ? undefined : { url, bare };
|
|
877
|
+
} catch {
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
var WRITE_OUT = `%{json}${SEPARATOR}%{header_json}`;
|
|
882
|
+
function seconds(value) {
|
|
883
|
+
return typeof value === "number" ? value : 0;
|
|
884
|
+
}
|
|
885
|
+
function ms(value) {
|
|
886
|
+
return Math.round(value * 1000);
|
|
887
|
+
}
|
|
888
|
+
function timingsOf(info) {
|
|
889
|
+
const lookup = seconds(info.time_namelookup);
|
|
890
|
+
const connect = seconds(info.time_connect);
|
|
891
|
+
const secure = seconds(info.time_appconnect);
|
|
892
|
+
const ready = secure > 0 ? secure : connect;
|
|
893
|
+
const first = seconds(info.time_starttransfer);
|
|
894
|
+
return {
|
|
895
|
+
dns: ms(lookup),
|
|
896
|
+
connect: ms(Math.max(0, connect - lookup)),
|
|
897
|
+
tls: secure > 0 ? ms(Math.max(0, secure - connect)) : 0,
|
|
898
|
+
firstByte: ms(Math.max(0, first - ready)),
|
|
899
|
+
total: ms(seconds(info.time_total))
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
function headersOf(json) {
|
|
903
|
+
const headers = {};
|
|
904
|
+
try {
|
|
905
|
+
const parsed = JSON.parse(json);
|
|
906
|
+
if (typeof parsed !== "object" || parsed === null)
|
|
907
|
+
return headers;
|
|
908
|
+
for (const [name, value] of Object.entries(parsed)) {
|
|
909
|
+
const values = Array.isArray(value) ? value.map(String) : [String(value)];
|
|
910
|
+
headers[name.toLowerCase()] = values.join(", ");
|
|
911
|
+
}
|
|
912
|
+
} catch {}
|
|
913
|
+
return headers;
|
|
914
|
+
}
|
|
915
|
+
function parseCurl(stdout) {
|
|
916
|
+
const at = stdout.indexOf(SEPARATOR);
|
|
917
|
+
const infoText = at === -1 ? stdout : stdout.slice(0, at);
|
|
918
|
+
let info;
|
|
919
|
+
try {
|
|
920
|
+
info = JSON.parse(infoText);
|
|
921
|
+
} catch {
|
|
922
|
+
return { exitcode: 1, errormsg: "curl printed no result" };
|
|
923
|
+
}
|
|
924
|
+
const exitcode = typeof info.exitcode === "number" ? info.exitcode : 1;
|
|
925
|
+
const errormsg = typeof info.errormsg === "string" ? info.errormsg : null;
|
|
926
|
+
const status = typeof info.response_code === "number" ? info.response_code : 0;
|
|
927
|
+
if (exitcode !== 0 || status === 0)
|
|
928
|
+
return { exitcode: exitcode === 0 ? 1 : exitcode, errormsg: errormsg ?? "no response" };
|
|
929
|
+
const headers = headersOf(at === -1 ? "" : stdout.slice(at + SEPARATOR.length));
|
|
930
|
+
const hop = {
|
|
931
|
+
url: String(info.url_effective ?? info.url ?? ""),
|
|
932
|
+
status,
|
|
933
|
+
version: String(info.http_version ?? ""),
|
|
934
|
+
timings: timingsOf(info),
|
|
935
|
+
headers
|
|
936
|
+
};
|
|
937
|
+
if (typeof info.redirect_url === "string" && info.redirect_url !== "")
|
|
938
|
+
hop.location = info.redirect_url;
|
|
939
|
+
else if (headers.location !== undefined)
|
|
940
|
+
hop.location = headers.location;
|
|
941
|
+
if (typeof info.remote_ip === "string" && info.remote_ip !== "")
|
|
942
|
+
hop.remoteIp = info.remote_ip;
|
|
943
|
+
return { exitcode, errormsg, hop };
|
|
944
|
+
}
|
|
945
|
+
function isRedirect(status) {
|
|
946
|
+
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
947
|
+
}
|
|
948
|
+
function nextUrl(current, location) {
|
|
949
|
+
try {
|
|
950
|
+
const next = new URL(location, current);
|
|
951
|
+
return next.protocol === "http:" || next.protocol === "https:" ? next.href : undefined;
|
|
952
|
+
} catch {
|
|
953
|
+
return;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
function versionLabel(version) {
|
|
957
|
+
return version === "" ? "unknown" : `HTTP/${version}`;
|
|
958
|
+
}
|
|
959
|
+
function altSvcProtocols(altSvc) {
|
|
960
|
+
if (altSvc === undefined || altSvc.trim() === "clear")
|
|
961
|
+
return [];
|
|
962
|
+
const ids = altSvc.split(",").map((entry) => entry.trim().replace(ALT_VALUE, "")).filter((id) => id !== "");
|
|
963
|
+
return [...new Set(ids)];
|
|
964
|
+
}
|
|
965
|
+
function offersOf(options) {
|
|
966
|
+
const altSvc = altSvcProtocols(options.altSvc);
|
|
967
|
+
return {
|
|
968
|
+
h2: options.alpn === "h2" || options.version === "2" || options.version === "3",
|
|
969
|
+
h3: options.version === "3" || altSvc.some((id) => id === "h3" || id.startsWith("h3-")),
|
|
970
|
+
altSvc
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
var KNOWN_SERVERS = [
|
|
974
|
+
[/cloudflare/i, "Cloudflare"],
|
|
975
|
+
[/cloudfront/i, "CloudFront"],
|
|
976
|
+
[/akamai/i, "Akamai"],
|
|
977
|
+
[/fastly/i, "Fastly"],
|
|
978
|
+
[/vercel/i, "Vercel"],
|
|
979
|
+
[/netlify/i, "Netlify"],
|
|
980
|
+
[/bunnycdn/i, "BunnyCDN"],
|
|
981
|
+
[/^(?:gws|esf|gse)$|google frontend/i, "Google"]
|
|
982
|
+
];
|
|
983
|
+
function cdnHint(headers) {
|
|
984
|
+
const served = headers["x-served-by"];
|
|
985
|
+
if (headers["cf-ray"] !== undefined)
|
|
986
|
+
return "Cloudflare (cf-ray)";
|
|
987
|
+
if (served !== undefined)
|
|
988
|
+
return `${CACHE_NODE.test(served) ? "Fastly" : served} (x-served-by)`;
|
|
989
|
+
if (headers["x-amz-cf-id"] !== undefined)
|
|
990
|
+
return "CloudFront (x-amz-cf-id)";
|
|
991
|
+
if (headers["x-vercel-id"] !== undefined)
|
|
992
|
+
return "Vercel (x-vercel-id)";
|
|
993
|
+
if (headers.via !== undefined)
|
|
994
|
+
return `${headers.via} (via)`;
|
|
995
|
+
if (headers["x-cache"] !== undefined)
|
|
996
|
+
return `${headers["x-cache"]} (x-cache)`;
|
|
997
|
+
const server = headers.server;
|
|
998
|
+
if (server !== undefined) {
|
|
999
|
+
const known = KNOWN_SERVERS.find(([pattern]) => pattern.test(server));
|
|
1000
|
+
if (known !== undefined)
|
|
1001
|
+
return `${known[1]} (server)`;
|
|
1002
|
+
}
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
var WORTH_KNOWING = ["server", "content-type", "content-encoding", "cache-control", "strict-transport-security"];
|
|
1006
|
+
function worthKnowing(headers) {
|
|
1007
|
+
const kept = {};
|
|
1008
|
+
for (const name of WORTH_KNOWING) {
|
|
1009
|
+
const value = headers[name];
|
|
1010
|
+
if (value !== undefined)
|
|
1011
|
+
kept[name] = value;
|
|
1012
|
+
}
|
|
1013
|
+
return kept;
|
|
1014
|
+
}
|
|
1015
|
+
function field(value) {
|
|
1016
|
+
if (typeof value === "string")
|
|
1017
|
+
return value;
|
|
1018
|
+
return Array.isArray(value) ? value.join(", ") : "";
|
|
1019
|
+
}
|
|
1020
|
+
function nameOf(entry) {
|
|
1021
|
+
if (entry === undefined)
|
|
1022
|
+
return "";
|
|
1023
|
+
const common = field(entry.CN);
|
|
1024
|
+
const organization = field(entry.O);
|
|
1025
|
+
if (common !== "" && organization !== "" && common !== organization)
|
|
1026
|
+
return `${common} (${organization})`;
|
|
1027
|
+
return common === "" ? organization : common;
|
|
1028
|
+
}
|
|
1029
|
+
function namesOf(subjectaltname) {
|
|
1030
|
+
if (subjectaltname === undefined)
|
|
1031
|
+
return [];
|
|
1032
|
+
return subjectaltname.split(",").map((entry) => entry.trim().replace(CERT_PREFIX, "")).filter((name) => name !== "");
|
|
1033
|
+
}
|
|
1034
|
+
function daysLeftLabel(days) {
|
|
1035
|
+
return `${days} ${days === 1 ? "day" : "days"} left`;
|
|
1036
|
+
}
|
|
1037
|
+
function certInfo(raw, now = Date.now()) {
|
|
1038
|
+
if (raw.valid_to === undefined || raw.valid_from === undefined)
|
|
1039
|
+
return;
|
|
1040
|
+
const end = Date.parse(raw.valid_to);
|
|
1041
|
+
const start = Date.parse(raw.valid_from);
|
|
1042
|
+
if (Number.isNaN(end) || Number.isNaN(start))
|
|
1043
|
+
return;
|
|
1044
|
+
return {
|
|
1045
|
+
subject: nameOf(raw.subject),
|
|
1046
|
+
issuer: nameOf(raw.issuer),
|
|
1047
|
+
names: namesOf(raw.subjectaltname),
|
|
1048
|
+
validFrom: new Date(start).toISOString(),
|
|
1049
|
+
validTo: new Date(end).toISOString(),
|
|
1050
|
+
daysLeft: Math.floor((end - now) / 86400000)
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
function httpRedirectOf(hop) {
|
|
1054
|
+
if (hop === undefined)
|
|
1055
|
+
return;
|
|
1056
|
+
const next = hop.location === undefined ? undefined : nextUrl(hop.url, hop.location);
|
|
1057
|
+
const redirect = { status: hop.status, toHttps: isRedirect(hop.status) && next !== undefined && new URL(next).protocol === "https:" };
|
|
1058
|
+
if (hop.location !== undefined)
|
|
1059
|
+
redirect.location = hop.location;
|
|
1060
|
+
return redirect;
|
|
1061
|
+
}
|
|
1062
|
+
function wantsHttpCheck(target) {
|
|
1063
|
+
return target.url.protocol === "https:" && target.url.port === "";
|
|
1064
|
+
}
|
|
1065
|
+
function warningsOf(input) {
|
|
1066
|
+
const warnings = [];
|
|
1067
|
+
const { cert, httpRedirect } = input;
|
|
1068
|
+
if (cert !== undefined) {
|
|
1069
|
+
if (cert.daysLeft === -1)
|
|
1070
|
+
warnings.push("certificate expired within the last day");
|
|
1071
|
+
else if (cert.daysLeft < 0)
|
|
1072
|
+
warnings.push(`certificate expired ${-cert.daysLeft} days ago`);
|
|
1073
|
+
else if (cert.daysLeft < SOON_DAYS)
|
|
1074
|
+
warnings.push(`certificate expires in ${cert.daysLeft} ${cert.daysLeft === 1 ? "day" : "days"}`);
|
|
1075
|
+
}
|
|
1076
|
+
if (input.authorizationError !== undefined)
|
|
1077
|
+
warnings.push(`certificate not trusted: ${input.authorizationError}`);
|
|
1078
|
+
if (httpRedirect !== undefined && !httpRedirect.toHttps)
|
|
1079
|
+
warnings.push(`http:// answers ${httpRedirect.status} and does not redirect to https`);
|
|
1080
|
+
if (input.tooManyRedirects)
|
|
1081
|
+
warnings.push(`more than ${MAX_HOPS} redirects`);
|
|
1082
|
+
return warnings;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
// src/net.ts
|
|
1086
|
+
import { lookup } from "dns/promises";
|
|
1087
|
+
import { isIP } from "net";
|
|
1088
|
+
import { connect } from "tls";
|
|
1089
|
+
var CONNECT_TIMEOUT = 10;
|
|
1090
|
+
var MAX_TIME = 20;
|
|
1091
|
+
var HTTP3_FEATURE = /^Features:.*\bHTTP3\b/m;
|
|
1092
|
+
var BRACKETS = /^\[|\]$/g;
|
|
1093
|
+
var http3;
|
|
1094
|
+
async function curlHasHttp3() {
|
|
1095
|
+
if (http3 !== undefined)
|
|
1096
|
+
return http3;
|
|
1097
|
+
try {
|
|
1098
|
+
const result = Bun.spawn(["curl", "--version"], { stdout: "pipe", stderr: "ignore" });
|
|
1099
|
+
const text = await new Response(result.stdout).text();
|
|
1100
|
+
http3 = HTTP3_FEATURE.test(text);
|
|
1101
|
+
} catch {
|
|
1102
|
+
http3 = false;
|
|
1103
|
+
}
|
|
1104
|
+
return http3;
|
|
1105
|
+
}
|
|
1106
|
+
function portOf(url) {
|
|
1107
|
+
if (url.port !== "")
|
|
1108
|
+
return Number(url.port);
|
|
1109
|
+
return url.protocol === "https:" ? 443 : 80;
|
|
1110
|
+
}
|
|
1111
|
+
function curlResolve(url, resolve) {
|
|
1112
|
+
const parsed = URL.canParse(url) ? new URL(url) : undefined;
|
|
1113
|
+
const address = parsed === undefined ? undefined : resolve?.get(parsed.hostname);
|
|
1114
|
+
if (parsed === undefined || address === undefined)
|
|
1115
|
+
return [];
|
|
1116
|
+
return ["--resolve", `${parsed.hostname}:${portOf(parsed)}:${isIP(address) === 6 ? `[${address}]` : address}`];
|
|
1117
|
+
}
|
|
1118
|
+
async function runCurl(url, { http3: wantsH3, insecure, get, headers = [], resolve, timeoutS = MAX_TIME }) {
|
|
1119
|
+
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)];
|
|
1120
|
+
for (const header of headers)
|
|
1121
|
+
args.push("-H", header);
|
|
1122
|
+
if (!get)
|
|
1123
|
+
args.push("-I");
|
|
1124
|
+
if (wantsH3)
|
|
1125
|
+
args.push("--http3");
|
|
1126
|
+
if (insecure)
|
|
1127
|
+
args.push("--insecure");
|
|
1128
|
+
try {
|
|
1129
|
+
const result = Bun.spawn(["curl", ...args, url], { stdout: "pipe", stderr: "pipe" });
|
|
1130
|
+
const [stdout] = await Promise.all([new Response(result.stdout).text(), new Response(result.stderr).text(), result.exited]);
|
|
1131
|
+
return parseCurl(stdout);
|
|
1132
|
+
} catch {
|
|
1133
|
+
return { exitcode: 127, errormsg: "curl is not installed" };
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
async function curlHop(url, options) {
|
|
1137
|
+
let result = await runCurl(url, options);
|
|
1138
|
+
if (result.hop === undefined && options.http3)
|
|
1139
|
+
result = await runCurl(url, { ...options, http3: false });
|
|
1140
|
+
if (result.hop !== undefined && !options.get && (result.hop.status === 405 || result.hop.status === 501))
|
|
1141
|
+
result = await runCurl(url, { ...options, get: true });
|
|
1142
|
+
return result;
|
|
1143
|
+
}
|
|
1144
|
+
async function addressesOf(host, resolve) {
|
|
1145
|
+
const bare = resolve?.get(host) ?? host.replace(BRACKETS, "");
|
|
1146
|
+
const family = isIP(bare);
|
|
1147
|
+
if (family !== 0)
|
|
1148
|
+
return family === 4 ? { a: [bare], aaaa: [] } : { a: [], aaaa: [bare] };
|
|
1149
|
+
try {
|
|
1150
|
+
const found = await lookup(bare, { all: true });
|
|
1151
|
+
return { a: found.filter((entry) => entry.family === 4).map((entry) => entry.address), aaaa: found.filter((entry) => entry.family === 6).map((entry) => entry.address) };
|
|
1152
|
+
} catch {
|
|
1153
|
+
return { a: [], aaaa: [] };
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
async function tlsInfo(host, port, { address, timeoutS = CONNECT_TIMEOUT } = {}) {
|
|
1157
|
+
const bare = host.replace(BRACKETS, "");
|
|
1158
|
+
return new Promise((resolve) => {
|
|
1159
|
+
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 });
|
|
1160
|
+
socket.on("secureConnect", () => {
|
|
1161
|
+
const error = socket.authorizationError;
|
|
1162
|
+
resolve({
|
|
1163
|
+
protocol: socket.getProtocol() ?? "",
|
|
1164
|
+
cipher: socket.getCipher().name,
|
|
1165
|
+
alpn: typeof socket.alpnProtocol === "string" ? socket.alpnProtocol : undefined,
|
|
1166
|
+
authorizationError: error === null || error === undefined || error === false ? undefined : String(error),
|
|
1167
|
+
cert: certInfo(socket.getPeerCertificate())
|
|
1168
|
+
});
|
|
1169
|
+
socket.end();
|
|
1170
|
+
});
|
|
1171
|
+
socket.on("error", () => resolve(undefined));
|
|
1172
|
+
socket.on("timeout", () => {
|
|
1173
|
+
socket.destroy();
|
|
1174
|
+
resolve(undefined);
|
|
1175
|
+
});
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
// src/probe.ts
|
|
1180
|
+
var LABEL_WIDTH = 13;
|
|
1181
|
+
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
|
|
1182
|
+
|
|
1183
|
+
By default one line per target: the HTTP version, status, final URL, total time, redirects, certificate expiry, first address and the warnings. --verbose prints the whole table.
|
|
1184
|
+
A bare domain is tried over https first and over http when that fails. Redirects are followed hop by hop (at most ${MAX_HOPS}), each hop's status and HTTP version listed. HTTP/3 is spoken only when the installed curl lists it, otherwise it is reported from alt-svc. The certificate is read even when it is not trusted, and --insecure also lets curl go on with it.
|
|
1185
|
+
-H adds a header to every request, --resolve host:ip reaches a host at that address instead of the DNS answer (the certificate and the Host header stay the host's), both repeatable.
|
|
1186
|
+
|
|
1187
|
+
Warns on a certificate with fewer than 14 days left or not trusted, and on an http:// twin that does not redirect to https (checked for a bare domain or an https URL on the default port).`;
|
|
1188
|
+
var EXITS = [[0, "every site answered, warnings or not"], [1, "a site could not be reached"], [2, "a usage error"]];
|
|
1189
|
+
var OPTIONS = {
|
|
1190
|
+
insecure: { type: "boolean", short: "k", description: "let curl go on with a certificate it does not trust" },
|
|
1191
|
+
header: { type: "string", short: "H", multiple: true, description: "a `Name: value` header sent with every request, repeatable" },
|
|
1192
|
+
resolve: { type: "string", multiple: true, description: "host:ip, reach the host at that address instead of the DNS answer, repeatable" },
|
|
1193
|
+
timeout: { type: "string", short: "t", description: "longest one request may take (20s): 5s, 1m, a bare number in seconds" },
|
|
1194
|
+
verbose: { type: "boolean", description: "the whole table for each target instead of one line" },
|
|
1195
|
+
json: jsonOption("one object per target {target, url, version, status, chain, timings, addresses, tls, certificate, headers, cdn, offers, httpRedirect, warnings}, an array of them for several targets (an unreachable one is {target, error})")
|
|
1196
|
+
};
|
|
1197
|
+
var BRACKETS2 = /^\[|\]$/g;
|
|
1198
|
+
var HEADER_LINE = /^[\w!#$%&'*+.^`|~-]+:/;
|
|
1199
|
+
async function follow(start, { insecure, wire }, http3) {
|
|
1200
|
+
const chain = [];
|
|
1201
|
+
let url = start;
|
|
1202
|
+
while (chain.length < MAX_HOPS) {
|
|
1203
|
+
const { hop, errormsg } = await curlHop(url, { ...wire, http3: http3 && url.startsWith("https:"), insecure, get: false });
|
|
1204
|
+
if (hop === undefined)
|
|
1205
|
+
return { chain, error: errormsg ?? "no response", tooMany: false };
|
|
1206
|
+
chain.push(hop);
|
|
1207
|
+
const next = hop.location === undefined ? undefined : nextUrl(hop.url, hop.location);
|
|
1208
|
+
if (!isRedirect(hop.status) || next === undefined)
|
|
1209
|
+
return { chain, tooMany: false };
|
|
1210
|
+
url = next;
|
|
1211
|
+
}
|
|
1212
|
+
return { chain, tooMany: true };
|
|
1213
|
+
}
|
|
1214
|
+
async function probe(target, input, settings) {
|
|
1215
|
+
const { wire } = settings;
|
|
1216
|
+
const http3 = await curlHasHttp3();
|
|
1217
|
+
let followed = await follow(target.url.href, settings, http3);
|
|
1218
|
+
if (followed.chain.length === 0 && target.bare) {
|
|
1219
|
+
const plain = new URL(target.url.href);
|
|
1220
|
+
plain.protocol = "http:";
|
|
1221
|
+
const second = await follow(plain.href, settings, http3);
|
|
1222
|
+
if (second.chain.length > 0)
|
|
1223
|
+
followed = second;
|
|
1224
|
+
}
|
|
1225
|
+
const final = followed.chain.at(-1);
|
|
1226
|
+
if (final === undefined)
|
|
1227
|
+
return { target: input, error: `could not reach ${target.url.host}: ${followed.error ?? "no response"}` };
|
|
1228
|
+
const finalUrl = new URL(final.url);
|
|
1229
|
+
const secure = finalUrl.protocol === "https:";
|
|
1230
|
+
const [addresses, tls, twin] = await Promise.all([
|
|
1231
|
+
addressesOf(target.url.hostname, wire.resolve),
|
|
1232
|
+
secure ? tlsInfo(finalUrl.hostname, portOf(finalUrl), { address: wire.resolve?.get(finalUrl.hostname), ...wire.timeoutS === undefined ? {} : { timeoutS: wire.timeoutS } }) : Promise.resolve(undefined),
|
|
1233
|
+
wantsHttpCheck(target) && secure ? twinOf(target.url, settings) : Promise.resolve(undefined)
|
|
1234
|
+
]);
|
|
1235
|
+
const httpRedirect = httpRedirectOf(twin);
|
|
1236
|
+
const offers = offersOf({ alpn: tls?.alpn, version: final.version, altSvc: final.headers["alt-svc"] });
|
|
1237
|
+
const warnings = warningsOf({ cert: tls?.cert, authorizationError: tls?.authorizationError, httpRedirect, tooManyRedirects: followed.tooMany });
|
|
1238
|
+
if (!secure)
|
|
1239
|
+
warnings.push("the site is not served over https");
|
|
1240
|
+
return {
|
|
1241
|
+
target: input,
|
|
1242
|
+
url: final.url,
|
|
1243
|
+
version: final.version,
|
|
1244
|
+
status: final.status,
|
|
1245
|
+
chain: followed.chain.map((hop) => ({ url: hop.url, status: hop.status, version: hop.version, ...hop.location === undefined ? {} : { location: hop.location }, ms: hop.timings.total })),
|
|
1246
|
+
timings: final.timings,
|
|
1247
|
+
addresses,
|
|
1248
|
+
tls: tls === undefined ? null : { protocol: tls.protocol, cipher: tls.cipher, ...tls.alpn === undefined ? {} : { alpn: tls.alpn } },
|
|
1249
|
+
certificate: tls?.cert ?? null,
|
|
1250
|
+
headers: worthKnowing(final.headers),
|
|
1251
|
+
cdn: cdnHint(final.headers) ?? null,
|
|
1252
|
+
offers,
|
|
1253
|
+
httpRedirect: httpRedirect ?? null,
|
|
1254
|
+
warnings
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
async function twinOf(url, { insecure, wire }) {
|
|
1258
|
+
const plain = new URL(url.href);
|
|
1259
|
+
plain.protocol = "http:";
|
|
1260
|
+
return (await curlHop(plain.href, { ...wire, http3: false, insecure, get: false })).hop;
|
|
1261
|
+
}
|
|
1262
|
+
function resolvesOf(entries) {
|
|
1263
|
+
const resolve = new Map;
|
|
1264
|
+
for (const entry of entries) {
|
|
1265
|
+
const at = entry.indexOf(":");
|
|
1266
|
+
const address = entry.slice(at + 1).replace(BRACKETS2, "");
|
|
1267
|
+
if (at < 1 || isIP2(address) === 0)
|
|
1268
|
+
badUsage(`--resolve takes host:ip, not ${entry}`);
|
|
1269
|
+
resolve.set(entry.slice(0, at).toLowerCase(), address);
|
|
1270
|
+
}
|
|
1271
|
+
return resolve;
|
|
1272
|
+
}
|
|
1273
|
+
function ms2(value) {
|
|
1274
|
+
return `${value}ms`;
|
|
1275
|
+
}
|
|
1276
|
+
function compact(report) {
|
|
1277
|
+
const { dim } = paint(process9.stdout);
|
|
1278
|
+
const redirects = report.chain.length - 1;
|
|
1279
|
+
const parts = [`${role("accent", process9.stdout)(versionLabel(report.version))} ${role("value", process9.stdout)(String(report.status))} ${role("path", process9.stdout)(report.url)}`, ms2(report.timings.total)];
|
|
1280
|
+
const address = report.addresses.a[0] ?? report.addresses.aaaa[0];
|
|
1281
|
+
if (redirects > 0)
|
|
1282
|
+
parts.push(`${redirects} ${redirects === 1 ? "redirect" : "redirects"}`);
|
|
1283
|
+
if (report.certificate !== null)
|
|
1284
|
+
parts.push(`cert ${daysLeftLabel(report.certificate.daysLeft)}`);
|
|
1285
|
+
if (address !== undefined)
|
|
1286
|
+
parts.push(address);
|
|
1287
|
+
const line = parts.join(dim(" "));
|
|
1288
|
+
return report.warnings.length === 0 ? line : `${line} ${marked("warn", report.warnings.join("; "), process9.stdout)}`;
|
|
1289
|
+
}
|
|
1290
|
+
function print(report) {
|
|
1291
|
+
const label = role("label", process9.stdout);
|
|
1292
|
+
const value = role("value", process9.stdout);
|
|
1293
|
+
const accent = role("accent", process9.stdout);
|
|
1294
|
+
const row = (name, text) => console.log(`${label(name.padEnd(LABEL_WIDTH))} ${text}`);
|
|
1295
|
+
console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path", process9.stdout)(report.url)}`);
|
|
1296
|
+
console.log("");
|
|
1297
|
+
if (report.chain.length > 1) {
|
|
1298
|
+
console.log(table(report.chain.map((hop) => [String(hop.status), versionLabel(hop.version), ms2(hop.ms), hop.url]), { align: ["right", "left", "right", "left"] }));
|
|
1299
|
+
console.log("");
|
|
1300
|
+
}
|
|
1301
|
+
const { timings } = report;
|
|
1302
|
+
row("timings", `dns ${ms2(timings.dns)}, connect ${ms2(timings.connect)}, tls ${ms2(timings.tls)}, first byte ${ms2(timings.firstByte)}, total ${ms2(timings.total)}`);
|
|
1303
|
+
row("addresses", [...report.addresses.a, ...report.addresses.aaaa].join(", ") || "none found");
|
|
1304
|
+
if (report.tls !== null)
|
|
1305
|
+
row("tls", `${report.tls.protocol} ${report.tls.cipher}`);
|
|
1306
|
+
const cert = report.certificate;
|
|
1307
|
+
if (cert !== null) {
|
|
1308
|
+
row("issuer", cert.issuer);
|
|
1309
|
+
row("expires", `${cert.validTo.slice(0, 10)} (${daysLeftLabel(cert.daysLeft)})`);
|
|
1310
|
+
row("names", cert.names.join(", "));
|
|
1311
|
+
}
|
|
1312
|
+
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(" ")})`}`);
|
|
1313
|
+
for (const [name, text] of Object.entries(report.headers))
|
|
1314
|
+
row(name === "strict-transport-security" ? "hsts" : name, text);
|
|
1315
|
+
if (report.cdn !== null)
|
|
1316
|
+
row("cdn", report.cdn);
|
|
1317
|
+
if (report.httpRedirect !== null)
|
|
1318
|
+
row("http://", report.httpRedirect.toHttps ? `redirects to https (${report.httpRedirect.status})` : `answers ${report.httpRedirect.status}`);
|
|
1319
|
+
for (const warning of report.warnings)
|
|
1320
|
+
console.log(marked("warn", warning, process9.stdout));
|
|
1321
|
+
}
|
|
1322
|
+
async function main(args) {
|
|
1323
|
+
const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["<url|domain>..."], exits: EXITS, replaces: "the httpversion fish function, curl -sI chains and openssl s_client 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"]] });
|
|
1324
|
+
const headers = values.header ?? [];
|
|
1325
|
+
for (const header of headers) {
|
|
1326
|
+
if (!HEADER_LINE.test(header))
|
|
1327
|
+
badUsage(`-H takes "Name: value", not ${header}`);
|
|
1328
|
+
}
|
|
1329
|
+
const timeoutMs = values.timeout === undefined ? undefined : duration(values.timeout, "timeout", 0, "s");
|
|
1330
|
+
const wire = { headers, resolve: resolvesOf(values.resolve ?? []), ...timeoutMs === undefined ? {} : { timeoutS: timeoutMs / 1000 } };
|
|
1331
|
+
const targets = positionals.map((input) => {
|
|
1332
|
+
const target = parseTarget(input);
|
|
1333
|
+
if (target === undefined)
|
|
1334
|
+
badUsage(`not a URL or domain: ${input}`);
|
|
1335
|
+
return { input, target };
|
|
1336
|
+
});
|
|
1337
|
+
const reports = await Promise.all(targets.map(async ({ input, target }) => probe(target, input, { insecure: values.insecure === true, wire })));
|
|
1338
|
+
const [only] = reports;
|
|
1339
|
+
if (reports.length === 1 && only !== undefined && "error" in only)
|
|
1340
|
+
fail(only.error, 1);
|
|
1341
|
+
if (values.json === true) {
|
|
1342
|
+
printJson(reports.length === 1 ? only : reports);
|
|
1343
|
+
return reports.some((report) => ("error" in report)) ? 1 : 0;
|
|
1344
|
+
}
|
|
1345
|
+
let first = true;
|
|
1346
|
+
for (const report of reports) {
|
|
1347
|
+
if ("error" in report) {
|
|
1348
|
+
console.error(marked("problem", report.error, process9.stderr));
|
|
1349
|
+
} else if (values.verbose === true) {
|
|
1350
|
+
if (!first)
|
|
1351
|
+
console.log("");
|
|
1352
|
+
if (reports.length > 1)
|
|
1353
|
+
console.log(role("label", process9.stdout)(report.target));
|
|
1354
|
+
print(report);
|
|
1355
|
+
} else {
|
|
1356
|
+
console.log(compact(report));
|
|
1357
|
+
}
|
|
1358
|
+
first = false;
|
|
1359
|
+
}
|
|
1360
|
+
return reports.some((report) => ("error" in report)) ? 1 : 0;
|
|
1361
|
+
}
|
|
1362
|
+
process9.exitCode = await runMain({ name: "probe", run: main });
|