@kaynooo/cli-page 0.0.0-stage → 0.0.2
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 +33 -2
- package/dist/cli.js +1916 -0
- package/inpage/compare.ts +159 -0
- package/inpage/measure.ts +336 -0
- package/package.json +44 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1916 @@
|
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
|
+
// @bun
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __returnValue = (v) => v;
|
|
5
|
+
function __exportSetter(name, newValue) {
|
|
6
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
7
|
+
}
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, {
|
|
11
|
+
get: all[name],
|
|
12
|
+
enumerable: true,
|
|
13
|
+
configurable: true,
|
|
14
|
+
set: __exportSetter.bind(all, name)
|
|
15
|
+
});
|
|
16
|
+
};
|
|
17
|
+
var __esm = (fn, res, err) => () => {
|
|
18
|
+
if (fn)
|
|
19
|
+
try {
|
|
20
|
+
res = fn(fn = 0);
|
|
21
|
+
} catch (e) {
|
|
22
|
+
err = [e];
|
|
23
|
+
}
|
|
24
|
+
if (err)
|
|
25
|
+
throw err[0];
|
|
26
|
+
return res;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// ../kit/src/advisory.ts
|
|
30
|
+
var init_advisory = () => {};
|
|
31
|
+
|
|
32
|
+
// ../kit/src/mode.ts
|
|
33
|
+
import process2 from "process";
|
|
34
|
+
function isSet(value) {
|
|
35
|
+
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
36
|
+
}
|
|
37
|
+
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
38
|
+
const chosen = env.KIT_MODE;
|
|
39
|
+
if (chosen !== undefined && MODES.has(chosen))
|
|
40
|
+
return chosen;
|
|
41
|
+
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
42
|
+
return "agent";
|
|
43
|
+
if (stream.isTTY === true)
|
|
44
|
+
return "terminal";
|
|
45
|
+
return isSet(env.CI) ? "ci" : "pipe";
|
|
46
|
+
}
|
|
47
|
+
var MODES, AGENT_VARIABLES;
|
|
48
|
+
var init_mode = __esm(() => {
|
|
49
|
+
MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
50
|
+
AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
54
|
+
function b(r) {
|
|
55
|
+
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
56
|
+
if (!G.test(e))
|
|
57
|
+
return [0, 0, 0];
|
|
58
|
+
if (e.length === 3 || e.length === 4)
|
|
59
|
+
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
60
|
+
if (e.length !== 6 && e.length !== 8)
|
|
61
|
+
throw Error(`Invalid hex color length: ${e.length}`);
|
|
62
|
+
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
63
|
+
}
|
|
64
|
+
function C(r, e = globalThis.process?.env ?? {}) {
|
|
65
|
+
if (e.FORCE_COLOR !== undefined)
|
|
66
|
+
return h.has(e.FORCE_COLOR);
|
|
67
|
+
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
68
|
+
return false;
|
|
69
|
+
return r?.isTTY === true;
|
|
70
|
+
}
|
|
71
|
+
function f(r, e = []) {
|
|
72
|
+
let l = "", n = "";
|
|
73
|
+
for (let t = 0, i = e.length;t < i; t++)
|
|
74
|
+
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
75
|
+
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
76
|
+
return new Proxy(c, { get(t, i) {
|
|
77
|
+
let a = B[i];
|
|
78
|
+
if (Array.isArray(a)) {
|
|
79
|
+
let s = g.get(i);
|
|
80
|
+
if (s === undefined)
|
|
81
|
+
s = f(r, [...e, a]), g.set(i, s);
|
|
82
|
+
return s;
|
|
83
|
+
}
|
|
84
|
+
if (typeof a === "function")
|
|
85
|
+
return (...s) => {
|
|
86
|
+
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
87
|
+
if (u === undefined) {
|
|
88
|
+
if (g.size >= 64)
|
|
89
|
+
g.clear();
|
|
90
|
+
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
91
|
+
}
|
|
92
|
+
return u;
|
|
93
|
+
};
|
|
94
|
+
throw Error(`Unknown style: ${String(i)}`);
|
|
95
|
+
} });
|
|
96
|
+
}
|
|
97
|
+
function Fe(r = {}) {
|
|
98
|
+
return f(r);
|
|
99
|
+
}
|
|
100
|
+
var G, B, h, o;
|
|
101
|
+
var init_chunk_x450vn3m = __esm(() => {
|
|
102
|
+
G = /^[a-f0-9]+$/i;
|
|
103
|
+
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") => {
|
|
104
|
+
let [l, n, c] = b(r);
|
|
105
|
+
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
106
|
+
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
107
|
+
h = new Set(["", "1", "2", "3", "true"]);
|
|
108
|
+
o = Fe();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
|
|
112
|
+
var init_colors = __esm(() => {
|
|
113
|
+
init_chunk_x450vn3m();
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
// ../kit/src/config.ts
|
|
117
|
+
import { existsSync } from "fs";
|
|
118
|
+
import { dirname, join, resolve } from "path";
|
|
119
|
+
import process3 from "process";
|
|
120
|
+
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
121
|
+
const wanted = typeof names === "string" ? [names] : names;
|
|
122
|
+
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
123
|
+
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
124
|
+
if (found !== undefined)
|
|
125
|
+
return found;
|
|
126
|
+
if (stop(dir) || dirname(dir) === dir)
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
var init_config = __esm(() => {
|
|
131
|
+
init_args();
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
// ../kit/src/user-config.ts
|
|
135
|
+
import { homedir } from "os";
|
|
136
|
+
import { isAbsolute, join as join2 } from "path";
|
|
137
|
+
import process4 from "process";
|
|
138
|
+
function xdgFolder(value, fallback) {
|
|
139
|
+
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
140
|
+
}
|
|
141
|
+
function configBase(where = {}) {
|
|
142
|
+
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
143
|
+
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
144
|
+
}
|
|
145
|
+
function userConfigPath(bin, where = {}) {
|
|
146
|
+
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
147
|
+
}
|
|
148
|
+
var init_user_config = () => {};
|
|
149
|
+
|
|
150
|
+
// ../kit/src/theme.ts
|
|
151
|
+
import { existsSync as existsSync2, readFileSync, statSync } from "fs";
|
|
152
|
+
import { homedir as homedir2 } from "os";
|
|
153
|
+
import { join as join3, resolve as resolve2 } from "path";
|
|
154
|
+
import process5 from "process";
|
|
155
|
+
function isColorSpec(spec) {
|
|
156
|
+
if (typeof spec === "number")
|
|
157
|
+
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
158
|
+
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
159
|
+
}
|
|
160
|
+
function cubeLevel(channel) {
|
|
161
|
+
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
162
|
+
}
|
|
163
|
+
function nearest256(hex) {
|
|
164
|
+
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
165
|
+
const levels = rgb.map(cubeLevel);
|
|
166
|
+
const cube = levels.map((level) => CUBE[level]);
|
|
167
|
+
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
168
|
+
const greyValue = 8 + grey * 10;
|
|
169
|
+
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
170
|
+
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
171
|
+
}
|
|
172
|
+
function hasTrueColor(env) {
|
|
173
|
+
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
174
|
+
}
|
|
175
|
+
function tinted(colors, spec, env = process5.env) {
|
|
176
|
+
if (typeof spec === "number")
|
|
177
|
+
return colors.ansi256(spec);
|
|
178
|
+
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
179
|
+
if (HEX.test(token))
|
|
180
|
+
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
181
|
+
return chain[token] ?? chain;
|
|
182
|
+
}, colors);
|
|
183
|
+
}
|
|
184
|
+
function isRecord(value) {
|
|
185
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
186
|
+
}
|
|
187
|
+
function readThemeFile(path, warn) {
|
|
188
|
+
try {
|
|
189
|
+
const stat = statSync(path, { throwIfNoEntry: false });
|
|
190
|
+
if (stat === undefined)
|
|
191
|
+
return;
|
|
192
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
193
|
+
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
197
|
+
if (isRecord(parsed))
|
|
198
|
+
return parsed;
|
|
199
|
+
warn(`${path} is not a JSON object, theme ignored`);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
202
|
+
}
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
function applyPreset(theme, name, warn, where) {
|
|
206
|
+
if (name === undefined)
|
|
207
|
+
return;
|
|
208
|
+
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
209
|
+
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const preset = PRESETS[name];
|
|
213
|
+
Object.assign(theme.colors, preset.colors);
|
|
214
|
+
Object.assign(theme.glyphs, preset.glyphs);
|
|
215
|
+
if (preset.accents !== undefined)
|
|
216
|
+
theme.accents = [...preset.accents];
|
|
217
|
+
if (Object.hasOwn(preset, "gradient"))
|
|
218
|
+
theme.gradient = preset.gradient;
|
|
219
|
+
return name;
|
|
220
|
+
}
|
|
221
|
+
function applyFile(theme, file, where, warn) {
|
|
222
|
+
if (isRecord(file.colors)) {
|
|
223
|
+
for (const [key, value] of Object.entries(file.colors)) {
|
|
224
|
+
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
225
|
+
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
226
|
+
else if (!isColorSpec(value))
|
|
227
|
+
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
228
|
+
else
|
|
229
|
+
theme.colors[key] = value;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (isRecord(file.glyphs)) {
|
|
233
|
+
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
234
|
+
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
235
|
+
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
236
|
+
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
237
|
+
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
238
|
+
else
|
|
239
|
+
theme.glyphs[key] = value;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
243
|
+
theme.accents = [...file.accents];
|
|
244
|
+
else if (file.accents !== undefined)
|
|
245
|
+
warn(`${where}: accents must be a non-empty list of colours`);
|
|
246
|
+
if (file.gradient === null)
|
|
247
|
+
theme.gradient = undefined;
|
|
248
|
+
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
249
|
+
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
250
|
+
else if (file.gradient !== undefined)
|
|
251
|
+
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
252
|
+
if (isRecord(file.bins)) {
|
|
253
|
+
for (const [bin, value] of Object.entries(file.bins)) {
|
|
254
|
+
if (isColorSpec(value))
|
|
255
|
+
theme.bins[bin] = value;
|
|
256
|
+
else
|
|
257
|
+
warn(`${where}: bin ${bin} has no valid colour`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function endsWalk(home) {
|
|
262
|
+
return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
|
|
263
|
+
}
|
|
264
|
+
function warnOnce(message) {
|
|
265
|
+
if (warned.has(message))
|
|
266
|
+
return;
|
|
267
|
+
warned.add(message);
|
|
268
|
+
console.error(`warning: theme ${message}`);
|
|
269
|
+
}
|
|
270
|
+
function isPath(chosen) {
|
|
271
|
+
return chosen.includes("/") || chosen.endsWith(".json");
|
|
272
|
+
}
|
|
273
|
+
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
274
|
+
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
275
|
+
const sources = [];
|
|
276
|
+
const chosen = env.KIT_THEME ?? "";
|
|
277
|
+
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
278
|
+
if (isPath(chosen))
|
|
279
|
+
wanted.push(resolve2(from, chosen));
|
|
280
|
+
const files = [];
|
|
281
|
+
for (const path of wanted) {
|
|
282
|
+
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
283
|
+
if (path !== undefined && file !== undefined)
|
|
284
|
+
files.push({ path, file });
|
|
285
|
+
}
|
|
286
|
+
let preset = "default";
|
|
287
|
+
if (chosen !== "" && !isPath(chosen)) {
|
|
288
|
+
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
289
|
+
} else {
|
|
290
|
+
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
291
|
+
if (named !== undefined)
|
|
292
|
+
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
293
|
+
}
|
|
294
|
+
for (const { path, file } of files) {
|
|
295
|
+
applyFile(theme, file, path, warn);
|
|
296
|
+
sources.push(path);
|
|
297
|
+
}
|
|
298
|
+
return { theme, sources, preset };
|
|
299
|
+
}
|
|
300
|
+
function activeTheme() {
|
|
301
|
+
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
302
|
+
if (current === undefined || key !== currentKey) {
|
|
303
|
+
current = loadTheme();
|
|
304
|
+
currentKey = key;
|
|
305
|
+
}
|
|
306
|
+
return current;
|
|
307
|
+
}
|
|
308
|
+
var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
|
|
309
|
+
var init_theme = __esm(() => {
|
|
310
|
+
init_config();
|
|
311
|
+
init_user_config();
|
|
312
|
+
ENDS = new Map;
|
|
313
|
+
DEFAULT = {
|
|
314
|
+
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" },
|
|
315
|
+
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" },
|
|
316
|
+
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
317
|
+
bins: {},
|
|
318
|
+
gradient: ["#c084fc", "#67e8f9"]
|
|
319
|
+
};
|
|
320
|
+
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" };
|
|
321
|
+
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" };
|
|
322
|
+
ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
323
|
+
PRESETS = {
|
|
324
|
+
default: {},
|
|
325
|
+
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
326
|
+
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
327
|
+
ascii: { glyphs: ASCII }
|
|
328
|
+
};
|
|
329
|
+
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"]);
|
|
330
|
+
HEX = /^#[0-9a-f]{6}$/i;
|
|
331
|
+
CONTROL = /\p{Cc}/u;
|
|
332
|
+
MAX_FILE_BYTES = 64 * 1024;
|
|
333
|
+
SPACES = /\s+/;
|
|
334
|
+
CUBE = [0, 95, 135, 175, 215, 255];
|
|
335
|
+
warned = new Set;
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
// ../kit/src/style.ts
|
|
339
|
+
import process6 from "process";
|
|
340
|
+
function takesControlCodes(stream, env = process6.env) {
|
|
341
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
342
|
+
}
|
|
343
|
+
function paint(stream, env = process6.env) {
|
|
344
|
+
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
345
|
+
}
|
|
346
|
+
function marked(mark, text, stream, detail, env = process6.env) {
|
|
347
|
+
const colors = paint(stream, env);
|
|
348
|
+
let head = MARK_WORDS[mark];
|
|
349
|
+
if (takesControlCodes(stream, env)) {
|
|
350
|
+
const { theme } = activeTheme();
|
|
351
|
+
head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
|
|
352
|
+
}
|
|
353
|
+
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
354
|
+
}
|
|
355
|
+
function warn(text, detail) {
|
|
356
|
+
console.error(marked("warn", text, process6.stderr, detail));
|
|
357
|
+
}
|
|
358
|
+
function problem(text, detail) {
|
|
359
|
+
console.error(marked("problem", text, process6.stderr, detail));
|
|
360
|
+
}
|
|
361
|
+
function role(name, stream, env = process6.env) {
|
|
362
|
+
const colors = paint(stream, env);
|
|
363
|
+
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
364
|
+
}
|
|
365
|
+
var MARK_WORDS, STATUS_WORDS, STATUS_OF;
|
|
366
|
+
var init_style = __esm(() => {
|
|
367
|
+
init_colors();
|
|
368
|
+
init_mode();
|
|
369
|
+
init_theme();
|
|
370
|
+
MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
|
|
371
|
+
STATUS_WORDS = {
|
|
372
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
373
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
374
|
+
running: ["running", "in_progress", "started", "holding"],
|
|
375
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
376
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
377
|
+
};
|
|
378
|
+
STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
// ../kit/src/format.ts
|
|
382
|
+
import process7 from "process";
|
|
383
|
+
function formatSeconds(total) {
|
|
384
|
+
let rest = Math.max(0, Math.round(total));
|
|
385
|
+
const amounts = UNITS.map(([unit, size]) => {
|
|
386
|
+
const amount = Math.floor(rest / size);
|
|
387
|
+
rest -= amount * size;
|
|
388
|
+
return `${amount}${unit}`;
|
|
389
|
+
});
|
|
390
|
+
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
391
|
+
if (first === -1)
|
|
392
|
+
return "0s";
|
|
393
|
+
const next = amounts[first + 1];
|
|
394
|
+
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
395
|
+
}
|
|
396
|
+
function formatDuration(ms) {
|
|
397
|
+
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
398
|
+
}
|
|
399
|
+
function upTo(text, separator) {
|
|
400
|
+
const end = text.indexOf(separator);
|
|
401
|
+
return end === -1 ? text : text.slice(0, end);
|
|
402
|
+
}
|
|
403
|
+
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
404
|
+
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
405
|
+
}
|
|
406
|
+
function printJson(value) {
|
|
407
|
+
console.log(jsonText(value));
|
|
408
|
+
}
|
|
409
|
+
function formatPercent(ratio, digits = 0) {
|
|
410
|
+
return `${(ratio * 100).toFixed(digits)}%`;
|
|
411
|
+
}
|
|
412
|
+
var UNITS, ESCAPE;
|
|
413
|
+
var init_format = __esm(() => {
|
|
414
|
+
init_mode();
|
|
415
|
+
init_style();
|
|
416
|
+
UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
417
|
+
ESCAPE = String.fromCharCode(27);
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
// ../kit/src/help.ts
|
|
421
|
+
import process8 from "process";
|
|
422
|
+
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
423
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
424
|
+
`);
|
|
425
|
+
const blank = lines.indexOf("");
|
|
426
|
+
const synopses = blank === -1 ? lines : lines.slice(0, blank);
|
|
427
|
+
const details = blank === -1 ? [] : lines.slice(blank + 1);
|
|
428
|
+
const colon = synopses[0].indexOf(": ");
|
|
429
|
+
const inline = synopses[0].slice(colon + 2);
|
|
430
|
+
const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
|
|
431
|
+
if (colon !== -1)
|
|
432
|
+
synopses[0] = synopses[0].slice(0, colon);
|
|
433
|
+
const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
|
|
434
|
+
`)}`;
|
|
435
|
+
const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
|
|
436
|
+
const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
|
|
437
|
+
return [head, ...lead, ...rest].join(`
|
|
438
|
+
`);
|
|
439
|
+
}
|
|
440
|
+
function prose(line, colors) {
|
|
441
|
+
if (colors.cyan("x") === "x")
|
|
442
|
+
return line;
|
|
443
|
+
return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
|
|
444
|
+
}
|
|
445
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
446
|
+
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
447
|
+
`);
|
|
448
|
+
}
|
|
449
|
+
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
450
|
+
if (exits.length === 0)
|
|
451
|
+
return [];
|
|
452
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
453
|
+
}
|
|
454
|
+
function wantsHelpJson(env = process8.env) {
|
|
455
|
+
return env.KIT_HELP === "json";
|
|
456
|
+
}
|
|
457
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
458
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
459
|
+
`);
|
|
460
|
+
const first = lines[0];
|
|
461
|
+
const colon = first.indexOf(": ");
|
|
462
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
463
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
464
|
+
return {
|
|
465
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
466
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
467
|
+
...replaces === undefined ? {} : { replaces },
|
|
468
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
469
|
+
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
470
|
+
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
474
|
+
if (examples.length === 0 || outputMode() === "agent")
|
|
475
|
+
return [];
|
|
476
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
477
|
+
}
|
|
478
|
+
function optionRows(options, colors = paint(process8.stdout)) {
|
|
479
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
480
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
481
|
+
const choices = option.choices?.join("|");
|
|
482
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
483
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
484
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
485
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
486
|
+
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
487
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
488
|
+
});
|
|
489
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
490
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
491
|
+
}
|
|
492
|
+
var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
|
|
493
|
+
var init_help = __esm(() => {
|
|
494
|
+
init_mode();
|
|
495
|
+
init_style();
|
|
496
|
+
OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
497
|
+
USAGE_PREFIX = /^usage:\s*/i;
|
|
498
|
+
FULL_STOP = /\.$/;
|
|
499
|
+
PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
// ../kit/src/text.ts
|
|
503
|
+
function distance(a, b) {
|
|
504
|
+
const left = [...a];
|
|
505
|
+
const right = [...b];
|
|
506
|
+
let before = [];
|
|
507
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
508
|
+
for (const [i, x] of left.entries()) {
|
|
509
|
+
const current = [i + 1];
|
|
510
|
+
for (const [j, y] of right.entries()) {
|
|
511
|
+
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
512
|
+
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
513
|
+
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
514
|
+
current.push(cost);
|
|
515
|
+
}
|
|
516
|
+
before = previous;
|
|
517
|
+
previous = current;
|
|
518
|
+
}
|
|
519
|
+
return previous[right.length] ?? 0;
|
|
520
|
+
}
|
|
521
|
+
function closest(name, names) {
|
|
522
|
+
const started = names.find((known) => known.startsWith(name));
|
|
523
|
+
if (started !== undefined)
|
|
524
|
+
return started;
|
|
525
|
+
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
526
|
+
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
527
|
+
}
|
|
528
|
+
var init_text = () => {};
|
|
529
|
+
|
|
530
|
+
// ../kit/src/input.ts
|
|
531
|
+
function wholeNumber(value, name, fallback, min = 1) {
|
|
532
|
+
if (value === undefined)
|
|
533
|
+
return fallback;
|
|
534
|
+
const number = Number(value);
|
|
535
|
+
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
536
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
537
|
+
return number;
|
|
538
|
+
}
|
|
539
|
+
var WHOLE;
|
|
540
|
+
var init_input = __esm(() => {
|
|
541
|
+
init_args();
|
|
542
|
+
WHOLE = /^\d+$/;
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
// ../kit/src/args.ts
|
|
546
|
+
import process9 from "process";
|
|
547
|
+
import { parseArgs } from "util";
|
|
548
|
+
function jsonOption(holds) {
|
|
549
|
+
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
550
|
+
}
|
|
551
|
+
function fail(message, code = 2, hint) {
|
|
552
|
+
throw new Exit(message, code, hint);
|
|
553
|
+
}
|
|
554
|
+
function badUsage(message) {
|
|
555
|
+
throw new UsageError(message);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
class Completing {
|
|
559
|
+
options;
|
|
560
|
+
positionals;
|
|
561
|
+
candidates;
|
|
562
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
563
|
+
this.options = options;
|
|
564
|
+
this.positionals = positionals;
|
|
565
|
+
this.candidates = candidates;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
function applyOutput(color, plain, env = process9.env) {
|
|
569
|
+
const when = plain === true ? "never" : color ?? "auto";
|
|
570
|
+
if (when === "auto")
|
|
571
|
+
return;
|
|
572
|
+
if (when !== "always" && when !== "never")
|
|
573
|
+
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
574
|
+
if (when === "always") {
|
|
575
|
+
env.FORCE_COLOR = "1";
|
|
576
|
+
delete env.NO_COLOR;
|
|
577
|
+
} else {
|
|
578
|
+
env.NO_COLOR = "1";
|
|
579
|
+
delete env.FORCE_COLOR;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
function parse(args, usage, options, settings = {}) {
|
|
583
|
+
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
584
|
+
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
585
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
586
|
+
if (completion.active)
|
|
587
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
588
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
589
|
+
let parsed;
|
|
590
|
+
try {
|
|
591
|
+
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
592
|
+
} catch (error) {
|
|
593
|
+
const message = parseError(error);
|
|
594
|
+
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
595
|
+
}
|
|
596
|
+
const values = parsed.values;
|
|
597
|
+
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
598
|
+
if (values.help === true) {
|
|
599
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
600
|
+
throw new HelpShown;
|
|
601
|
+
}
|
|
602
|
+
checkChoices(parsed.values, all);
|
|
603
|
+
checkConflicts(parsed.values, all);
|
|
604
|
+
if (settings.positionals !== undefined)
|
|
605
|
+
checkPositionals(parsed.positionals, settings.positionals);
|
|
606
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
607
|
+
}
|
|
608
|
+
function splitRest(args, passes) {
|
|
609
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
610
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
611
|
+
}
|
|
612
|
+
function splitTrailing(args, options, count) {
|
|
613
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
614
|
+
let seen = 0;
|
|
615
|
+
if (count === 0)
|
|
616
|
+
return { own: args, rest: undefined };
|
|
617
|
+
for (let at = 0;at < args.length; at++) {
|
|
618
|
+
const word = args[at];
|
|
619
|
+
if (word === "--")
|
|
620
|
+
break;
|
|
621
|
+
if (word.startsWith("-")) {
|
|
622
|
+
if (takesValue(word))
|
|
623
|
+
at++;
|
|
624
|
+
continue;
|
|
625
|
+
}
|
|
626
|
+
seen++;
|
|
627
|
+
if (seen === count)
|
|
628
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
629
|
+
}
|
|
630
|
+
return { own: args, rest: undefined };
|
|
631
|
+
}
|
|
632
|
+
function listed(options, allowNegative) {
|
|
633
|
+
if (!allowNegative)
|
|
634
|
+
return options;
|
|
635
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
636
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
637
|
+
return [[name, option]];
|
|
638
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
639
|
+
}));
|
|
640
|
+
}
|
|
641
|
+
function withAliases(args, options) {
|
|
642
|
+
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
643
|
+
if (named.size === 0)
|
|
644
|
+
return args;
|
|
645
|
+
const separator = args.indexOf("--");
|
|
646
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
647
|
+
return [...own.map((arg) => {
|
|
648
|
+
const at = arg.indexOf("=");
|
|
649
|
+
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
650
|
+
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
651
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
652
|
+
}
|
|
653
|
+
function withBare(args, options) {
|
|
654
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
655
|
+
if (bare.size === 0)
|
|
656
|
+
return args;
|
|
657
|
+
const separator = args.indexOf("--");
|
|
658
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
659
|
+
return [...own.flatMap((arg, index) => {
|
|
660
|
+
const optional = bare.get(arg);
|
|
661
|
+
const next = own[index + 1];
|
|
662
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
663
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
664
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
665
|
+
}
|
|
666
|
+
function checkConflicts(values, options) {
|
|
667
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
668
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
669
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
670
|
+
if (other !== undefined)
|
|
671
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
function checkChoices(values, options) {
|
|
675
|
+
for (const [name, option] of Object.entries(options)) {
|
|
676
|
+
if (option.choices === undefined)
|
|
677
|
+
continue;
|
|
678
|
+
const given = values[name];
|
|
679
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
680
|
+
if (typeof value === "string")
|
|
681
|
+
oneOf(value, name, option.choices);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
function oneOf(value, name, choices) {
|
|
686
|
+
if (!choices.includes(value))
|
|
687
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
688
|
+
return value;
|
|
689
|
+
}
|
|
690
|
+
function checkPositionals(given, names) {
|
|
691
|
+
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
692
|
+
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
693
|
+
if (given.length < required)
|
|
694
|
+
badUsage(`missing ${names[given.length]}`);
|
|
695
|
+
if (!variadic && given.length > names.length)
|
|
696
|
+
badUsage(`unexpected argument ${given[names.length]}`);
|
|
697
|
+
}
|
|
698
|
+
function joinDashValues(args, options) {
|
|
699
|
+
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
700
|
+
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
701
|
+
const joined = [];
|
|
702
|
+
for (let i = 0;i < args.length; i++) {
|
|
703
|
+
const arg = args[i] ?? "";
|
|
704
|
+
if (arg === "--")
|
|
705
|
+
return [...joined, ...args.slice(i)];
|
|
706
|
+
const name = longOf.get(arg);
|
|
707
|
+
const next = args[i + 1];
|
|
708
|
+
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
709
|
+
joined.push(`--${name}=${next}`);
|
|
710
|
+
i++;
|
|
711
|
+
} else {
|
|
712
|
+
joined.push(arg);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
return joined;
|
|
716
|
+
}
|
|
717
|
+
function parseError(error) {
|
|
718
|
+
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
719
|
+
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
720
|
+
}
|
|
721
|
+
function nearestOption(message, options, allowNegative) {
|
|
722
|
+
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
723
|
+
if (typed === undefined)
|
|
724
|
+
return;
|
|
725
|
+
const word = typed.replace(DASHES, "");
|
|
726
|
+
if (word.length < 2 && !typed.startsWith("--"))
|
|
727
|
+
return;
|
|
728
|
+
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
729
|
+
...option.short === undefined ? [] : [`-${option.short}`],
|
|
730
|
+
`--${name}`,
|
|
731
|
+
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
732
|
+
]);
|
|
733
|
+
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
734
|
+
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
735
|
+
}
|
|
736
|
+
var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
|
|
737
|
+
var init_args = __esm(() => {
|
|
738
|
+
init_format();
|
|
739
|
+
init_help();
|
|
740
|
+
init_text();
|
|
741
|
+
init_help();
|
|
742
|
+
init_input();
|
|
743
|
+
DASHES = /^-+/;
|
|
744
|
+
EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
|
|
745
|
+
Exit = class Exit extends Error {
|
|
746
|
+
code;
|
|
747
|
+
hint;
|
|
748
|
+
[EXIT] = true;
|
|
749
|
+
constructor(message, code, hint) {
|
|
750
|
+
super(message);
|
|
751
|
+
this.code = code;
|
|
752
|
+
this.hint = hint;
|
|
753
|
+
}
|
|
754
|
+
static [Symbol.hasInstance](value) {
|
|
755
|
+
if (this !== Exit)
|
|
756
|
+
return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
757
|
+
return typeof value === "object" && value !== null && value[EXIT] === true;
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
UsageError = class UsageError extends Exit {
|
|
761
|
+
constructor(message, hint) {
|
|
762
|
+
super(message, 2, hint);
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
HelpShown = class HelpShown extends Exit {
|
|
766
|
+
constructor() {
|
|
767
|
+
super("help shown", 0);
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
completion = { active: false };
|
|
771
|
+
OUTPUT_OPTIONS = {
|
|
772
|
+
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
773
|
+
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
774
|
+
};
|
|
775
|
+
UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
776
|
+
});
|
|
777
|
+
|
|
778
|
+
// ../kit/src/argv.ts
|
|
779
|
+
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
780
|
+
import { resolve as resolve3 } from "path";
|
|
781
|
+
import process10 from "process";
|
|
782
|
+
function commandLine() {
|
|
783
|
+
try {
|
|
784
|
+
return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
785
|
+
} catch {
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
function realPath(word) {
|
|
790
|
+
try {
|
|
791
|
+
return realpathSync(resolve3(word));
|
|
792
|
+
} catch {
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
797
|
+
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
798
|
+
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
799
|
+
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
800
|
+
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
801
|
+
}
|
|
802
|
+
var init_argv = () => {};
|
|
803
|
+
|
|
804
|
+
// ../kit/src/chart.ts
|
|
805
|
+
var init_chart = __esm(() => {
|
|
806
|
+
init_format();
|
|
807
|
+
init_mode();
|
|
808
|
+
init_style();
|
|
809
|
+
init_theme();
|
|
810
|
+
});
|
|
811
|
+
|
|
812
|
+
// ../kit/src/process.ts
|
|
813
|
+
var GROUP_SIGNALS;
|
|
814
|
+
var init_process = __esm(() => {
|
|
815
|
+
GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
816
|
+
});
|
|
817
|
+
|
|
818
|
+
// ../kit/src/progress.ts
|
|
819
|
+
var ESC, ESCAPE_CODE, RESET_STYLE, CLOSE_LINK;
|
|
820
|
+
var init_progress = __esm(() => {
|
|
821
|
+
init_format();
|
|
822
|
+
init_process();
|
|
823
|
+
init_style();
|
|
824
|
+
init_theme();
|
|
825
|
+
ESC = String.fromCharCode(27);
|
|
826
|
+
ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
827
|
+
RESET_STYLE = `${ESC}[0m`;
|
|
828
|
+
CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
829
|
+
});
|
|
830
|
+
|
|
831
|
+
// ../kit/src/tool.ts
|
|
832
|
+
var init_tool = __esm(() => {
|
|
833
|
+
init_format();
|
|
834
|
+
init_process();
|
|
835
|
+
});
|
|
836
|
+
|
|
837
|
+
// ../kit/src/ci.ts
|
|
838
|
+
var init_ci = __esm(() => {
|
|
839
|
+
init_args();
|
|
840
|
+
init_format();
|
|
841
|
+
init_progress();
|
|
842
|
+
init_style();
|
|
843
|
+
init_tool();
|
|
844
|
+
});
|
|
845
|
+
|
|
846
|
+
// ../kit/src/askpass.ts
|
|
847
|
+
import process11 from "process";
|
|
848
|
+
async function askpassClient(argv) {
|
|
849
|
+
const socketPath = process11.env[SOCKET_VARIABLE];
|
|
850
|
+
if (socketPath === undefined)
|
|
851
|
+
return;
|
|
852
|
+
const request = { prompt: argv[0] ?? "", ...process11.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
853
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
854
|
+
let received = "";
|
|
855
|
+
try {
|
|
856
|
+
await Bun.connect({
|
|
857
|
+
unix: socketPath,
|
|
858
|
+
socket: {
|
|
859
|
+
open: (socket) => void socket.write(`${JSON.stringify(request)}
|
|
860
|
+
`),
|
|
861
|
+
data: (_, chunk) => {
|
|
862
|
+
received += chunk.toString();
|
|
863
|
+
},
|
|
864
|
+
close: () => resolve(received),
|
|
865
|
+
error: () => resolve("")
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
} catch {
|
|
869
|
+
return 1;
|
|
870
|
+
}
|
|
871
|
+
const reply = await promise;
|
|
872
|
+
if (reply === "")
|
|
873
|
+
return 1;
|
|
874
|
+
const { answer } = JSON.parse(reply);
|
|
875
|
+
if (request.notice === true)
|
|
876
|
+
return 0;
|
|
877
|
+
if (answer === undefined)
|
|
878
|
+
return 1;
|
|
879
|
+
process11.stdout.write(`${answer}
|
|
880
|
+
`);
|
|
881
|
+
return 0;
|
|
882
|
+
}
|
|
883
|
+
var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
|
|
884
|
+
var init_askpass = () => {};
|
|
885
|
+
|
|
886
|
+
// ../kit/src/completions.ts
|
|
887
|
+
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
888
|
+
if (shell === "fish")
|
|
889
|
+
return `${header}
|
|
890
|
+
${FISH_FUNCTION}
|
|
891
|
+
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
892
|
+
`).join("")}`;
|
|
893
|
+
if (shell === "bash")
|
|
894
|
+
return `${header}
|
|
895
|
+
${BASH_FUNCTION}
|
|
896
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
897
|
+
`;
|
|
898
|
+
return `${header}
|
|
899
|
+
${ZSH_FUNCTION}
|
|
900
|
+
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
901
|
+
`;
|
|
902
|
+
}
|
|
903
|
+
var COMPLETION_SHELLS, 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'
|
|
904
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
905
|
+
set -l current (commandline -ct)
|
|
906
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
907
|
+
if test "$line" = __files__
|
|
908
|
+
__fish_complete_path $current
|
|
909
|
+
else
|
|
910
|
+
echo $line
|
|
911
|
+
end
|
|
912
|
+
end
|
|
913
|
+
end`, BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
914
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
915
|
+
local -a lines
|
|
916
|
+
COMPREPLY=()
|
|
917
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
918
|
+
for line in "\${lines[@]}"; do
|
|
919
|
+
if [[ $line == __files__ ]]; then
|
|
920
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
921
|
+
else
|
|
922
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
923
|
+
fi
|
|
924
|
+
done
|
|
925
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
926
|
+
}`, ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
927
|
+
local line
|
|
928
|
+
local -a described plain
|
|
929
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
930
|
+
if [[ $line == __files__ ]]; then
|
|
931
|
+
_files
|
|
932
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
933
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
934
|
+
else
|
|
935
|
+
plain+=("$line")
|
|
936
|
+
fi
|
|
937
|
+
done
|
|
938
|
+
(( \${#described} )) && _describe -V value described
|
|
939
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
940
|
+
return 0
|
|
941
|
+
}`;
|
|
942
|
+
var init_completions = __esm(() => {
|
|
943
|
+
COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
944
|
+
});
|
|
945
|
+
|
|
946
|
+
// ../kit/src/notify.ts
|
|
947
|
+
import process12 from "process";
|
|
948
|
+
function base64(text) {
|
|
949
|
+
return Buffer.from(text).toString("base64");
|
|
950
|
+
}
|
|
951
|
+
function notification(title, body, env = process12.env) {
|
|
952
|
+
const id = `kit${process12.pid}`;
|
|
953
|
+
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\\`];
|
|
954
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
955
|
+
}
|
|
956
|
+
function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
|
|
957
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
958
|
+
return;
|
|
959
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
960
|
+
}
|
|
961
|
+
var NOTIFY_AFTER_MS = 1e4, CANCELLED = 130;
|
|
962
|
+
var init_notify = __esm(() => {
|
|
963
|
+
init_format();
|
|
964
|
+
init_mode();
|
|
965
|
+
});
|
|
966
|
+
|
|
967
|
+
// ../kit/src/logs.ts
|
|
968
|
+
var DAY_MS, CLI_FOLDER = "kaynooo-cli";
|
|
969
|
+
var init_logs = __esm(() => {
|
|
970
|
+
init_user_config();
|
|
971
|
+
DAY_MS = 24 * 60 * 60 * 1000;
|
|
972
|
+
});
|
|
973
|
+
|
|
974
|
+
// ../kit/src/usage.ts
|
|
975
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
976
|
+
import { homedir as homedir3 } from "os";
|
|
977
|
+
import { dirname as dirname2, join as join4 } from "path";
|
|
978
|
+
import process13 from "process";
|
|
979
|
+
function noteUsageError(message) {
|
|
980
|
+
usageError = message;
|
|
981
|
+
}
|
|
982
|
+
function stateHome(env = process13.env) {
|
|
983
|
+
return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
|
|
984
|
+
}
|
|
985
|
+
function usagePath(env = process13.env) {
|
|
986
|
+
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
987
|
+
}
|
|
988
|
+
function usageRecorded(env = process13.env) {
|
|
989
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
990
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
991
|
+
}
|
|
992
|
+
function flagNames(argv) {
|
|
993
|
+
const end = argv.indexOf("--");
|
|
994
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
995
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
996
|
+
}
|
|
997
|
+
function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
998
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
999
|
+
usageError = undefined;
|
|
1000
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
1001
|
+
}
|
|
1002
|
+
function recordUsage(entry, env = process13.env) {
|
|
1003
|
+
if (!usageRecorded(env))
|
|
1004
|
+
return;
|
|
1005
|
+
try {
|
|
1006
|
+
const path = usagePath(env);
|
|
1007
|
+
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1008
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1009
|
+
`, { mode: 384 });
|
|
1010
|
+
} catch {}
|
|
1011
|
+
}
|
|
1012
|
+
var UNKNOWN_OPTION2, FLAG_NAME, LONGEST_NAME = 40, usageError;
|
|
1013
|
+
var init_usage = __esm(() => {
|
|
1014
|
+
init_logs();
|
|
1015
|
+
init_user_config();
|
|
1016
|
+
UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1017
|
+
FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1018
|
+
});
|
|
1019
|
+
|
|
1020
|
+
// ../kit/src/cli.ts
|
|
1021
|
+
import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
|
|
1022
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
1023
|
+
import process14 from "process";
|
|
1024
|
+
async function commandRows(all, colors) {
|
|
1025
|
+
const commands = shown(all);
|
|
1026
|
+
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
1027
|
+
const groups = new Map([["Commands:", []]]);
|
|
1028
|
+
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
1029
|
+
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
1030
|
+
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
1031
|
+
const rows = groups.get(heading) ?? [];
|
|
1032
|
+
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
1033
|
+
groups.set(heading, rows);
|
|
1034
|
+
}
|
|
1035
|
+
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
1036
|
+
}
|
|
1037
|
+
function shown(commands) {
|
|
1038
|
+
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
1039
|
+
}
|
|
1040
|
+
function takeOutputFlags(argv) {
|
|
1041
|
+
let index = 0;
|
|
1042
|
+
for (;index < argv.length; index++) {
|
|
1043
|
+
const word = argv[index];
|
|
1044
|
+
if (word === "--plain")
|
|
1045
|
+
applyOutput(undefined, true);
|
|
1046
|
+
else if (word.startsWith("--color="))
|
|
1047
|
+
applyOutput(word.slice("--color=".length), undefined);
|
|
1048
|
+
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
1049
|
+
applyOutput(argv[++index], undefined);
|
|
1050
|
+
else
|
|
1051
|
+
break;
|
|
1052
|
+
}
|
|
1053
|
+
return argv.slice(index);
|
|
1054
|
+
}
|
|
1055
|
+
async function resolveSummary(summary) {
|
|
1056
|
+
return typeof summary === "string" ? summary : summary();
|
|
1057
|
+
}
|
|
1058
|
+
function lookup({ commands, aliases }, word) {
|
|
1059
|
+
const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
|
|
1060
|
+
return Object.hasOwn(commands, name) ? commands[name] : undefined;
|
|
1061
|
+
}
|
|
1062
|
+
function scopeOf(commands, extra, aliases) {
|
|
1063
|
+
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
1064
|
+
}
|
|
1065
|
+
async function expand(scope, words) {
|
|
1066
|
+
if (scope.lazy.length === 0)
|
|
1067
|
+
return scope;
|
|
1068
|
+
const commands = { ...scope.commands };
|
|
1069
|
+
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
1070
|
+
for (const [name, command] of Object.entries(added))
|
|
1071
|
+
commands[name] ??= command;
|
|
1072
|
+
}
|
|
1073
|
+
return { ...scope, commands, lazy: [] };
|
|
1074
|
+
}
|
|
1075
|
+
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
1076
|
+
const colors = paint(stream);
|
|
1077
|
+
const prefix = path.join(" ");
|
|
1078
|
+
const summary = await resolveSummary(lazySummary);
|
|
1079
|
+
if (wantsHelpJson())
|
|
1080
|
+
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
1081
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1082
|
+
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
1083
|
+
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
1084
|
+
return [
|
|
1085
|
+
header(colors, summary),
|
|
1086
|
+
"",
|
|
1087
|
+
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
1088
|
+
"",
|
|
1089
|
+
...await commandRows(commands, colors),
|
|
1090
|
+
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
1091
|
+
"",
|
|
1092
|
+
colors.bold("Options:"),
|
|
1093
|
+
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
1094
|
+
...exampleRows(examples ?? [], colors),
|
|
1095
|
+
"",
|
|
1096
|
+
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
1097
|
+
].join(`
|
|
1098
|
+
`);
|
|
1099
|
+
}
|
|
1100
|
+
function printError(prefix, message, hint, cause) {
|
|
1101
|
+
const colors = paint(process14.stderr);
|
|
1102
|
+
const styled = takesControlCodes(process14.stderr);
|
|
1103
|
+
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1104
|
+
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1105
|
+
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1106
|
+
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1107
|
+
}
|
|
1108
|
+
function printJsonError(message, hint, cause) {
|
|
1109
|
+
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1110
|
+
}
|
|
1111
|
+
function wantsJson(argv) {
|
|
1112
|
+
const end = argv.indexOf("--");
|
|
1113
|
+
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1114
|
+
}
|
|
1115
|
+
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1116
|
+
if (error instanceof HelpShown)
|
|
1117
|
+
return 0;
|
|
1118
|
+
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1119
|
+
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1120
|
+
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1121
|
+
if (error instanceof Exit && error.code === 2)
|
|
1122
|
+
noteUsageError(error.message);
|
|
1123
|
+
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1124
|
+
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1125
|
+
return error instanceof Exit ? error.code : 1;
|
|
1126
|
+
}
|
|
1127
|
+
async function dispatch(level, typed, { version, redact }) {
|
|
1128
|
+
const prefix = level.path.join(" ");
|
|
1129
|
+
let argv;
|
|
1130
|
+
try {
|
|
1131
|
+
argv = takeOutputFlags(typed);
|
|
1132
|
+
} catch (error) {
|
|
1133
|
+
return reportThrown(prefix, error);
|
|
1134
|
+
}
|
|
1135
|
+
const [name, ...args] = argv;
|
|
1136
|
+
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
1137
|
+
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
1138
|
+
try {
|
|
1139
|
+
return await fallback.run([]);
|
|
1140
|
+
} catch (error) {
|
|
1141
|
+
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
if (name === undefined && level.path.length > 1) {
|
|
1145
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
|
|
1146
|
+
return 2;
|
|
1147
|
+
}
|
|
1148
|
+
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1149
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
|
|
1150
|
+
return 0;
|
|
1151
|
+
}
|
|
1152
|
+
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1153
|
+
console.log(version);
|
|
1154
|
+
return 0;
|
|
1155
|
+
}
|
|
1156
|
+
let command = lookup(level, name);
|
|
1157
|
+
let rest = args;
|
|
1158
|
+
let ran = name;
|
|
1159
|
+
if (command === undefined && level.lazy.length > 0) {
|
|
1160
|
+
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1161
|
+
command = lookup(level, name);
|
|
1162
|
+
}
|
|
1163
|
+
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1164
|
+
command = level.commands[level.defaultCommand];
|
|
1165
|
+
rest = argv;
|
|
1166
|
+
ran = level.defaultCommand;
|
|
1167
|
+
}
|
|
1168
|
+
if (command === undefined) {
|
|
1169
|
+
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
1170
|
+
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
1171
|
+
return 2;
|
|
1172
|
+
}
|
|
1173
|
+
if ("commands" in command) {
|
|
1174
|
+
const { summary } = command;
|
|
1175
|
+
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
1176
|
+
}
|
|
1177
|
+
try {
|
|
1178
|
+
return await command.run(rest);
|
|
1179
|
+
} catch (error) {
|
|
1180
|
+
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
async function completingOf(run) {
|
|
1184
|
+
completion.active = true;
|
|
1185
|
+
try {
|
|
1186
|
+
await run([]);
|
|
1187
|
+
} catch (error) {
|
|
1188
|
+
if (error instanceof Completing)
|
|
1189
|
+
return error;
|
|
1190
|
+
} finally {
|
|
1191
|
+
completion.active = false;
|
|
1192
|
+
}
|
|
1193
|
+
return new Completing({});
|
|
1194
|
+
}
|
|
1195
|
+
async function optionsOf(run) {
|
|
1196
|
+
return (await completingOf(run)).options;
|
|
1197
|
+
}
|
|
1198
|
+
function candidateLine(candidate) {
|
|
1199
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1200
|
+
}
|
|
1201
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
1202
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1203
|
+
const typed = [];
|
|
1204
|
+
let at = 0;
|
|
1205
|
+
while (at < before.length) {
|
|
1206
|
+
const word = before[at];
|
|
1207
|
+
if (word === "--") {
|
|
1208
|
+
typed.push(...before.slice(at + 1));
|
|
1209
|
+
break;
|
|
1210
|
+
}
|
|
1211
|
+
if (!word.startsWith("-"))
|
|
1212
|
+
typed.push(word);
|
|
1213
|
+
else if (takesValue(word))
|
|
1214
|
+
at++;
|
|
1215
|
+
at++;
|
|
1216
|
+
}
|
|
1217
|
+
const last = positionals.at(-1);
|
|
1218
|
+
if (typed.length < positionals.length)
|
|
1219
|
+
return { name: positionals[typed.length], typed };
|
|
1220
|
+
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1221
|
+
}
|
|
1222
|
+
async function leafCandidates(run, words) {
|
|
1223
|
+
const completing = await completingOf(run);
|
|
1224
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1225
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1226
|
+
const flag = words.at(-2);
|
|
1227
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1228
|
+
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1229
|
+
if (option?.type === "string") {
|
|
1230
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1231
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1232
|
+
}
|
|
1233
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1234
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1235
|
+
}
|
|
1236
|
+
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1237
|
+
const [word = "", ...rest] = words;
|
|
1238
|
+
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1239
|
+
let { commands } = scope;
|
|
1240
|
+
let command = lookup(scope, word);
|
|
1241
|
+
if (listing || command === undefined) {
|
|
1242
|
+
const expanded = await expand(scope, [...before, ...words]);
|
|
1243
|
+
commands = expanded.commands;
|
|
1244
|
+
command = lookup(expanded, word);
|
|
1245
|
+
}
|
|
1246
|
+
if (listing) {
|
|
1247
|
+
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1248
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1249
|
+
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1250
|
+
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1251
|
+
return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
|
|
1252
|
+
}
|
|
1253
|
+
if (command === undefined) {
|
|
1254
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1255
|
+
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1256
|
+
}
|
|
1257
|
+
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1258
|
+
}
|
|
1259
|
+
function flagValue([flag = "", ...rest]) {
|
|
1260
|
+
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1261
|
+
}
|
|
1262
|
+
function printCompletionScript(name, args) {
|
|
1263
|
+
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1264
|
+
if (shell === undefined || args.length !== 1) {
|
|
1265
|
+
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1266
|
+
return 2;
|
|
1267
|
+
}
|
|
1268
|
+
console.log(completionScript(shell, [name]).trimEnd());
|
|
1269
|
+
return 0;
|
|
1270
|
+
}
|
|
1271
|
+
async function printCandidates(found) {
|
|
1272
|
+
for (const line of await found)
|
|
1273
|
+
console.log(line);
|
|
1274
|
+
return 0;
|
|
1275
|
+
}
|
|
1276
|
+
function packageVersion(entry = Bun.main) {
|
|
1277
|
+
let resolved = entry;
|
|
1278
|
+
try {
|
|
1279
|
+
resolved = realpathSync2(entry);
|
|
1280
|
+
} catch {}
|
|
1281
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1282
|
+
try {
|
|
1283
|
+
const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
|
|
1284
|
+
if (typeof version === "string")
|
|
1285
|
+
return version;
|
|
1286
|
+
} catch {}
|
|
1287
|
+
if (dirname3(dir) === dir)
|
|
1288
|
+
return "0.0.0";
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
async function runCli(cli, argv = scriptArgs()) {
|
|
1292
|
+
const version = cli.version ?? packageVersion();
|
|
1293
|
+
const answered = await askpassClient(argv);
|
|
1294
|
+
if (answered !== undefined)
|
|
1295
|
+
return answered;
|
|
1296
|
+
if (argv[0] === COMPLETE)
|
|
1297
|
+
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1298
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1299
|
+
return printCompletionScript(cli.name, flagValue(argv));
|
|
1300
|
+
const started = performance.now();
|
|
1301
|
+
const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
|
|
1302
|
+
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1303
|
+
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1304
|
+
if (cli.usage !== false) {
|
|
1305
|
+
try {
|
|
1306
|
+
recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
|
|
1307
|
+
} catch {}
|
|
1308
|
+
}
|
|
1309
|
+
return code;
|
|
1310
|
+
}
|
|
1311
|
+
function commandPath(scope, argv) {
|
|
1312
|
+
const path = [];
|
|
1313
|
+
let level = scope;
|
|
1314
|
+
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1315
|
+
const command = lookup(level, word);
|
|
1316
|
+
if (command === undefined)
|
|
1317
|
+
break;
|
|
1318
|
+
path.push(word);
|
|
1319
|
+
if (!("commands" in command))
|
|
1320
|
+
break;
|
|
1321
|
+
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1322
|
+
}
|
|
1323
|
+
return path.length === 0 ? undefined : path.join(" ");
|
|
1324
|
+
}
|
|
1325
|
+
var LEVEL_OPTIONS, TOP_OPTIONS, COMPLETE = "__complete", FILES = "__files__", COMPLETIONS = "--completions";
|
|
1326
|
+
var init_cli = __esm(() => {
|
|
1327
|
+
init_args();
|
|
1328
|
+
init_argv();
|
|
1329
|
+
init_askpass();
|
|
1330
|
+
init_completions();
|
|
1331
|
+
init_notify();
|
|
1332
|
+
init_style();
|
|
1333
|
+
init_text();
|
|
1334
|
+
init_usage();
|
|
1335
|
+
LEVEL_OPTIONS = {
|
|
1336
|
+
...OUTPUT_OPTIONS,
|
|
1337
|
+
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1338
|
+
};
|
|
1339
|
+
TOP_OPTIONS = {
|
|
1340
|
+
...LEVEL_OPTIONS,
|
|
1341
|
+
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1342
|
+
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1343
|
+
};
|
|
1344
|
+
});
|
|
1345
|
+
// ../kit/src/excerpt.ts
|
|
1346
|
+
var init_excerpt = __esm(() => {
|
|
1347
|
+
init_text();
|
|
1348
|
+
});
|
|
1349
|
+
|
|
1350
|
+
// ../kit/src/folders.ts
|
|
1351
|
+
import { homedir as homedir4 } from "os";
|
|
1352
|
+
import { join as join6 } from "path";
|
|
1353
|
+
import process15 from "process";
|
|
1354
|
+
function cacheFolder({ home = homedir4(), env = process15.env } = {}) {
|
|
1355
|
+
return xdgFolder(env.XDG_CACHE_HOME, join6(home, ".cache"));
|
|
1356
|
+
}
|
|
1357
|
+
var SKIPPED_FOLDERS;
|
|
1358
|
+
var init_folders = __esm(() => {
|
|
1359
|
+
init_user_config();
|
|
1360
|
+
SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
1361
|
+
});
|
|
1362
|
+
|
|
1363
|
+
// ../kit/src/git.ts
|
|
1364
|
+
var init_git = __esm(() => {
|
|
1365
|
+
init_args();
|
|
1366
|
+
init_tool();
|
|
1367
|
+
});
|
|
1368
|
+
|
|
1369
|
+
// ../kit/src/limit.ts
|
|
1370
|
+
var init_limit = __esm(() => {
|
|
1371
|
+
init_args();
|
|
1372
|
+
});
|
|
1373
|
+
// ../kit/src/report.ts
|
|
1374
|
+
var init_report = __esm(() => {
|
|
1375
|
+
init_cli();
|
|
1376
|
+
init_style();
|
|
1377
|
+
init_text();
|
|
1378
|
+
});
|
|
1379
|
+
|
|
1380
|
+
// ../kit/src/secrets.ts
|
|
1381
|
+
var SECRET_WORDS, NOT_PASSWORDS;
|
|
1382
|
+
var init_secrets = __esm(() => {
|
|
1383
|
+
SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1384
|
+
NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
|
|
1385
|
+
});
|
|
1386
|
+
|
|
1387
|
+
// ../kit/src/sessions.ts
|
|
1388
|
+
var {Glob } = globalThis.Bun;
|
|
1389
|
+
var SESSION_FILES, ACCOUNT_DIRS;
|
|
1390
|
+
var init_sessions = __esm(() => {
|
|
1391
|
+
SESSION_FILES = new Glob("*.json");
|
|
1392
|
+
ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1393
|
+
});
|
|
1394
|
+
|
|
1395
|
+
// ../kit/src/size.ts
|
|
1396
|
+
var init_size = () => {};
|
|
1397
|
+
|
|
1398
|
+
// ../kit/src/watch.ts
|
|
1399
|
+
var init_watch = __esm(() => {
|
|
1400
|
+
init_args();
|
|
1401
|
+
init_input();
|
|
1402
|
+
init_style();
|
|
1403
|
+
});
|
|
1404
|
+
|
|
1405
|
+
// ../kit/src/workspace-root.ts
|
|
1406
|
+
var init_workspace_root = __esm(() => {
|
|
1407
|
+
init_user_config();
|
|
1408
|
+
});
|
|
1409
|
+
|
|
1410
|
+
// ../kit/src/index.ts
|
|
1411
|
+
var init_src = __esm(() => {
|
|
1412
|
+
init_excerpt();
|
|
1413
|
+
init_advisory();
|
|
1414
|
+
init_args();
|
|
1415
|
+
init_argv();
|
|
1416
|
+
init_chart();
|
|
1417
|
+
init_ci();
|
|
1418
|
+
init_cli();
|
|
1419
|
+
init_completions();
|
|
1420
|
+
init_config();
|
|
1421
|
+
init_folders();
|
|
1422
|
+
init_format();
|
|
1423
|
+
init_git();
|
|
1424
|
+
init_limit();
|
|
1425
|
+
init_logs();
|
|
1426
|
+
init_mode();
|
|
1427
|
+
init_process();
|
|
1428
|
+
init_report();
|
|
1429
|
+
init_secrets();
|
|
1430
|
+
init_sessions();
|
|
1431
|
+
init_size();
|
|
1432
|
+
init_style();
|
|
1433
|
+
init_text();
|
|
1434
|
+
init_theme();
|
|
1435
|
+
init_tool();
|
|
1436
|
+
init_usage();
|
|
1437
|
+
init_user_config();
|
|
1438
|
+
init_watch();
|
|
1439
|
+
init_workspace_root();
|
|
1440
|
+
});
|
|
1441
|
+
|
|
1442
|
+
// src/inpage.ts
|
|
1443
|
+
async function source(file) {
|
|
1444
|
+
let code = sources.get(file);
|
|
1445
|
+
if (code === undefined) {
|
|
1446
|
+
code = transpiler.transformSync(await Bun.file(new URL(`../inpage/${file}.ts`, import.meta.url)).text()).replace(EXPORT, "");
|
|
1447
|
+
sources.set(file, code);
|
|
1448
|
+
}
|
|
1449
|
+
return code;
|
|
1450
|
+
}
|
|
1451
|
+
async function inPage(page, file, name, arg) {
|
|
1452
|
+
return page.evaluate(`(() => {
|
|
1453
|
+
${await source(file)}
|
|
1454
|
+
return ${name}(${JSON.stringify(arg) ?? ""})
|
|
1455
|
+
})()`);
|
|
1456
|
+
}
|
|
1457
|
+
async function beforeLoad(page, file, name) {
|
|
1458
|
+
await page.addInitScript({ content: `(() => {
|
|
1459
|
+
${await source(file)}
|
|
1460
|
+
${name}()
|
|
1461
|
+
})()` });
|
|
1462
|
+
}
|
|
1463
|
+
var EXPORT, transpiler, sources;
|
|
1464
|
+
var init_inpage = __esm(() => {
|
|
1465
|
+
EXPORT = /^export /gm;
|
|
1466
|
+
transpiler = new Bun.Transpiler({ loader: "ts", target: "browser" });
|
|
1467
|
+
sources = new Map;
|
|
1468
|
+
});
|
|
1469
|
+
|
|
1470
|
+
// src/browser.ts
|
|
1471
|
+
import { existsSync as existsSync3, readdirSync } from "fs";
|
|
1472
|
+
import { homedir as homedir5 } from "os";
|
|
1473
|
+
import { basename, dirname as dirname4, join as join7, resolve as resolve4 } from "path";
|
|
1474
|
+
import process17 from "process";
|
|
1475
|
+
import { pathToFileURL } from "url";
|
|
1476
|
+
function playwrightBuilds(cache) {
|
|
1477
|
+
if (!existsSync3(cache))
|
|
1478
|
+
return [];
|
|
1479
|
+
const folders = readdirSync(cache).filter((name) => name.startsWith("chromium")).toSorted((a, b) => Number(a.includes("headless")) - Number(b.includes("headless")) || revision(b) - revision(a));
|
|
1480
|
+
return folders.flatMap((folder) => [join7(cache, folder, "chrome-headless-shell-linux64/chrome-headless-shell"), join7(cache, folder, "chrome-linux64/chrome"), join7(cache, folder, "chrome-linux/chrome")]);
|
|
1481
|
+
}
|
|
1482
|
+
function revision(folder) {
|
|
1483
|
+
return Number(folder.split("-").at(-1)) || 0;
|
|
1484
|
+
}
|
|
1485
|
+
function findChromium(env = process17.env, home = homedir5()) {
|
|
1486
|
+
if (env.PAGE_CHROMIUM !== undefined && env.PAGE_CHROMIUM !== "") {
|
|
1487
|
+
if (!existsSync3(env.PAGE_CHROMIUM))
|
|
1488
|
+
fail(`PAGE_CHROMIUM points at ${env.PAGE_CHROMIUM}, which does not exist`);
|
|
1489
|
+
return env.PAGE_CHROMIUM;
|
|
1490
|
+
}
|
|
1491
|
+
const cache = env.PLAYWRIGHT_BROWSERS_PATH ?? join7(home, ".cache/ms-playwright");
|
|
1492
|
+
const found = [...playwrightBuilds(cache), ...SYSTEM_CHROMES].find((path) => existsSync3(path));
|
|
1493
|
+
if (found === undefined)
|
|
1494
|
+
fail(`no Chromium under ${cache} or /usr/bin`, 2, "bunx playwright install chromium-headless-shell, or set PAGE_CHROMIUM to a Chrome or Chromium binary");
|
|
1495
|
+
return found;
|
|
1496
|
+
}
|
|
1497
|
+
async function launch() {
|
|
1498
|
+
const { chromium } = await import("playwright-core");
|
|
1499
|
+
return chromium.launch({ executablePath: findChromium() });
|
|
1500
|
+
}
|
|
1501
|
+
function targetOf(given, out) {
|
|
1502
|
+
if (HTTP_URL.test(given)) {
|
|
1503
|
+
const url = new URL(given);
|
|
1504
|
+
const name = `${url.host}${url.pathname}`.replace(UNSAFE, "-").replace(EDGE_DASHES, "");
|
|
1505
|
+
return { label: given, url: given, stem: join7(out ?? join7(cacheFolder(), "kaynooo-page"), name) };
|
|
1506
|
+
}
|
|
1507
|
+
const path = resolve4(given);
|
|
1508
|
+
if (!existsSync3(path))
|
|
1509
|
+
fail(`${given} does not exist`);
|
|
1510
|
+
const name = basename(path).replace(HTML_EXT, "");
|
|
1511
|
+
return { label: given, url: pathToFileURL(path).href, stem: join7(out === undefined ? dirname4(path) : resolve4(out), name) };
|
|
1512
|
+
}
|
|
1513
|
+
function sessionOf(values) {
|
|
1514
|
+
const cookies = (values.cookie ?? []).map((cookie) => {
|
|
1515
|
+
const at = cookie.indexOf("=");
|
|
1516
|
+
if (at < 1)
|
|
1517
|
+
badUsage("--cookie takes name=value");
|
|
1518
|
+
return { name: cookie.slice(0, at), value: cookie.slice(at + 1) };
|
|
1519
|
+
});
|
|
1520
|
+
const headers = {};
|
|
1521
|
+
for (const header of values.header ?? []) {
|
|
1522
|
+
if (!HEADER_LINE.test(header))
|
|
1523
|
+
badUsage('-H takes "Name: value"');
|
|
1524
|
+
const at = header.indexOf(":");
|
|
1525
|
+
headers[header.slice(0, at).trim().toLowerCase()] = header.slice(at + 1).trim();
|
|
1526
|
+
}
|
|
1527
|
+
const storageState = values["storage-state"];
|
|
1528
|
+
if (storageState !== undefined && !existsSync3(storageState))
|
|
1529
|
+
fail(`--storage-state ${storageState} does not exist`);
|
|
1530
|
+
return { cookies, headers, ...storageState === undefined ? {} : { storageState } };
|
|
1531
|
+
}
|
|
1532
|
+
async function open(browser, url, width, session, prepare) {
|
|
1533
|
+
const context = await browser.newContext({ viewport: { width, height: 900 }, deviceScaleFactor: 1, hasTouch: width < PHONE_WIDTH, isMobile: false, ...session.storageState === undefined ? {} : { storageState: session.storageState } });
|
|
1534
|
+
if (HTTP_URL.test(url)) {
|
|
1535
|
+
if (session.cookies.length > 0)
|
|
1536
|
+
await context.addCookies(session.cookies.map((cookie) => ({ ...cookie, url })));
|
|
1537
|
+
if (Object.keys(session.headers).length > 0) {
|
|
1538
|
+
const { origin } = new URL(url);
|
|
1539
|
+
await context.route((requested) => requested.origin === origin, async (route) => route.continue({ headers: { ...route.request().headers(), ...session.headers } }));
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
const page = await context.newPage();
|
|
1543
|
+
await prepare?.(page);
|
|
1544
|
+
await page.goto(url, { waitUntil: "load", timeout: 30000 });
|
|
1545
|
+
try {
|
|
1546
|
+
await page.waitForLoadState("networkidle", { timeout: 5000 });
|
|
1547
|
+
} catch {}
|
|
1548
|
+
await inPage(page, "measure", "fontsReady");
|
|
1549
|
+
return { context, page, landed: page.url() };
|
|
1550
|
+
}
|
|
1551
|
+
function redirectedTo(asked, landed) {
|
|
1552
|
+
const bare = (url) => {
|
|
1553
|
+
const parsed = new URL(url);
|
|
1554
|
+
parsed.hash = "";
|
|
1555
|
+
return parsed.href;
|
|
1556
|
+
};
|
|
1557
|
+
return bare(asked) === bare(landed) ? undefined : landed;
|
|
1558
|
+
}
|
|
1559
|
+
async function shoot(page, path) {
|
|
1560
|
+
const options = { ...path === undefined ? {} : { path }, fullPage: true, animations: "disabled", caret: "hide" };
|
|
1561
|
+
try {
|
|
1562
|
+
return await page.screenshot(options);
|
|
1563
|
+
} catch {
|
|
1564
|
+
return page.screenshot(options);
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
var HTTP_URL, HEADER_LINE, HTML_EXT, UNSAFE, EDGE_DASHES, PHONE_WIDTH = 600, SYSTEM_CHROMES, SESSION_OPTIONS;
|
|
1568
|
+
var init_browser = __esm(() => {
|
|
1569
|
+
init_src();
|
|
1570
|
+
init_inpage();
|
|
1571
|
+
HTTP_URL = /^https?:\/\//;
|
|
1572
|
+
HEADER_LINE = /^[\w!#$%&'*+.^`|~-]+:/;
|
|
1573
|
+
HTML_EXT = /\.html?$/;
|
|
1574
|
+
UNSAFE = /[^\w.-]+/g;
|
|
1575
|
+
EDGE_DASHES = /^-+|-+$/g;
|
|
1576
|
+
SYSTEM_CHROMES = ["/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/usr/bin/brave", "/usr/bin/brave-browser"];
|
|
1577
|
+
SESSION_OPTIONS = {
|
|
1578
|
+
cookie: { type: "string", multiple: true, description: "name=value, a cookie for a URL target's site, repeatable" },
|
|
1579
|
+
header: { type: "string", short: "H", multiple: true, description: `"Name: value", a header sent with every request to a URL target's origin and nowhere else, repeatable` },
|
|
1580
|
+
"storage-state": { type: "string", description: "a Playwright storage state file (cookies and localStorage) every page starts from" }
|
|
1581
|
+
};
|
|
1582
|
+
});
|
|
1583
|
+
|
|
1584
|
+
// src/fonts.ts
|
|
1585
|
+
function families(stack) {
|
|
1586
|
+
return stack.split(",").map((family) => family.trim().replace(QUOTES, "")).filter((family) => family !== "");
|
|
1587
|
+
}
|
|
1588
|
+
function fallbackOf(stack, drawn, monospaced) {
|
|
1589
|
+
const declared = families(stack);
|
|
1590
|
+
const firstGeneric = declared.findIndex((family) => GENERIC.has(family.toLowerCase()));
|
|
1591
|
+
const named = firstGeneric === -1 ? declared : declared.slice(0, firstGeneric);
|
|
1592
|
+
const wanted = drawn.toLowerCase();
|
|
1593
|
+
if (named.length > 0)
|
|
1594
|
+
return declared.some((family) => family.toLowerCase() === wanted) ? undefined : `${named.join(", ")} ${named.length === 1 ? "is" : "are"} not available`;
|
|
1595
|
+
const generic = declared[0]?.toLowerCase() ?? "";
|
|
1596
|
+
return monospaced && !MONOSPACE.has(generic) ? `${declared[0]} resolves to a monospace font` : undefined;
|
|
1597
|
+
}
|
|
1598
|
+
async function fontFindings(page) {
|
|
1599
|
+
const samples = await inPage(page, "measure", "markFontSamples", { mark: MARK, perStyle: SAMPLES_PER_STYLE, max: MAX_SAMPLES });
|
|
1600
|
+
if (samples.length === 0)
|
|
1601
|
+
return [];
|
|
1602
|
+
const cdp = await page.context().newCDPSession(page);
|
|
1603
|
+
try {
|
|
1604
|
+
await cdp.send("DOM.enable");
|
|
1605
|
+
await cdp.send("CSS.enable");
|
|
1606
|
+
const { root } = await cdp.send("DOM.getDocument", { depth: 0 });
|
|
1607
|
+
const { nodeIds } = await cdp.send("DOM.querySelectorAll", { nodeId: root.nodeId, selector: `[${MARK}]` });
|
|
1608
|
+
const drawn = new Map;
|
|
1609
|
+
for (const nodeId of nodeIds) {
|
|
1610
|
+
const { attributes } = await cdp.send("DOM.getAttributes", { nodeId });
|
|
1611
|
+
const sample = samples[Number(attributes[attributes.indexOf(MARK) + 1])];
|
|
1612
|
+
const { fonts } = await cdp.send("CSS.getPlatformFontsForNode", { nodeId });
|
|
1613
|
+
const main = fonts.toSorted((a, b) => b.glyphCount - a.glyphCount)[0];
|
|
1614
|
+
if (sample !== undefined && main !== undefined && !main.familyName.toLowerCase().includes("emoji"))
|
|
1615
|
+
drawn.set(sample, main.familyName);
|
|
1616
|
+
}
|
|
1617
|
+
const mono = new Set;
|
|
1618
|
+
for (const name of new Set(drawn.values())) {
|
|
1619
|
+
if (await inPage(page, "measure", "monospaced", name))
|
|
1620
|
+
mono.add(name);
|
|
1621
|
+
}
|
|
1622
|
+
const found = new Map;
|
|
1623
|
+
for (const [sample, font] of drawn) {
|
|
1624
|
+
const why = fallbackOf(sample.stack, font, mono.has(font));
|
|
1625
|
+
const key = `${sample.stack}|${font}`;
|
|
1626
|
+
if (why === undefined)
|
|
1627
|
+
continue;
|
|
1628
|
+
const entry = found.get(key) ?? { first: sample, why: `font-family ${sample.stack} drawn in ${font}: ${why}`, counts: new Map };
|
|
1629
|
+
entry.counts.set(sample.style, sample.count);
|
|
1630
|
+
found.set(key, entry);
|
|
1631
|
+
}
|
|
1632
|
+
return [...found.values()].map(({ first, why, counts }) => {
|
|
1633
|
+
const count = [...counts.values()].reduce((sum, each) => sum + each, 0);
|
|
1634
|
+
return { kind: "font", selector: first.selector, message: count > 1 ? `${why} (${count} elements)` : why };
|
|
1635
|
+
});
|
|
1636
|
+
} finally {
|
|
1637
|
+
await cdp.detach();
|
|
1638
|
+
await inPage(page, "measure", "unmarkFontSamples", MARK);
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
var MARK = "data-page-font", SAMPLES_PER_STYLE = 3, MAX_SAMPLES = 300, GENERIC, MONOSPACE, QUOTES;
|
|
1642
|
+
var init_fonts = __esm(() => {
|
|
1643
|
+
init_inpage();
|
|
1644
|
+
GENERIC = new Set(["serif", "sans-serif", "monospace", "cursive", "fantasy", "math", "emoji", "fangsong", "system-ui", "ui-serif", "ui-sans-serif", "ui-monospace", "ui-rounded", "-apple-system", "blinkmacsystemfont"]);
|
|
1645
|
+
MONOSPACE = new Set(["monospace", "ui-monospace"]);
|
|
1646
|
+
QUOTES = /^["']|["']$/g;
|
|
1647
|
+
});
|
|
1648
|
+
|
|
1649
|
+
// src/report.ts
|
|
1650
|
+
import process18 from "process";
|
|
1651
|
+
function widthsOf(given) {
|
|
1652
|
+
if (given === undefined)
|
|
1653
|
+
return DEFAULT_WIDTHS;
|
|
1654
|
+
const widths = given.split(",").map((width) => wholeNumber(width.trim(), "widths", 0, 200));
|
|
1655
|
+
if (widths.some((width) => width > 7680))
|
|
1656
|
+
badUsage(`--widths takes widths up to 7680, not ${given}`);
|
|
1657
|
+
return widths;
|
|
1658
|
+
}
|
|
1659
|
+
function findingLines(findings, stream = process18.stdout) {
|
|
1660
|
+
const label = role("label", stream);
|
|
1661
|
+
const kind = role("warn", stream);
|
|
1662
|
+
const accent = role("accent", stream);
|
|
1663
|
+
const seen = new Map;
|
|
1664
|
+
const lines = [];
|
|
1665
|
+
for (const finding of findings) {
|
|
1666
|
+
const group = `${finding.target} ${finding.width}px ${finding.kind}`;
|
|
1667
|
+
const count = (seen.get(group) ?? 0) + 1;
|
|
1668
|
+
seen.set(group, count);
|
|
1669
|
+
if (count <= MAX_PER_KIND)
|
|
1670
|
+
lines.push(`${finding.target} ${label(`${finding.width}px`)} ${kind(finding.kind)}${finding.selector === undefined ? "" : ` ${accent(finding.selector)}`}: ${finding.message}`);
|
|
1671
|
+
}
|
|
1672
|
+
for (const [group, count] of seen) {
|
|
1673
|
+
if (count > MAX_PER_KIND)
|
|
1674
|
+
lines.push(`${group}: ${count - MAX_PER_KIND} more`);
|
|
1675
|
+
}
|
|
1676
|
+
return lines;
|
|
1677
|
+
}
|
|
1678
|
+
function printLines(lines, stream = process18.stdout) {
|
|
1679
|
+
if (lines.length > 0)
|
|
1680
|
+
stream.write(`${lines.join(`
|
|
1681
|
+
`)}
|
|
1682
|
+
`);
|
|
1683
|
+
}
|
|
1684
|
+
var MAX_PER_KIND = 10, DEFAULT_WIDTHS;
|
|
1685
|
+
var init_report2 = __esm(() => {
|
|
1686
|
+
init_src();
|
|
1687
|
+
DEFAULT_WIDTHS = [1440, 400];
|
|
1688
|
+
});
|
|
1689
|
+
|
|
1690
|
+
// src/check.ts
|
|
1691
|
+
var exports_check = {};
|
|
1692
|
+
__export(exports_check, {
|
|
1693
|
+
check: () => check
|
|
1694
|
+
});
|
|
1695
|
+
import { mkdirSync as mkdirSync2 } from "fs";
|
|
1696
|
+
import { dirname as dirname5 } from "path";
|
|
1697
|
+
import process19 from "process";
|
|
1698
|
+
function shortUrl(url) {
|
|
1699
|
+
return url.length > URL_CAP ? `${url.slice(0, URL_CAP - 3)}...` : url;
|
|
1700
|
+
}
|
|
1701
|
+
function listen(page, into) {
|
|
1702
|
+
page.on("console", (message) => {
|
|
1703
|
+
if (message.type() === "error" && !message.text().startsWith("Failed to load resource"))
|
|
1704
|
+
into.push({ kind: "console", message: message.text() });
|
|
1705
|
+
});
|
|
1706
|
+
page.on("pageerror", (error) => into.push({ kind: "console", message: `uncaught ${error.name}: ${error.message}` }));
|
|
1707
|
+
page.on("requestfailed", (request) => into.push({ kind: "request", message: `${request.method()} ${shortUrl(request.url())} failed: ${request.failure()?.errorText ?? "no answer"}` }));
|
|
1708
|
+
page.on("response", (response) => {
|
|
1709
|
+
if (response.status() >= 400)
|
|
1710
|
+
into.push({ kind: "request", message: `${response.request().method()} ${shortUrl(response.url())} answered ${response.status()}` });
|
|
1711
|
+
});
|
|
1712
|
+
}
|
|
1713
|
+
async function check(args) {
|
|
1714
|
+
const { values, positionals } = parse(args, USAGE, OPTIONS, {
|
|
1715
|
+
positionals: ["<file|url>..."],
|
|
1716
|
+
exits: EXITS,
|
|
1717
|
+
examples: [["page check mockup.html", "mockup-1440.png and mockup-400.png beside it, then the defects"], ["page check http://localhost:5173/settings --cookie session=<value>", "a page behind a login"], "page check http://localhost:5173/settings -w 1280,768,375 -o shots", "page check index.html --skip font,padding --json"]
|
|
1718
|
+
});
|
|
1719
|
+
const widths = widthsOf(values.widths);
|
|
1720
|
+
const skipped = new Set(values.skip?.split(",").map((kind) => kind.trim()) ?? []);
|
|
1721
|
+
const unknown = [...skipped].find((kind) => !KINDS.includes(kind));
|
|
1722
|
+
if (unknown !== undefined)
|
|
1723
|
+
badUsage(`--skip takes ${KINDS.join(", ")}, not ${unknown}`);
|
|
1724
|
+
const targets = positionals.map((given) => targetOf(given, values.out));
|
|
1725
|
+
const session = sessionOf(values);
|
|
1726
|
+
const shots = [];
|
|
1727
|
+
const findings = [];
|
|
1728
|
+
const failed = [];
|
|
1729
|
+
const path = role("path", process19.stdout);
|
|
1730
|
+
const browser = await launch();
|
|
1731
|
+
try {
|
|
1732
|
+
for (const target of targets) {
|
|
1733
|
+
const once = new Set;
|
|
1734
|
+
for (const width of widths) {
|
|
1735
|
+
const heard = [];
|
|
1736
|
+
let loaded;
|
|
1737
|
+
try {
|
|
1738
|
+
loaded = await open(browser, target.url, width, session, async (page) => {
|
|
1739
|
+
listen(page, heard);
|
|
1740
|
+
await beforeLoad(page, "measure", "watchShifts");
|
|
1741
|
+
});
|
|
1742
|
+
} catch (error) {
|
|
1743
|
+
const { message } = error;
|
|
1744
|
+
failed.push({ target: target.label, error: message.includes(`
|
|
1745
|
+
`) ? message.slice(0, message.indexOf(`
|
|
1746
|
+
`)) : message });
|
|
1747
|
+
break;
|
|
1748
|
+
}
|
|
1749
|
+
const { context, page, landed } = loaded;
|
|
1750
|
+
const redirect = redirectedTo(target.url, landed);
|
|
1751
|
+
if (redirect !== undefined)
|
|
1752
|
+
heard.unshift({ kind: "redirect", message: `landed on ${shortUrl(redirect)}` });
|
|
1753
|
+
const file = `${target.stem}-${width}.png`;
|
|
1754
|
+
mkdirSync2(dirname5(file), { recursive: true });
|
|
1755
|
+
await shoot(page, file);
|
|
1756
|
+
shots.push({ target: target.label, width, path: file });
|
|
1757
|
+
if (!values.json)
|
|
1758
|
+
console.log(path(file));
|
|
1759
|
+
const found = [...heard, ...await inPage(page, "measure", "measureDom", width < PHONE_WIDTH), ...skipped.has("font") ? [] : await fontFindings(page)];
|
|
1760
|
+
await context.close();
|
|
1761
|
+
for (const finding of found) {
|
|
1762
|
+
const key = `${finding.kind}|${finding.selector ?? ""}|${finding.message}`;
|
|
1763
|
+
if (skipped.has(finding.kind) || ONCE.has(finding.kind) && once.has(key))
|
|
1764
|
+
continue;
|
|
1765
|
+
once.add(key);
|
|
1766
|
+
findings.push({ target: target.label, width, ...finding });
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
} finally {
|
|
1771
|
+
await browser.close();
|
|
1772
|
+
}
|
|
1773
|
+
if (values.json) {
|
|
1774
|
+
printJson({ shots, findings, failed });
|
|
1775
|
+
} else {
|
|
1776
|
+
printLines(findingLines(findings));
|
|
1777
|
+
for (const { target, error } of failed)
|
|
1778
|
+
problem(`${target} would not load`, error);
|
|
1779
|
+
if (findings.length === 0 && failed.length === 0)
|
|
1780
|
+
console.log(marked("ok", `no defect at ${widths.join(", ")}px`, process19.stdout));
|
|
1781
|
+
}
|
|
1782
|
+
if (failed.length > 0)
|
|
1783
|
+
return 2;
|
|
1784
|
+
return findings.length > 0 ? 1 : 0;
|
|
1785
|
+
}
|
|
1786
|
+
var KINDS, ONCE, URL_CAP = 160, EXITS, USAGE, OPTIONS;
|
|
1787
|
+
var init_check = __esm(() => {
|
|
1788
|
+
init_src();
|
|
1789
|
+
init_browser();
|
|
1790
|
+
init_fonts();
|
|
1791
|
+
init_inpage();
|
|
1792
|
+
init_report2();
|
|
1793
|
+
KINDS = ["redirect", "overflow", "console", "request", "font", "tap-target", "padding", "image", "layout-shift"];
|
|
1794
|
+
ONCE = new Set(["redirect", "console", "request", "font"]);
|
|
1795
|
+
EXITS = [[0, "nothing found"], [1, "a defect was found"], [2, "a usage error, or a target that would not load"]];
|
|
1796
|
+
USAGE = `page check <file|url>...
|
|
1797
|
+
|
|
1798
|
+
Opens each HTML file or URL in a local Chromium at every width, writes a full-page PNG per width (next to a file as <name>-<width>.png, into --out, or the cache folder for a URL) and prints its path, then one line per defect: <target> <width>px <kind> <selector>: <measure>.
|
|
1799
|
+
Kinds: redirect (the page landed elsewhere, a login page say, so what follows is about that page), overflow (the page scrolls sideways; the elements where it starts), console (errors and uncaught exceptions), request (failed, or answered 4xx/5xx), font (text drawn in another font than its stack asks for, naming the one drawn), tap-target (under 44px below ${PHONE_WIDTH}px wide, under 24px otherwise; a link inside a sentence is exempt), padding (text touching the border or background edge of its box), image (did not load), layout-shift (a score above 0.1).
|
|
1800
|
+
It never starts or builds an app: give it a file or a URL already served. A page behind a login takes --cookie, -H or --storage-state; a header goes to the target's origin alone.
|
|
1801
|
+
Chromium comes from PAGE_CHROMIUM, ~/.cache/ms-playwright or /usr/bin, never downloaded.
|
|
1802
|
+
|
|
1803
|
+
Exits 0 when nothing is found, 1 when something is, 2 on a usage error or when a target would not load.`;
|
|
1804
|
+
OPTIONS = {
|
|
1805
|
+
widths: { type: "string", short: "w", description: "viewport widths, comma separated (1440,400)" },
|
|
1806
|
+
out: { type: "string", short: "o", description: "folder the PNGs go to instead of next to each file" },
|
|
1807
|
+
skip: { type: "string", description: `kinds left out, comma separated: ${KINDS.join(", ")}` },
|
|
1808
|
+
...SESSION_OPTIONS,
|
|
1809
|
+
json: jsonOption("{shots: [{target, width, path}], findings: [{target, width, kind, selector, message}], failed: [{target, error}]}")
|
|
1810
|
+
};
|
|
1811
|
+
});
|
|
1812
|
+
|
|
1813
|
+
// src/diff.ts
|
|
1814
|
+
var exports_diff = {};
|
|
1815
|
+
__export(exports_diff, {
|
|
1816
|
+
diff: () => diff
|
|
1817
|
+
});
|
|
1818
|
+
import { mkdirSync as mkdirSync3 } from "fs";
|
|
1819
|
+
import { dirname as dirname6 } from "path";
|
|
1820
|
+
import process20 from "process";
|
|
1821
|
+
async function capture(browser, target, width, session) {
|
|
1822
|
+
const { context, page, landed } = await open(browser, target.url, width, session);
|
|
1823
|
+
const redirect = redirectedTo(target.url, landed);
|
|
1824
|
+
if (redirect !== undefined)
|
|
1825
|
+
warn(`${target.label} landed on ${redirect} at ${width}px`, "the shot is of that page");
|
|
1826
|
+
try {
|
|
1827
|
+
return await shoot(page);
|
|
1828
|
+
} finally {
|
|
1829
|
+
await context.close();
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
function regionLine(region) {
|
|
1833
|
+
return `${region.width}\xD7${region.height}px at ${region.x},${region.y}`;
|
|
1834
|
+
}
|
|
1835
|
+
async function diff(args) {
|
|
1836
|
+
const { values, positionals } = parse(args, USAGE2, OPTIONS2, {
|
|
1837
|
+
positionals: ["<mockup>", "<built>"],
|
|
1838
|
+
exits: EXITS2,
|
|
1839
|
+
examples: [["page diff mockup.html dist/index.html", "index-side-1440.png, index-diff-1440.png and the 400px pair"], "page diff mockup.html http://localhost:5173/ -w 1280 -o shots"]
|
|
1840
|
+
});
|
|
1841
|
+
const [mockupGiven, builtGiven] = positionals;
|
|
1842
|
+
const widths = widthsOf(values.widths);
|
|
1843
|
+
const threshold = wholeNumber(values.threshold, "threshold", THRESHOLD, 0);
|
|
1844
|
+
const mockup = targetOf(mockupGiven, values.out);
|
|
1845
|
+
const built = targetOf(builtGiven, values.out);
|
|
1846
|
+
const session = sessionOf(values);
|
|
1847
|
+
const results = [];
|
|
1848
|
+
const findings = [];
|
|
1849
|
+
const path = role("path", process20.stdout);
|
|
1850
|
+
const browser = await launch();
|
|
1851
|
+
try {
|
|
1852
|
+
const blank = await browser.newPage();
|
|
1853
|
+
for (const width of widths) {
|
|
1854
|
+
const [left, right] = await Promise.all([capture(browser, mockup, width, session), capture(browser, built, width, session)]);
|
|
1855
|
+
const compared = await inPage(blank, "compare", "compareImages", { mockup: left.toString("base64"), built: right.toString("base64"), threshold: Math.min(threshold, 255) });
|
|
1856
|
+
const side = `${built.stem}-side-${width}.png`;
|
|
1857
|
+
const overlay = `${built.stem}-diff-${width}.png`;
|
|
1858
|
+
mkdirSync3(dirname6(side), { recursive: true });
|
|
1859
|
+
await Bun.write(side, Buffer.from(compared.side, "base64"));
|
|
1860
|
+
await Bun.write(overlay, Buffer.from(compared.overlay, "base64"));
|
|
1861
|
+
results.push({ ...compared, side, overlay });
|
|
1862
|
+
if (compared.mockupHeight !== compared.builtHeight)
|
|
1863
|
+
findings.push({ target: built.label, width, kind: "height", message: `the mockup is ${compared.mockupHeight}px tall, the built page ${compared.builtHeight}px` });
|
|
1864
|
+
for (const [index, region] of compared.regions.entries())
|
|
1865
|
+
findings.push({ target: built.label, width, kind: "region", selector: String(index + 1), message: regionLine(region) });
|
|
1866
|
+
if (!values.json) {
|
|
1867
|
+
console.log(path(side));
|
|
1868
|
+
console.log(path(overlay));
|
|
1869
|
+
console.log(compared.regions.length === 0 ? marked("ok", `${width}px: no region differs`, process20.stdout) : marked("warn", `${width}px: ${compared.regions.length} ${compared.regions.length === 1 ? "region differs" : "regions differ"}`, process20.stdout, `${formatPercent(compared.differing, 1)} of the pixels`));
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
} finally {
|
|
1873
|
+
await browser.close();
|
|
1874
|
+
}
|
|
1875
|
+
if (values.json)
|
|
1876
|
+
printJson(results);
|
|
1877
|
+
else
|
|
1878
|
+
printLines(findingLines(findings));
|
|
1879
|
+
return results.some((result) => result.regions.length > 0) ? 1 : 0;
|
|
1880
|
+
}
|
|
1881
|
+
var THRESHOLD = 32, EXITS2, USAGE2, OPTIONS2;
|
|
1882
|
+
var init_diff = __esm(() => {
|
|
1883
|
+
init_src();
|
|
1884
|
+
init_browser();
|
|
1885
|
+
init_inpage();
|
|
1886
|
+
init_report2();
|
|
1887
|
+
EXITS2 = [[0, "both pages look the same at every width"], [1, "a region differs, or a page would not load"], [2, "a usage error"]];
|
|
1888
|
+
USAGE2 = `page diff <mockup> <built>
|
|
1889
|
+
|
|
1890
|
+
Shoots the mockup and the built page (HTML files or URLs) full-page at every width, then writes two PNGs per width next to the built file, into --out, or the cache folder for a URL: <name>-side-<width>.png, the mockup left and the built page right, and <name>-diff-<width>.png, the built page faded with every differing pixel in red. The differing regions are boxed and numbered on both, then printed one line each: <built> <width>px region <n>: <width>\xD7<height>px at <x>,<y>.
|
|
1891
|
+
A page behind a login takes --cookie, -H or --storage-state, as page check does; a page landing elsewhere is warned about on stderr.
|
|
1892
|
+
A pixel differs when a colour channel moves by more than --threshold (${THRESHOLD} of 255); a lone differing pixel in an 8px cell is taken for antialiasing and left out.
|
|
1893
|
+
|
|
1894
|
+
Exits 0 when both look the same at every width, 1 when a region differs or a page would not load, 2 on a usage error.`;
|
|
1895
|
+
OPTIONS2 = {
|
|
1896
|
+
widths: { type: "string", short: "w", description: "viewport widths, comma separated (1440,400)" },
|
|
1897
|
+
out: { type: "string", short: "o", description: "folder the PNGs go to instead of next to the built file" },
|
|
1898
|
+
threshold: { type: "string", description: `largest per-channel difference still counted as the same pixel, 0 to 255 (${THRESHOLD})` },
|
|
1899
|
+
...SESSION_OPTIONS,
|
|
1900
|
+
json: jsonOption("[{width, side, overlay, mockupHeight, builtHeight, differing, regions: [{x, y, width, height}]}]")
|
|
1901
|
+
};
|
|
1902
|
+
});
|
|
1903
|
+
|
|
1904
|
+
// src/cli.ts
|
|
1905
|
+
init_src();
|
|
1906
|
+
import process21 from "process";
|
|
1907
|
+
process21.exitCode = await runCli({
|
|
1908
|
+
name: "page",
|
|
1909
|
+
about: "shoots HTML files or URLs at several widths in a local Chromium and reports their layout defects one line each, or diffs a built page against its mockup",
|
|
1910
|
+
replaces: "reading screenshots by eye for overflow, squashed controls and fallback fonts, and one-off Playwright scripts shooting a page",
|
|
1911
|
+
examples: [["page check mockup.html", "PNGs at 1440 and 400px, then one line per defect"], "page check http://localhost:5173/ -w 1280,375", ["page diff mockup.html http://localhost:5173/", "side-by-side and pixel-diff PNGs, differing regions boxed"]],
|
|
1912
|
+
commands: {
|
|
1913
|
+
check: { summary: "shoot each target at every width and report its layout defects", run: async (args) => (await Promise.resolve().then(() => (init_check(), exports_check))).check(args) },
|
|
1914
|
+
diff: { summary: "shoot a mockup and the built page at every width and box where they differ", run: async (args) => (await Promise.resolve().then(() => (init_diff(), exports_diff))).diff(args) }
|
|
1915
|
+
}
|
|
1916
|
+
});
|