@kaynooo/cli-workspace 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -23
- package/dist/cli.js +89 -34
- package/package.json +9 -15
- package/dist/audit-cli.js +0 -1846
- package/dist/repos-cli.js +0 -1716
- package/dist/sweep-cli.js +0 -2108
package/dist/sweep-cli.js
DELETED
|
@@ -1,2108 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
|
-
// @bun
|
|
3
|
-
|
|
4
|
-
// src/sweep-cli.ts
|
|
5
|
-
import process21 from "process";
|
|
6
|
-
|
|
7
|
-
// ../kit/src/advisory.ts
|
|
8
|
-
var SEVERITIES = ["low", "moderate", "high", "critical"];
|
|
9
|
-
function severityRank(severity) {
|
|
10
|
-
return SEVERITIES.indexOf(severity);
|
|
11
|
-
}
|
|
12
|
-
function isIgnored(advisory, ignore) {
|
|
13
|
-
return ignore.includes(advisory.ghsa ?? "") || ignore.includes(String(advisory.id));
|
|
14
|
-
}
|
|
15
|
-
// ../kit/src/args.ts
|
|
16
|
-
import process9 from "process";
|
|
17
|
-
import { parseArgs } from "util";
|
|
18
|
-
|
|
19
|
-
// ../kit/src/format.ts
|
|
20
|
-
import process7 from "process";
|
|
21
|
-
|
|
22
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-n6z2kk96.js
|
|
23
|
-
var r = new Map;
|
|
24
|
-
var i = new Map;
|
|
25
|
-
var l = new Map;
|
|
26
|
-
function a(e, t, o) {
|
|
27
|
-
return JSON.stringify([e ?? null, t ?? null, o]);
|
|
28
|
-
}
|
|
29
|
-
function y(e, t) {
|
|
30
|
-
let o = a(e, t), n = i.get(o);
|
|
31
|
-
if (!n)
|
|
32
|
-
n = new Intl.NumberFormat(e, t), i.set(o, n);
|
|
33
|
-
return n;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
|
|
37
|
-
var N = new Map;
|
|
38
|
-
var Nt = /\s+\S*$/;
|
|
39
|
-
var Y = /\s/;
|
|
40
|
-
function ko(t, e, r = "...") {
|
|
41
|
-
let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
|
|
42
|
-
if (t.length <= e)
|
|
43
|
-
return t;
|
|
44
|
-
let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
|
|
45
|
-
if (o && !Y.test(t[c.length] ?? " "))
|
|
46
|
-
c = c.replace(Nt, "") || c;
|
|
47
|
-
if (o)
|
|
48
|
-
c = c.trimEnd();
|
|
49
|
-
return s ? (c + n).slice(0, l) : c + n;
|
|
50
|
-
}
|
|
51
|
-
var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
|
|
52
|
-
var z = new Map;
|
|
53
|
-
|
|
54
|
-
// ../kit/src/mode.ts
|
|
55
|
-
import process2 from "process";
|
|
56
|
-
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
57
|
-
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
58
|
-
function isSet(value) {
|
|
59
|
-
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
60
|
-
}
|
|
61
|
-
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
62
|
-
const chosen = env.KIT_MODE;
|
|
63
|
-
if (chosen !== undefined && MODES.has(chosen))
|
|
64
|
-
return chosen;
|
|
65
|
-
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
66
|
-
return "agent";
|
|
67
|
-
if (stream.isTTY === true)
|
|
68
|
-
return "terminal";
|
|
69
|
-
return isSet(env.CI) ? "ci" : "pipe";
|
|
70
|
-
}
|
|
71
|
-
function isInteractive(streams = process2) {
|
|
72
|
-
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// ../kit/src/style.ts
|
|
76
|
-
import process6 from "process";
|
|
77
|
-
|
|
78
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
79
|
-
var G2 = /^[a-f0-9]+$/i;
|
|
80
|
-
function b(r) {
|
|
81
|
-
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
82
|
-
if (!G2.test(e))
|
|
83
|
-
return [0, 0, 0];
|
|
84
|
-
if (e.length === 3 || e.length === 4)
|
|
85
|
-
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
86
|
-
if (e.length !== 6 && e.length !== 8)
|
|
87
|
-
throw Error(`Invalid hex color length: ${e.length}`);
|
|
88
|
-
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
89
|
-
}
|
|
90
|
-
var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
|
|
91
|
-
let [l, n, c] = b(r);
|
|
92
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
93
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
94
|
-
var h = new Set(["", "1", "2", "3", "true"]);
|
|
95
|
-
function C(r, e = globalThis.process?.env ?? {}) {
|
|
96
|
-
if (e.FORCE_COLOR !== undefined)
|
|
97
|
-
return h.has(e.FORCE_COLOR);
|
|
98
|
-
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
99
|
-
return false;
|
|
100
|
-
return r?.isTTY === true;
|
|
101
|
-
}
|
|
102
|
-
function f(r, e = []) {
|
|
103
|
-
let l = "", n = "";
|
|
104
|
-
for (let t = 0, i = e.length;t < i; t++)
|
|
105
|
-
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
106
|
-
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
107
|
-
return new Proxy(c, { get(t, i) {
|
|
108
|
-
let a = B2[i];
|
|
109
|
-
if (Array.isArray(a)) {
|
|
110
|
-
let s = g.get(i);
|
|
111
|
-
if (s === undefined)
|
|
112
|
-
s = f(r, [...e, a]), g.set(i, s);
|
|
113
|
-
return s;
|
|
114
|
-
}
|
|
115
|
-
if (typeof a === "function")
|
|
116
|
-
return (...s) => {
|
|
117
|
-
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
118
|
-
if (u === undefined) {
|
|
119
|
-
if (g.size >= 64)
|
|
120
|
-
g.clear();
|
|
121
|
-
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
122
|
-
}
|
|
123
|
-
return u;
|
|
124
|
-
};
|
|
125
|
-
throw Error(`Unknown style: ${String(i)}`);
|
|
126
|
-
} });
|
|
127
|
-
}
|
|
128
|
-
function Fe(r = {}) {
|
|
129
|
-
return f(r);
|
|
130
|
-
}
|
|
131
|
-
var o = Fe();
|
|
132
|
-
|
|
133
|
-
// ../kit/src/theme.ts
|
|
134
|
-
import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
|
|
135
|
-
import { homedir as homedir2 } from "os";
|
|
136
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
137
|
-
import process5 from "process";
|
|
138
|
-
|
|
139
|
-
// ../kit/src/config.ts
|
|
140
|
-
import { existsSync } from "fs";
|
|
141
|
-
import { dirname, join, resolve } from "path";
|
|
142
|
-
import process3 from "process";
|
|
143
|
-
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
144
|
-
const wanted = typeof names === "string" ? [names] : names;
|
|
145
|
-
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
146
|
-
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
147
|
-
if (found !== undefined)
|
|
148
|
-
return found;
|
|
149
|
-
if (stop(dir) || dirname(dir) === dir)
|
|
150
|
-
return;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
// ../kit/src/user-config.ts
|
|
155
|
-
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
156
|
-
import { homedir } from "os";
|
|
157
|
-
import { join as join2 } from "path";
|
|
158
|
-
import process4 from "process";
|
|
159
|
-
function configBase(where = {}) {
|
|
160
|
-
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
161
|
-
return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
|
|
162
|
-
}
|
|
163
|
-
function userConfigPath(bin, where = {}) {
|
|
164
|
-
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
165
|
-
}
|
|
166
|
-
function userConfigReadPath(bin, legacy = [], where = {}) {
|
|
167
|
-
const current = userConfigPath(bin, where);
|
|
168
|
-
if (existsSync2(current))
|
|
169
|
-
return current;
|
|
170
|
-
const base = configBase(where);
|
|
171
|
-
return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
|
|
172
|
-
}
|
|
173
|
-
function readUserConfig(bin, where = {}, legacy = []) {
|
|
174
|
-
const path = userConfigReadPath(bin, legacy, where);
|
|
175
|
-
if (!existsSync2(path))
|
|
176
|
-
return {};
|
|
177
|
-
try {
|
|
178
|
-
const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
|
|
179
|
-
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
|
|
180
|
-
} catch {
|
|
181
|
-
return {};
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
|
|
185
|
-
const value = readUserConfig(bin, where, legacy)[key];
|
|
186
|
-
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// ../kit/src/theme.ts
|
|
190
|
-
var ENDS = new Map;
|
|
191
|
-
var DEFAULT = {
|
|
192
|
-
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" },
|
|
193
|
-
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" },
|
|
194
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
195
|
-
bins: {},
|
|
196
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
197
|
-
};
|
|
198
|
-
var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
|
|
199
|
-
var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
|
|
200
|
-
var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
201
|
-
var PRESETS = {
|
|
202
|
-
default: {},
|
|
203
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
204
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
205
|
-
ascii: { glyphs: ASCII }
|
|
206
|
-
};
|
|
207
|
-
var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
|
|
208
|
-
var HEX = /^#[0-9a-f]{6}$/i;
|
|
209
|
-
var CONTROL = /\p{Cc}/u;
|
|
210
|
-
var MAX_FILE_BYTES = 64 * 1024;
|
|
211
|
-
var SPACES = /\s+/;
|
|
212
|
-
function isColorSpec(spec) {
|
|
213
|
-
if (typeof spec === "number")
|
|
214
|
-
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
215
|
-
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
216
|
-
}
|
|
217
|
-
var CUBE = [0, 95, 135, 175, 215, 255];
|
|
218
|
-
function cubeLevel(channel) {
|
|
219
|
-
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
220
|
-
}
|
|
221
|
-
function nearest256(hex) {
|
|
222
|
-
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
223
|
-
const levels = rgb.map(cubeLevel);
|
|
224
|
-
const cube = levels.map((level) => CUBE[level]);
|
|
225
|
-
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
226
|
-
const greyValue = 8 + grey * 10;
|
|
227
|
-
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
228
|
-
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
229
|
-
}
|
|
230
|
-
function hasTrueColor(env) {
|
|
231
|
-
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
232
|
-
}
|
|
233
|
-
function tinted(colors, spec, env = process5.env) {
|
|
234
|
-
if (typeof spec === "number")
|
|
235
|
-
return colors.ansi256(spec);
|
|
236
|
-
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
237
|
-
if (HEX.test(token))
|
|
238
|
-
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
239
|
-
return chain[token] ?? chain;
|
|
240
|
-
}, colors);
|
|
241
|
-
}
|
|
242
|
-
function isRecord(value) {
|
|
243
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
244
|
-
}
|
|
245
|
-
function readThemeFile(path, warn) {
|
|
246
|
-
try {
|
|
247
|
-
const stat = statSync(path, { throwIfNoEntry: false });
|
|
248
|
-
if (stat === undefined)
|
|
249
|
-
return;
|
|
250
|
-
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
251
|
-
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
255
|
-
if (isRecord(parsed))
|
|
256
|
-
return parsed;
|
|
257
|
-
warn(`${path} is not a JSON object, theme ignored`);
|
|
258
|
-
} catch (error) {
|
|
259
|
-
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
260
|
-
}
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
|
-
function applyPreset(theme, name, warn, where) {
|
|
264
|
-
if (name === undefined)
|
|
265
|
-
return;
|
|
266
|
-
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
267
|
-
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
268
|
-
return;
|
|
269
|
-
}
|
|
270
|
-
const preset = PRESETS[name];
|
|
271
|
-
Object.assign(theme.colors, preset.colors);
|
|
272
|
-
Object.assign(theme.glyphs, preset.glyphs);
|
|
273
|
-
if (preset.accents !== undefined)
|
|
274
|
-
theme.accents = [...preset.accents];
|
|
275
|
-
if (Object.hasOwn(preset, "gradient"))
|
|
276
|
-
theme.gradient = preset.gradient;
|
|
277
|
-
return name;
|
|
278
|
-
}
|
|
279
|
-
function applyFile(theme, file, where, warn) {
|
|
280
|
-
if (isRecord(file.colors)) {
|
|
281
|
-
for (const [key, value] of Object.entries(file.colors)) {
|
|
282
|
-
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
283
|
-
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
284
|
-
else if (!isColorSpec(value))
|
|
285
|
-
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
286
|
-
else
|
|
287
|
-
theme.colors[key] = value;
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
if (isRecord(file.glyphs)) {
|
|
291
|
-
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
292
|
-
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
293
|
-
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
294
|
-
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
295
|
-
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
296
|
-
else
|
|
297
|
-
theme.glyphs[key] = value;
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
301
|
-
theme.accents = [...file.accents];
|
|
302
|
-
else if (file.accents !== undefined)
|
|
303
|
-
warn(`${where}: accents must be a non-empty list of colours`);
|
|
304
|
-
if (file.gradient === null)
|
|
305
|
-
theme.gradient = undefined;
|
|
306
|
-
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
307
|
-
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
308
|
-
else if (file.gradient !== undefined)
|
|
309
|
-
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
310
|
-
if (isRecord(file.bins)) {
|
|
311
|
-
for (const [bin, value] of Object.entries(file.bins)) {
|
|
312
|
-
if (isColorSpec(value))
|
|
313
|
-
theme.bins[bin] = value;
|
|
314
|
-
else
|
|
315
|
-
warn(`${where}: bin ${bin} has no valid colour`);
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
function endsWalk(home) {
|
|
320
|
-
return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
|
|
321
|
-
}
|
|
322
|
-
var warned = new Set;
|
|
323
|
-
function warnOnce(message) {
|
|
324
|
-
if (warned.has(message))
|
|
325
|
-
return;
|
|
326
|
-
warned.add(message);
|
|
327
|
-
console.error(`warning: theme ${message}`);
|
|
328
|
-
}
|
|
329
|
-
function isPath(chosen) {
|
|
330
|
-
return chosen.includes("/") || chosen.endsWith(".json");
|
|
331
|
-
}
|
|
332
|
-
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
333
|
-
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
334
|
-
const sources = [];
|
|
335
|
-
const chosen = env.KIT_THEME ?? "";
|
|
336
|
-
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
337
|
-
if (isPath(chosen))
|
|
338
|
-
wanted.push(resolve2(from, chosen));
|
|
339
|
-
const files = [];
|
|
340
|
-
for (const path of wanted) {
|
|
341
|
-
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
342
|
-
if (path !== undefined && file !== undefined)
|
|
343
|
-
files.push({ path, file });
|
|
344
|
-
}
|
|
345
|
-
let preset = "default";
|
|
346
|
-
if (chosen !== "" && !isPath(chosen)) {
|
|
347
|
-
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
348
|
-
} else {
|
|
349
|
-
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
350
|
-
if (named !== undefined)
|
|
351
|
-
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
352
|
-
}
|
|
353
|
-
for (const { path, file } of files) {
|
|
354
|
-
applyFile(theme, file, path, warn);
|
|
355
|
-
sources.push(path);
|
|
356
|
-
}
|
|
357
|
-
return { theme, sources, preset };
|
|
358
|
-
}
|
|
359
|
-
var current;
|
|
360
|
-
var currentKey = "";
|
|
361
|
-
function activeTheme() {
|
|
362
|
-
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
363
|
-
if (current === undefined || key !== currentKey) {
|
|
364
|
-
current = loadTheme();
|
|
365
|
-
currentKey = key;
|
|
366
|
-
}
|
|
367
|
-
return current;
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
// ../kit/src/style.ts
|
|
371
|
-
var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
|
|
372
|
-
function takesControlCodes(stream, env = process6.env) {
|
|
373
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
374
|
-
}
|
|
375
|
-
function paint(stream, env = process6.env) {
|
|
376
|
-
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
377
|
-
}
|
|
378
|
-
function marked(mark, text, stream, detail, env = process6.env) {
|
|
379
|
-
const colors = paint(stream, env);
|
|
380
|
-
let head = MARK_WORDS[mark];
|
|
381
|
-
if (takesControlCodes(stream, env)) {
|
|
382
|
-
const { theme } = activeTheme();
|
|
383
|
-
head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
|
|
384
|
-
}
|
|
385
|
-
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
386
|
-
}
|
|
387
|
-
function ok(text, detail) {
|
|
388
|
-
console.log(marked("ok", text, process6.stdout, detail));
|
|
389
|
-
}
|
|
390
|
-
function note(text, detail) {
|
|
391
|
-
console.log(marked("note", text, process6.stdout, detail));
|
|
392
|
-
}
|
|
393
|
-
function problem(text, detail) {
|
|
394
|
-
console.error(marked("problem", text, process6.stderr, detail));
|
|
395
|
-
}
|
|
396
|
-
function role(name, stream, env = process6.env) {
|
|
397
|
-
const colors = paint(stream, env);
|
|
398
|
-
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
399
|
-
}
|
|
400
|
-
var STATUS_WORDS = {
|
|
401
|
-
passed: ["passed", "success", "succeeded", "ok"],
|
|
402
|
-
failed: ["failed", "failure", "error", "errored"],
|
|
403
|
-
running: ["running", "in_progress", "started", "holding"],
|
|
404
|
-
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
405
|
-
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
406
|
-
};
|
|
407
|
-
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
408
|
-
function header(bin, context, stream, env = process6.env) {
|
|
409
|
-
if (!takesControlCodes(stream, env))
|
|
410
|
-
return "";
|
|
411
|
-
const colors = paint(stream, env);
|
|
412
|
-
const hash = [...bin].reduce((sum, char) => sum + char.charCodeAt(0), 0);
|
|
413
|
-
const { theme } = activeTheme();
|
|
414
|
-
const spec = theme.bins[bin] ?? theme.accents[hash % theme.accents.length];
|
|
415
|
-
const accent = tinted(typeof spec === "string" && spec.split(" ").includes("bold") ? colors : colors.bold, spec, env);
|
|
416
|
-
return `${accent(bin)}${context === undefined ? "" : colors.dim(` \u203A ${context}`)}`;
|
|
417
|
-
}
|
|
418
|
-
function printHeader(bin, context, stream = process6.stdout, env = process6.env) {
|
|
419
|
-
const line = header(bin, context, stream, env);
|
|
420
|
-
if (line !== "")
|
|
421
|
-
console.log(line);
|
|
422
|
-
}
|
|
423
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-knqbxp56.js
|
|
424
|
-
function tt(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
|
|
425
|
-
let e = r === "si" ? 1000 : 1024;
|
|
426
|
-
if (Math.abs(i) < e)
|
|
427
|
-
return `${i} B`;
|
|
428
|
-
let s = r === "iec" ? ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] : ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], o = -1, a = 10 ** t;
|
|
429
|
-
do
|
|
430
|
-
i /= e, ++o;
|
|
431
|
-
while (Math.round(Math.abs(i) * a) / a >= e && o < s.length - 1);
|
|
432
|
-
return `${n ? y(n, { minimumFractionDigits: t, maximumFractionDigits: t }).format(i) : i.toFixed(t)} ${s[o]}`;
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
// ../kit/src/format.ts
|
|
436
|
-
var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
437
|
-
function formatSeconds(total) {
|
|
438
|
-
let rest = Math.max(0, Math.round(total));
|
|
439
|
-
const amounts = UNITS.map(([unit, size]) => {
|
|
440
|
-
const amount = Math.floor(rest / size);
|
|
441
|
-
rest -= amount * size;
|
|
442
|
-
return `${amount}${unit}`;
|
|
443
|
-
});
|
|
444
|
-
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
445
|
-
if (first === -1)
|
|
446
|
-
return "0s";
|
|
447
|
-
const next = amounts[first + 1];
|
|
448
|
-
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
449
|
-
}
|
|
450
|
-
function formatDuration(ms) {
|
|
451
|
-
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
452
|
-
}
|
|
453
|
-
function upTo(text, separator) {
|
|
454
|
-
const end = text.indexOf(separator);
|
|
455
|
-
return end === -1 ? text : text.slice(0, end);
|
|
456
|
-
}
|
|
457
|
-
function formatAge(date, now = Date.now()) {
|
|
458
|
-
const at = typeof date === "number" ? date : Date.parse(date);
|
|
459
|
-
if (Number.isNaN(at))
|
|
460
|
-
return "-";
|
|
461
|
-
const seconds = (now - at) / 1000;
|
|
462
|
-
return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
|
|
463
|
-
}
|
|
464
|
-
function truncate(text, width) {
|
|
465
|
-
return ko(text, width, { suffix: "\u2026", includeSuffix: true });
|
|
466
|
-
}
|
|
467
|
-
var LINE_BREAKS = /\s*\n\s*/g;
|
|
468
|
-
var ESCAPE = String.fromCharCode(27);
|
|
469
|
-
function textWidth(text) {
|
|
470
|
-
return Bun.stringWidth(text);
|
|
471
|
-
}
|
|
472
|
-
function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
|
|
473
|
-
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
474
|
-
if (outputMode(stream, env) === "agent")
|
|
475
|
-
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
476
|
-
`);
|
|
477
|
-
const widths = [];
|
|
478
|
-
for (const row of cells) {
|
|
479
|
-
for (const [index, cell] of row.entries())
|
|
480
|
-
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
481
|
-
}
|
|
482
|
-
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
483
|
-
const colors = paint(stream);
|
|
484
|
-
const lines = shown.map((row) => row.map((cell, index) => {
|
|
485
|
-
const width = widths[index] ?? 0;
|
|
486
|
-
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
487
|
-
if (align[index] === "right")
|
|
488
|
-
return `${gap}${cell}`;
|
|
489
|
-
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
490
|
-
}).join(" ").trimEnd());
|
|
491
|
-
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
492
|
-
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
493
|
-
`);
|
|
494
|
-
}
|
|
495
|
-
function narrow(rows, widths, limit) {
|
|
496
|
-
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
497
|
-
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
498
|
-
const floor = 8;
|
|
499
|
-
while (used() > limit) {
|
|
500
|
-
let widest = -1;
|
|
501
|
-
for (const [index, width] of widths.entries()) {
|
|
502
|
-
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
503
|
-
widest = index;
|
|
504
|
-
}
|
|
505
|
-
if (widest === -1)
|
|
506
|
-
break;
|
|
507
|
-
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
508
|
-
}
|
|
509
|
-
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
510
|
-
}
|
|
511
|
-
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
512
|
-
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
513
|
-
}
|
|
514
|
-
function printJson(value) {
|
|
515
|
-
console.log(jsonText(value));
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
// ../kit/src/help.ts
|
|
519
|
-
import process8 from "process";
|
|
520
|
-
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
521
|
-
var USAGE_PREFIX = /^usage:\s*/i;
|
|
522
|
-
var FULL_STOP = /\.$/;
|
|
523
|
-
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
524
|
-
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
525
|
-
}
|
|
526
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
527
|
-
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
528
|
-
`);
|
|
529
|
-
}
|
|
530
|
-
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
531
|
-
if (exits.length === 0)
|
|
532
|
-
return [];
|
|
533
|
-
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
534
|
-
}
|
|
535
|
-
function wantsHelpJson(env = process8.env) {
|
|
536
|
-
return env.KIT_HELP === "json";
|
|
537
|
-
}
|
|
538
|
-
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
539
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
540
|
-
`);
|
|
541
|
-
const first = lines[0];
|
|
542
|
-
const colon = first.indexOf(": ");
|
|
543
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
544
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
545
|
-
return {
|
|
546
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
547
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
548
|
-
...replaces === undefined ? {} : { replaces },
|
|
549
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
550
|
-
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
551
|
-
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
552
|
-
};
|
|
553
|
-
}
|
|
554
|
-
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
555
|
-
if (examples.length === 0 || outputMode() === "agent")
|
|
556
|
-
return [];
|
|
557
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
558
|
-
}
|
|
559
|
-
var MAX_INLINE_CHOICES = 24;
|
|
560
|
-
function optionRows(options, colors = paint(process8.stdout)) {
|
|
561
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
562
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
563
|
-
const choices = option.choices?.join("|");
|
|
564
|
-
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
565
|
-
const named = inline ? `<${choices}>` : "<value>";
|
|
566
|
-
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
567
|
-
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
568
|
-
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
569
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
570
|
-
});
|
|
571
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
572
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
// ../kit/src/text.ts
|
|
576
|
-
function distance(a, b) {
|
|
577
|
-
const left = [...a];
|
|
578
|
-
const right = [...b];
|
|
579
|
-
let before = [];
|
|
580
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
581
|
-
for (const [i, x] of left.entries()) {
|
|
582
|
-
const current = [i + 1];
|
|
583
|
-
for (const [j, y] of right.entries()) {
|
|
584
|
-
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
585
|
-
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
586
|
-
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
587
|
-
current.push(cost);
|
|
588
|
-
}
|
|
589
|
-
before = previous;
|
|
590
|
-
previous = current;
|
|
591
|
-
}
|
|
592
|
-
return previous[right.length] ?? 0;
|
|
593
|
-
}
|
|
594
|
-
function closest(name, names) {
|
|
595
|
-
const started = names.find((known) => known.startsWith(name));
|
|
596
|
-
if (started !== undefined)
|
|
597
|
-
return started;
|
|
598
|
-
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
599
|
-
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
600
|
-
}
|
|
601
|
-
// ../kit/src/input.ts
|
|
602
|
-
var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
|
|
603
|
-
var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
604
|
-
function duration(value, name, fallback, unit = "s") {
|
|
605
|
-
if (value === undefined)
|
|
606
|
-
return fallback;
|
|
607
|
-
const match = DURATION.exec(value.trim());
|
|
608
|
-
const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
|
|
609
|
-
if (ms < 1)
|
|
610
|
-
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
611
|
-
return ms;
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
// ../kit/src/args.ts
|
|
615
|
-
var DASHES = /^-+/;
|
|
616
|
-
function jsonOption(holds) {
|
|
617
|
-
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
618
|
-
}
|
|
619
|
-
class Exit extends Error {
|
|
620
|
-
code;
|
|
621
|
-
hint;
|
|
622
|
-
constructor(message, code, hint) {
|
|
623
|
-
super(message);
|
|
624
|
-
this.code = code;
|
|
625
|
-
this.hint = hint;
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
function fail(message, code = 2, hint) {
|
|
629
|
-
throw new Exit(message, code, hint);
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
class UsageError extends Exit {
|
|
633
|
-
constructor(message, hint) {
|
|
634
|
-
super(message, 2, hint);
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
function badUsage(message) {
|
|
638
|
-
throw new UsageError(message);
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
class HelpShown extends Exit {
|
|
642
|
-
constructor() {
|
|
643
|
-
super("help shown", 0);
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
class Completing {
|
|
648
|
-
options;
|
|
649
|
-
positionals;
|
|
650
|
-
candidates;
|
|
651
|
-
constructor(options, positionals = [], candidates = {}) {
|
|
652
|
-
this.options = options;
|
|
653
|
-
this.positionals = positionals;
|
|
654
|
-
this.candidates = candidates;
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
var completion = { active: false };
|
|
658
|
-
var OUTPUT_OPTIONS = {
|
|
659
|
-
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
660
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
661
|
-
};
|
|
662
|
-
function applyOutput(color, plain, env = process9.env) {
|
|
663
|
-
const when = plain === true ? "never" : color ?? "auto";
|
|
664
|
-
if (when === "auto")
|
|
665
|
-
return;
|
|
666
|
-
if (when !== "always" && when !== "never")
|
|
667
|
-
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
668
|
-
if (when === "always") {
|
|
669
|
-
env.FORCE_COLOR = "1";
|
|
670
|
-
delete env.NO_COLOR;
|
|
671
|
-
} else {
|
|
672
|
-
env.NO_COLOR = "1";
|
|
673
|
-
delete env.FORCE_COLOR;
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
function parse(args, usage, options, settings = {}) {
|
|
677
|
-
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
678
|
-
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
679
|
-
const listing = listed(all, settings.allowNegative === true);
|
|
680
|
-
if (completion.active)
|
|
681
|
-
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
682
|
-
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
683
|
-
let parsed;
|
|
684
|
-
try {
|
|
685
|
-
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
686
|
-
} catch (error) {
|
|
687
|
-
const message = parseError(error);
|
|
688
|
-
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
689
|
-
}
|
|
690
|
-
const values = parsed.values;
|
|
691
|
-
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
692
|
-
if (values.help === true) {
|
|
693
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
694
|
-
throw new HelpShown;
|
|
695
|
-
}
|
|
696
|
-
checkChoices(parsed.values, all);
|
|
697
|
-
checkConflicts(parsed.values, all);
|
|
698
|
-
if (settings.positionals !== undefined)
|
|
699
|
-
checkPositionals(parsed.positionals, settings.positionals);
|
|
700
|
-
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
701
|
-
}
|
|
702
|
-
function splitRest(args, passes) {
|
|
703
|
-
const separator = passes ? args.indexOf("--") : -1;
|
|
704
|
-
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
705
|
-
}
|
|
706
|
-
function splitTrailing(args, options, count) {
|
|
707
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
708
|
-
let seen = 0;
|
|
709
|
-
if (count === 0)
|
|
710
|
-
return { own: args, rest: undefined };
|
|
711
|
-
for (let at = 0;at < args.length; at++) {
|
|
712
|
-
const word = args[at];
|
|
713
|
-
if (word === "--")
|
|
714
|
-
break;
|
|
715
|
-
if (word.startsWith("-")) {
|
|
716
|
-
if (takesValue(word))
|
|
717
|
-
at++;
|
|
718
|
-
continue;
|
|
719
|
-
}
|
|
720
|
-
seen++;
|
|
721
|
-
if (seen === count)
|
|
722
|
-
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
723
|
-
}
|
|
724
|
-
return { own: args, rest: undefined };
|
|
725
|
-
}
|
|
726
|
-
function listed(options, allowNegative) {
|
|
727
|
-
if (!allowNegative)
|
|
728
|
-
return options;
|
|
729
|
-
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
730
|
-
if (option.type !== "boolean" || option.negative === undefined)
|
|
731
|
-
return [[name, option]];
|
|
732
|
-
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
733
|
-
}));
|
|
734
|
-
}
|
|
735
|
-
function withAliases(args, options) {
|
|
736
|
-
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
737
|
-
if (named.size === 0)
|
|
738
|
-
return args;
|
|
739
|
-
const separator = args.indexOf("--");
|
|
740
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
741
|
-
return [...own.map((arg) => {
|
|
742
|
-
const at = arg.indexOf("=");
|
|
743
|
-
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
744
|
-
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
745
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
746
|
-
}
|
|
747
|
-
function withBare(args, options) {
|
|
748
|
-
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
749
|
-
if (bare.size === 0)
|
|
750
|
-
return args;
|
|
751
|
-
const separator = args.indexOf("--");
|
|
752
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
753
|
-
return [...own.flatMap((arg, index) => {
|
|
754
|
-
const optional = bare.get(arg);
|
|
755
|
-
const next = own[index + 1];
|
|
756
|
-
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
757
|
-
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
758
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
759
|
-
}
|
|
760
|
-
function checkConflicts(values, options) {
|
|
761
|
-
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
762
|
-
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
763
|
-
const other = given(name) ? conflicts.find(given) : undefined;
|
|
764
|
-
if (other !== undefined)
|
|
765
|
-
badUsage(`--${name} cannot be used with --${other}`);
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
function checkChoices(values, options) {
|
|
769
|
-
for (const [name, option] of Object.entries(options)) {
|
|
770
|
-
if (option.choices === undefined)
|
|
771
|
-
continue;
|
|
772
|
-
const given = values[name];
|
|
773
|
-
for (const value of Array.isArray(given) ? given : [given]) {
|
|
774
|
-
if (typeof value === "string")
|
|
775
|
-
oneOf(value, name, option.choices);
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
function oneOf(value, name, choices) {
|
|
780
|
-
if (!choices.includes(value))
|
|
781
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
782
|
-
return value;
|
|
783
|
-
}
|
|
784
|
-
function checkPositionals(given, names) {
|
|
785
|
-
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
786
|
-
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
787
|
-
if (given.length < required)
|
|
788
|
-
badUsage(`missing ${names[given.length]}`);
|
|
789
|
-
if (!variadic && given.length > names.length)
|
|
790
|
-
badUsage(`unexpected argument ${given[names.length]}`);
|
|
791
|
-
}
|
|
792
|
-
function joinDashValues(args, options) {
|
|
793
|
-
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
794
|
-
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
795
|
-
const joined = [];
|
|
796
|
-
for (let i = 0;i < args.length; i++) {
|
|
797
|
-
const arg = args[i] ?? "";
|
|
798
|
-
if (arg === "--")
|
|
799
|
-
return [...joined, ...args.slice(i)];
|
|
800
|
-
const name = longOf.get(arg);
|
|
801
|
-
const next = args[i + 1];
|
|
802
|
-
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
803
|
-
joined.push(`--${name}=${next}`);
|
|
804
|
-
i++;
|
|
805
|
-
} else {
|
|
806
|
-
joined.push(arg);
|
|
807
|
-
}
|
|
808
|
-
}
|
|
809
|
-
return joined;
|
|
810
|
-
}
|
|
811
|
-
function parseError(error) {
|
|
812
|
-
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
813
|
-
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
814
|
-
}
|
|
815
|
-
var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
816
|
-
function nearestOption(message, options, allowNegative) {
|
|
817
|
-
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
818
|
-
if (typed === undefined)
|
|
819
|
-
return;
|
|
820
|
-
const word = typed.replace(DASHES, "");
|
|
821
|
-
if (word.length < 2 && !typed.startsWith("--"))
|
|
822
|
-
return;
|
|
823
|
-
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
824
|
-
...option.short === undefined ? [] : [`-${option.short}`],
|
|
825
|
-
`--${name}`,
|
|
826
|
-
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
827
|
-
]);
|
|
828
|
-
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
829
|
-
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
830
|
-
}
|
|
831
|
-
// ../kit/src/argv.ts
|
|
832
|
-
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
833
|
-
import { resolve as resolve3 } from "path";
|
|
834
|
-
import process10 from "process";
|
|
835
|
-
function commandLine() {
|
|
836
|
-
try {
|
|
837
|
-
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
838
|
-
} catch {
|
|
839
|
-
return;
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
function realPath(word) {
|
|
843
|
-
try {
|
|
844
|
-
return realpathSync(resolve3(word));
|
|
845
|
-
} catch {
|
|
846
|
-
return;
|
|
847
|
-
}
|
|
848
|
-
}
|
|
849
|
-
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
850
|
-
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
851
|
-
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
852
|
-
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
853
|
-
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
854
|
-
}
|
|
855
|
-
// ../kit/src/process.ts
|
|
856
|
-
import { constants } from "os";
|
|
857
|
-
import process11 from "process";
|
|
858
|
-
var KILL_GRACE_MS = 2000;
|
|
859
|
-
function exitCodeOf(code, signal) {
|
|
860
|
-
if (code !== null)
|
|
861
|
-
return code;
|
|
862
|
-
if (typeof signal === "number")
|
|
863
|
-
return 128 + signal;
|
|
864
|
-
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
865
|
-
}
|
|
866
|
-
async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
867
|
-
const chunks = [];
|
|
868
|
-
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
869
|
-
const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
|
|
870
|
-
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
871
|
-
const timers = [];
|
|
872
|
-
const killGroup = (killing) => {
|
|
873
|
-
if (state.done)
|
|
874
|
-
return;
|
|
875
|
-
try {
|
|
876
|
-
if (grouped)
|
|
877
|
-
process11.kill(-proc.pid, killing);
|
|
878
|
-
else
|
|
879
|
-
proc.kill(killing);
|
|
880
|
-
} catch {}
|
|
881
|
-
};
|
|
882
|
-
const stop = () => {
|
|
883
|
-
killGroup("SIGTERM");
|
|
884
|
-
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
885
|
-
};
|
|
886
|
-
const onAbort = () => stop();
|
|
887
|
-
if (timeoutMs !== undefined) {
|
|
888
|
-
timers.push(setTimeout(() => {
|
|
889
|
-
state.timedOut = true;
|
|
890
|
-
stop();
|
|
891
|
-
}, timeoutMs));
|
|
892
|
-
}
|
|
893
|
-
if (signal?.aborted === true)
|
|
894
|
-
onAbort();
|
|
895
|
-
else
|
|
896
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
897
|
-
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
898
|
-
const drain = async (stream, name) => {
|
|
899
|
-
for await (const data of stream) {
|
|
900
|
-
if (state.failure !== undefined)
|
|
901
|
-
continue;
|
|
902
|
-
try {
|
|
903
|
-
onChunk?.({ stream: name, data });
|
|
904
|
-
} catch (error) {
|
|
905
|
-
state.failure = error;
|
|
906
|
-
stop();
|
|
907
|
-
continue;
|
|
908
|
-
}
|
|
909
|
-
if (state.kept + data.length > maxBytes) {
|
|
910
|
-
state.truncated = true;
|
|
911
|
-
continue;
|
|
912
|
-
}
|
|
913
|
-
state.kept += data.length;
|
|
914
|
-
chunks.push({ stream: name, data });
|
|
915
|
-
}
|
|
916
|
-
};
|
|
917
|
-
try {
|
|
918
|
-
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
919
|
-
await proc.exited;
|
|
920
|
-
} finally {
|
|
921
|
-
state.done = true;
|
|
922
|
-
for (const timer of timers)
|
|
923
|
-
clearTimeout(timer);
|
|
924
|
-
signal?.removeEventListener("abort", onAbort);
|
|
925
|
-
}
|
|
926
|
-
if (state.failure !== undefined)
|
|
927
|
-
throw state.failure;
|
|
928
|
-
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
929
|
-
let output;
|
|
930
|
-
let text;
|
|
931
|
-
return {
|
|
932
|
-
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
933
|
-
chunks,
|
|
934
|
-
timedOut: state.timedOut,
|
|
935
|
-
truncated: state.truncated,
|
|
936
|
-
get output() {
|
|
937
|
-
return output ??= joined();
|
|
938
|
-
},
|
|
939
|
-
get text() {
|
|
940
|
-
return text ??= (output ??= joined()).toString();
|
|
941
|
-
}
|
|
942
|
-
};
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
// ../kit/src/progress.ts
|
|
946
|
-
var ESC = String.fromCharCode(27);
|
|
947
|
-
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
948
|
-
var RESET_STYLE = `${ESC}[0m`;
|
|
949
|
-
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
950
|
-
|
|
951
|
-
// ../kit/src/tool.ts
|
|
952
|
-
import process12 from "process";
|
|
953
|
-
function cwdGone() {
|
|
954
|
-
try {
|
|
955
|
-
process12.cwd();
|
|
956
|
-
return false;
|
|
957
|
-
} catch {
|
|
958
|
-
return true;
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
class SpawnError extends Error {
|
|
963
|
-
missing;
|
|
964
|
-
constructor(message, missing) {
|
|
965
|
-
super(message);
|
|
966
|
-
this.missing = missing;
|
|
967
|
-
}
|
|
968
|
-
}
|
|
969
|
-
function spawnFailure(command, error) {
|
|
970
|
-
const gone = cwdGone();
|
|
971
|
-
const missing = !gone && error?.code === "ENOENT";
|
|
972
|
-
return new SpawnError(`${command}: ${error instanceof Error ? error.message : String(error)}${gone ? " (the working directory was removed)" : ""}`, missing);
|
|
973
|
-
}
|
|
974
|
-
async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
|
|
975
|
-
let ran;
|
|
976
|
-
try {
|
|
977
|
-
ran = await runCommand(argv, { env: process12.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
|
|
978
|
-
} catch (error) {
|
|
979
|
-
throw spawnFailure(label, error);
|
|
980
|
-
}
|
|
981
|
-
if (ran.timedOut)
|
|
982
|
-
throw new Error(`${label}: no answer in ${formatDuration(timeoutMs ?? 0)}`);
|
|
983
|
-
const decoders = { stdout: new TextDecoder, stderr: new TextDecoder };
|
|
984
|
-
const streams = { stdout: "", stderr: "" };
|
|
985
|
-
for (const { stream, data } of ran.chunks)
|
|
986
|
-
streams[stream] += decoders[stream].decode(data, { stream: true });
|
|
987
|
-
streams.stdout += decoders.stdout.decode();
|
|
988
|
-
streams.stderr += decoders.stderr.decode();
|
|
989
|
-
return { code: ran.code, ...streams };
|
|
990
|
-
}
|
|
991
|
-
// ../kit/src/cli.ts
|
|
992
|
-
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
993
|
-
import { dirname as dirname3, join as join5 } from "path";
|
|
994
|
-
import process15 from "process";
|
|
995
|
-
|
|
996
|
-
// ../kit/src/notify.ts
|
|
997
|
-
import process13 from "process";
|
|
998
|
-
var NOTIFY_AFTER_MS = 1e4;
|
|
999
|
-
var CANCELLED = 130;
|
|
1000
|
-
function base64(text) {
|
|
1001
|
-
return Buffer.from(text).toString("base64");
|
|
1002
|
-
}
|
|
1003
|
-
function notification(title, body, env = process13.env) {
|
|
1004
|
-
const id = `kit${process13.pid}`;
|
|
1005
|
-
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\\`];
|
|
1006
|
-
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1007
|
-
}
|
|
1008
|
-
function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
|
|
1009
|
-
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1010
|
-
return;
|
|
1011
|
-
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1012
|
-
}
|
|
1013
|
-
|
|
1014
|
-
// ../kit/src/usage.ts
|
|
1015
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
1016
|
-
import { homedir as homedir3 } from "os";
|
|
1017
|
-
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
1018
|
-
import process14 from "process";
|
|
1019
|
-
|
|
1020
|
-
// ../kit/src/logs.ts
|
|
1021
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1022
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
1023
|
-
|
|
1024
|
-
// ../kit/src/usage.ts
|
|
1025
|
-
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1026
|
-
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1027
|
-
var LONGEST_NAME = 40;
|
|
1028
|
-
var usageError;
|
|
1029
|
-
function noteUsageError(message) {
|
|
1030
|
-
usageError = message;
|
|
1031
|
-
}
|
|
1032
|
-
function stateHome(env = process14.env) {
|
|
1033
|
-
const dir = env.XDG_STATE_HOME;
|
|
1034
|
-
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
1035
|
-
}
|
|
1036
|
-
function usagePath(env = process14.env) {
|
|
1037
|
-
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1038
|
-
}
|
|
1039
|
-
function usageRecorded(env = process14.env) {
|
|
1040
|
-
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1041
|
-
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1042
|
-
}
|
|
1043
|
-
function flagNames(argv) {
|
|
1044
|
-
const end = argv.indexOf("--");
|
|
1045
|
-
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1046
|
-
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1047
|
-
}
|
|
1048
|
-
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
1049
|
-
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1050
|
-
usageError = undefined;
|
|
1051
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
1052
|
-
}
|
|
1053
|
-
function recordUsage(entry, env = process14.env) {
|
|
1054
|
-
if (!usageRecorded(env))
|
|
1055
|
-
return;
|
|
1056
|
-
try {
|
|
1057
|
-
const path = usagePath(env);
|
|
1058
|
-
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1059
|
-
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1060
|
-
`, { mode: 384 });
|
|
1061
|
-
} catch {}
|
|
1062
|
-
}
|
|
1063
|
-
|
|
1064
|
-
// ../kit/src/cli.ts
|
|
1065
|
-
var LEVEL_OPTIONS = {
|
|
1066
|
-
...OUTPUT_OPTIONS,
|
|
1067
|
-
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1068
|
-
};
|
|
1069
|
-
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
1070
|
-
async function commandRows(all, colors) {
|
|
1071
|
-
const commands = shown(all);
|
|
1072
|
-
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
1073
|
-
const groups = new Map([["Commands:", []]]);
|
|
1074
|
-
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
1075
|
-
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
1076
|
-
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
1077
|
-
const rows = groups.get(heading) ?? [];
|
|
1078
|
-
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
1079
|
-
groups.set(heading, rows);
|
|
1080
|
-
}
|
|
1081
|
-
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
1082
|
-
}
|
|
1083
|
-
function shown(commands) {
|
|
1084
|
-
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
1085
|
-
}
|
|
1086
|
-
function takeOutputFlags(argv) {
|
|
1087
|
-
let index = 0;
|
|
1088
|
-
for (;index < argv.length; index++) {
|
|
1089
|
-
const word = argv[index];
|
|
1090
|
-
if (word === "--plain")
|
|
1091
|
-
applyOutput(undefined, true);
|
|
1092
|
-
else if (word.startsWith("--color="))
|
|
1093
|
-
applyOutput(word.slice("--color=".length), undefined);
|
|
1094
|
-
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
1095
|
-
applyOutput(argv[++index], undefined);
|
|
1096
|
-
else
|
|
1097
|
-
break;
|
|
1098
|
-
}
|
|
1099
|
-
return argv.slice(index);
|
|
1100
|
-
}
|
|
1101
|
-
async function resolveSummary(summary) {
|
|
1102
|
-
return typeof summary === "string" ? summary : summary();
|
|
1103
|
-
}
|
|
1104
|
-
function scopeOf(commands, extra, aliases) {
|
|
1105
|
-
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
1106
|
-
}
|
|
1107
|
-
async function expand(scope, words) {
|
|
1108
|
-
if (scope.lazy.length === 0)
|
|
1109
|
-
return scope;
|
|
1110
|
-
const commands = { ...scope.commands };
|
|
1111
|
-
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
1112
|
-
for (const [name, command] of Object.entries(added))
|
|
1113
|
-
commands[name] ??= command;
|
|
1114
|
-
}
|
|
1115
|
-
return { ...scope, commands, lazy: [] };
|
|
1116
|
-
}
|
|
1117
|
-
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
1118
|
-
const colors = paint(stream);
|
|
1119
|
-
const prefix = path.join(" ");
|
|
1120
|
-
const summary = await resolveSummary(lazySummary);
|
|
1121
|
-
if (wantsHelpJson())
|
|
1122
|
-
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
1123
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1124
|
-
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
1125
|
-
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
1126
|
-
return [
|
|
1127
|
-
header(colors, summary),
|
|
1128
|
-
"",
|
|
1129
|
-
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
1130
|
-
"",
|
|
1131
|
-
...await commandRows(commands, colors),
|
|
1132
|
-
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
1133
|
-
"",
|
|
1134
|
-
colors.bold("Options:"),
|
|
1135
|
-
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
1136
|
-
...exampleRows(examples ?? [], colors),
|
|
1137
|
-
"",
|
|
1138
|
-
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
1139
|
-
].join(`
|
|
1140
|
-
`);
|
|
1141
|
-
}
|
|
1142
|
-
function printError(prefix, message, hint, cause) {
|
|
1143
|
-
const colors = paint(process15.stderr);
|
|
1144
|
-
const styled = takesControlCodes(process15.stderr);
|
|
1145
|
-
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1146
|
-
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1147
|
-
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1148
|
-
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1149
|
-
}
|
|
1150
|
-
function printJsonError(message, hint, cause) {
|
|
1151
|
-
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1152
|
-
}
|
|
1153
|
-
function wantsJson(argv) {
|
|
1154
|
-
const end = argv.indexOf("--");
|
|
1155
|
-
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1156
|
-
}
|
|
1157
|
-
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1158
|
-
if (error instanceof HelpShown)
|
|
1159
|
-
return 0;
|
|
1160
|
-
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1161
|
-
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1162
|
-
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1163
|
-
if (error instanceof Exit && error.code === 2)
|
|
1164
|
-
noteUsageError(error.message);
|
|
1165
|
-
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1166
|
-
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1167
|
-
return error instanceof Exit ? error.code : 1;
|
|
1168
|
-
}
|
|
1169
|
-
async function dispatch(level, typed, { version, redact }) {
|
|
1170
|
-
const prefix = level.path.join(" ");
|
|
1171
|
-
let argv;
|
|
1172
|
-
try {
|
|
1173
|
-
argv = takeOutputFlags(typed);
|
|
1174
|
-
} catch (error) {
|
|
1175
|
-
return reportThrown(prefix, error);
|
|
1176
|
-
}
|
|
1177
|
-
const [name, ...args] = argv;
|
|
1178
|
-
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
1179
|
-
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
1180
|
-
try {
|
|
1181
|
-
return await fallback.run([]);
|
|
1182
|
-
} catch (error) {
|
|
1183
|
-
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
|
-
if (name === undefined && level.path.length > 1) {
|
|
1187
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
|
|
1188
|
-
return 2;
|
|
1189
|
-
}
|
|
1190
|
-
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1191
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
|
|
1192
|
-
return 0;
|
|
1193
|
-
}
|
|
1194
|
-
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1195
|
-
console.log(version);
|
|
1196
|
-
return 0;
|
|
1197
|
-
}
|
|
1198
|
-
let command = level.commands[level.aliases?.[name] ?? name];
|
|
1199
|
-
let rest = args;
|
|
1200
|
-
let ran = name;
|
|
1201
|
-
if (command === undefined && level.lazy.length > 0) {
|
|
1202
|
-
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1203
|
-
command = level.commands[level.aliases?.[name] ?? name];
|
|
1204
|
-
}
|
|
1205
|
-
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1206
|
-
command = level.commands[level.defaultCommand];
|
|
1207
|
-
rest = argv;
|
|
1208
|
-
ran = level.defaultCommand;
|
|
1209
|
-
}
|
|
1210
|
-
if (command === undefined) {
|
|
1211
|
-
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
1212
|
-
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
1213
|
-
return 2;
|
|
1214
|
-
}
|
|
1215
|
-
if ("commands" in command) {
|
|
1216
|
-
const { summary } = command;
|
|
1217
|
-
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 });
|
|
1218
|
-
}
|
|
1219
|
-
try {
|
|
1220
|
-
return await command.run(rest);
|
|
1221
|
-
} catch (error) {
|
|
1222
|
-
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
1223
|
-
}
|
|
1224
|
-
}
|
|
1225
|
-
var COMPLETE = "__complete";
|
|
1226
|
-
var FILES = "__files__";
|
|
1227
|
-
async function completingOf(run) {
|
|
1228
|
-
completion.active = true;
|
|
1229
|
-
try {
|
|
1230
|
-
await run([]);
|
|
1231
|
-
} catch (error) {
|
|
1232
|
-
if (error instanceof Completing)
|
|
1233
|
-
return error;
|
|
1234
|
-
} finally {
|
|
1235
|
-
completion.active = false;
|
|
1236
|
-
}
|
|
1237
|
-
return new Completing({});
|
|
1238
|
-
}
|
|
1239
|
-
async function optionsOf(run) {
|
|
1240
|
-
return (await completingOf(run)).options;
|
|
1241
|
-
}
|
|
1242
|
-
function candidateLine(candidate) {
|
|
1243
|
-
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1244
|
-
}
|
|
1245
|
-
function positionalBeingTyped(before, { options, positionals }) {
|
|
1246
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1247
|
-
const typed = [];
|
|
1248
|
-
let at = 0;
|
|
1249
|
-
while (at < before.length) {
|
|
1250
|
-
const word = before[at];
|
|
1251
|
-
if (word === "--") {
|
|
1252
|
-
typed.push(...before.slice(at + 1));
|
|
1253
|
-
break;
|
|
1254
|
-
}
|
|
1255
|
-
if (!word.startsWith("-"))
|
|
1256
|
-
typed.push(word);
|
|
1257
|
-
else if (takesValue(word))
|
|
1258
|
-
at++;
|
|
1259
|
-
at++;
|
|
1260
|
-
}
|
|
1261
|
-
const last = positionals.at(-1);
|
|
1262
|
-
if (typed.length < positionals.length)
|
|
1263
|
-
return { name: positionals[typed.length], typed };
|
|
1264
|
-
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1265
|
-
}
|
|
1266
|
-
async function leafCandidates(run, words) {
|
|
1267
|
-
const completing = await completingOf(run);
|
|
1268
|
-
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1269
|
-
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1270
|
-
const flag = words.at(-2);
|
|
1271
|
-
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1272
|
-
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1273
|
-
if (option?.type === "string") {
|
|
1274
|
-
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1275
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1276
|
-
}
|
|
1277
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1278
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1279
|
-
}
|
|
1280
|
-
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1281
|
-
const [word = "", ...rest] = words;
|
|
1282
|
-
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1283
|
-
let { commands, aliases } = scope;
|
|
1284
|
-
let command = commands[aliases?.[word] ?? word];
|
|
1285
|
-
if (listing || command === undefined) {
|
|
1286
|
-
({ commands, aliases } = await expand(scope, [...before, ...words]));
|
|
1287
|
-
command = commands[aliases?.[word] ?? word];
|
|
1288
|
-
}
|
|
1289
|
-
if (listing) {
|
|
1290
|
-
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1291
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1292
|
-
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1293
|
-
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1294
|
-
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
|
|
1295
|
-
}
|
|
1296
|
-
if (command === undefined) {
|
|
1297
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1298
|
-
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1299
|
-
}
|
|
1300
|
-
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1301
|
-
}
|
|
1302
|
-
async function printCandidates(found) {
|
|
1303
|
-
for (const line of await found)
|
|
1304
|
-
console.log(line);
|
|
1305
|
-
return 0;
|
|
1306
|
-
}
|
|
1307
|
-
function packageVersion(entry = Bun.main) {
|
|
1308
|
-
let resolved = entry;
|
|
1309
|
-
try {
|
|
1310
|
-
resolved = realpathSync2(entry);
|
|
1311
|
-
} catch {}
|
|
1312
|
-
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1313
|
-
try {
|
|
1314
|
-
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1315
|
-
if (typeof version === "string")
|
|
1316
|
-
return version;
|
|
1317
|
-
} catch {}
|
|
1318
|
-
if (dirname3(dir) === dir)
|
|
1319
|
-
return "0.0.0";
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
async function runCli(cli, argv = scriptArgs()) {
|
|
1323
|
-
const version = cli.version ?? packageVersion();
|
|
1324
|
-
if (argv[0] === COMPLETE)
|
|
1325
|
-
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1326
|
-
const started = performance.now();
|
|
1327
|
-
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 });
|
|
1328
|
-
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1329
|
-
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1330
|
-
if (cli.usage !== false) {
|
|
1331
|
-
try {
|
|
1332
|
-
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1333
|
-
} catch {}
|
|
1334
|
-
}
|
|
1335
|
-
return code;
|
|
1336
|
-
}
|
|
1337
|
-
function commandPath(scope, argv) {
|
|
1338
|
-
const path = [];
|
|
1339
|
-
let level = scope;
|
|
1340
|
-
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1341
|
-
const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
|
|
1342
|
-
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
1343
|
-
if (command === undefined)
|
|
1344
|
-
break;
|
|
1345
|
-
path.push(word);
|
|
1346
|
-
if (!("commands" in command))
|
|
1347
|
-
break;
|
|
1348
|
-
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1349
|
-
}
|
|
1350
|
-
return path.length === 0 ? undefined : path.join(" ");
|
|
1351
|
-
}
|
|
1352
|
-
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1353
|
-
if (argv[0] === COMPLETE)
|
|
1354
|
-
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1355
|
-
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1356
|
-
console.log(version ?? packageVersion());
|
|
1357
|
-
return 0;
|
|
1358
|
-
}
|
|
1359
|
-
let code;
|
|
1360
|
-
const started = performance.now();
|
|
1361
|
-
try {
|
|
1362
|
-
code = await run(argv);
|
|
1363
|
-
} catch (error) {
|
|
1364
|
-
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1365
|
-
}
|
|
1366
|
-
notifyEnd(name, code, performance.now() - started);
|
|
1367
|
-
if (usage !== false) {
|
|
1368
|
-
try {
|
|
1369
|
-
recordUsage(usageEntry(name, undefined, argv, code));
|
|
1370
|
-
} catch {}
|
|
1371
|
-
}
|
|
1372
|
-
return code;
|
|
1373
|
-
}
|
|
1374
|
-
// ../kit/src/folders.ts
|
|
1375
|
-
var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
1376
|
-
// ../kit/src/pool.ts
|
|
1377
|
-
async function pool(items, limit, task) {
|
|
1378
|
-
const results = Array.from({ length: items.length });
|
|
1379
|
-
let next = 0;
|
|
1380
|
-
async function worker() {
|
|
1381
|
-
while (next < items.length) {
|
|
1382
|
-
const index = next++;
|
|
1383
|
-
results[index] = await task(items[index]);
|
|
1384
|
-
}
|
|
1385
|
-
}
|
|
1386
|
-
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
1387
|
-
return results;
|
|
1388
|
-
}
|
|
1389
|
-
// ../kit/src/secrets.ts
|
|
1390
|
-
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1391
|
-
// ../kit/src/sessions.ts
|
|
1392
|
-
var {Glob } = globalThis.Bun;
|
|
1393
|
-
var SESSION_FILES = new Glob("*.json");
|
|
1394
|
-
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1395
|
-
// ../kit/src/size.ts
|
|
1396
|
-
var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
|
|
1397
|
-
var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
|
|
1398
|
-
function parseSize(text, bareUnit = 1) {
|
|
1399
|
-
const match = SIZE.exec(text.trim());
|
|
1400
|
-
if (match === null)
|
|
1401
|
-
return;
|
|
1402
|
-
const suffix = match[2].toLowerCase();
|
|
1403
|
-
return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
|
|
1404
|
-
}
|
|
1405
|
-
// ../kit/src/watch.ts
|
|
1406
|
-
import process16 from "process";
|
|
1407
|
-
import { format } from "util";
|
|
1408
|
-
var CLEAR_SCREEN = "\x1B[H\x1B[2J";
|
|
1409
|
-
var DEFAULT_SECONDS = 2;
|
|
1410
|
-
var ATTACHED_SHORT = /^-w./;
|
|
1411
|
-
var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
|
|
1412
|
-
function watchOption(what) {
|
|
1413
|
-
return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
|
|
1414
|
-
}
|
|
1415
|
-
function withoutWatch(args) {
|
|
1416
|
-
const rest = [];
|
|
1417
|
-
for (let at = 0;at < args.length; at++) {
|
|
1418
|
-
const arg = args[at];
|
|
1419
|
-
if (arg === "--watch" || arg === "-w") {
|
|
1420
|
-
if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
|
|
1421
|
-
at++;
|
|
1422
|
-
} else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
|
|
1423
|
-
rest.push(arg);
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
return rest;
|
|
1427
|
-
}
|
|
1428
|
-
async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
|
|
1429
|
-
const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
|
|
1430
|
-
if (!takesControlCodes(stream))
|
|
1431
|
-
badUsage("--watch redraws the screen, so it needs a terminal");
|
|
1432
|
-
let code = 0;
|
|
1433
|
-
for (let round = 0;round < rounds; round++) {
|
|
1434
|
-
const held = [];
|
|
1435
|
-
const { log, info } = console;
|
|
1436
|
-
const write = process16.stdout.write.bind(process16.stdout);
|
|
1437
|
-
const hold = (...parts) => void held.push(`${format(...parts)}
|
|
1438
|
-
`);
|
|
1439
|
-
console.log = hold;
|
|
1440
|
-
console.info = hold;
|
|
1441
|
-
process16.stdout.write = (text) => {
|
|
1442
|
-
held.push(typeof text === "string" ? text : Buffer.from(text).toString());
|
|
1443
|
-
return true;
|
|
1444
|
-
};
|
|
1445
|
-
try {
|
|
1446
|
-
code = await step();
|
|
1447
|
-
} finally {
|
|
1448
|
-
console.log = log;
|
|
1449
|
-
console.info = info;
|
|
1450
|
-
process16.stdout.write = write;
|
|
1451
|
-
}
|
|
1452
|
-
stream.write(`${CLEAR_SCREEN}${held.join("")}`);
|
|
1453
|
-
await sleep(interval);
|
|
1454
|
-
}
|
|
1455
|
-
return code;
|
|
1456
|
-
}
|
|
1457
|
-
// ../kit/src/workspace-root.ts
|
|
1458
|
-
import { homedir as homedir4 } from "os";
|
|
1459
|
-
import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
|
|
1460
|
-
import process17 from "process";
|
|
1461
|
-
function expandHome(path, home) {
|
|
1462
|
-
if (path === "~")
|
|
1463
|
-
return home;
|
|
1464
|
-
return path.startsWith("~/") ? join6(home, path.slice(2)) : path;
|
|
1465
|
-
}
|
|
1466
|
-
function configured(env, home) {
|
|
1467
|
-
const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
|
|
1468
|
-
return typeof folder === "string" && folder !== "" ? folder : undefined;
|
|
1469
|
-
}
|
|
1470
|
-
function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
|
|
1471
|
-
const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
|
|
1472
|
-
return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
|
|
1473
|
-
}
|
|
1474
|
-
// src/sweep.ts
|
|
1475
|
-
import { existsSync as existsSync6, statSync as statSync2 } from "fs";
|
|
1476
|
-
import { homedir as homedir6 } from "os";
|
|
1477
|
-
import { relative } from "path";
|
|
1478
|
-
|
|
1479
|
-
// ../kit/src/prompt.ts
|
|
1480
|
-
import process20 from "process";
|
|
1481
|
-
|
|
1482
|
-
// ../kit/src/job.ts
|
|
1483
|
-
import process19 from "process";
|
|
1484
|
-
function stopJob() {
|
|
1485
|
-
process19.kill(0, "SIGTSTP");
|
|
1486
|
-
}
|
|
1487
|
-
|
|
1488
|
-
// ../kit/src/picker/line.ts
|
|
1489
|
-
var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
|
|
1490
|
-
var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
|
|
1491
|
-
var FORWARD_KILLS = new Set(["killnext", "killend"]);
|
|
1492
|
-
function isEditKey(key) {
|
|
1493
|
-
return EDIT_KEYS.has(key);
|
|
1494
|
-
}
|
|
1495
|
-
|
|
1496
|
-
// ../kit/src/picker/score.ts
|
|
1497
|
-
var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
1498
|
-
var NONE = Number.NEGATIVE_INFINITY;
|
|
1499
|
-
|
|
1500
|
-
// ../kit/src/picker/state.ts
|
|
1501
|
-
var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
1502
|
-
var PASTE_START = "\x1B[200~";
|
|
1503
|
-
var PASTE_END = "\x1B[201~";
|
|
1504
|
-
var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
|
|
1505
|
-
var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
|
|
1506
|
-
var WHEEL_LINES = 3;
|
|
1507
|
-
var KEYS = {
|
|
1508
|
-
"\x1B[A": "up",
|
|
1509
|
-
"\x1BOA": "up",
|
|
1510
|
-
"\x10": "up",
|
|
1511
|
-
"\x1B[B": "down",
|
|
1512
|
-
"\x1BOB": "down",
|
|
1513
|
-
"\x0E": "down",
|
|
1514
|
-
"\x1B[5~": "pageup",
|
|
1515
|
-
"\x1B[6~": "pagedown",
|
|
1516
|
-
"\x1B[H": "home",
|
|
1517
|
-
"\x1B[1~": "home",
|
|
1518
|
-
"\x1BOH": "home",
|
|
1519
|
-
"\x1B[F": "end",
|
|
1520
|
-
"\x1B[4~": "end",
|
|
1521
|
-
"\x1BOF": "end",
|
|
1522
|
-
"\r": "enter",
|
|
1523
|
-
"\n": "enter",
|
|
1524
|
-
"\x03": "cancel",
|
|
1525
|
-
"\x1B": "cancel",
|
|
1526
|
-
"\x1B[D": "left",
|
|
1527
|
-
"\x1BOD": "left",
|
|
1528
|
-
"\x1B[C": "right",
|
|
1529
|
-
"\x1BOC": "right",
|
|
1530
|
-
"\x1B[1;5D": "wordleft",
|
|
1531
|
-
"\x1B[1;3D": "wordleft",
|
|
1532
|
-
"\x1Bb": "wordleft",
|
|
1533
|
-
"\x1B[1;5C": "wordright",
|
|
1534
|
-
"\x1B[1;3C": "wordright",
|
|
1535
|
-
"\x1Bf": "wordright",
|
|
1536
|
-
"\x01": "linestart",
|
|
1537
|
-
"\x05": "lineend",
|
|
1538
|
-
"\x7F": "erase",
|
|
1539
|
-
"\x1B[3~": "delete",
|
|
1540
|
-
"\b": "killword",
|
|
1541
|
-
"\x1B\x7F": "killword",
|
|
1542
|
-
"\x1B[3;5~": "killnext",
|
|
1543
|
-
"\x1Bd": "killnext",
|
|
1544
|
-
"\x15": "clear",
|
|
1545
|
-
"\v": "killend",
|
|
1546
|
-
"\x17": "word",
|
|
1547
|
-
"\x19": "yank",
|
|
1548
|
-
"\x1A": "suspend",
|
|
1549
|
-
"\t": "tab",
|
|
1550
|
-
"\x1F": "help",
|
|
1551
|
-
"\x1BOP": "help",
|
|
1552
|
-
"\x1B[11~": "help"
|
|
1553
|
-
};
|
|
1554
|
-
function repeat(value, count) {
|
|
1555
|
-
return Array.from({ length: count }).fill(value);
|
|
1556
|
-
}
|
|
1557
|
-
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
1558
|
-
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
1559
|
-
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
1560
|
-
const wheel = MOUSE.exec(sequence)?.[1];
|
|
1561
|
-
if (wheel !== undefined)
|
|
1562
|
-
return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
|
|
1563
|
-
const named = codes.get(sequence);
|
|
1564
|
-
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
1565
|
-
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
1566
|
-
paste.active = sequence === PASTE_START;
|
|
1567
|
-
return [];
|
|
1568
|
-
}
|
|
1569
|
-
if (paste.active && (sequence === "\r" || sequence === `
|
|
1570
|
-
`))
|
|
1571
|
-
return [];
|
|
1572
|
-
if (key !== undefined)
|
|
1573
|
-
return [key];
|
|
1574
|
-
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
1575
|
-
});
|
|
1576
|
-
}
|
|
1577
|
-
|
|
1578
|
-
// ../kit/src/redraw.ts
|
|
1579
|
-
var SYNC_START = "\x1B[?2026h";
|
|
1580
|
-
var SYNC_END = "\x1B[?2026l";
|
|
1581
|
-
function overwrite(lines, columns) {
|
|
1582
|
-
return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
|
|
1583
|
-
`);
|
|
1584
|
-
}
|
|
1585
|
-
function rowsTaken(lines, columns) {
|
|
1586
|
-
return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
|
|
1587
|
-
}
|
|
1588
|
-
|
|
1589
|
-
// ../kit/src/prompt.ts
|
|
1590
|
-
var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
|
|
1591
|
-
function readKeys(input, paste = { active: false }) {
|
|
1592
|
-
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
|
|
1593
|
-
}
|
|
1594
|
-
async function confirm(question, { default: fallback, ...settings } = {}) {
|
|
1595
|
-
let answered = fallback;
|
|
1596
|
-
const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
|
|
1597
|
-
const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
|
|
1598
|
-
if (key === "cancel")
|
|
1599
|
-
return "cancel";
|
|
1600
|
-
if (key === "enter")
|
|
1601
|
-
return answered === undefined ? undefined : "enter";
|
|
1602
|
-
const letter = typeof key === "object" ? key.text.toLowerCase() : "";
|
|
1603
|
-
if (letter !== "y" && letter !== "n")
|
|
1604
|
-
return;
|
|
1605
|
-
answered = letter === "y";
|
|
1606
|
-
return "enter";
|
|
1607
|
-
});
|
|
1608
|
-
return accepted ? answered : undefined;
|
|
1609
|
-
}
|
|
1610
|
-
function asking(colors, question, typed, keys) {
|
|
1611
|
-
return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
|
|
1612
|
-
}
|
|
1613
|
-
function answer(colors, question, state, picked) {
|
|
1614
|
-
return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
|
|
1615
|
-
}
|
|
1616
|
-
async function ask(question, { hint, terminal = process20 }, render, press) {
|
|
1617
|
-
const { stdin, stderr } = terminal;
|
|
1618
|
-
if (!isInteractive(terminal))
|
|
1619
|
-
fail(`cannot ask "${question}" off a terminal`, 2, hint);
|
|
1620
|
-
const colors = paint(stderr);
|
|
1621
|
-
let current = "asking";
|
|
1622
|
-
let outcome;
|
|
1623
|
-
const columns = () => stderr.columns || 80;
|
|
1624
|
-
const draw = (state, last = false) => {
|
|
1625
|
-
const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
|
|
1626
|
-
const rows = rowsTaken(frame, columns());
|
|
1627
|
-
stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
|
|
1628
|
-
current = state;
|
|
1629
|
-
};
|
|
1630
|
-
const redraw = () => draw(current);
|
|
1631
|
-
const paste = { active: false };
|
|
1632
|
-
const stop = terminal.stop ?? (terminal === process20 ? stopJob : undefined);
|
|
1633
|
-
const suspend = () => {
|
|
1634
|
-
if (stop === undefined)
|
|
1635
|
-
return;
|
|
1636
|
-
stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
|
|
1637
|
-
stdin.setRawMode(false);
|
|
1638
|
-
stop();
|
|
1639
|
-
stdin.setRawMode(true);
|
|
1640
|
-
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1641
|
-
};
|
|
1642
|
-
try {
|
|
1643
|
-
stderr.on?.("resize", redraw);
|
|
1644
|
-
stdin.setRawMode(true);
|
|
1645
|
-
stdin.resume();
|
|
1646
|
-
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1647
|
-
draw("asking");
|
|
1648
|
-
return await new Promise((resolve) => {
|
|
1649
|
-
function onData(data) {
|
|
1650
|
-
for (const key of readKeys(data.toString(), paste)) {
|
|
1651
|
-
if (key === "suspend") {
|
|
1652
|
-
suspend();
|
|
1653
|
-
continue;
|
|
1654
|
-
}
|
|
1655
|
-
const pressed = press(key);
|
|
1656
|
-
if (pressed !== undefined) {
|
|
1657
|
-
settle(pressed);
|
|
1658
|
-
return;
|
|
1659
|
-
}
|
|
1660
|
-
}
|
|
1661
|
-
draw("asking");
|
|
1662
|
-
}
|
|
1663
|
-
function onEnd() {
|
|
1664
|
-
settle("cancel");
|
|
1665
|
-
}
|
|
1666
|
-
function settle(settled) {
|
|
1667
|
-
outcome = settled;
|
|
1668
|
-
stdin.off("data", onData);
|
|
1669
|
-
stdin.off("end", onEnd);
|
|
1670
|
-
resolve(settled === "enter");
|
|
1671
|
-
}
|
|
1672
|
-
stdin.on("data", onData);
|
|
1673
|
-
stdin.on("end", onEnd);
|
|
1674
|
-
});
|
|
1675
|
-
} finally {
|
|
1676
|
-
stderr.off?.("resize", redraw);
|
|
1677
|
-
draw(outcome ?? "cancel", true);
|
|
1678
|
-
stderr.write(`
|
|
1679
|
-
\x1B[?25h\x1B[?2004l`);
|
|
1680
|
-
stdin.setRawMode(false);
|
|
1681
|
-
stdin.pause();
|
|
1682
|
-
}
|
|
1683
|
-
}
|
|
1684
|
-
|
|
1685
|
-
// src/apply.ts
|
|
1686
|
-
import { existsSync as existsSync5 } from "fs";
|
|
1687
|
-
import { lstat as lstat3, rm } from "fs/promises";
|
|
1688
|
-
import { basename as basename2, join as join9 } from "path";
|
|
1689
|
-
|
|
1690
|
-
// src/sweep-scan.ts
|
|
1691
|
-
import { existsSync as existsSync4 } from "fs";
|
|
1692
|
-
import { lstat as lstat2, readdir as readdir2, realpath } from "fs/promises";
|
|
1693
|
-
import { homedir as homedir5 } from "os";
|
|
1694
|
-
import { basename, dirname as dirname5, join as join8 } from "path";
|
|
1695
|
-
|
|
1696
|
-
// src/size.ts
|
|
1697
|
-
import { lstat, readdir } from "fs/promises";
|
|
1698
|
-
import { join as join7 } from "path";
|
|
1699
|
-
var FS_LIMIT = 32;
|
|
1700
|
-
var FIND_MS = 60000;
|
|
1701
|
-
var FIND_LINE = /^(\d+) (\S+) (\d+)$/gm;
|
|
1702
|
-
var waiting = [];
|
|
1703
|
-
var running = 0;
|
|
1704
|
-
async function gated(call) {
|
|
1705
|
-
if (running >= FS_LIMIT)
|
|
1706
|
-
await new Promise((resolve) => waiting.push(resolve));
|
|
1707
|
-
running++;
|
|
1708
|
-
try {
|
|
1709
|
-
return await call();
|
|
1710
|
-
} finally {
|
|
1711
|
-
running--;
|
|
1712
|
-
waiting.shift()?.();
|
|
1713
|
-
}
|
|
1714
|
-
}
|
|
1715
|
-
async function walkSize(folder) {
|
|
1716
|
-
const seen = new Set;
|
|
1717
|
-
let total = 0;
|
|
1718
|
-
const visit = async (dir) => {
|
|
1719
|
-
let entries;
|
|
1720
|
-
try {
|
|
1721
|
-
entries = await gated(async () => readdir(dir, { withFileTypes: true }));
|
|
1722
|
-
} catch {
|
|
1723
|
-
return;
|
|
1724
|
-
}
|
|
1725
|
-
await Promise.all(entries.map(async (entry) => {
|
|
1726
|
-
const path = join7(dir, entry.name);
|
|
1727
|
-
if (entry.isDirectory())
|
|
1728
|
-
return visit(path);
|
|
1729
|
-
try {
|
|
1730
|
-
const stat = await gated(async () => lstat(path));
|
|
1731
|
-
if (stat.nlink > 1) {
|
|
1732
|
-
const key = `${stat.dev}:${stat.ino}`;
|
|
1733
|
-
if (seen.has(key))
|
|
1734
|
-
return;
|
|
1735
|
-
seen.add(key);
|
|
1736
|
-
}
|
|
1737
|
-
total += stat.size;
|
|
1738
|
-
} catch {}
|
|
1739
|
-
}));
|
|
1740
|
-
};
|
|
1741
|
-
await visit(folder);
|
|
1742
|
-
return total;
|
|
1743
|
-
}
|
|
1744
|
-
async function findSize(folder) {
|
|
1745
|
-
try {
|
|
1746
|
-
const ran = await runCommand(["find", "-P", folder, "(", "-type", "f", "-o", "-type", "l", ")", "-printf", "%n %D:%i %s\\n"], { timeoutMs: FIND_MS });
|
|
1747
|
-
const lines = [...ran.text.matchAll(FIND_LINE)];
|
|
1748
|
-
if (ran.timedOut || ran.code !== 0 && lines.length === 0)
|
|
1749
|
-
return;
|
|
1750
|
-
const seen = new Set;
|
|
1751
|
-
let total = 0;
|
|
1752
|
-
for (const [, links, id, bytes] of lines) {
|
|
1753
|
-
if (Number(links) > 1) {
|
|
1754
|
-
if (seen.has(id))
|
|
1755
|
-
continue;
|
|
1756
|
-
seen.add(id);
|
|
1757
|
-
}
|
|
1758
|
-
total += Number(bytes);
|
|
1759
|
-
}
|
|
1760
|
-
return total;
|
|
1761
|
-
} catch {
|
|
1762
|
-
return;
|
|
1763
|
-
}
|
|
1764
|
-
}
|
|
1765
|
-
async function sizeOf(folder) {
|
|
1766
|
-
return await findSize(folder) ?? await walkSize(folder);
|
|
1767
|
-
}
|
|
1768
|
-
|
|
1769
|
-
// src/sweep-scan.ts
|
|
1770
|
-
var FOLDER_NAMES = new Set(["node_modules", ".nuxt", ".next", ".output", "dist", "build", ".turbo", ".svelte-kit", "target", "vendor", ".venv", "__pycache__", ".gradle"]);
|
|
1771
|
-
var NEEDS_BESIDE = { target: ["Cargo.toml"], vendor: ["composer.json", "composer.lock"] };
|
|
1772
|
-
var MAX_DEPTH = 3;
|
|
1773
|
-
var PROJECT_CACHE_NAMES = new Set([".turbo", ".nuxt", ".next", ".svelte-kit", "__pycache__", ".gradle"]);
|
|
1774
|
-
var GLOBAL_CACHES = [".bun/install/cache", ".npm/_cacache", ".cache/pip", ".cache/uv", ".cache/ms-playwright", ".cache/puppeteer", ".cache/go-build", ".cache/typescript", ".cargo/registry"];
|
|
1775
|
-
function isCachePath(path, home = homedir5()) {
|
|
1776
|
-
return GLOBAL_CACHES.some((cache) => join8(home, cache) === path) || basename(path) === ".cache" && basename(dirname5(path)) === "node_modules";
|
|
1777
|
-
}
|
|
1778
|
-
async function listing(dir) {
|
|
1779
|
-
try {
|
|
1780
|
-
return await readdir2(dir, { withFileTypes: true });
|
|
1781
|
-
} catch {
|
|
1782
|
-
return [];
|
|
1783
|
-
}
|
|
1784
|
-
}
|
|
1785
|
-
async function addGlobalCaches(found, home) {
|
|
1786
|
-
for (const cache of GLOBAL_CACHES) {
|
|
1787
|
-
const path = join8(home, cache);
|
|
1788
|
-
try {
|
|
1789
|
-
const stat = await lstat2(path);
|
|
1790
|
-
if (stat.isSymbolicLink())
|
|
1791
|
-
found.skipped.push({ path, reason: "symlink" });
|
|
1792
|
-
else if (stat.isDirectory())
|
|
1793
|
-
found.candidates.push({ path, kind: "cache", global: true });
|
|
1794
|
-
} catch {}
|
|
1795
|
-
}
|
|
1796
|
-
}
|
|
1797
|
-
async function findCandidates(root, home = homedir5(), withGlobal = true) {
|
|
1798
|
-
const found = { candidates: [], skipped: [] };
|
|
1799
|
-
const visit = async (dir, depth) => {
|
|
1800
|
-
const entries = await listing(dir);
|
|
1801
|
-
for (const entry of entries) {
|
|
1802
|
-
const path = join8(dir, entry.name);
|
|
1803
|
-
if (entry.name === ".git")
|
|
1804
|
-
continue;
|
|
1805
|
-
if (entry.name === ".worktrees" || entry.name === "worktrees" && basename(dir) === ".claude") {
|
|
1806
|
-
if (!entry.isDirectory()) {
|
|
1807
|
-
found.skipped.push({ path, reason: "symlink" });
|
|
1808
|
-
continue;
|
|
1809
|
-
}
|
|
1810
|
-
for (const worktree of await listing(path)) {
|
|
1811
|
-
if (worktree.isDirectory())
|
|
1812
|
-
found.candidates.push({ path: join8(path, worktree.name), kind: "worktree" });
|
|
1813
|
-
else if (worktree.isSymbolicLink())
|
|
1814
|
-
found.skipped.push({ path: join8(path, worktree.name), reason: "symlink" });
|
|
1815
|
-
}
|
|
1816
|
-
continue;
|
|
1817
|
-
}
|
|
1818
|
-
if (FOLDER_NAMES.has(entry.name) && (NEEDS_BESIDE[entry.name]?.some((file) => existsSync4(join8(dir, file))) ?? true)) {
|
|
1819
|
-
if (entry.isSymbolicLink()) {
|
|
1820
|
-
found.skipped.push({ path, reason: "symlink" });
|
|
1821
|
-
} else if (entry.isDirectory()) {
|
|
1822
|
-
found.candidates.push({ path, kind: PROJECT_CACHE_NAMES.has(entry.name) ? "cache" : "folder" });
|
|
1823
|
-
if (entry.name === "node_modules") {
|
|
1824
|
-
const cache = (await listing(path)).find((inner) => inner.name === ".cache");
|
|
1825
|
-
if (cache?.isSymbolicLink())
|
|
1826
|
-
found.skipped.push({ path: join8(path, ".cache"), reason: "symlink" });
|
|
1827
|
-
else if (cache?.isDirectory())
|
|
1828
|
-
found.candidates.push({ path: join8(path, ".cache"), kind: "cache", inside: path });
|
|
1829
|
-
}
|
|
1830
|
-
}
|
|
1831
|
-
continue;
|
|
1832
|
-
}
|
|
1833
|
-
if (entry.isDirectory() && depth < MAX_DEPTH)
|
|
1834
|
-
await visit(path, depth + 1);
|
|
1835
|
-
}
|
|
1836
|
-
};
|
|
1837
|
-
await visit(root, 0);
|
|
1838
|
-
if (withGlobal)
|
|
1839
|
-
await addGlobalCaches(found, home);
|
|
1840
|
-
return found;
|
|
1841
|
-
}
|
|
1842
|
-
async function realOf(path) {
|
|
1843
|
-
try {
|
|
1844
|
-
return await realpath(path);
|
|
1845
|
-
} catch {
|
|
1846
|
-
return;
|
|
1847
|
-
}
|
|
1848
|
-
}
|
|
1849
|
-
var HEADS_PREFIX = /^refs\/heads\//;
|
|
1850
|
-
var TRAILING_SLASH = /\/$/;
|
|
1851
|
-
async function gitIn(cwd, args) {
|
|
1852
|
-
try {
|
|
1853
|
-
const { code, stdout, stderr } = await runTool(`git ${args.join(" ")}`, ["git", "-C", cwd, ...args], { timeoutMs: 30000 });
|
|
1854
|
-
return { code, stdout: stdout.trim(), stderr };
|
|
1855
|
-
} catch (error) {
|
|
1856
|
-
return { code: -1, stdout: "", stderr: String(error) };
|
|
1857
|
-
}
|
|
1858
|
-
}
|
|
1859
|
-
function memo(make) {
|
|
1860
|
-
const cache = new Map;
|
|
1861
|
-
return async (key) => {
|
|
1862
|
-
let value = cache.get(key);
|
|
1863
|
-
if (value === undefined) {
|
|
1864
|
-
value = make(key);
|
|
1865
|
-
cache.set(key, value);
|
|
1866
|
-
}
|
|
1867
|
-
return value;
|
|
1868
|
-
};
|
|
1869
|
-
}
|
|
1870
|
-
var NOT_A_REPO = /not a git repository/i;
|
|
1871
|
-
var toplevelOf = memo(async (dir) => {
|
|
1872
|
-
const { code, stdout, stderr } = await gitIn(dir, ["rev-parse", "--show-toplevel"]);
|
|
1873
|
-
if (code === 0 && stdout !== "")
|
|
1874
|
-
return { top: stdout };
|
|
1875
|
-
return NOT_A_REPO.test(stderr) ? "none" : "failed";
|
|
1876
|
-
});
|
|
1877
|
-
var lastCommitOf = memo(async (top) => {
|
|
1878
|
-
const { code, stdout } = await gitIn(top, ["log", "-1", "--format=%ct"]);
|
|
1879
|
-
return code === 0 && stdout !== "" ? Number(stdout) * 1000 : undefined;
|
|
1880
|
-
});
|
|
1881
|
-
var worktreesOf = memo(async (repo) => {
|
|
1882
|
-
const { code, stdout } = await gitIn(repo, ["worktree", "list", "--porcelain"]);
|
|
1883
|
-
const branches = new Map;
|
|
1884
|
-
if (code !== 0)
|
|
1885
|
-
return branches;
|
|
1886
|
-
for (const block of stdout.split(`
|
|
1887
|
-
|
|
1888
|
-
`)) {
|
|
1889
|
-
const lines = block.split(`
|
|
1890
|
-
`);
|
|
1891
|
-
const path = lines.find((line) => line.startsWith("worktree "))?.slice("worktree ".length);
|
|
1892
|
-
const branch = lines.find((line) => line.startsWith("branch "))?.slice("branch ".length);
|
|
1893
|
-
if (path !== undefined)
|
|
1894
|
-
branches.set(await realOf(path) ?? path, branch);
|
|
1895
|
-
}
|
|
1896
|
-
return branches;
|
|
1897
|
-
});
|
|
1898
|
-
async function judgeFolder(path, kind, inside) {
|
|
1899
|
-
const parent = dirname5(path);
|
|
1900
|
-
const name = basename(path);
|
|
1901
|
-
const located = await toplevelOf(parent);
|
|
1902
|
-
if (located === "failed")
|
|
1903
|
-
return { skip: "git failed" };
|
|
1904
|
-
if (existsSync4(join8(path, ".git")))
|
|
1905
|
-
return { skip: "holds a git repository" };
|
|
1906
|
-
if (located === "none")
|
|
1907
|
-
return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside } } : { skip: "not in a git repository" };
|
|
1908
|
-
const tracked = await gitIn(parent, ["ls-files", "--", name]);
|
|
1909
|
-
if (tracked.code !== 0 || tracked.stdout !== "")
|
|
1910
|
-
return { skip: "tracked by git" };
|
|
1911
|
-
if (name !== "node_modules" && inside === undefined && (await gitIn(parent, ["check-ignore", "-q", "--", name])).code !== 0)
|
|
1912
|
-
return { skip: "not ignored by git" };
|
|
1913
|
-
return { entry: { path, kind, committedAt: await lastCommitOf(located.top), action: "remove", inside } };
|
|
1914
|
-
}
|
|
1915
|
-
async function judgeWorktree(path) {
|
|
1916
|
-
const located = await toplevelOf(dirname5(path));
|
|
1917
|
-
if (located === "failed")
|
|
1918
|
-
return { skip: "git failed" };
|
|
1919
|
-
if (located === "none")
|
|
1920
|
-
return { skip: "not in a git repository" };
|
|
1921
|
-
const { top } = located;
|
|
1922
|
-
const real = await realOf(path);
|
|
1923
|
-
const branches = await worktreesOf(top);
|
|
1924
|
-
if (real === undefined || !branches.has(real))
|
|
1925
|
-
return { skip: "not a worktree of this repo" };
|
|
1926
|
-
const committedAt = await lastCommitOf(top);
|
|
1927
|
-
const keep = (reason) => ({ entry: { path, kind: "worktree", committedAt, action: "keep", reason, repo: top } });
|
|
1928
|
-
const branch = branches.get(real);
|
|
1929
|
-
if (branch === undefined)
|
|
1930
|
-
return keep("detached HEAD");
|
|
1931
|
-
const status = await gitIn(path, ["status", "--porcelain", "-z", "--ignored=matching"]);
|
|
1932
|
-
if (status.code !== 0)
|
|
1933
|
-
return keep("status failed");
|
|
1934
|
-
const changes = status.stdout.split("\x00").filter((line) => line !== "");
|
|
1935
|
-
if (changes.some((line) => !line.startsWith("!! ")))
|
|
1936
|
-
return keep("uncommitted changes");
|
|
1937
|
-
if (changes.some((line) => !line.endsWith("/") || !FOLDER_NAMES.has(basename(line.slice(3).replace(TRAILING_SLASH, "")))))
|
|
1938
|
-
return keep("ignored files (.env, local data) that removing would delete");
|
|
1939
|
-
const unique = await gitIn(path, ["log", "--format=%h", branch, "--not", "--remotes", `--exclude=${branch.replace(HEADS_PREFIX, "")}`, "--branches"]);
|
|
1940
|
-
if (unique.code !== 0)
|
|
1941
|
-
return keep("log failed");
|
|
1942
|
-
if (unique.stdout !== "")
|
|
1943
|
-
return keep(`${unique.stdout.split(`
|
|
1944
|
-
`).length} commits on no other branch or remote`);
|
|
1945
|
-
return { entry: { path, kind: "worktree", committedAt, action: "remove", repo: top } };
|
|
1946
|
-
}
|
|
1947
|
-
async function judge(candidate) {
|
|
1948
|
-
if (candidate.global === true)
|
|
1949
|
-
return { entry: { path: candidate.path, kind: candidate.kind, committedAt: undefined, action: "remove" } };
|
|
1950
|
-
return candidate.kind === "worktree" ? judgeWorktree(candidate.path) : judgeFolder(candidate.path, candidate.kind, candidate.inside);
|
|
1951
|
-
}
|
|
1952
|
-
async function inspect({ candidates, skipped }) {
|
|
1953
|
-
const entries = [];
|
|
1954
|
-
const rejected = [...skipped];
|
|
1955
|
-
await pool(candidates, 8, async (candidate) => {
|
|
1956
|
-
const verdict = await judge(candidate);
|
|
1957
|
-
if ("skip" in verdict)
|
|
1958
|
-
rejected.push({ path: candidate.path, reason: verdict.skip });
|
|
1959
|
-
else
|
|
1960
|
-
entries.push({ ...verdict.entry, bytes: await sizeOf(candidate.path) });
|
|
1961
|
-
});
|
|
1962
|
-
const listed = new Set(entries.filter((entry) => entry.action === "remove").map((entry) => entry.path));
|
|
1963
|
-
return { entries: entries.filter((entry) => entry.inside === undefined || !listed.has(entry.inside)), skipped: rejected };
|
|
1964
|
-
}
|
|
1965
|
-
|
|
1966
|
-
// src/apply.ts
|
|
1967
|
-
async function removeFolder(entry) {
|
|
1968
|
-
try {
|
|
1969
|
-
const stat = await lstat3(entry.path);
|
|
1970
|
-
if (stat.isSymbolicLink() || !stat.isDirectory() || !(FOLDER_NAMES.has(basename2(entry.path)) || entry.kind === "cache" && isCachePath(entry.path)))
|
|
1971
|
-
return { path: entry.path, removed: false, error: "no longer a plain folder" };
|
|
1972
|
-
if (existsSync5(join9(entry.path, ".git")))
|
|
1973
|
-
return { path: entry.path, removed: false, error: "holds a git repository" };
|
|
1974
|
-
await rm(entry.path, { recursive: true, force: true });
|
|
1975
|
-
return { path: entry.path, removed: true };
|
|
1976
|
-
} catch (error) {
|
|
1977
|
-
return { path: entry.path, removed: false, error: error instanceof Error ? error.message : String(error) };
|
|
1978
|
-
}
|
|
1979
|
-
}
|
|
1980
|
-
async function removeWorktree(entry) {
|
|
1981
|
-
if (entry.repo === undefined)
|
|
1982
|
-
return { path: entry.path, removed: false, error: "no repository known" };
|
|
1983
|
-
try {
|
|
1984
|
-
const ran = await runTool("git worktree remove", ["git", "-C", entry.repo, "worktree", "remove", entry.path]);
|
|
1985
|
-
return ran.code === 0 ? { path: entry.path, removed: true } : { path: entry.path, removed: false, error: ran.stderr.trim() };
|
|
1986
|
-
} catch (error) {
|
|
1987
|
-
return { path: entry.path, removed: false, error: String(error) };
|
|
1988
|
-
}
|
|
1989
|
-
}
|
|
1990
|
-
async function applyAll(entries, done) {
|
|
1991
|
-
const outcomes = [];
|
|
1992
|
-
for (const entry of entries) {
|
|
1993
|
-
if (entry.action !== "remove")
|
|
1994
|
-
continue;
|
|
1995
|
-
const outcome = await (entry.kind === "worktree" ? removeWorktree(entry) : removeFolder(entry));
|
|
1996
|
-
outcomes.push(outcome);
|
|
1997
|
-
done(outcome);
|
|
1998
|
-
}
|
|
1999
|
-
return outcomes;
|
|
2000
|
-
}
|
|
2001
|
-
|
|
2002
|
-
// src/sweep.ts
|
|
2003
|
-
var LARGE = 100 * 1024 ** 2;
|
|
2004
|
-
var BIG = 1024 ** 3;
|
|
2005
|
-
var USAGE = `sweep [options] [root]: lists the regenerable folders (node_modules, .output, dist, build, .venv, target beside a Cargo.toml, vendor beside a composer.json or composer.lock), the caches (.nuxt, .next, .turbo, .svelte-kit, __pycache__, .gradle and node_modules/.cache per project; ~/.bun/install/cache, ~/.npm/_cacache, ~/.cache/{pip,uv,ms-playwright,puppeteer,go-build,typescript} and ~/.cargo/registry, exact paths only, listed only when no root is given or with --only caches) and the .worktrees/* and .claude/worktrees/* entries under root (the configured workspace, ~/Workspace by default, ${MAX_DEPTH} levels down), largest first with the age of the repo's last commit; --only worktrees, folders or caches keeps one kind
|
|
2006
|
-
|
|
2007
|
-
Dry unless --apply, which deletes after a confirm showing the total (read from the terminal; off one, pass --yes). A folder is deleted for good, not trashed. Never touched: a symlink, a folder git tracks files in, a build folder git does not ignore. A worktree is removed with git worktree remove, never forced, and only when it is clean and every commit of its branch is on another branch or a remote; the others stay listed as kept and count for nothing in the total. With --docker the Docker usage comes after the list, left to dclean.`;
|
|
2008
|
-
var EXITS = [[0, "it listed, or removed every entry it was allowed to"], [1, "a removal failed or the confirm was declined"], [2, "a usage error, a missing root, or --apply off a terminal without --yes"]];
|
|
2009
|
-
var ONLY_KINDS = { worktrees: "worktree", folders: "folder", caches: "cache" };
|
|
2010
|
-
var OPTIONS = {
|
|
2011
|
-
apply: { type: "boolean", description: "delete what is listed as removable, after the confirm" },
|
|
2012
|
-
yes: { type: "boolean", short: "y", description: "with --apply, skip the confirm" },
|
|
2013
|
-
older: { type: "string", description: "only the entries whose repo last committed longer ago than this (30d, 12h)" },
|
|
2014
|
-
min: { type: "string", description: "only the entries of at least this size (500K, 10M, 1G)" },
|
|
2015
|
-
only: { type: "string", description: "worktrees, folders or caches: leave the other kinds out (.nuxt, .next, .turbo, .svelte-kit, __pycache__ and .gradle are caches; the global caches are listed with no root or with caches)" },
|
|
2016
|
-
docker: { type: "boolean", description: "add the docker system df output, which alone takes about ten seconds" },
|
|
2017
|
-
json: jsonOption("{root, entries: [{path, kind (folder, worktree or cache), bytes, committedAt, action (remove or keep), reason}], skipped: [{path, reason}], reclaimable, docker, removed?}")
|
|
2018
|
-
};
|
|
2019
|
-
async function dockerUsage() {
|
|
2020
|
-
if (Bun.which("docker") === null)
|
|
2021
|
-
return;
|
|
2022
|
-
try {
|
|
2023
|
-
const { code, stdout } = await runTool("docker system df", ["docker", "system", "df"], { timeoutMs: 1e4 });
|
|
2024
|
-
return code === 0 ? stdout.trimEnd() : undefined;
|
|
2025
|
-
} catch {
|
|
2026
|
-
return;
|
|
2027
|
-
}
|
|
2028
|
-
}
|
|
2029
|
-
async function sweep(args) {
|
|
2030
|
-
const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, positionals: ["[root]"], replaces: "find ~/Workspace -name node_modules, du -sh and rm -rf by hand", examples: ["sweep", "sweep ~/Workspace --older 30d --min 100M --apply", "sweep --only worktrees --apply"] });
|
|
2031
|
-
if (positionals.length > 1)
|
|
2032
|
-
badUsage("give one root");
|
|
2033
|
-
const root = workspaceRoot({ given: positionals[0] });
|
|
2034
|
-
if (!existsSync6(root) || !statSync2(root).isDirectory())
|
|
2035
|
-
fail(`${root} is not a folder`);
|
|
2036
|
-
if (values.only !== undefined && !Object.hasOwn(ONLY_KINDS, values.only))
|
|
2037
|
-
badUsage(`--only takes worktrees, folders or caches, not ${values.only}`);
|
|
2038
|
-
const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0);
|
|
2039
|
-
const minBytes = values.min === undefined ? 0 : parseSize(values.min);
|
|
2040
|
-
if (minBytes === undefined)
|
|
2041
|
-
badUsage(`--min takes a size such as 500K, 10M or 1G, not ${values.min}`);
|
|
2042
|
-
const now = Date.now();
|
|
2043
|
-
const found = await findCandidates(root, homedir6(), positionals.length === 0 || values.only === "caches");
|
|
2044
|
-
const wanted = values.only === undefined ? found.candidates : found.candidates.filter((candidate) => candidate.kind === ONLY_KINDS[values.only]);
|
|
2045
|
-
const { entries: all, skipped } = await inspect({ candidates: wanted, skipped: found.skipped });
|
|
2046
|
-
const entries = all.filter((entry) => entry.bytes >= minBytes && (olderMs === undefined || entry.committedAt !== undefined && now - entry.committedAt >= olderMs)).sort((a, b) => b.bytes - a.bytes || a.path.localeCompare(b.path));
|
|
2047
|
-
const removable = entries.filter((entry) => entry.action === "remove");
|
|
2048
|
-
const reclaimable = removable.reduce((sum, entry) => sum + entry.bytes, 0);
|
|
2049
|
-
const docker = values.docker === true ? await dockerUsage() : undefined;
|
|
2050
|
-
const json = values.json === true;
|
|
2051
|
-
if (values.apply === true && removable.length > 0 && values.yes !== true) {
|
|
2052
|
-
if (!json)
|
|
2053
|
-
print(root, entries, skipped.length, reclaimable, now);
|
|
2054
|
-
const agreed = await confirm(`Delete ${removable.length} ${removable.length === 1 ? "entry" : "entries"} (${tt(reclaimable)})?`, { default: false, hint: "pass --yes to skip the confirm" });
|
|
2055
|
-
if (agreed !== true) {
|
|
2056
|
-
if (json)
|
|
2057
|
-
fail("nothing deleted: the confirm was declined", 1, "pass --yes to skip the confirm");
|
|
2058
|
-
note("nothing deleted");
|
|
2059
|
-
return 1;
|
|
2060
|
-
}
|
|
2061
|
-
}
|
|
2062
|
-
const outcomes = values.apply === true ? await applyAll(removable, (outcome) => report2(root, outcome, json)) : undefined;
|
|
2063
|
-
const failed = outcomes?.filter((outcome) => !outcome.removed).length ?? 0;
|
|
2064
|
-
if (json) {
|
|
2065
|
-
printJson({ root, entries: entries.map((entry) => ({ path: entry.path, kind: entry.kind, bytes: entry.bytes, committedAt: entry.committedAt === undefined ? null : new Date(entry.committedAt).toISOString(), action: entry.action, reason: entry.reason ?? null })), skipped, reclaimable, docker: docker ?? null, ...outcomes === undefined ? {} : { removed: outcomes } });
|
|
2066
|
-
return failed === 0 ? 0 : 1;
|
|
2067
|
-
}
|
|
2068
|
-
if (outcomes === undefined) {
|
|
2069
|
-
print(root, entries, skipped.length, reclaimable, now);
|
|
2070
|
-
if (removable.length > 0)
|
|
2071
|
-
console.log("dry run, pass --apply to delete");
|
|
2072
|
-
} else {
|
|
2073
|
-
const bytes = new Map(removable.map((entry) => [entry.path, entry.bytes]));
|
|
2074
|
-
note(`freed ${tt(outcomes.reduce((sum, outcome) => sum + (outcome.removed ? bytes.get(outcome.path) ?? 0 : 0), 0))}`);
|
|
2075
|
-
}
|
|
2076
|
-
if (docker !== undefined)
|
|
2077
|
-
console.log(`
|
|
2078
|
-
docker (left to dclean):
|
|
2079
|
-
${docker}`);
|
|
2080
|
-
return failed === 0 ? 0 : 1;
|
|
2081
|
-
}
|
|
2082
|
-
function report2(root, outcome, json) {
|
|
2083
|
-
if (json)
|
|
2084
|
-
return;
|
|
2085
|
-
if (outcome.removed)
|
|
2086
|
-
ok(`removed ${relative(root, outcome.path)}`);
|
|
2087
|
-
else
|
|
2088
|
-
problem(`kept ${relative(root, outcome.path)}`, outcome.error);
|
|
2089
|
-
}
|
|
2090
|
-
function print(root, entries, skipped, reclaimable, now) {
|
|
2091
|
-
if (entries.length === 0) {
|
|
2092
|
-
console.log("nothing to sweep");
|
|
2093
|
-
return;
|
|
2094
|
-
}
|
|
2095
|
-
const colors = paint(process.stdout);
|
|
2096
|
-
const path = role("path", process.stdout);
|
|
2097
|
-
const sized = (bytes) => {
|
|
2098
|
-
if (bytes >= BIG)
|
|
2099
|
-
return colors.red(tt(bytes));
|
|
2100
|
-
return bytes >= LARGE ? colors.yellow(tt(bytes)) : tt(bytes);
|
|
2101
|
-
};
|
|
2102
|
-
console.log(table([["size", "age", "what", "path", "note"], ...entries.map((entry) => [sized(entry.bytes), entry.committedAt === undefined ? colors.dim("-") : colors.dim(formatAge(entry.committedAt, now)), entry.kind, path(relative(root, entry.path)), entry.action === "keep" ? colors.dim(`kept: ${entry.reason}`) : ""])], { header: true, align: ["right", "right", "left", "left", "left"] }));
|
|
2103
|
-
console.log(`
|
|
2104
|
-
${tt(reclaimable)} reclaimable${skipped === 0 ? "" : `, ${skipped} skipped (symlinks, tracked or not ignored by git)`}`);
|
|
2105
|
-
}
|
|
2106
|
-
|
|
2107
|
-
// src/sweep-cli.ts
|
|
2108
|
-
process21.exitCode = await runMain({ name: "sweep", run: sweep });
|