@kaynooo/cli-guard 0.0.0-stage → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +3600 -0
  4. package/package.json +45 -4
package/dist/cli.js ADDED
@@ -0,0 +1,3600 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/cli.ts
5
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "fs";
6
+ import { homedir } from "os";
7
+ import { dirname } from "path";
8
+ import process7 from "process";
9
+
10
+ // ../kit/src/args.ts
11
+ import process3 from "process";
12
+ import { parseArgs } from "util";
13
+
14
+ // ../kit/src/style.ts
15
+ import process2 from "process";
16
+
17
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
+ function x(s) {
19
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
+ if (!/^[a-f0-9]+$/.test(r))
21
+ return [0, 0, 0];
22
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
23
+ if (t === 3 || t === 4) {
24
+ let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
25
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
26
+ }
27
+ if (t !== 6 && t !== 8)
28
+ throw Error(`Invalid hex color length: ${t}`);
29
+ let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
30
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
31
+ throw Error(`Invalid hex color value: ${s}`);
32
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
33
+ }
34
+ function A(s) {
35
+ let [r, t, n, a] = s;
36
+ if (a)
37
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
38
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
39
+ }
40
+ function R(s, r, t) {
41
+ s = (s % 360 + 360) % 360, t /= 100;
42
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
43
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
44
+ return Math.round(255 * y);
45
+ };
46
+ return [a(0), a(8), a(4)];
47
+ }
48
+ function k(s) {
49
+ let [r, t, n] = s;
50
+ r /= 255, t /= 255, n /= 255;
51
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
52
+ if (a !== b) {
53
+ let u = a - b;
54
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
55
+ o = (t - n) / u + (t < n ? 6 : 0);
56
+ else if (a === t)
57
+ o = (n - r) / u + 2;
58
+ else
59
+ o = (r - t) / u + 4;
60
+ o /= 6;
61
+ }
62
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
63
+ }
64
+ function H(s, r, t) {
65
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
66
+ let n = (a) => {
67
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
68
+ return Math.round(255 * o);
69
+ };
70
+ return [n(5), n(3), n(1)];
71
+ }
72
+ function f(s) {
73
+ let [r, t, n] = s;
74
+ r /= 255, t /= 255, n /= 255;
75
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
76
+ if (o !== 0) {
77
+ if (a === r)
78
+ y = (t - n) / o + (t < n ? 6 : 0);
79
+ else if (a === t)
80
+ y = (n - r) / o + 2;
81
+ else
82
+ y = (r - t) / o + 4;
83
+ y /= 6;
84
+ }
85
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
86
+ }
87
+ function O(s) {
88
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
89
+ if (a === 1)
90
+ return [0, 0, 0, 100];
91
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
92
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
93
+ }
94
+ function v(s, r, t, n) {
95
+ return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
96
+ }
97
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
98
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
99
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
100
+ function T(s) {
101
+ let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
102
+ return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
103
+ }
104
+ function M(s, r, t) {
105
+ let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
106
+ return [u(o), u(y), u(c)];
107
+ }
108
+ function d(s) {
109
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
110
+ return [i(r, 4), i(a, 4), i(b, 2)];
111
+ }
112
+ function C(s, r, t) {
113
+ let n = t * Math.PI / 180;
114
+ return M(s, r * Math.cos(n), r * Math.sin(n));
115
+ }
116
+ function l(s) {
117
+ let r = s / 255;
118
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
119
+ }
120
+
121
+ class e {
122
+ r;
123
+ g;
124
+ b;
125
+ a;
126
+ constructor(s, r, t, n = 1) {
127
+ this.r = s, this.g = r, this.b = t, this.a = n;
128
+ }
129
+ static from(s, r) {
130
+ if (s === "hex") {
131
+ let [t, n, a, b] = x(r);
132
+ return new e(t, n, a, b);
133
+ }
134
+ if (s === "rgb") {
135
+ if (Array.isArray(r)) {
136
+ let [o, y, c, u] = r;
137
+ return new e(o, y, c, u);
138
+ }
139
+ let { r: t, g: n, b: a, a: b } = r;
140
+ return new e(t, n, a, b);
141
+ }
142
+ if (s === "hsl") {
143
+ let t, n, a, b;
144
+ if (Array.isArray(r))
145
+ [t, n, a, b] = r;
146
+ else
147
+ ({ h: t, s: n, l: a, a: b } = r);
148
+ let [o, y, c] = R(t, n, a);
149
+ return new e(o, y, c, b);
150
+ }
151
+ if (s === "hsv") {
152
+ let t, n, a, b;
153
+ if (Array.isArray(r))
154
+ [t, n, a, b] = r;
155
+ else
156
+ ({ h: t, s: n, v: a, a: b } = r);
157
+ let [o, y, c] = H(t, n, a);
158
+ return new e(o, y, c, b);
159
+ }
160
+ if (s === "cmyk") {
161
+ let t, n, a, b, o;
162
+ if (Array.isArray(r))
163
+ [t, n, a, b, o] = r;
164
+ else
165
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
166
+ let [y, c, u] = v(t, n, a, b);
167
+ return new e(y, c, u, o);
168
+ }
169
+ if (s === "oklch") {
170
+ let t, n, a, b;
171
+ if (Array.isArray(r))
172
+ [t, n, a, b] = r;
173
+ else
174
+ ({ l: t, c: n, h: a, a: b } = r);
175
+ let [o, y, c] = C(t, n, a);
176
+ return new e(o, y, c, b);
177
+ }
178
+ if (s === "oklab") {
179
+ let t, n, a, b;
180
+ if (Array.isArray(r))
181
+ [t, n, a, b] = r;
182
+ else
183
+ ({ l: t, a: n, b: a, alpha: b } = r);
184
+ let [o, y, c] = M(t, n, a);
185
+ return new e(o, y, c, b);
186
+ }
187
+ throw Error("Invalid input");
188
+ }
189
+ to(s) {
190
+ switch (s) {
191
+ case "rgb":
192
+ return [this.r, this.g, this.b];
193
+ case "rgba":
194
+ return [this.r, this.g, this.b, this.a];
195
+ case "hex":
196
+ return A([this.r, this.g, this.b]);
197
+ case "hexa":
198
+ return A([this.r, this.g, this.b, this.a]);
199
+ case "hsl":
200
+ return k([this.r, this.g, this.b]);
201
+ case "hsla":
202
+ return [...k([this.r, this.g, this.b]), this.a];
203
+ case "hsv":
204
+ return f([this.r, this.g, this.b]);
205
+ case "hsva":
206
+ return [...f([this.r, this.g, this.b]), this.a];
207
+ case "cmyk":
208
+ return O([this.r, this.g, this.b]);
209
+ case "cmyka":
210
+ return [...O([this.r, this.g, this.b]), this.a];
211
+ case "oklch":
212
+ return d([this.r, this.g, this.b]);
213
+ case "oklcha":
214
+ return [...d([this.r, this.g, this.b]), this.a];
215
+ case "oklab":
216
+ return T([this.r, this.g, this.b]);
217
+ case "oklaba":
218
+ return [...T([this.r, this.g, this.b]), this.a];
219
+ default:
220
+ return [this.r, this.g, this.b];
221
+ }
222
+ }
223
+ getLuminance() {
224
+ let s = l(this.r), r = l(this.g), t = l(this.b);
225
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
226
+ }
227
+ contrastRatio(s) {
228
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
229
+ return (n + 0.05) / (a + 0.05);
230
+ }
231
+ bestContrastForeground() {
232
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
233
+ return t >= n ? s : r;
234
+ }
235
+ }
236
+
237
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
+ var r = 39;
239
+ var o = 49;
240
+ var f2 = "\x1B[";
241
+ var C2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
242
+ let [a, l, s] = e.from("hex", i).to("rgb");
243
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
244
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
245
+ var b = new Set(["", "1", "2", "3", "true"]);
246
+ function h(i, n = globalThis.process?.env ?? {}) {
247
+ if (n.FORCE_COLOR !== undefined)
248
+ return b.has(n.FORCE_COLOR);
249
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
250
+ return false;
251
+ return i?.isTTY === true;
252
+ }
253
+ function d2(i, n, a) {
254
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
255
+ return n;
256
+ let l = "", s = "";
257
+ for (let g = 0, y = i.length;g < y; g++) {
258
+ let [c, p] = i[g];
259
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
260
+ }
261
+ return l + n + s;
262
+ }
263
+ function u(i, n = []) {
264
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
265
+ let g = C2[s];
266
+ if (Array.isArray(g))
267
+ return u(i, [...n, g]);
268
+ if (typeof g === "function")
269
+ return (...y) => u(i, [...n, g(...y)]);
270
+ throw Error(`Unknown style: ${String(s)}`);
271
+ } });
272
+ }
273
+ function le(i = {}) {
274
+ return u(i);
275
+ }
276
+ var t = le();
277
+
278
+ // ../kit/src/style.ts
279
+ function takesControlCodes(stream, env = process2.env) {
280
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
281
+ }
282
+ function paint(stream, env = process2.env) {
283
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
284
+ }
285
+ var STATUSES = {
286
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
287
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
288
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
289
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
290
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
291
+ };
292
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
293
+
294
+ // ../kit/src/format.ts
295
+ function upTo(text, separator) {
296
+ const end = text.indexOf(separator);
297
+ return end === -1 ? text : text.slice(0, end);
298
+ }
299
+ var ESCAPE = String.fromCharCode(27);
300
+
301
+ // ../kit/src/text.ts
302
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
303
+ function distance(a, b) {
304
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
305
+ for (const [i, left] of [...a].entries()) {
306
+ const current = [i + 1];
307
+ for (const [j, right] of [...b].entries())
308
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
309
+ previous = current;
310
+ }
311
+ return previous[b.length] ?? 0;
312
+ }
313
+ function closest(name, names) {
314
+ const started = names.find((known) => known.startsWith(name));
315
+ if (started !== undefined)
316
+ return started;
317
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
318
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
319
+ }
320
+
321
+ // ../kit/src/args.ts
322
+ function jsonOption(holds) {
323
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
324
+ }
325
+
326
+ class Exit extends Error {
327
+ code;
328
+ hint;
329
+ constructor(message, code, hint) {
330
+ super(message);
331
+ this.code = code;
332
+ this.hint = hint;
333
+ }
334
+ }
335
+ function fail(message, code = 2, hint) {
336
+ throw new Exit(message, code, hint);
337
+ }
338
+
339
+ class UsageError extends Exit {
340
+ constructor(message, hint) {
341
+ super(message, 2, hint);
342
+ }
343
+ }
344
+ function badUsage(message) {
345
+ throw new UsageError(message);
346
+ }
347
+
348
+ class HelpShown extends Exit {
349
+ constructor() {
350
+ super("help shown", 0);
351
+ }
352
+ }
353
+
354
+ class Completing {
355
+ options;
356
+ positionals;
357
+ candidates;
358
+ constructor(options, positionals = [], candidates = {}) {
359
+ this.options = options;
360
+ this.positionals = positionals;
361
+ this.candidates = candidates;
362
+ }
363
+ }
364
+ var completion = { active: false };
365
+ var OPTIONAL = /\[[^\]]+\]/g;
366
+ var USAGE_PREFIX = /^usage:\s*/i;
367
+ var FULL_STOP = /\.$/;
368
+ var DASHES = /^-+/;
369
+ function usageLine(usage, colors = paint(process3.stdout)) {
370
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
371
+ }
372
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
373
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
374
+ `);
375
+ }
376
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
377
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
378
+ }
379
+ function wantsHelpJson(env = process3.env) {
380
+ return env.KIT_HELP === "json";
381
+ }
382
+ function description(usage, { examples = [], replaces } = {}) {
383
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
384
+ `);
385
+ const first = lines[0];
386
+ const colon = first.indexOf(": ");
387
+ const prose = lines[lines.indexOf("") + 1] ?? "";
388
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
389
+ return {
390
+ synopsis: colon === -1 ? first : first.slice(0, colon),
391
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
392
+ ...replaces === undefined ? {} : { replaces },
393
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
394
+ };
395
+ }
396
+ function exampleRows(examples, colors = paint(process3.stdout)) {
397
+ if (examples.length === 0)
398
+ return [];
399
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
400
+ }
401
+ function optionRows(options, colors = paint(process3.stdout)) {
402
+ const rows = Object.entries(options).map(([name, option]) => {
403
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
404
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
405
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
406
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
407
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
408
+ });
409
+ const width = Math.max(0, ...rows.map((row) => row.width));
410
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
411
+ }
412
+ var OUTPUT_OPTIONS = {
413
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
414
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
415
+ };
416
+ function applyOutput(color, plain, env = process3.env) {
417
+ const when = plain === true ? "never" : color ?? "auto";
418
+ if (when === "auto")
419
+ return;
420
+ if (when !== "always" && when !== "never")
421
+ badUsage(`--color takes auto, always or never, not ${when}`);
422
+ if (when === "always") {
423
+ env.FORCE_COLOR = "1";
424
+ delete env.NO_COLOR;
425
+ } else {
426
+ env.NO_COLOR = "1";
427
+ delete env.FORCE_COLOR;
428
+ }
429
+ }
430
+ function parse(args, usage, options, settings = {}) {
431
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
432
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
433
+ const listing = listed(all, settings.allowNegative === true);
434
+ if (completion.active)
435
+ throw new Completing(listing, settings.positionals, settings.candidates);
436
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
437
+ let parsed;
438
+ try {
439
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
440
+ } catch (error) {
441
+ const message = parseError(error);
442
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
443
+ }
444
+ const values = parsed.values;
445
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
446
+ if (values.help === true) {
447
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
448
+ throw new HelpShown;
449
+ }
450
+ checkChoices(parsed.values, all);
451
+ checkConflicts(parsed.values, all);
452
+ if (settings.positionals !== undefined)
453
+ checkPositionals(parsed.positionals, settings.positionals);
454
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
455
+ }
456
+ function splitRest(args, passes) {
457
+ const separator = passes ? args.indexOf("--") : -1;
458
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
459
+ }
460
+ function splitTrailing(args, options, count) {
461
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
462
+ let seen = 0;
463
+ if (count === 0)
464
+ return { own: args, rest: undefined };
465
+ for (let at = 0;at < args.length; at++) {
466
+ const word = args[at];
467
+ if (word === "--")
468
+ break;
469
+ if (word.startsWith("-")) {
470
+ if (takesValue(word))
471
+ at++;
472
+ continue;
473
+ }
474
+ seen++;
475
+ if (seen === count)
476
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
477
+ }
478
+ return { own: args, rest: undefined };
479
+ }
480
+ function listed(options, allowNegative) {
481
+ if (!allowNegative)
482
+ return options;
483
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
484
+ if (option.type !== "boolean" || option.negative === undefined)
485
+ return [[name, option]];
486
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
487
+ }));
488
+ }
489
+ function withBare(args, options) {
490
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
491
+ if (bare.size === 0)
492
+ return args;
493
+ const separator = args.indexOf("--");
494
+ const own = separator === -1 ? args : args.slice(0, separator);
495
+ return [...own.flatMap((arg, index) => {
496
+ const optional = bare.get(arg);
497
+ const next = own[index + 1];
498
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
499
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
500
+ }), ...separator === -1 ? [] : args.slice(separator)];
501
+ }
502
+ function checkConflicts(values, options) {
503
+ const given = (name) => values[name] !== undefined && values[name] !== false;
504
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
505
+ const other = given(name) ? conflicts.find(given) : undefined;
506
+ if (other !== undefined)
507
+ badUsage(`--${name} cannot be used with --${other}`);
508
+ }
509
+ }
510
+ function checkChoices(values, options) {
511
+ for (const [name, option] of Object.entries(options)) {
512
+ if (option.choices === undefined)
513
+ continue;
514
+ const given = values[name];
515
+ for (const value of Array.isArray(given) ? given : [given]) {
516
+ if (typeof value === "string")
517
+ oneOf(value, name, option.choices);
518
+ }
519
+ }
520
+ }
521
+ function oneOf(value, name, choices) {
522
+ if (!choices.includes(value))
523
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
524
+ return value;
525
+ }
526
+ function checkPositionals(given, names) {
527
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
528
+ const required = names.filter((name) => !name.startsWith("[")).length;
529
+ if (given.length < required)
530
+ badUsage(`missing ${names[given.length]}`);
531
+ if (!variadic && given.length > names.length)
532
+ badUsage(`unexpected argument ${given[names.length]}`);
533
+ }
534
+ function joinDashValues(args, options) {
535
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
536
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
537
+ const joined = [];
538
+ for (let i = 0;i < args.length; i++) {
539
+ const arg = args[i] ?? "";
540
+ if (arg === "--")
541
+ return [...joined, ...args.slice(i)];
542
+ const name = longOf.get(arg);
543
+ const next = args[i + 1];
544
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
545
+ joined.push(`--${name}=${next}`);
546
+ i++;
547
+ } else {
548
+ joined.push(arg);
549
+ }
550
+ }
551
+ return joined;
552
+ }
553
+ function parseError(error) {
554
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
555
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
556
+ }
557
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
558
+ function nearestOption(message, options, allowNegative) {
559
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
560
+ if (typed === undefined)
561
+ return;
562
+ const word = typed.replace(DASHES, "");
563
+ if (word.length < 2 && !typed.startsWith("--"))
564
+ return;
565
+ const known = Object.entries(options).flatMap(([name, option]) => [
566
+ ...option.short === undefined ? [] : [`-${option.short}`],
567
+ `--${name}`,
568
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
569
+ ]);
570
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
571
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
572
+ }
573
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
574
+ if (path === "-") {
575
+ if (process3.stdin.isTTY)
576
+ fail(noStdin);
577
+ return Bun.stdin.text();
578
+ }
579
+ const file = Bun.file(path);
580
+ if (!await file.exists())
581
+ fail(`no file ${path}`);
582
+ return file.text();
583
+ }
584
+ // ../kit/src/process.ts
585
+ import { constants } from "os";
586
+ import process4 from "process";
587
+ var KILL_GRACE_MS = 2000;
588
+ function exitCodeOf(code, signal) {
589
+ if (code !== null)
590
+ return code;
591
+ if (typeof signal === "number")
592
+ return 128 + signal;
593
+ return signal === null ? 129 : 128 + constants.signals[signal];
594
+ }
595
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
596
+ const chunks = [];
597
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
598
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
599
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
600
+ const timers = [];
601
+ const killGroup = (killing) => {
602
+ if (state.done)
603
+ return;
604
+ try {
605
+ if (grouped)
606
+ process4.kill(-proc.pid, killing);
607
+ else
608
+ proc.kill(killing);
609
+ } catch {}
610
+ };
611
+ const stop = () => {
612
+ killGroup("SIGTERM");
613
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
614
+ };
615
+ const onAbort = () => stop();
616
+ if (timeoutMs !== undefined) {
617
+ timers.push(setTimeout(() => {
618
+ state.timedOut = true;
619
+ stop();
620
+ }, timeoutMs));
621
+ }
622
+ if (signal?.aborted === true)
623
+ onAbort();
624
+ else
625
+ signal?.addEventListener("abort", onAbort, { once: true });
626
+ onStart?.({ kill: (killing) => killGroup(killing) });
627
+ const drain = async (stream, name) => {
628
+ for await (const data of stream) {
629
+ if (state.failure !== undefined)
630
+ continue;
631
+ try {
632
+ onChunk?.({ stream: name, data });
633
+ } catch (error) {
634
+ state.failure = error;
635
+ stop();
636
+ continue;
637
+ }
638
+ if (state.kept + data.length > maxBytes) {
639
+ state.truncated = true;
640
+ continue;
641
+ }
642
+ state.kept += data.length;
643
+ chunks.push({ stream: name, data });
644
+ }
645
+ };
646
+ try {
647
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
648
+ await proc.exited;
649
+ } finally {
650
+ state.done = true;
651
+ for (const timer of timers)
652
+ clearTimeout(timer);
653
+ signal?.removeEventListener("abort", onAbort);
654
+ }
655
+ if (state.failure !== undefined)
656
+ throw state.failure;
657
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
658
+ let output;
659
+ let text;
660
+ return {
661
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
662
+ chunks,
663
+ timedOut: state.timedOut,
664
+ truncated: state.truncated,
665
+ get output() {
666
+ return output ??= joined();
667
+ },
668
+ get text() {
669
+ return text ??= (output ??= joined()).toString();
670
+ }
671
+ };
672
+ }
673
+
674
+ // ../kit/src/progress.ts
675
+ var ESC = String.fromCharCode(27);
676
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
677
+ var RESET_STYLE = `${ESC}[0m`;
678
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
679
+ // ../kit/src/cli.ts
680
+ import process5 from "process";
681
+ var LEVEL_OPTIONS = {
682
+ ...OUTPUT_OPTIONS,
683
+ help: { type: "boolean", short: "h", description: "show this help" }
684
+ };
685
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
686
+ async function commandRows(all, colors) {
687
+ const commands = shown(all);
688
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
689
+ const groups = new Map([["Commands:", []]]);
690
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
691
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
692
+ const heading = group === undefined ? "Commands:" : `${group}:`;
693
+ const rows = groups.get(heading) ?? [];
694
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
695
+ groups.set(heading, rows);
696
+ }
697
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
698
+ }
699
+ function shown(commands) {
700
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
701
+ }
702
+ function takeOutputFlags(argv) {
703
+ let index = 0;
704
+ for (;index < argv.length; index++) {
705
+ const word = argv[index];
706
+ if (word === "--plain")
707
+ applyOutput(undefined, true);
708
+ else if (word.startsWith("--color="))
709
+ applyOutput(word.slice("--color=".length), undefined);
710
+ else if (word === "--color" && argv[index + 1] !== undefined)
711
+ applyOutput(argv[++index], undefined);
712
+ else
713
+ break;
714
+ }
715
+ return argv.slice(index);
716
+ }
717
+ async function resolveSummary(summary) {
718
+ return typeof summary === "string" ? summary : summary();
719
+ }
720
+ function scopeOf(commands, extra, aliases) {
721
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
722
+ }
723
+ async function expand(scope, words) {
724
+ if (scope.lazy.length === 0)
725
+ return scope;
726
+ const commands = { ...scope.commands };
727
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
728
+ for (const [name, command] of Object.entries(added))
729
+ commands[name] ??= command;
730
+ }
731
+ return { ...scope, commands, lazy: [] };
732
+ }
733
+ async function help({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
734
+ const colors = paint(stream);
735
+ const prefix = path.join(" ");
736
+ const summary = await resolveSummary(lazySummary);
737
+ if (wantsHelpJson())
738
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
739
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
740
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
741
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
742
+ return [
743
+ header(colors, summary),
744
+ "",
745
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
746
+ ...replacesRows(replaces, colors),
747
+ "",
748
+ ...await commandRows(commands, colors),
749
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
750
+ "",
751
+ colors.bold("Options:"),
752
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
753
+ ...exampleRows(examples ?? [], colors),
754
+ "",
755
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
756
+ ].join(`
757
+ `);
758
+ }
759
+ function printError(prefix, message, hint, cause) {
760
+ const colors = paint(process5.stderr);
761
+ const styled = takesControlCodes(process5.stderr);
762
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
763
+ const under = (label, text, tint) => text === undefined ? "" : `
764
+ ${styled ? tint(label) : `${label}:`} ${text}`;
765
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
766
+ }
767
+ function printJsonError(message, hint, cause) {
768
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
769
+ }
770
+ function wantsJson(argv) {
771
+ const end = argv.indexOf("--");
772
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
773
+ }
774
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
775
+ if (error instanceof HelpShown)
776
+ return 0;
777
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
778
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
779
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
780
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
781
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
782
+ return error instanceof Exit ? error.code : 1;
783
+ }
784
+ async function dispatch(level, typed, { version, redact }) {
785
+ const prefix = level.path.join(" ");
786
+ let argv;
787
+ try {
788
+ argv = takeOutputFlags(typed);
789
+ } catch (error) {
790
+ return reportThrown(prefix, error);
791
+ }
792
+ const [name, ...args] = argv;
793
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
794
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
795
+ try {
796
+ return await fallback.run([]);
797
+ } catch (error) {
798
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
799
+ }
800
+ }
801
+ if (name === undefined && level.path.length > 1) {
802
+ console.error(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
803
+ return 2;
804
+ }
805
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
806
+ console.log(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
807
+ return 0;
808
+ }
809
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
810
+ console.log(version);
811
+ return 0;
812
+ }
813
+ let command = level.commands[level.aliases?.[name] ?? name];
814
+ let rest = args;
815
+ let ran = name;
816
+ if (command === undefined && level.lazy.length > 0) {
817
+ level = await expand(level, [...level.path.slice(1), ...argv]);
818
+ command = level.commands[level.aliases?.[name] ?? name];
819
+ }
820
+ if (command === undefined && level.defaultCommand !== undefined) {
821
+ command = level.commands[level.defaultCommand];
822
+ rest = argv;
823
+ ran = level.defaultCommand;
824
+ }
825
+ if (command === undefined) {
826
+ const meant = closest(name, Object.keys(shown(level.commands)));
827
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
828
+ return 2;
829
+ }
830
+ if ("commands" in command) {
831
+ const { summary } = command;
832
+ 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 });
833
+ }
834
+ try {
835
+ return await command.run(rest);
836
+ } catch (error) {
837
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
838
+ }
839
+ }
840
+ var COMPLETE = "__complete";
841
+ var FILES = "__files__";
842
+ async function completingOf(run) {
843
+ completion.active = true;
844
+ try {
845
+ await run([]);
846
+ } catch (error) {
847
+ if (error instanceof Completing)
848
+ return error;
849
+ } finally {
850
+ completion.active = false;
851
+ }
852
+ return new Completing({});
853
+ }
854
+ async function optionsOf(run) {
855
+ return (await completingOf(run)).options;
856
+ }
857
+ function candidateLine(candidate) {
858
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
859
+ }
860
+ function positionalBeingTyped(before, { options, positionals }) {
861
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
862
+ let index = 0;
863
+ let at = 0;
864
+ while (at < before.length) {
865
+ const word = before[at];
866
+ if (word === "--") {
867
+ index += before.length - at - 1;
868
+ break;
869
+ }
870
+ if (!word.startsWith("-"))
871
+ index++;
872
+ else if (takesValue(word))
873
+ at++;
874
+ at++;
875
+ }
876
+ const last = positionals.at(-1);
877
+ if (index < positionals.length)
878
+ return positionals[index];
879
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
880
+ }
881
+ async function leafCandidates(run, words) {
882
+ const completing = await completingOf(run);
883
+ if ((words.at(-1) ?? "").startsWith("-"))
884
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
885
+ const flag = words.at(-2);
886
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
887
+ if (option?.type === "string") {
888
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
889
+ return values === undefined ? [FILES] : values.map(candidateLine);
890
+ }
891
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
892
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
893
+ return values === undefined ? [FILES] : values.map(candidateLine);
894
+ }
895
+ async function candidates(scope, defaultCommand, words, before = []) {
896
+ const [word = "", ...rest] = words;
897
+ const listing = rest.length === 0 && !word.startsWith("-");
898
+ let { commands, aliases } = scope;
899
+ let command = commands[aliases?.[word] ?? word];
900
+ if (listing || command === undefined) {
901
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
902
+ command = commands[aliases?.[word] ?? word];
903
+ }
904
+ if (listing) {
905
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
906
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
907
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
908
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
909
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
910
+ }
911
+ if (command === undefined) {
912
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
913
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
914
+ }
915
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
916
+ }
917
+ async function printCandidates(found) {
918
+ for (const line of await found)
919
+ console.log(line);
920
+ return 0;
921
+ }
922
+ async function runCli(cli, argv = process5.argv.slice(2)) {
923
+ if (argv[0] === COMPLETE)
924
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
925
+ return dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.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: cli.version, redact: cli.redact });
926
+ }
927
+ // ../kit/src/logs.ts
928
+ var DAY_MS = 24 * 60 * 60 * 1000;
929
+ // ../kit/src/secrets.ts
930
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
931
+ // ../kit/src/sessions.ts
932
+ var {Glob } = globalThis.Bun;
933
+ var SESSION_FILES = new Glob("*.json");
934
+ var ACCOUNT_DIRS = new Glob("*/sessions");
935
+ // package.json
936
+ var version = "0.7.1";
937
+
938
+ // ../kit/src/shell.ts
939
+ var SEPARATORS = new Set([`
940
+ `, ";", "|"]);
941
+ var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
942
+ var GLOB_CHARS = new Set(["*", "?", "["]);
943
+ var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
944
+ var WHITESPACE = /\s/;
945
+ var ASSIGNMENT = /^\w+=/;
946
+ var TRAILING_SLASHES = /\/+$/;
947
+ var TRAILING_CR = /\r$/;
948
+ var LEADING_TILDE = /^~(?=\/|$)/;
949
+ var LEADING_TABS = /^\t+/;
950
+ var OPENERS = /^[({]+/;
951
+ var CLOSERS = /[)}]+$/;
952
+ var CASE_LABEL = /^\(?[^\s()]*\)$/;
953
+ var REDIRECT_ONLY = /^\d*(?:<|>|>>|<&|>&|&>|>\||<>)$/;
954
+ var REDIRECT_START = /^\d*[<>]|^&>/;
955
+ var SAFE_WORD = /^[\w@%+=:,./-]+$/;
956
+ var LEADING_HEX = /^[\da-f]*/i;
957
+ var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
958
+ var HEREDOC = /^<<(-?)[ \t]*(?:'([^']*)'|"([^"]*)"|([^\s;&|<>()-][^\s;&|<>()]*))/;
959
+ var ANSI_QUOTE = "$'";
960
+ var ANSI_ESCAPES = { n: `
961
+ `, t: "\t", r: "\r", a: "\x07", b: "\b", f: "\f", v: "\v", e: "\x1B", E: "\x1B", "\\": "\\", "'": "'", '"': '"', "?": "?" };
962
+ var ANSI_DIGITS = { x: 2, u: 4, U: 8 };
963
+ var OCTAL = /^[0-7]{1,3}/;
964
+ var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
965
+ var MAX_DEPTH = 8;
966
+ var MAX_BRACES = 256;
967
+ var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh"]);
968
+ var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, "su", "runuser"]);
969
+ var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
970
+ var PRINTERS = new Set(["echo", "printf"]);
971
+ var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
972
+ function wrapper(short = "", long = [], operands = 0) {
973
+ return { short, long, operands };
974
+ }
975
+ var WRAPPERS = new Map([
976
+ ["command", wrapper()],
977
+ ["builtin", wrapper()],
978
+ ["nohup", wrapper()],
979
+ ["setsid", wrapper()],
980
+ ["busybox", wrapper()],
981
+ ["exec", wrapper("a")],
982
+ ["time", wrapper("fo", ["--format", "--output"])],
983
+ ["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
984
+ ["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
985
+ ["doas", wrapper("uC")],
986
+ ["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
987
+ ["nice", wrapper("n", ["--adjustment"])],
988
+ ["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
989
+ ["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
990
+ ["chroot", wrapper("", ["--userspec", "--groups"], 1)],
991
+ ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
992
+ ]);
993
+ function closerOf(quote) {
994
+ return quote === ANSI_QUOTE ? "'" : quote;
995
+ }
996
+ function startsComment(command, i) {
997
+ const before = command[i - 1] ?? "";
998
+ return i === 0 || WHITESPACE.test(before) || COMMENT_PREFIXES.has(before);
999
+ }
1000
+ function separatorWidth(command, i) {
1001
+ const pair = command.slice(i, i + 2);
1002
+ if (pair === "&&" || pair === "||")
1003
+ return 2;
1004
+ const char = command[i] ?? "";
1005
+ if (char === "&")
1006
+ return command[i - 1] === ">" || command[i - 1] === "<" || command[i + 1] === ">" ? 0 : 1;
1007
+ return SEPARATORS.has(char) ? 1 : 0;
1008
+ }
1009
+ function heredocEnd(command, newline, words) {
1010
+ let lineStart = newline + 1;
1011
+ for (const { word, stripsTabs } of words) {
1012
+ while (lineStart <= command.length) {
1013
+ const next = command.indexOf(`
1014
+ `, lineStart);
1015
+ const lineEnd = next === -1 ? command.length : next;
1016
+ const line = command.slice(lineStart, lineEnd).replace(TRAILING_CR, "");
1017
+ lineStart = lineEnd + 1;
1018
+ if ((stripsTabs ? line.replace(LEADING_TABS, "") : line) === word)
1019
+ break;
1020
+ }
1021
+ }
1022
+ return Math.min(lineStart - 1, command.length);
1023
+ }
1024
+ function withoutRanges(command, start, end, ranges) {
1025
+ let text = "";
1026
+ let at = start;
1027
+ for (const [from, to] of ranges) {
1028
+ if (to <= start || from >= end)
1029
+ continue;
1030
+ text += command.slice(at, Math.max(at, from));
1031
+ at = Math.max(at, to);
1032
+ }
1033
+ return text + command.slice(at, end);
1034
+ }
1035
+ function splitCommand(command) {
1036
+ const bounds = [];
1037
+ const bodies = [];
1038
+ const comments = [];
1039
+ let heredocs = [];
1040
+ let start = 0;
1041
+ let quote = null;
1042
+ for (let i = 0;i < command.length; i++) {
1043
+ const char = command[i] ?? "";
1044
+ if (char === "\\" && quote !== "'") {
1045
+ i++;
1046
+ continue;
1047
+ }
1048
+ if (quote !== null) {
1049
+ if (char === closerOf(quote))
1050
+ quote = null;
1051
+ continue;
1052
+ }
1053
+ if (char === "$" && command[i + 1] === "'") {
1054
+ quote = ANSI_QUOTE;
1055
+ i++;
1056
+ continue;
1057
+ }
1058
+ if (char === "'" || char === '"') {
1059
+ quote = char;
1060
+ continue;
1061
+ }
1062
+ if (char === "`") {
1063
+ i = closingBackquote(command, i);
1064
+ continue;
1065
+ }
1066
+ if (char === "#" && startsComment(command, i)) {
1067
+ const newline = command.indexOf(`
1068
+ `, i);
1069
+ const end = newline === -1 ? command.length : newline;
1070
+ comments.push([i, end]);
1071
+ i = end - 1;
1072
+ continue;
1073
+ }
1074
+ const heredoc = char === "<" && command[i + 1] === "<" && command[i + 2] !== "<" ? HEREDOC.exec(command.slice(i)) : null;
1075
+ if (heredoc) {
1076
+ heredocs.push({ word: heredoc[2] ?? heredoc[3] ?? heredoc[4] ?? "", stripsTabs: heredoc[1] === "-", isQuoted: heredoc[4] === undefined });
1077
+ i += heredoc[0].length - 1;
1078
+ continue;
1079
+ }
1080
+ if (char === `
1081
+ ` && heredocs.length > 0) {
1082
+ const end = heredocEnd(command, i, heredocs);
1083
+ bodies.push([i, end, heredocs.some((each) => !each.isQuoted)]);
1084
+ heredocs = [];
1085
+ i = end - 1;
1086
+ continue;
1087
+ }
1088
+ const width = separatorWidth(command, i);
1089
+ if (width === 0)
1090
+ continue;
1091
+ bounds.push([start, i, command.slice(i, i + width)]);
1092
+ i += width - 1;
1093
+ start = i + 1;
1094
+ }
1095
+ bounds.push([start, command.length, ""]);
1096
+ const ranges = [...bodies, ...comments].map(([from, to]) => [from, to]).sort(([a], [b]) => a - b);
1097
+ return bounds.map(([from, to, separator]) => {
1098
+ const inside = bodies.filter(([body]) => body >= from && body < to);
1099
+ return {
1100
+ text: command.slice(from, to),
1101
+ start: from,
1102
+ end: to,
1103
+ command: withoutRanges(command, from, to, ranges),
1104
+ separator,
1105
+ expanded: inside.filter(([, , expands]) => expands).map(([body, bodyEnd]) => command.slice(body, bodyEnd)).join(""),
1106
+ heredocs: inside.map(([body, bodyEnd]) => command.slice(body, bodyEnd))
1107
+ };
1108
+ });
1109
+ }
1110
+ function isPlain(text) {
1111
+ let quote = null;
1112
+ for (let i = 0;i < text.length; i++) {
1113
+ const char = text[i] ?? "";
1114
+ const isSubstitution = char === "`" || char === "$" && text[i + 1] === "(";
1115
+ if (quote === null && char === "$" && text[i + 1] === "'") {
1116
+ quote = ANSI_QUOTE;
1117
+ i++;
1118
+ continue;
1119
+ }
1120
+ if (char === "\\" && quote !== "'")
1121
+ i++;
1122
+ else if (quote !== null && char === closerOf(quote))
1123
+ quote = null;
1124
+ else if (quote === null && (char === '"' || char === "'"))
1125
+ quote = char;
1126
+ else if (quote !== "'" && quote !== ANSI_QUOTE && (isSubstitution || quote === null && PLAIN_BREAKERS.has(char)))
1127
+ return false;
1128
+ }
1129
+ return quote === null;
1130
+ }
1131
+ function unmatchedClosers(text) {
1132
+ let depth = 0;
1133
+ let unmatched = 0;
1134
+ let quote = null;
1135
+ for (let i = 0;i < text.length; i++) {
1136
+ const char = text[i] ?? "";
1137
+ if (quote === null && char === "$" && text[i + 1] === "'") {
1138
+ quote = ANSI_QUOTE;
1139
+ i++;
1140
+ continue;
1141
+ }
1142
+ if (char === "\\" && quote !== "'")
1143
+ i++;
1144
+ else if (quote !== null && char === closerOf(quote))
1145
+ quote = null;
1146
+ else if (quote === null && (char === '"' || char === "'"))
1147
+ quote = char;
1148
+ else if (quote === null && char === "(")
1149
+ depth++;
1150
+ else if (quote === null && char === ")" && depth > 0)
1151
+ depth--;
1152
+ else if (quote === null && char === ")")
1153
+ unmatched++;
1154
+ }
1155
+ return unmatched;
1156
+ }
1157
+ function withoutSubshell(text) {
1158
+ let result = text.trim();
1159
+ let closers = unmatchedClosers(result);
1160
+ while (result.startsWith("("))
1161
+ result = result.slice(1).trimStart();
1162
+ while (closers > 0 && result.endsWith(")")) {
1163
+ result = result.slice(0, -1).trimEnd();
1164
+ closers--;
1165
+ }
1166
+ return result;
1167
+ }
1168
+ function closingParen(text, open) {
1169
+ let depth = 0;
1170
+ let quote = null;
1171
+ for (let i = open;i < text.length; i++) {
1172
+ const char = text[i] ?? "";
1173
+ if (char === "\\" && quote !== "'") {
1174
+ i++;
1175
+ } else if (quote !== null) {
1176
+ if (char === closerOf(quote))
1177
+ quote = null;
1178
+ } else if (char === "$" && text[i + 1] === "'") {
1179
+ quote = ANSI_QUOTE;
1180
+ i++;
1181
+ } else if (char === "'" || char === '"') {
1182
+ quote = char;
1183
+ } else if (char === "(") {
1184
+ depth++;
1185
+ } else if (char === ")" && --depth === 0) {
1186
+ return i;
1187
+ }
1188
+ }
1189
+ return text.length;
1190
+ }
1191
+ function closingBackquote(text, open) {
1192
+ for (let i = open + 1;i < text.length; i++) {
1193
+ if (text[i] === "\\")
1194
+ i++;
1195
+ else if (text[i] === "`")
1196
+ return i;
1197
+ }
1198
+ return text.length;
1199
+ }
1200
+ function bodies(text, isQuoting) {
1201
+ const found = [];
1202
+ let quote = null;
1203
+ for (let i = 0;i < text.length; i++) {
1204
+ const char = text[i] ?? "";
1205
+ const next = text[i + 1];
1206
+ if (quote === "'") {
1207
+ if (char === "'")
1208
+ quote = null;
1209
+ } else if (quote === ANSI_QUOTE) {
1210
+ if (char === "\\")
1211
+ i++;
1212
+ else if (char === "'")
1213
+ quote = null;
1214
+ } else if (char === "\\") {
1215
+ i++;
1216
+ } else if (char === "$" && next === "(" || isQuoting && quote === null && (char === "<" || char === ">") && next === "(") {
1217
+ const end = closingParen(text, i + 1);
1218
+ found.push(text.slice(i + 2, end));
1219
+ i = end;
1220
+ } else if (char === "`") {
1221
+ const end = closingBackquote(text, i);
1222
+ found.push(text.slice(i + 1, end));
1223
+ i = end;
1224
+ } else if (isQuoting && char === '"') {
1225
+ quote = quote === null ? char : null;
1226
+ } else if (isQuoting && char === "$" && next === "'" && quote === null) {
1227
+ quote = ANSI_QUOTE;
1228
+ i++;
1229
+ } else if (isQuoting && char === "'" && quote === null) {
1230
+ quote = char;
1231
+ }
1232
+ }
1233
+ return found;
1234
+ }
1235
+ function substitutions(command) {
1236
+ return splitCommand(command).flatMap((piece) => [...bodies(piece.command, true), ...bodies(piece.expanded, false)]);
1237
+ }
1238
+ function ansiEscape(text, at) {
1239
+ const letter = text[at + 1] ?? "";
1240
+ const simple = ANSI_ESCAPES[letter];
1241
+ if (simple !== undefined)
1242
+ return [simple, at + 1];
1243
+ const hex = LEADING_HEX.exec(text.slice(at + 2, at + 2 + (ANSI_DIGITS[letter] ?? 0)))?.[0] ?? "";
1244
+ if (hex !== "")
1245
+ return [String.fromCodePoint(Number.parseInt(hex, 16)), at + 1 + hex.length];
1246
+ const octal = OCTAL.exec(text.slice(at + 1))?.[0];
1247
+ if (octal !== undefined)
1248
+ return [String.fromCodePoint(Number.parseInt(octal, 8)), at + octal.length];
1249
+ return [`\\${letter}`, at + 1];
1250
+ }
1251
+ function words(text) {
1252
+ const found = [];
1253
+ let current = "";
1254
+ let isStarted = false;
1255
+ let isProse = false;
1256
+ let hasGlob = false;
1257
+ let hasBrace = false;
1258
+ let quote = null;
1259
+ for (let i = 0;i < text.length; i++) {
1260
+ const char = text[i] ?? "";
1261
+ const isContinuation = char === "\\" && quote !== "'" && text[i + 1] === `
1262
+ `;
1263
+ if (isContinuation)
1264
+ i++;
1265
+ if (quote === null && (isContinuation || WHITESPACE.test(char))) {
1266
+ if (isStarted)
1267
+ found.push({ text: current, isProse, hasGlob, hasBrace });
1268
+ current = "";
1269
+ isStarted = false;
1270
+ isProse = false;
1271
+ hasGlob = false;
1272
+ hasBrace = false;
1273
+ continue;
1274
+ }
1275
+ if (isContinuation)
1276
+ continue;
1277
+ isStarted = true;
1278
+ if (char === "\\" && quote === ANSI_QUOTE) {
1279
+ const [decoded, last] = ansiEscape(text, i);
1280
+ current += decoded;
1281
+ i = last;
1282
+ } else if (char === "\\" && quote === '"' && !DOUBLE_QUOTED_ESCAPES.has(text[i + 1] ?? "")) {
1283
+ current += char;
1284
+ } else if (char === "\\" && quote !== "'") {
1285
+ current += text[++i] ?? "";
1286
+ } else if (quote !== null && char === closerOf(quote)) {
1287
+ quote = null;
1288
+ } else if (quote === null && char === "$" && text[i + 1] === "'") {
1289
+ quote = ANSI_QUOTE;
1290
+ i++;
1291
+ } else if (quote === null && (char === '"' || char === "'")) {
1292
+ quote = char;
1293
+ } else {
1294
+ current += char;
1295
+ hasGlob ||= quote === null && GLOB_CHARS.has(char);
1296
+ hasBrace ||= quote === null && char === "{";
1297
+ }
1298
+ isProse ||= quote !== null && WHITESPACE.test(char);
1299
+ }
1300
+ if (isStarted)
1301
+ found.push({ text: current, isProse, hasGlob, hasBrace });
1302
+ return found;
1303
+ }
1304
+ function tokenize(text) {
1305
+ return words(text).map((word) => word.text);
1306
+ }
1307
+ function skipOptions(tokens, spec) {
1308
+ const take = (name, attached) => {
1309
+ const value = attached === "" ? tokens.shift() ?? "" : attached;
1310
+ if (name === "S" || name === "--split-string")
1311
+ tokens.unshift(...tokenize(value));
1312
+ };
1313
+ while (tokens[0] !== undefined && tokens[0].startsWith("-") && tokens[0] !== "-") {
1314
+ const option = tokens.shift() ?? "";
1315
+ if (option === "--")
1316
+ break;
1317
+ if (option.startsWith("--")) {
1318
+ const [name = "", ...value] = option.split("=");
1319
+ if (spec.long.includes(name))
1320
+ take(name, value.join("="));
1321
+ continue;
1322
+ }
1323
+ for (const [index, letter] of [...option.slice(1)].entries()) {
1324
+ if (!spec.short.includes(letter))
1325
+ continue;
1326
+ take(letter, option.slice(index + 2));
1327
+ break;
1328
+ }
1329
+ }
1330
+ for (let operand = 0;operand < spec.operands; operand++)
1331
+ tokens.shift();
1332
+ }
1333
+ function parseCommand(text) {
1334
+ const tokens = tokenize(text);
1335
+ const assignments = [];
1336
+ let isWrapped = false;
1337
+ for (;; ) {
1338
+ const first = tokens[0] ?? "";
1339
+ const spec = WRAPPERS.get(first.split("/").pop() ?? "");
1340
+ if (OPENERS.test(first)) {
1341
+ isWrapped = true;
1342
+ const rest = first.replace(OPENERS, "");
1343
+ if (rest === "")
1344
+ tokens.shift();
1345
+ else
1346
+ tokens[0] = rest;
1347
+ } else if (ASSIGNMENT.test(first)) {
1348
+ assignments.push(tokens.shift() ?? "");
1349
+ } else if (KEYWORDS.has(first)) {
1350
+ isWrapped = true;
1351
+ tokens.shift();
1352
+ } else if (first === "case") {
1353
+ isWrapped = true;
1354
+ const at = tokens.indexOf("in");
1355
+ tokens.splice(0, at === -1 ? tokens.length : at + 1);
1356
+ } else if (tokens.length > 1 && CASE_LABEL.test(first)) {
1357
+ isWrapped = true;
1358
+ tokens.shift();
1359
+ } else if (spec !== undefined) {
1360
+ isWrapped = true;
1361
+ tokens.shift();
1362
+ skipOptions(tokens, spec);
1363
+ } else {
1364
+ break;
1365
+ }
1366
+ }
1367
+ const closers = CLOSERS.exec(text.trimEnd())?.[0].length ?? 0;
1368
+ const word = tokens.at(-1) ?? "";
1369
+ const trimmed = word.length - (CLOSERS.exec(word)?.[0].length ?? 0);
1370
+ const last = word.slice(0, Math.max(trimmed, word.length - closers));
1371
+ if (tokens.length > 0)
1372
+ tokens.splice(-1, 1, ...last === "" ? [] : [last]);
1373
+ const [program = "", ...args] = tokens;
1374
+ return { program: program.split("/").pop() ?? "", args, assignments, isWrapped };
1375
+ }
1376
+ function shellQuote(word) {
1377
+ return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
1378
+ }
1379
+ function quoted(word) {
1380
+ return word === "{}" ? word : shellQuote(word);
1381
+ }
1382
+ function commandStrings(tokens) {
1383
+ const found = [];
1384
+ for (const [i, token] of tokens.entries()) {
1385
+ const name = token.split("/").pop() ?? "";
1386
+ if (!COMMAND_STRING_PROGRAMS.has(name))
1387
+ continue;
1388
+ const isUser = name === "su" || name === "runuser";
1389
+ let isValue = false;
1390
+ for (let j = i + 1;j < tokens.length; j++) {
1391
+ const option = tokens[j] ?? "";
1392
+ if (isValue) {
1393
+ isValue = false;
1394
+ continue;
1395
+ }
1396
+ if (SHELL_VALUE_OPTIONS.has(option)) {
1397
+ isValue = true;
1398
+ continue;
1399
+ }
1400
+ if (option.startsWith("--command=")) {
1401
+ found.push(option.slice("--command=".length));
1402
+ break;
1403
+ }
1404
+ if (option === "--command" || !option.startsWith("--") && option.startsWith("-") && option.slice(1).includes("c")) {
1405
+ found.push(tokens[j + 1] ?? "");
1406
+ break;
1407
+ }
1408
+ if (!option.startsWith("-") && !isUser)
1409
+ break;
1410
+ }
1411
+ }
1412
+ return found;
1413
+ }
1414
+ function redirections(args) {
1415
+ const operands = [];
1416
+ const hereStrings = [];
1417
+ for (let i = 0;i < args.length; i++) {
1418
+ const arg = args[i] ?? "";
1419
+ if (arg.startsWith("<<<"))
1420
+ hereStrings.push(arg.length > 3 ? arg.slice(3) : args[++i] ?? "");
1421
+ else if (REDIRECT_ONLY.test(arg))
1422
+ i++;
1423
+ else if (!REDIRECT_START.test(arg))
1424
+ operands.push(arg);
1425
+ }
1426
+ return { operands, hereStrings };
1427
+ }
1428
+ function findExecs(args) {
1429
+ const found = [];
1430
+ for (const [i, arg] of args.entries()) {
1431
+ if (!FIND_EXEC.has(arg))
1432
+ continue;
1433
+ const rest = args.slice(i + 1);
1434
+ const end = rest.findIndex((word) => word === ";" || word === "+");
1435
+ found.push((end === -1 ? rest : rest.slice(0, end)).map(quoted).join(" "));
1436
+ }
1437
+ return found;
1438
+ }
1439
+ function nestedCommands(piece, previous) {
1440
+ const tokens = tokenize(piece.command);
1441
+ const { program, args } = parseCommand(piece.command);
1442
+ const found = commandStrings(tokens);
1443
+ if (program === "eval")
1444
+ found.push(args.join(" "));
1445
+ if (program === "find")
1446
+ found.push(...findExecs(args));
1447
+ if (!SHELLS.has(program))
1448
+ return found;
1449
+ const { operands, hereStrings } = redirections(args);
1450
+ if (operands.length > 0)
1451
+ return found;
1452
+ found.push(...piece.heredocs, ...hereStrings);
1453
+ if (previous?.separator === "|") {
1454
+ const before = parseCommand(previous.command);
1455
+ if (PRINTERS.has(before.program))
1456
+ found.push(...before.args, before.args.join(" "));
1457
+ }
1458
+ return found;
1459
+ }
1460
+ function commandsRun(command, depth = 0) {
1461
+ const found = [command];
1462
+ if (depth >= MAX_DEPTH)
1463
+ return found;
1464
+ const pieces = splitCommand(command);
1465
+ for (const [index, piece] of pieces.entries()) {
1466
+ const inner = withoutSubshell(piece.command);
1467
+ const nested = [...bodies(piece.command, true), ...bodies(piece.expanded, false), ...nestedCommands(piece, pieces[index - 1])];
1468
+ if (inner !== piece.command.trim())
1469
+ nested.push(inner);
1470
+ for (const each of nested)
1471
+ found.push(...commandsRun(each, depth + 1));
1472
+ }
1473
+ return found;
1474
+ }
1475
+ function expandBraces(word) {
1476
+ const open = word.indexOf("{");
1477
+ if (open === -1)
1478
+ return [word];
1479
+ const alternatives = [];
1480
+ let depth = 0;
1481
+ let cut = open;
1482
+ for (let i = open;i < word.length; i++) {
1483
+ const char = word[i];
1484
+ if (char === "{") {
1485
+ depth++;
1486
+ } else if (char === "," && depth === 1) {
1487
+ alternatives.push(word.slice(cut + 1, i));
1488
+ cut = i;
1489
+ } else if (char === "}" && --depth === 0) {
1490
+ if (alternatives.length === 0)
1491
+ break;
1492
+ alternatives.push(word.slice(cut + 1, i));
1493
+ const prefix = word.slice(0, open);
1494
+ const suffix = word.slice(i + 1);
1495
+ return alternatives.flatMap((alternative) => expandBraces(prefix + alternative + suffix)).slice(0, MAX_BRACES + 1);
1496
+ }
1497
+ }
1498
+ return expandBraces(word.slice(open + 1)).map((rest) => `${word.slice(0, open + 1)}${rest}`);
1499
+ }
1500
+ function braceExpand(word) {
1501
+ const found = expandBraces(word);
1502
+ return found.length > MAX_BRACES ? [word] : found;
1503
+ }
1504
+ function replacePieces(command, replacements) {
1505
+ let result = command;
1506
+ for (const [piece, text] of [...replacements].sort(([a], [b]) => b.start - a.start)) {
1507
+ result = result.slice(0, piece.start) + text + result.slice(piece.end);
1508
+ }
1509
+ return result;
1510
+ }
1511
+ function parentDir(path) {
1512
+ const cut = path.replace(TRAILING_SLASHES, "").lastIndexOf("/");
1513
+ return cut <= 0 ? "/" : path.slice(0, cut);
1514
+ }
1515
+ function resolvePath(base, arg, home) {
1516
+ const expanded = arg.replace(LEADING_TILDE, home);
1517
+ const parts = [];
1518
+ for (const part of (expanded.startsWith("/") ? expanded : `${base}/${expanded}`).split("/")) {
1519
+ if (part === "..")
1520
+ parts.pop();
1521
+ else if (part !== "" && part !== ".")
1522
+ parts.push(part);
1523
+ }
1524
+ return `/${parts.join("/")}`;
1525
+ }
1526
+
1527
+ // ../db/src/guard.ts
1528
+ var WORD_START = /[a-z_\P{ASCII}]/iu;
1529
+ var WORD_PART = /[\w$\P{ASCII}]/u;
1530
+ var SPACE = /\s/;
1531
+ var ESCAPE_PREFIX = /e/i;
1532
+ var DOLLAR_TAG = /^\$(?:[a-z_]\w*)?\$/i;
1533
+ var LOCK_KIND = /^(?:update|share|no|key)$/;
1534
+ var DIGITS = /\d/;
1535
+ var COMMAND_ENDS = ";";
1536
+ var UNCLOSED = "unclosed";
1537
+ var NUL = "\x00";
1538
+ var UNICODE_IDENTIFIER = 'U&"';
1539
+ var UNICODE_PREFIX = /u&$/i;
1540
+ var LINE_END = /[\r\n]/;
1541
+ var PRIVILEGED_SET = new Set(["role", "session", "transaction", "global", "persist", "persist_only", "password", "default"]);
1542
+ var READ_STARTS = new Set(["select", "with", "values", "table", "show", "explain", "describe", "desc"]);
1543
+ var WRITING_STARTS = new Set(["replace", "load", "rename", "flush", "kill", "shutdown", "install", "uninstall", "purge", "optimize", "repair", "import", "prepare", "execute"]);
1544
+ var WRITE_WORDS = new Set(["insert", "update", "delete", "merge", "truncate", "drop", "alter", "create", "grant", "revoke", "into", "call", "vacuum", "lock", "refresh", "reindex", "cluster", "do"]);
1545
+ var SIDE_EFFECT_FUNCTIONS = /^(?:nextval|setval|set_config|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_switch_wal|pg_create_restore_point|pg_advisory_lock\w*|pg_advisory_xact_lock\w*|pg_try_advisory\w*|pg_notify|lo_\w+|dblink\w*|pg_read_file|pg_read_binary_file|pg_ls_\w+|pg_stat_file|pg_sleep\w*|pg_export_snapshot|pg_backup_start|pg_backup_stop|pg_start_backup|pg_stop_backup|txid_current|pg_current_xact_id|pg_current_logfile|pg_wal_replay_\w+|\w+_to_xml\w*|pg_logical_\w+|pg_replication_\w+|pg_drop_replication_slot|pg_stat_reset\w*|pg_promote|pg_file_\w+|sleep|benchmark|get_lock|release_lock|release_all_locks|load_file|master_pos_wait|source_pos_wait|sys_exec|sys_eval)$/;
1546
+ function tokenize2(sql, dialect = "postgres") {
1547
+ const tokens = [];
1548
+ const isMysql = dialect === "mysql";
1549
+ let at = 0;
1550
+ while (at < sql.length) {
1551
+ const char = sql.charAt(at);
1552
+ const next = sql.charAt(at + 1);
1553
+ if (SPACE.test(char)) {
1554
+ at++;
1555
+ } else if (char === NUL) {
1556
+ tokens.push({ kind: "punct", text: NUL });
1557
+ at++;
1558
+ } else if (char === "-" && next === "-" && (!isMysql || isDashGap(sql.charAt(at + 2))) || isMysql && char === "#") {
1559
+ const end = sql.slice(at).search(LINE_END);
1560
+ at = end === -1 ? sql.length : at + end + 1;
1561
+ } else if (char === "/" && next === "*" && (sql.charAt(at + 2) === "!" || sql.charAt(at + 2) === "M" && sql.charAt(at + 3) === "!")) {
1562
+ at += sql.charAt(at + 2) === "!" ? 3 : 4;
1563
+ while (DIGITS.test(sql.charAt(at)))
1564
+ at++;
1565
+ } else if (char === "/" && next === "*") {
1566
+ at = skipComment(sql, at, !isMysql);
1567
+ } else if (char === "'" || isMysql && char === '"') {
1568
+ const backslashes = isMysql || ESCAPE_PREFIX.test(sql.charAt(at - 1)) && !WORD_PART.test(sql.charAt(at - 2));
1569
+ const end = skipQuoted(sql, at, char, backslashes);
1570
+ at = end ?? sql.length;
1571
+ tokens.push({ kind: "punct", text: end === undefined ? UNCLOSED : "'" });
1572
+ } else if (char === '"' || char === "`") {
1573
+ const end = skipQuoted(sql, at, char, false);
1574
+ if (char === '"' && UNICODE_PREFIX.test(sql.slice(Math.max(0, at - 2), at)) && !WORD_PART.test(sql.charAt(at - 3)))
1575
+ tokens.push({ kind: "punct", text: UNICODE_IDENTIFIER });
1576
+ tokens.push(end === undefined ? { kind: "punct", text: UNCLOSED } : { kind: "quoted", text: sql.slice(at + 1, end - 1).replaceAll(char + char, char) });
1577
+ at = end ?? sql.length;
1578
+ } else if (!isMysql && char === "$" && DOLLAR_TAG.test(sql.slice(at))) {
1579
+ const tag = DOLLAR_TAG.exec(sql.slice(at))?.[0] ?? "$$";
1580
+ const end = sql.indexOf(tag, at + tag.length);
1581
+ at = end === -1 ? sql.length : end + tag.length;
1582
+ tokens.push({ kind: "punct", text: end === -1 ? UNCLOSED : "$" });
1583
+ } else if (WORD_START.test(char)) {
1584
+ let end = at + 1;
1585
+ while (end < sql.length && WORD_PART.test(sql.charAt(end)))
1586
+ end++;
1587
+ tokens.push({ kind: "word", text: sql.slice(at, end).toLowerCase() });
1588
+ at = end;
1589
+ } else {
1590
+ tokens.push({ kind: "punct", text: char });
1591
+ at++;
1592
+ }
1593
+ }
1594
+ return tokens;
1595
+ }
1596
+ function isDashGap(char) {
1597
+ return char <= " ";
1598
+ }
1599
+ function skipComment(sql, start, nests) {
1600
+ let depth = 0;
1601
+ let at = start;
1602
+ while (at < sql.length) {
1603
+ if (sql.startsWith("/*", at) && (nests || depth === 0)) {
1604
+ depth++;
1605
+ at += 2;
1606
+ } else if (sql.startsWith("*/", at)) {
1607
+ depth--;
1608
+ at += 2;
1609
+ if (depth === 0)
1610
+ return at;
1611
+ } else {
1612
+ at++;
1613
+ }
1614
+ }
1615
+ return sql.length;
1616
+ }
1617
+ function skipQuoted(sql, start, quote, backslashes) {
1618
+ let at = start + 1;
1619
+ while (at < sql.length) {
1620
+ const char = sql.charAt(at);
1621
+ if (backslashes && char === "\\") {
1622
+ at += 2;
1623
+ } else if (char === quote) {
1624
+ if (sql.charAt(at + 1) !== quote)
1625
+ return at + 1;
1626
+ at += 2;
1627
+ } else {
1628
+ at++;
1629
+ }
1630
+ }
1631
+ return;
1632
+ }
1633
+ function splitStatements(tokens) {
1634
+ const statements = [[]];
1635
+ for (const token of tokens) {
1636
+ if (token.kind === "punct" && token.text === COMMAND_ENDS)
1637
+ statements.push([]);
1638
+ else
1639
+ statements.at(-1)?.push(token);
1640
+ }
1641
+ return statements.filter((statement) => statement.length > 0);
1642
+ }
1643
+ var isPunct = (token, text) => token?.kind === "punct" && token.text === text;
1644
+ function copyReads(statement, index) {
1645
+ let depth = 0;
1646
+ for (const [at, token] of statement.entries()) {
1647
+ if (at <= index)
1648
+ continue;
1649
+ if (isPunct(token, "("))
1650
+ depth++;
1651
+ else if (isPunct(token, ")"))
1652
+ depth--;
1653
+ else if (depth === 0 && token.kind === "word" && (token.text === "from" || token.text === "to"))
1654
+ return token.text === "to" && (statement[at + 1]?.text === "stdout" || isPunct(statement[index - 1], "\\"));
1655
+ }
1656
+ return false;
1657
+ }
1658
+ function statementWrites(statement) {
1659
+ const first = statement[0];
1660
+ const start = isPunct(first, "\\") ? 1 : 0;
1661
+ const reasons = [];
1662
+ for (const [index, token] of statement.entries()) {
1663
+ if (isPunct(token, UNCLOSED))
1664
+ reasons.push("has a quote that never closes");
1665
+ else if (isPunct(token, NUL))
1666
+ reasons.push("contains a NUL byte");
1667
+ else if (isPunct(token, UNICODE_IDENTIFIER))
1668
+ reasons.push("uses a U& escaped identifier");
1669
+ if (token.kind === "quoted" && SIDE_EFFECT_FUNCTIONS.test(token.text))
1670
+ reasons.push(`calls ${token.text}`);
1671
+ if (token.kind !== "word")
1672
+ continue;
1673
+ if (SIDE_EFFECT_FUNCTIONS.test(token.text)) {
1674
+ reasons.push(`calls ${token.text}`);
1675
+ } else if (isPunct(statement[index - 1], ".")) {
1676
+ continue;
1677
+ } else if (token.text === "set") {
1678
+ if (index !== start || PRIVILEGED_SET.has(statement[index + 1]?.text ?? "") || isPunct(statement[index + 1], "@") && isPunct(statement[index + 2], "@"))
1679
+ reasons.push("uses SET");
1680
+ } else if (index === start && WRITING_STARTS.has(token.text)) {
1681
+ reasons.push(`uses ${token.text.toUpperCase()}`);
1682
+ } else if (token.text === "copy") {
1683
+ if (!copyReads(statement, index))
1684
+ reasons.push("uses COPY");
1685
+ } else if (WRITE_WORDS.has(token.text)) {
1686
+ reasons.push(`uses ${token.text.toUpperCase()}`);
1687
+ } else if (token.text === "analyze" && first?.text !== "explain") {
1688
+ reasons.push("uses ANALYZE");
1689
+ } else if (token.text === "for" && LOCK_KIND.test(statement[index + 1]?.text ?? "")) {
1690
+ reasons.push("takes row locks with FOR UPDATE or SHARE");
1691
+ } else if (token.text === "comment" && statement[index + 1]?.text === "on") {
1692
+ reasons.push("uses COMMENT ON");
1693
+ }
1694
+ }
1695
+ return reasons;
1696
+ }
1697
+ function writes(sql, dialect = "postgres") {
1698
+ return [...new Set(splitStatements(tokenize2(sql, dialect)).flatMap(statementWrites))];
1699
+ }
1700
+ var TEST_WRITE_STARTS = new Set(["insert", "update", "delete", "replace", "merge", "truncate", "create", "alter", "drop", "rename", "with", "select", "values", "table", "comment", "refresh"]);
1701
+ var DEFINITION_STARTS = new Set(["create", "alter", "drop", "rename"]);
1702
+ var STORED_CODE = new Set(["event", "procedure", "function", "trigger", "rule", "aggregate"]);
1703
+ var DEFINITION_MODIFIERS = new Set(["or", "replace", "temporary", "temp", "unlogged", "unique", "fulltext", "spatial", "definer"]);
1704
+ var SERVER_OBJECTS = new Set(["database", "user", "role", "server", "tablespace", "extension", "system", "subscription", "publication", "logfile", "instance", "resource"]);
1705
+ var FILE_WORDS = new Set(["infile", "outfile", "dumpfile"]);
1706
+ var SEQUENCE_FUNCTIONS = new Set(["nextval", "setval"]);
1707
+
1708
+ // ../db/src/clients.ts
1709
+ var SQL_CLIENTS = new Set(["psql", "mysql", "mariadb", "pgcli", "mycli", "sqlite3"]);
1710
+ var WRITING_TOOLS = new Set(["dropdb", "createdb", "pg_restore"]);
1711
+ var CONSOLE_PROGRAMS = new Set(["php", "docker", "symfony", "console", "artisan"]);
1712
+ var VALUE_SHORTS = { psql: "cdfhLopPRTUvF", pgcli: "dhUpW", mysql: "eDhPSuTA", mariadb: "eDhPSuTA", mycli: "eDhPSuTA", sqlite3: "" };
1713
+ var STATEMENT_SHORTS = { psql: "c", pgcli: "c", mysql: "e", mariadb: "e", mycli: "e", sqlite3: "" };
1714
+ var FILE_SHORTS = { psql: "f", pgcli: "", mysql: "", mariadb: "", mycli: "", sqlite3: "" };
1715
+ var IS_MYSQL = new Set(["mysql", "mariadb", "mycli"]);
1716
+ var DATABASE_SHORTS = new Set(["d", "D"]);
1717
+ var STATEMENT_LONGS = new Set(["--command", "--execute"]);
1718
+ var DATABASE_LONGS = new Set(["--dbname", "--database"]);
1719
+ var VALUE_LONGS = new Set(["--host", "--port", "--username", "--user", "--output", "--set", "--variable", "--field-separator", "--record-separator", "--pset", "--log-file", "--socket"]);
1720
+ var PRINTERS2 = new Set(["echo", "printf"]);
1721
+ var LIST_OPTIONS = new Set(["-l", "--list"]);
1722
+ var REDIRECT_ONLY2 = /^\d*(?:>|>>|>&|&>|>\||<&|<>)$/;
1723
+ var REDIRECT_START2 = /^\d*>|^&>/;
1724
+ var URL_DATABASE = /^[a-z][a-z\d+.-]*:\/\/[^/]*\/([^?#]*)/i;
1725
+ var WRITING_CONSOLE = /^(?:doctrine:(?:migrations:(?:migrate|execute|rollup)|schema:(?:update|create|drop)|database:(?:create|drop)|fixtures:load)|migrate(?::\w+)?|db:(?:seed|wipe))$/;
1726
+ var TEST_SCOPED = /(?:^|[^a-z])test/i;
1727
+ var SHOT_STACK = /\.worktrees\/[^/\s]+\/shot(?:\/|$)|--shot(?:-|$)/;
1728
+ var DEVICE_PATH = /^\/(?:dev|proc|sys)\//;
1729
+ var STDIN_PATHS = new Set(["-", "/dev/stdin"]);
1730
+ var SQL_WRITE = "Statements that write (INSERT, UPDATE, DELETE, DDL, migrations, fixtures) are handed over: list the exact command for the user to run. Only a clearly test-only database runs them directly.";
1731
+ var SQL_UNREADABLE = "A file this SQL client is fed cannot be read here (missing, a device, or too large), so what it runs is unknown. Hand over the exact command for the user to run.";
1732
+ function hasWrite(statement) {
1733
+ return writes(statement, "postgres").length > 0 || writes(statement, "mysql").length > 0;
1734
+ }
1735
+ function programOf(word) {
1736
+ return word.split("/").pop() ?? "";
1737
+ }
1738
+ function databaseOf(operand) {
1739
+ return URL_DATABASE.exec(operand)?.[1] ?? operand;
1740
+ }
1741
+ function clientInput(name, args) {
1742
+ const input = { statements: [], files: [], databases: [], operands: [] };
1743
+ const valueShorts = VALUE_SHORTS[name] ?? "";
1744
+ let isOperands = false;
1745
+ for (let i = 0;i < args.length; i++) {
1746
+ const arg = args[i] ?? "";
1747
+ if (isOperands) {
1748
+ input.operands.push(arg);
1749
+ } else if (arg === "--") {
1750
+ isOperands = true;
1751
+ } else if (arg.startsWith("<<<")) {
1752
+ input.statements.push(arg.length > 3 ? arg.slice(3) : args[++i] ?? "");
1753
+ } else if (arg.startsWith("<<")) {
1754
+ continue;
1755
+ } else if (arg === "<") {
1756
+ input.files.push(args[++i] ?? "");
1757
+ } else if (arg.startsWith("<")) {
1758
+ input.files.push(arg.slice(1));
1759
+ } else if (REDIRECT_ONLY2.test(arg)) {
1760
+ i++;
1761
+ } else if (REDIRECT_START2.test(arg)) {
1762
+ continue;
1763
+ } else if (arg.startsWith("--")) {
1764
+ const [option = "", ...rest] = arg.split("=");
1765
+ const attached = rest.length > 0 ? rest.join("=") : undefined;
1766
+ const value = attached ?? args[i + 1] ?? "";
1767
+ if (STATEMENT_LONGS.has(option))
1768
+ input.statements.push(value);
1769
+ else if (option === "--file")
1770
+ input.files.push(value);
1771
+ else if (DATABASE_LONGS.has(option))
1772
+ input.databases.push(databaseOf(value));
1773
+ if (attached === undefined && (STATEMENT_LONGS.has(option) || option === "--file" || DATABASE_LONGS.has(option) || VALUE_LONGS.has(option)))
1774
+ i++;
1775
+ } else if (arg === "-cmd" && name === "sqlite3") {
1776
+ input.statements.push(args[++i] ?? "");
1777
+ } else if (arg.startsWith("-p") && IS_MYSQL.has(name)) {
1778
+ continue;
1779
+ } else if (arg.startsWith("-") && arg.length > 1) {
1780
+ for (const [index, letter] of [...arg.slice(1)].entries()) {
1781
+ if (!valueShorts.includes(letter))
1782
+ continue;
1783
+ const attached = arg.slice(index + 2);
1784
+ const value = attached === "" ? args[++i] ?? "" : attached;
1785
+ if (STATEMENT_SHORTS[name]?.includes(letter) === true)
1786
+ input.statements.push(value);
1787
+ else if (FILE_SHORTS[name]?.includes(letter) === true)
1788
+ input.files.push(value);
1789
+ else if (DATABASE_SHORTS.has(letter))
1790
+ input.databases.push(databaseOf(value));
1791
+ break;
1792
+ }
1793
+ } else {
1794
+ input.operands.push(arg);
1795
+ }
1796
+ }
1797
+ if (name === "sqlite3")
1798
+ input.statements.push(...input.operands.slice(1));
1799
+ else if (input.operands[0] !== undefined)
1800
+ input.databases.push(databaseOf(input.operands[0]));
1801
+ return input;
1802
+ }
1803
+ function isTestScoped(words, client, input) {
1804
+ if (client === -1)
1805
+ return words.some((word) => TEST_SCOPED.test(word) || SHOT_STACK.test(word));
1806
+ return words.slice(0, client).some((word) => TEST_SCOPED.test(word) || SHOT_STACK.test(word)) || (input?.databases ?? []).some((name) => TEST_SCOPED.test(name));
1807
+ }
1808
+ async function fileText(path, read) {
1809
+ return DEVICE_PATH.test(path) ? null : read(path);
1810
+ }
1811
+ async function sqlViolation(command, read) {
1812
+ const pieces = splitCommand(command);
1813
+ let inShotStack = false;
1814
+ for (const [index, piece] of pieces.entries()) {
1815
+ const words = tokenize(piece.command);
1816
+ const { program, args } = parseCommand(piece.command);
1817
+ if (program === "cd")
1818
+ inShotStack = SHOT_STACK.test(args[0] ?? "");
1819
+ const client = words.findIndex((word) => SQL_CLIENTS.has(programOf(word)));
1820
+ const input = client === -1 ? null : clientInput(programOf(words[client] ?? ""), words.slice(client + 1));
1821
+ if (inShotStack || isTestScoped(words, client, input))
1822
+ continue;
1823
+ if (WRITING_TOOLS.has(program) && !words.some((word) => LIST_OPTIONS.has(word)))
1824
+ return SQL_WRITE;
1825
+ if (CONSOLE_PROGRAMS.has(program) && words.some((word) => WRITING_CONSOLE.test(word)))
1826
+ return SQL_WRITE;
1827
+ if (input === null)
1828
+ continue;
1829
+ const before = index === 0 ? null : parseCommand(pieces[index - 1]?.command ?? "");
1830
+ const isPiped = pieces[index - 1]?.separator === "|";
1831
+ const paths = input.files.filter((path) => !STDIN_PATHS.has(path));
1832
+ const texts = await Promise.all([...paths, ...isPiped && before?.program === "cat" ? before.args.filter((arg) => !arg.startsWith("-")) : []].map(async (path) => fileText(path, read)));
1833
+ if (texts.includes(null))
1834
+ return SQL_UNREADABLE;
1835
+ const statements = [
1836
+ ...input.statements,
1837
+ ...piece.heredocs,
1838
+ isPiped && before !== null && PRINTERS2.has(before.program) ? before.args.join(" ") : "",
1839
+ ...texts.map((text) => text ?? "")
1840
+ ];
1841
+ if (statements.some(hasWrite))
1842
+ return SQL_WRITE;
1843
+ }
1844
+ return null;
1845
+ }
1846
+
1847
+ // ../env/src/files.ts
1848
+ var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
1849
+ var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
1850
+ var SKIPPED = new Set(["node_modules", ".git", "vendor"]);
1851
+
1852
+ // ../env/src/guard.ts
1853
+ var REDIRECT = /^\d*[<>]+&?/;
1854
+ var ENVRC = ".envrc";
1855
+ var PROC_ENVIRON = /^\/proc\/[^/]+\/environ$/;
1856
+ var ENV_NAME_IN_CODE = /(?:^|[^\w.-])(\.env(?:\.[\w.-]*\w)?|\.envrc)(?![\w-])/g;
1857
+ var ENV_NAME_IN_PATTERN = /(?:^|[^\w-])\.env(?![\w-])/;
1858
+ var PYTHON_ENVIRON = /\bos\.environ\b(?!\s*(?:\[|\.get\b))/;
1859
+ var VARIABLE = /\$(?:(\w+)|\{(\w+)\})/;
1860
+ var ASSIGNMENT2 = /^\w+=/;
1861
+ var SHORT_FLAGS = /^-[a-z]+$/i;
1862
+ var OPENER = /^[({]+/;
1863
+ var ENV_SAMPLES = [".env", ".env.local", ".env.production", ".envrc"];
1864
+ var MAX_VARIANTS = 64;
1865
+ var INTERPRETERS = new Set(["bun", "deno", "node", "python", "python3", "ruby", "perl", "php", "lua", "awk", "gawk"]);
1866
+ var CODE_OPTIONS = new Set(["-e", "-c", "-p", "-E", "-pe", "-r", "--eval", "--print", "--command"]);
1867
+ var GREPS = new Set(["grep", "egrep", "fgrep"]);
1868
+ var GREP_VALUE_OPTIONS = new Set(["-e", "-f", "-m", "-A", "-B", "-C", "-d", "-D", "--regexp", "--file", "--max-count", "--include", "--exclude", "--exclude-dir", "--exclude-from", "--context", "--after-context", "--before-context", "--label", "--binary-files", "--directories", "--devices"]);
1869
+ var RG_VALUE_OPTIONS = new Set(["-e", "-f", "-g", "-t", "-T", "-m", "-A", "-B", "-C", "-j", "-d", "-r", "-M", "-E", "--replace", "--max-columns", "--encoding", "--regexp", "--file", "--glob", "--iglob", "--type", "--type-not", "--max-count", "--context", "--after-context", "--before-context", "--threads", "--max-depth", "--max-filesize"]);
1870
+ var PATTERN_OPTIONS = new Set(["-e", "-f", "--regexp", "--file"]);
1871
+ var GREP_NAMES_ONLY = new Set("lLcq");
1872
+ var RG_NAMES_ONLY = new Set("lcq");
1873
+ var NAMES_ONLY_LONG = new Set(["--files-with-matches", "--files-without-match", "--count", "--count-matches", "--quiet", "--silent"]);
1874
+ var FIND_ACTIONS = new Set(["-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", "-fls", "-files0-from"]);
1875
+ var CAN_REACH_FILES = /read|write|open|exec|spawn|system|popen|import|require|eval|load|fetch|glob|stream|source|getline|constructor|file(?!s\b)|\bcat\b|\b(?:Bun|Deno|fs|os|io|sh|bash|process|globalThis|window|Function|qx)\b|\$\s*[`({]|`/i;
1876
+ var HIDDEN_FLAGS = /^(?:-u{2,}|--hidden|-\.)$/i;
1877
+ var REGEX_SPECIALS = /[.+^${}()|\\[\]]/g;
1878
+ var NEGATED_CLASS = /^!/;
1879
+ var GLOB_CHAR = /[*?[]/;
1880
+ var HAS_R = /r/i;
1881
+ var DUMP_FLAGS = /^-[a-z]*[px]/;
1882
+ var DECLARERS = new Set(["export", "declare", "local", "readonly", "typeset"]);
1883
+ var WHOLE_TREE_OPERAND = /^(?:(?:\.\.?\/?)+|~\/?|\$HOME\/?|\/)$/;
1884
+ var GIT_PATCHES = new Set(["diff", "log", "show", "whatchanged", "format-patch", "grep"]);
1885
+ var GIT_NO_PATCH = new Set(["--stat", "--numstat", "--shortstat", "--name-only", "--name-status", "--summary", "-s", "--no-patch", "--check", "--quiet"]);
1886
+ var GIT_VALUE_OPTIONS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"]);
1887
+ var GIT_PATCH_FLAGS = new Set(["-p", "-u", "--patch", "-c", "--cc", "--patch-with-stat", "--patch-with-raw"]);
1888
+ var GIT_EXCLUDE = /^:(?:!|\^|\(exclude\))/;
1889
+ var EXCLUDES_ENV = /^(?:--exclude(?:-dir)?=.*env|(?:--glob=|--iglob=|-g)?!.*env)/;
1890
+ var EXCLUDE_OPTIONS = new Set(["--exclude", "--exclude-dir", "-g", "--glob", "--iglob"]);
1891
+ var ENV_DUMP = /(?:console\.\w+|JSON\.stringify|Object\.(?:entries|keys|values)|print)\(\s*process\.env\s*[,)]/;
1892
+ var HARMLESS = new Set(["ev", "redact", "ls", "stat", "test", "[", "[[", "touch"]);
1893
+ var GIT_HARMLESS = new Set(["check-ignore", "ls-files", "status"]);
1894
+ var XARGS_SAFE = new Set(["ls", "stat", "wc", "test", "[", "touch", "echo", "printf", "basename", "dirname", "ev", "redact", ""]);
1895
+ var PARALLEL_VALUE_OPTIONS = new Set(["-j", "--jobs", "-P", "--max-procs", "-S", "--sshlogin", "-C", "--colsep", "-n", "--max-args", "-N", "-d", "--delimiter", "-E", "-I", "--timeout", "--delay", "--joblog", "--results", "--tmpdir", "-a", "--arg-file", "--halt", "--retries", "--tag-string"]);
1896
+ var IDENTIFIER = /^[A-Z_]\w*$/i;
1897
+ var READ_VALUE_OPTIONS = new Set(["-a", "-d", "-i", "-n", "-N", "-p", "-t", "-u"]);
1898
+ var ENV_PRINTERS = new Set(["env", "printenv"]);
1899
+ var DOCKER = new Set(["docker", "docker-compose"]);
1900
+ var SHELLS2 = new Set(["sh", "bash", "zsh", "ash"]);
1901
+ var DOCKER_VALUE_OPTIONS = new Set(["-f", "--file", "-p", "--project-name", "--profile", "--env-file", "--project-directory", "--ansi", "--progress", "--parallel", "-H", "--host", "-c", "--context", "--config", "-l", "--log-level"]);
1902
+ var EXEC_VALUE_OPTIONS = new Set(["-e", "--env", "--env-file", "-u", "--user", "-w", "--workdir", "--index", "--detach-keys"]);
1903
+ var CONFIG_LISTS = new Set(["--services", "--volumes", "--profiles", "--images", "--networks", "--hash", "-q", "--quiet"]);
1904
+ var FORMAT_OPTIONS = new Set(["-f", "--format"]);
1905
+ var WHOLE_FORMAT = /Env|\{\{\s*json\s+\.\s*\}\}|^json$/;
1906
+ var USE_EV = '.env files hold secrets that must never reach the transcript, so they are not read, edited or printed directly. Use `ev` instead: `ev list`, `ev get KEY` (masked), `ev grep <regex>` for the keys matching it, `ev show <rev>:<file>` for one at a git revision, `printf %s "$value" | ev set KEY [file]` (`--empty` for an empty value), `ev unset KEY`, `ev cp KEY --from .env --to .env.local`, `ev mv KEY --from .env --to .env.local`, `ev diff a b`, `ev missing`; and pipe output that may carry a secret through `redact`, as `docker compose exec <svc> printenv | redact` or `docker compose config | redact`. If `ev` is missing: `bun install -g @kaynooo/cli-env`.';
1907
+ var USE_EV_SEARCH = "To search them, `ev grep <regex>` prints the matching keys, masked. `grep -l`, `-L` and `-c` (file names and counts) are allowed, and a tree-wide search can run as `rg <regex>`, which skips gitignored files, or `grep -r --exclude='.env*' <regex> .`.";
1908
+ function isSearchCommand(piece) {
1909
+ const { program } = parseCommand(piece.command);
1910
+ return GREPS.has(program) || program === "rg" || program === "ag";
1911
+ }
1912
+ function isEnvFile(path) {
1913
+ const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf(":")) + 1);
1914
+ return (ENV_FILE.test(name) || name === ".env*" || name === ENVRC) && !TEMPLATE.test(name);
1915
+ }
1916
+ function globRegex(glob) {
1917
+ let source = "";
1918
+ for (let i = 0;i < glob.length; i++) {
1919
+ const char = glob[i] ?? "";
1920
+ const close = char === "[" ? glob.indexOf("]", i + 2) : -1;
1921
+ if (char === "*") {
1922
+ source += ".*";
1923
+ } else if (char === "?") {
1924
+ source += ".";
1925
+ } else if (close === -1) {
1926
+ source += char.replace(REGEX_SPECIALS, String.raw`\$&`);
1927
+ } else {
1928
+ source += `[${glob.slice(i + 1, close).replace(NEGATED_CLASS, "^")}]`;
1929
+ i = close;
1930
+ }
1931
+ }
1932
+ return new RegExp(`^${source}$`);
1933
+ }
1934
+ function globReachesEnv(path) {
1935
+ const name = path.slice(path.lastIndexOf("/") + 1);
1936
+ if (!name.startsWith(".") || !GLOB_CHAR.test(name))
1937
+ return false;
1938
+ const regex = globRegex(name);
1939
+ return ENV_SAMPLES.some((sample) => regex.test(sample));
1940
+ }
1941
+ function reachesEnvFile(path) {
1942
+ return braceExpand(path).some((each) => isEnvFile(each) || globReachesEnv(each));
1943
+ }
1944
+ function targetOf(word) {
1945
+ const bare = word.replace(REDIRECT, "");
1946
+ return bare.includes("=") ? bare.slice(bare.indexOf("=") + 1) : bare;
1947
+ }
1948
+ function namesEnvFile(word, previous, isGlob) {
1949
+ if (previous === "--env-file" || word.startsWith("--env-file=") || word.startsWith("--exclude") || EXCLUDE_OPTIONS.has(previous ?? ""))
1950
+ return false;
1951
+ const path = targetOf(word);
1952
+ return isEnvFile(path) || PROC_ENVIRON.test(path) || isGlob && globReachesEnv(path);
1953
+ }
1954
+ function variablesOf(command) {
1955
+ const variables = new Map;
1956
+ const add = (assignment) => {
1957
+ const at = assignment.indexOf("=");
1958
+ const name = assignment.slice(0, at);
1959
+ variables.set(name, [...variables.get(name) ?? [], assignment.slice(at + 1)]);
1960
+ };
1961
+ for (const piece of splitCommand(command)) {
1962
+ const { program, args, assignments } = parseCommand(piece.command);
1963
+ const tokens = tokenize(piece.command);
1964
+ const declared = DECLARERS.has(program) ? args.filter((arg) => ASSIGNMENT2.test(arg)) : [];
1965
+ for (const assignment of [...assignments, ...declared])
1966
+ add(assignment);
1967
+ if (tokens[0] === "for" && tokens[2] === "in" && tokens[1] !== undefined)
1968
+ variables.set(tokens[1], [...variables.get(tokens[1]) ?? [], ...tokens.slice(3)]);
1969
+ }
1970
+ return variables;
1971
+ }
1972
+ function variantsOf(word, variables) {
1973
+ let found = [word.text];
1974
+ for (let round = 0;round < 4 && found.some((each) => VARIABLE.test(each)); round++) {
1975
+ found = found.flatMap((each) => {
1976
+ const match = VARIABLE.exec(each);
1977
+ const values = variables.get(match?.[1] ?? match?.[2] ?? "");
1978
+ if (match === null || values === undefined)
1979
+ return [each.replace(VARIABLE, "")];
1980
+ return values.map((value) => each.slice(0, match.index) + value + each.slice(match.index + match[0].length));
1981
+ }).slice(0, MAX_VARIANTS);
1982
+ }
1983
+ return found.flatMap((each) => word.hasBrace ? braceExpand(each) : [each]);
1984
+ }
1985
+ function codeReadsEnvFile(code) {
1986
+ return [...code.matchAll(ENV_NAME_IN_CODE)].some((match) => isEnvFile(match[1] ?? "")) && CAN_REACH_FILES.test(code);
1987
+ }
1988
+ function codeReadsEnv(found, heredocs) {
1989
+ const sources = [...found.filter((word, i) => word.isProse || CODE_OPTIONS.has(found[i - 1]?.text ?? "")).map((word) => word.text), ...heredocs];
1990
+ return sources.some((code) => PYTHON_ENVIRON.test(code) || codeReadsEnvFile(code));
1991
+ }
1992
+ function printsNamesOnly(program, args) {
1993
+ const isGrep = GREPS.has(program);
1994
+ if (!isGrep && program !== "rg")
1995
+ return false;
1996
+ const valueOptions = isGrep ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS;
1997
+ const valueLetters = valueLettersOf(valueOptions);
1998
+ const namesOnly = isGrep ? GREP_NAMES_ONLY : RG_NAMES_ONLY;
1999
+ let isValue = false;
2000
+ for (const arg of args) {
2001
+ if (isValue) {
2002
+ isValue = false;
2003
+ continue;
2004
+ }
2005
+ if (arg === "--")
2006
+ return false;
2007
+ if (NAMES_ONLY_LONG.has(arg))
2008
+ return true;
2009
+ if (valueOptions.has(arg)) {
2010
+ isValue = true;
2011
+ continue;
2012
+ }
2013
+ if (!SHORT_FLAGS.test(arg))
2014
+ continue;
2015
+ for (const [i, letter] of [...arg.slice(1)].entries()) {
2016
+ if (valueLetters.has(letter)) {
2017
+ isValue = i === arg.length - 2;
2018
+ break;
2019
+ }
2020
+ if (namesOnly.has(letter))
2021
+ return true;
2022
+ }
2023
+ }
2024
+ return false;
2025
+ }
2026
+ function listsFiles(program, args) {
2027
+ return program === "find" && !args.some((arg) => FIND_ACTIONS.has(arg));
2028
+ }
2029
+ function valueLettersOf(valueOptions) {
2030
+ return new Set([...valueOptions].filter((option) => option.length === 2 && !option.startsWith("--")).map((option) => option.slice(1)));
2031
+ }
2032
+ function patternIndex(args, valueOptions) {
2033
+ const valueLetters = valueLettersOf(valueOptions);
2034
+ for (let i = 0;i < args.length; i++) {
2035
+ const arg = args[i] ?? "";
2036
+ if (arg.startsWith("--regexp=") || arg.startsWith("--file="))
2037
+ return;
2038
+ if (!arg.startsWith("-") || arg === "-")
2039
+ return i;
2040
+ if (arg.startsWith("--")) {
2041
+ if (PATTERN_OPTIONS.has(arg))
2042
+ return;
2043
+ if (valueOptions.has(arg))
2044
+ i++;
2045
+ continue;
2046
+ }
2047
+ const at = [...arg.slice(1)].findIndex((letter) => valueLetters.has(letter));
2048
+ const letter = arg[at + 1];
2049
+ if (at === -1)
2050
+ continue;
2051
+ if (letter === "e" || letter === "f")
2052
+ return;
2053
+ if (at === arg.length - 2)
2054
+ i++;
2055
+ }
2056
+ return;
2057
+ }
2058
+ function firstOperand(words, valueOptions) {
2059
+ for (let i = 0;i < words.length; i++) {
2060
+ const word = words[i] ?? "";
2061
+ if (valueOptions.has(word))
2062
+ i++;
2063
+ else if (!word.startsWith("-"))
2064
+ return i;
2065
+ }
2066
+ return words.length;
2067
+ }
2068
+ function printsEnv([program = "", ...args]) {
2069
+ if (SHELLS2.has(program) && args[0] === "-c")
2070
+ return splitCommand(args[1] ?? "").some((piece) => ENV_PRINTERS.has(tokenize(piece.command)[0] ?? ""));
2071
+ return ENV_PRINTERS.has(program);
2072
+ }
2073
+ function dumpsContainerEnv(program, args) {
2074
+ if (!DOCKER.has(program))
2075
+ return false;
2076
+ const afterOptions = (words) => words.slice(firstOperand(words, DOCKER_VALUE_OPTIONS));
2077
+ let rest = afterOptions(args);
2078
+ const isCompose = program === "docker-compose" || rest[0] === "compose";
2079
+ if (program === "docker" && isCompose)
2080
+ rest = afterOptions(rest.slice(1));
2081
+ const [subcommand = "", ...after] = rest;
2082
+ if (subcommand === "exec")
2083
+ return printsEnv(after.slice(firstOperand(after, EXEC_VALUE_OPTIONS) + 1));
2084
+ if (isCompose)
2085
+ return subcommand === "config" && !after.some((word) => CONFIG_LISTS.has(word));
2086
+ if (subcommand !== "inspect" && (subcommand !== "container" || after[0] !== "inspect"))
2087
+ return false;
2088
+ const format = after.find((_, i) => FORMAT_OPTIONS.has(after[i - 1] ?? "")) ?? after.find((word) => word.startsWith("--format="))?.slice("--format=".length);
2089
+ return format === undefined || WHOLE_FORMAT.test(format);
2090
+ }
2091
+ function readsEnv(piece, variables) {
2092
+ const { program, args } = parseCommand(piece.command);
2093
+ if (program === "" || HARMLESS.has(program) || program === "git" && GIT_HARMLESS.has(args[0] ?? ""))
2094
+ return false;
2095
+ if (INTERPRETERS.has(program) && codeReadsEnv(words(piece.command), piece.heredocs))
2096
+ return true;
2097
+ if (printsNamesOnly(program, args) || listsFiles(program, args))
2098
+ return false;
2099
+ return namesEnv(piece, variables);
2100
+ }
2101
+ function namesEnv(piece, variables) {
2102
+ const { program, args } = parseCommand(piece.command);
2103
+ const found = words(piece.command);
2104
+ const isExclusion = (word) => program === "git" && GIT_EXCLUDE.test(word.text);
2105
+ const isSearch = GREPS.has(program) || program === "rg" || program === "ag";
2106
+ const patternAt = isSearch ? patternIndex(args, GREPS.has(program) ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS) : undefined;
2107
+ const pattern = patternAt === undefined ? undefined : found.length - args.length + patternAt;
2108
+ return found.some((word, index) => index !== pattern && !word.isProse && !isExclusion(word) && variantsOf(word, variables).some((variant) => namesEnvFile(variant, found[index - 1]?.text, word.hasGlob)));
2109
+ }
2110
+ function operandsOf(args, valueOptions) {
2111
+ const operands = [];
2112
+ let hasPattern = false;
2113
+ for (let i = 0;i < args.length; i++) {
2114
+ const arg = args[i] ?? "";
2115
+ if (PATTERN_OPTIONS.has(arg) || arg.startsWith("--regexp=") || arg.startsWith("--file="))
2116
+ hasPattern = true;
2117
+ if (valueOptions.has(arg))
2118
+ i++;
2119
+ else if (!arg.startsWith("-"))
2120
+ operands.push(arg);
2121
+ }
2122
+ return hasPattern ? operands : operands.slice(1);
2123
+ }
2124
+ function searchesEnv(program, args) {
2125
+ const isGrep = GREPS.has(program);
2126
+ if (!isGrep && program !== "rg" && program !== "ag" || printsNamesOnly(program, args))
2127
+ return false;
2128
+ const isRecursive = args.some((arg) => SHORT_FLAGS.test(arg) && HAS_R.test(arg) || arg === "--recursive" || arg === "--dereference-recursive");
2129
+ const isHidden = args.some((arg) => HIDDEN_FLAGS.test(arg) || program === "ag" && (arg === "-u" || arg === "--unrestricted"));
2130
+ const isLimited = args.some((arg, i) => arg.startsWith("--include") || EXCLUDES_ENV.test(arg) || EXCLUDE_OPTIONS.has(args[i - 1] ?? "") && arg.includes("env"));
2131
+ if (isLimited || (isGrep ? !isRecursive : !isHidden))
2132
+ return false;
2133
+ const operands = operandsOf(args, isGrep ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS);
2134
+ return operands.length === 0 || operands.some((operand) => WHOLE_TREE_OPERAND.test(operand));
2135
+ }
2136
+ function dumpsEnvironment(program, args, tokens) {
2137
+ const isBare = args.every((arg) => arg.startsWith("-"));
2138
+ if (program === "printenv" || program === "export")
2139
+ return isBare;
2140
+ if (program === "declare" || program === "typeset")
2141
+ return isBare && args.some((arg) => DUMP_FLAGS.test(arg));
2142
+ if (program === "set")
2143
+ return args.length === 0;
2144
+ return program === "" && tokens.some((token) => token.replace(OPENER, "") === "env");
2145
+ }
2146
+ function printsTrackedEnv(program, args) {
2147
+ if (program !== "git")
2148
+ return false;
2149
+ const at = args.findIndex((arg, i) => !arg.startsWith("-") && !GIT_VALUE_OPTIONS.has(args[i - 1] ?? ""));
2150
+ const name = args[at] ?? "";
2151
+ const rest = args.slice(at + 1);
2152
+ if (!GIT_PATCHES.has(name) || rest.some((arg) => GIT_EXCLUDE.test(arg)))
2153
+ return false;
2154
+ if (name === "grep")
2155
+ return true;
2156
+ if (name === "log" || name === "whatchanged")
2157
+ return rest.some((arg) => GIT_PATCH_FLAGS.has(arg));
2158
+ return !rest.some((arg) => GIT_NO_PATCH.has(arg));
2159
+ }
2160
+ function searchesEnvNames(piece) {
2161
+ const { program, args } = parseCommand(piece.command);
2162
+ if (!GREPS.has(program) && program !== "rg")
2163
+ return false;
2164
+ const at = patternIndex(args, GREPS.has(program) ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS);
2165
+ return at !== undefined && ENV_NAME_IN_PATTERN.test((args[at] ?? "").replaceAll("\\", ""));
2166
+ }
2167
+ function listsEnvUpstream(pieces, index, variables) {
2168
+ for (let at = index - 1;at >= 0 && pieces[at]?.separator.startsWith("|"); at--) {
2169
+ if (namesEnv(pieces[at], variables) || searchesEnvNames(pieces[at]))
2170
+ return true;
2171
+ }
2172
+ return false;
2173
+ }
2174
+ function parallelRunner(args) {
2175
+ const at = args.findIndex((arg, i) => !arg.startsWith("-") && !PARALLEL_VALUE_OPTIONS.has(args[i - 1] ?? ""));
2176
+ return at === -1 ? "" : (args[at] ?? "").split("/").at(-1) ?? "";
2177
+ }
2178
+ function runnerReadsListedEnv(pieces, index, variables) {
2179
+ const command = pieces[index]?.command ?? "";
2180
+ const { program, args, isWrapped } = parseCommand(command);
2181
+ const isXargs = isWrapped && tokenize(command).includes("xargs");
2182
+ if (program !== "parallel" && !isXargs)
2183
+ return false;
2184
+ return !XARGS_SAFE.has(isXargs ? program : parallelRunner(args)) && listsEnvUpstream(pieces, index, variables);
2185
+ }
2186
+ function readVariables(args) {
2187
+ const names = args.filter((arg, i) => !arg.startsWith("-") && !READ_VALUE_OPTIONS.has(args[i - 1] ?? "") && IDENTIFIER.test(arg));
2188
+ return names.length === 0 ? ["REPLY"] : names;
2189
+ }
2190
+ function loopReadsListedEnv(pieces, index, variables) {
2191
+ const { program } = parseCommand(pieces[index]?.command ?? "");
2192
+ if (XARGS_SAFE.has(program) || program === "done")
2193
+ return false;
2194
+ for (let at = index - 1;at >= 0; at--) {
2195
+ const piece = pieces[at];
2196
+ const head = parseCommand(piece.command);
2197
+ if (head.program === "done")
2198
+ return false;
2199
+ const opener = tokenize(piece.command)[0];
2200
+ if (head.program !== "read" || opener !== "while" && opener !== "until")
2201
+ continue;
2202
+ const used = readVariables(head.args).some((name) => new RegExp(`\\$\\{?${name}\\b`).test(pieces[index]?.command ?? ""));
2203
+ return used && listsEnvUpstream(pieces, at, variables);
2204
+ }
2205
+ return false;
2206
+ }
2207
+ function touchingPieces(command, options = {}) {
2208
+ const pieces = splitCommand(command);
2209
+ if (ENV_DUMP.test(command) || substitutions(command).some((each) => touchesEnv(each, options)))
2210
+ return pieces;
2211
+ const variables = variablesOf(command);
2212
+ return pieces.filter((piece, index) => {
2213
+ const { program, args } = parseCommand(piece.command);
2214
+ if (readsEnv(piece, variables) || searchesEnv(program, args) || runnerReadsListedEnv(pieces, index, variables) || loopReadsListedEnv(pieces, index, variables))
2215
+ return true;
2216
+ const isDump = dumpsContainerEnv(program, args) || dumpsEnvironment(program, args, tokenize(piece.command)) || options.hasTrackedEnv === true && printsTrackedEnv(program, args);
2217
+ if (!isDump)
2218
+ return false;
2219
+ for (let at = index;pieces[at]?.separator === "|"; at++) {
2220
+ if (parseCommand(pieces[at + 1]?.command ?? "").program === "redact")
2221
+ return false;
2222
+ }
2223
+ return true;
2224
+ });
2225
+ }
2226
+ function touchesEnv(command, options = {}) {
2227
+ return touchingPieces(command, options).length > 0;
2228
+ }
2229
+
2230
+ // ../git/src/message.ts
2231
+ var CONVENTIONAL = /^(?:feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\([^()\n]+\))?!?: \S/;
2232
+ var MAX_TITLE = 100;
2233
+ var GIT_MADE = /^(?:Merge |Revert "|fixup! |squash! |amend! )/;
2234
+ var TICKET = /^(?:[\w.-]+\/[\w.-]+)?#\d+ - /;
2235
+ var BREAKING = /^BREAKING[ -]CHANGE: /;
2236
+ var BREAKING_TITLE = /^[a-z]+(?:\([^()\n]+\))?!: /;
2237
+ var TRAILER = /^(?:co-authored-by|signed-off-by|reviewed-by|acked-by|tested-by|reported-by|suggested-by|helped-by|change-id):|^\W*generated with \W*claude/i;
2238
+ var BULLET = /^\s*(?:[-*+]|\d+[.)])\s/;
2239
+ var SENTENCE_END = /[.!?:;)\]`'"]$/;
2240
+ var LOWER_START = /^\p{Ll}/u;
2241
+ var RULE = 'The rule: a `type(scope): title` line, `!` after the scope for a breaking change, type and scope taken from the repository\'s history; then optionally a blank line and one or two lines on what changed, never a bullet list or a hard-wrapped sentence; then a blank line and one line per ticket, its title copied verbatim, `#<n> - <title>` (`owner/repo#<n> - <title>` for another repository). The message ends there: no Co-Authored-By, Signed-off-by or "Generated with" trailer. Only a breaking change gives full details.';
2242
+ var TITLE = `The title is no Conventional Commit. ${RULE}`;
2243
+ var TITLE_TOO_LONG = `The title runs past ${MAX_TITLE} characters: shorten it and move the detail to the body. ${RULE}`;
2244
+ var TITLE_LINE = `The title takes one line and a blank line follows it. ${RULE}`;
2245
+ var TRAILERS = `No trailers, ever: no Co-Authored-By, Signed-off-by or "Generated with" line, no --signoff or --trailer. ${RULE}`;
2246
+ var BULLETS = `The body names what changed in a line or two, never a bullet list narrating the diff. ${RULE}`;
2247
+ var TOO_LONG = `The body holds at most two lines besides the ticket lines; what goes beyond belongs in the reply. ${RULE}`;
2248
+ var WRAPPED = `A body sentence stays on one line however long it runs: never hard-wrap it. ${RULE}`;
2249
+ var USE_GC = "Commit with `gc`, which stages exactly the paths given once the message keeps the rule: `gc 'fix(api): retry a timed-out fetch' -m 'A 502 is retried once before failing.' --ticket '#12 - [UC3] Retry failed fetches' -- src/api.ts`.";
2250
+ function isDescription(line) {
2251
+ return line !== undefined && line !== "" && !TICKET.test(line);
2252
+ }
2253
+ function commitMessageViolation(message) {
2254
+ const lines = message.split(`
2255
+ `).map((line) => line.trimEnd());
2256
+ while (lines[0] === "")
2257
+ lines.shift();
2258
+ while (lines.at(-1) === "")
2259
+ lines.pop();
2260
+ const [title = "", second, ...body] = lines;
2261
+ if (title === "")
2262
+ return null;
2263
+ if (lines.some((line) => TRAILER.test(line)))
2264
+ return TRAILERS;
2265
+ if (!CONVENTIONAL.test(title) && !GIT_MADE.test(title))
2266
+ return TITLE;
2267
+ if (second !== undefined && second !== "")
2268
+ return TITLE_LINE;
2269
+ if (!GIT_MADE.test(title) && title.length > MAX_TITLE)
2270
+ return TITLE_TOO_LONG;
2271
+ if (BREAKING_TITLE.test(title))
2272
+ return null;
2273
+ const footer = body.findIndex((line) => BREAKING.test(line));
2274
+ const described = footer === -1 ? body : body.slice(0, footer);
2275
+ const descriptions = described.filter(isDescription);
2276
+ if (descriptions.some((line) => BULLET.test(line)))
2277
+ return BULLETS;
2278
+ if (descriptions.length > 2)
2279
+ return TOO_LONG;
2280
+ const isWrapped = described.some((line, i) => isDescription(line) && isDescription(described[i + 1]) && !SENTENCE_END.test(line) && LOWER_START.test(described[i + 1] ?? ""));
2281
+ return isWrapped ? WRAPPED : null;
2282
+ }
2283
+
2284
+ // ../out/src/fold.ts
2285
+ var FOLD_LINES = 150;
2286
+
2287
+ // ../out/src/wrap.ts
2288
+ var ASSIGNMENT3 = /^\w+=/;
2289
+ var EXCLUDED = /(?:^|\s)(?:--json|--help|--version|-h|--watch(?:-?all|=\S*)?|--watchAll)(?:\s|$)/;
2290
+ var SHORT_WATCH = /(?:^|\s)(?:\S*\/)?(?:tsc|tsgo|vue-tsc|vitest|jest)\s(?:.*\s)?-w(?:\s|$)/;
2291
+ var LONG_RUNNING = /^(?:dev|watch|serve|start|up|run|preview|storybook)(?:[:-]\S*)?$/;
2292
+ var BUN_SCRIPT = /^(?:build|check|lint|typecheck|types|test|ci|verify|compile)(?::|$)/;
2293
+ var BUN_TOOLS = new Set(["tsc", "tsgo", "eslint", "keslint", "vitest", "jest", "prettier", "playwright", "biome", "vue-tsc"]);
2294
+ var BUN_SUBCOMMANDS = new Set(["install", "i", "add", "remove", "rm", "update", "test", "check", "lint", "build"]);
2295
+ var STDERR_MERGE = /\s+2>&1$/;
2296
+ var CUTS = new Set(["tail", "head"]);
2297
+ var CUT_COUNT = /^(?:-n ?|--lines=|-)(\d+)$/;
2298
+ var PHP_VALUE_OPTIONS = new Set(["-d", "-c", "-z"]);
2299
+ var BUNX_VALUE_OPTIONS = new Set(["-p", "--package"]);
2300
+ var COMPOSE_VALUE_OPTIONS = new Set(["-f", "--file", "-p", "--project-name", "--profile", "--env-file", "--project-directory", "--ansi", "--progress", "--parallel"]);
2301
+ var EXEC_VALUE_OPTIONS2 = new Set(["-e", "--env", "--env-file", "-u", "--user", "-w", "--workdir", "--index", "--detach-keys", "--name", "--entrypoint", "-v", "--volume", "-p", "--publish", "-l", "--label", "--cap-add", "--cap-drop", "--pull"]);
2302
+ var always = () => true;
2303
+ var typecheck = ([sub]) => sub === "typecheck";
2304
+ var RULES = {
2305
+ bun: ([sub, script]) => sub !== undefined && (BUN_SUBCOMMANDS.has(sub) || sub === "run" && script !== undefined && BUN_SCRIPT.test(script)),
2306
+ bunx: (args) => {
2307
+ const [tool, ...rest] = afterOptions(args, BUNX_VALUE_OPTIONS);
2308
+ return tool !== undefined && (BUN_TOOLS.has(tool) || (tool === "nuxi" || tool === "nuxt") && typecheck(rest));
2309
+ },
2310
+ tsc: always,
2311
+ tsgo: always,
2312
+ "vue-tsc": always,
2313
+ nuxi: typecheck,
2314
+ nuxt: typecheck,
2315
+ eslint: always,
2316
+ keslint: always,
2317
+ vitest: always,
2318
+ jest: always,
2319
+ pytest: always,
2320
+ phpunit: always,
2321
+ paratest: always,
2322
+ phpstan: always,
2323
+ pest: always,
2324
+ "php-cs-fixer": always,
2325
+ rector: always,
2326
+ php: (args) => listed2(afterOptions(args, PHP_VALUE_OPTIONS)),
2327
+ make: ([first]) => first === undefined || !LONG_RUNNING.test(first),
2328
+ check: always,
2329
+ just: ([first]) => first !== undefined && !first.startsWith("-") && !LONG_RUNNING.test(first),
2330
+ composer: ([sub]) => sub === "install" || sub === "update" || sub === "require",
2331
+ pip: ([sub]) => sub === "install",
2332
+ cargo: ([sub]) => ["build", "test", "check", "clippy"].includes(sub ?? ""),
2333
+ go: ([sub]) => ["build", "test", "vet"].includes(sub ?? ""),
2334
+ docker: (args) => {
2335
+ if (args[0] === "build")
2336
+ return true;
2337
+ if (args[0] === "exec")
2338
+ return listed2(afterOptions(args.slice(1), EXEC_VALUE_OPTIONS2).slice(1));
2339
+ if (args[0] !== "compose")
2340
+ return false;
2341
+ const [sub, ...rest] = afterOptions(args.slice(1), COMPOSE_VALUE_OPTIONS);
2342
+ if (sub === "exec" || sub === "run")
2343
+ return listed2(afterOptions(rest, EXEC_VALUE_OPTIONS2).slice(1));
2344
+ return sub === "build" || sub === "pull";
2345
+ }
2346
+ };
2347
+ function afterOptions(args, valued) {
2348
+ let index = 0;
2349
+ while (args[index]?.startsWith("-") === true) {
2350
+ index += valued.has(args[index] ?? "") ? 2 : 1;
2351
+ }
2352
+ return args.slice(index);
2353
+ }
2354
+ function scan(command) {
2355
+ const segments = [];
2356
+ const pipes = [];
2357
+ let current = "";
2358
+ let plain = true;
2359
+ for (const piece of splitCommand(command)) {
2360
+ current += piece.text;
2361
+ plain &&= isPlain(piece.text) && piece.separator !== "&";
2362
+ if (piece.separator === "|") {
2363
+ pipes.push(piece.end);
2364
+ current += "|";
2365
+ plain = false;
2366
+ continue;
2367
+ }
2368
+ segments.push(current);
2369
+ current = "";
2370
+ }
2371
+ return { segments: segments.map((segment) => segment.trim()).filter((segment) => segment !== ""), plain, pipes };
2372
+ }
2373
+ function isFilter(stage) {
2374
+ const { segments, plain } = scan(stage);
2375
+ const [bin, ...args] = tokenize(stage);
2376
+ const count = CUT_COUNT.exec(args.join(" "))?.[1];
2377
+ return plain && segments.length === 1 && bin !== undefined && CUTS.has(bin) && count !== undefined && Number(count) >= FOLD_LINES;
2378
+ }
2379
+ function withoutFilters(command) {
2380
+ let rest = command;
2381
+ const stages = [];
2382
+ for (let at = scan(rest).pipes.at(-1);at !== undefined && isFilter(rest.slice(at + 1).trim()); at = scan(rest).pipes.at(-1)) {
2383
+ stages.unshift(rest.slice(at + 1).trim());
2384
+ rest = rest.slice(0, at).trimEnd().replace(STDERR_MERGE, "");
2385
+ }
2386
+ return { rest, stages };
2387
+ }
2388
+ function listed2(words) {
2389
+ const start = words.findIndex((word) => !ASSIGNMENT3.test(word));
2390
+ const path = words[start];
2391
+ if (path === undefined)
2392
+ return false;
2393
+ return RULES[path.slice(path.lastIndexOf("/") + 1)]?.(words.slice(start + 1)) ?? false;
2394
+ }
2395
+ function listedSegment(segment) {
2396
+ return !EXCLUDED.test(segment) && !SHORT_WATCH.test(segment) && listed2(tokenize(segment));
2397
+ }
2398
+ function isCd(segment) {
2399
+ return segment === "cd" || segment.startsWith("cd ");
2400
+ }
2401
+ function shouldWrap(command) {
2402
+ const { segments, plain } = scan(withoutFilters(command.trim()).rest);
2403
+ if (!plain || !segments.some((segment) => listedSegment(segment)))
2404
+ return false;
2405
+ return segments.every((segment) => isCd(segment) || listedSegment(segment));
2406
+ }
2407
+ function wrap(command) {
2408
+ const { rest, stages } = withoutFilters(command.trim());
2409
+ const out = ["out", ...stages.flatMap((stage) => ["--was", shellQuote(stage)]), "--"].join(" ");
2410
+ if (scan(rest).segments.length <= 1 && !ASSIGNMENT3.test(rest))
2411
+ return `${out} ${rest}`;
2412
+ return `${out} sh -c ${shellQuote(rest)}`;
2413
+ }
2414
+
2415
+ // ../pkg/src/added.ts
2416
+ var REDIRECT2 = /^\d*[<>]/;
2417
+ var BARE_REDIRECT = /^\d*(?:[<>]|>>)$/;
2418
+ var ADDS = {
2419
+ bun: new Set(["add", "a", "install", "i"]),
2420
+ npm: new Set(["install", "i", "add", "in", "isntall"]),
2421
+ pnpm: new Set(["add", "i", "install"]),
2422
+ yarn: new Set(["add"])
2423
+ };
2424
+ var RUNS = {
2425
+ bun: new Set(["x"]),
2426
+ npm: new Set(["exec", "x"]),
2427
+ pnpm: new Set(["dlx"]),
2428
+ yarn: new Set(["dlx"])
2429
+ };
2430
+ var RUNNERS = new Set(["bunx", "npx"]);
2431
+ var PACKAGE_FLAGS = new Set(["-p", "--package"]);
2432
+ var VALUE_FLAGS = new Set(["--cwd", "--filter", "-F", "--workspace", "--registry", "--prefix", "-C", "--dir", "--config", "--cache-dir", "--loglevel", "--tag", "--save-prefix", "--userconfig", "--omit", "--include", "--fetch-timeout", "--fetch-retries", "--install-strategy", "--cache", ...PACKAGE_FLAGS]);
2433
+ var NOT_REGISTRY = /^(?:[./~]|file:|link:|portal:|workspace:|git[+:]|github:|gitlab:|bitbucket:|https?:)|\.tgz$|^[\w.-]+\/[\w.-]+(?:#.*)?$/;
2434
+ var NPM_ALIAS = /^(?:@[^/]+\/)?[^@]+@npm:(.+)$/;
2435
+ var PUBLISH = /\b(?:ft|cli\.ts)\s+release\b|\b(?:bun|npm|pnpm|yarn)\s+publish\b|\bjust\s+(?:patch|minor|major)\b/;
2436
+ function addedPackages(command) {
2437
+ let published = false;
2438
+ return splitCommand(command).flatMap((piece) => {
2439
+ published ||= PUBLISH.test(piece.command);
2440
+ const { program, args } = parseCommand(piece.command);
2441
+ const [sub = "", ...rest] = args;
2442
+ if (published)
2443
+ return [];
2444
+ if (RUNNERS.has(program))
2445
+ return runnerPackages(args);
2446
+ if (RUNS[program]?.has(sub))
2447
+ return runnerPackages(rest);
2448
+ if (!ADDS[program]?.has(sub))
2449
+ return [];
2450
+ return rest.flatMap((word, index) => isSkipped(word, rest[index - 1] ?? "") ? [] : registryName(word));
2451
+ });
2452
+ }
2453
+ function isSkipped(word, previous) {
2454
+ return word.startsWith("-") || REDIRECT2.test(word) || VALUE_FLAGS.has(previous) || BARE_REDIRECT.test(previous);
2455
+ }
2456
+ function registryName(word) {
2457
+ return NOT_REGISTRY.test(word) ? [] : [NPM_ALIAS.exec(word)?.[1] ?? word];
2458
+ }
2459
+ function runnerPackages(words) {
2460
+ const named = [];
2461
+ for (const [index, word] of words.entries()) {
2462
+ const previous = words[index - 1] ?? "";
2463
+ if (PACKAGE_FLAGS.has(previous))
2464
+ named.push(word);
2465
+ else if (word.startsWith("--package="))
2466
+ named.push(word.slice("--package=".length));
2467
+ else if (!isSkipped(word, previous) && named.length === 0)
2468
+ return registryName(word);
2469
+ else if (!isSkipped(word, previous))
2470
+ break;
2471
+ }
2472
+ return named.flatMap(registryName);
2473
+ }
2474
+
2475
+ // ../pkg/src/pin.ts
2476
+ var LOCKFILES = [
2477
+ ["bun.lock", "bun"],
2478
+ ["bun.lockb", "bun"],
2479
+ ["pnpm-lock.yaml", "pnpm"],
2480
+ ["yarn.lock", "yarn"],
2481
+ ["package-lock.json", "npm"]
2482
+ ];
2483
+ var ACTIONS = {
2484
+ bun: actions({ install: ["install", "i"], add: ["add", "a"], remove: ["remove", "rm"], update: ["update"] }),
2485
+ pnpm: actions({ install: ["install", "i"], add: ["add"], remove: ["remove", "rm"], update: ["update", "up"] }),
2486
+ yarn: new Map([...actions({ install: ["", "install"], add: ["add"], remove: ["remove"], update: ["upgrade"] }), ["upgrade-interactive", null], ["import", null]]),
2487
+ npm: actions({
2488
+ install: ["install", "i", "in", "ins", "inst", "insta", "instal", "isnt", "isnta", "isntal", "isntall"],
2489
+ add: ["add"],
2490
+ frozen: ["ci", "clean-install", "ic", "install-clean", "isntall-clean"],
2491
+ remove: ["uninstall", "unlink", "remove", "rm", "r", "un"],
2492
+ update: ["update", "u", "up", "upgrade", "udpate"]
2493
+ })
2494
+ };
2495
+ var COMMANDS = {
2496
+ bun: { install: "install", frozen: "install --frozen-lockfile", add: "add", remove: "remove", update: "update" },
2497
+ pnpm: { install: "install", frozen: "install --frozen-lockfile", add: "add", remove: "remove", update: "update" },
2498
+ yarn: { install: "install", add: "add", remove: "remove" },
2499
+ npm: { install: "install", frozen: "ci", add: "install", remove: "uninstall", update: "update" }
2500
+ };
2501
+ var OPTIONS = {
2502
+ bun: { dev: "--dev", exact: "--exact" },
2503
+ pnpm: { dev: "--save-dev", exact: "--save-exact" },
2504
+ yarn: { dev: "--dev", exact: "--exact" },
2505
+ npm: { dev: "--save-dev", exact: "--save-exact" }
2506
+ };
2507
+ var OPTION_FLAGS = new Map([
2508
+ ["-D", "dev"],
2509
+ ["--save-dev", "dev"],
2510
+ ["--dev", "dev"],
2511
+ ["-E", "exact"],
2512
+ ["--save-exact", "exact"],
2513
+ ["--exact", "exact"]
2514
+ ]);
2515
+ var DIR_FLAGS = new Set(["--cwd", "-C", "--dir", "--prefix"]);
2516
+ var VALUE_FLAGS2 = new Set([...DIR_FLAGS, "--filter", "-F"]);
2517
+ var PLAIN_WORD = /^[\w=@./:+-]+$/;
2518
+ function actions(byAction) {
2519
+ return new Map(Object.entries(byAction).flatMap(([action, names]) => names.map((name) => [name, action])));
2520
+ }
2521
+ function isManager(program) {
2522
+ return Object.hasOwn(ACTIONS, program);
2523
+ }
2524
+ function translate(from, to, subcommand, rest) {
2525
+ const packages = rest.filter((arg) => !arg.startsWith("-"));
2526
+ const flags = rest.filter((arg) => arg.startsWith("-"));
2527
+ const listed = ACTIONS[from].get(subcommand);
2528
+ const action = listed === "install" && packages.length > 0 ? "add" : listed;
2529
+ const command = action ? COMMANDS[to][action] : undefined;
2530
+ if (!action || command === undefined || !packages.every((name) => PLAIN_WORD.test(name)))
2531
+ return null;
2532
+ const options = [];
2533
+ for (const flag of flags) {
2534
+ const option = OPTION_FLAGS.get(flag) ?? (from === "bun" && flag === "-d" ? "dev" : undefined);
2535
+ if (option === undefined || action !== "add")
2536
+ return null;
2537
+ options.push(OPTIONS[to][option]);
2538
+ }
2539
+ return [to, command, ...options, ...packages].join(" ");
2540
+ }
2541
+ function installRequests(command, cwd, home) {
2542
+ const requests = [];
2543
+ for (const piece of splitCommand(command)) {
2544
+ const { program, args, assignments, isWrapped } = parseCommand(piece.command);
2545
+ if (program === "cd" && args[0] !== undefined) {
2546
+ cwd = resolvePath(cwd, args[0], home);
2547
+ continue;
2548
+ }
2549
+ if (!isManager(program))
2550
+ continue;
2551
+ let dir = cwd;
2552
+ let subcommand = "";
2553
+ let rest = [];
2554
+ let hasLeadingFlag = false;
2555
+ for (let i = 0;i < args.length; i++) {
2556
+ const arg = args[i] ?? "";
2557
+ const [flag = "", value] = arg.split("=", 2);
2558
+ if (DIR_FLAGS.has(flag) && value !== undefined && value !== "") {
2559
+ dir = resolvePath(cwd, value, home);
2560
+ } else if (VALUE_FLAGS2.has(arg)) {
2561
+ if (DIR_FLAGS.has(arg) && args[i + 1] !== undefined)
2562
+ dir = resolvePath(cwd, args[i + 1] ?? "", home);
2563
+ i++;
2564
+ } else if (!arg.startsWith("-")) {
2565
+ subcommand = arg;
2566
+ rest = args.slice(i + 1);
2567
+ break;
2568
+ }
2569
+ hasLeadingFlag = true;
2570
+ }
2571
+ if (ACTIONS[program].has(subcommand))
2572
+ requests.push({ piece, program, subcommand, rest, dir, assignments, isRewritable: !hasLeadingFlag && !isWrapped && piece.command === piece.text });
2573
+ }
2574
+ return requests;
2575
+ }
2576
+ function mismatchFor(request, pinned) {
2577
+ const { piece, program, subcommand, rest, isRewritable, assignments } = request;
2578
+ if (!pinned || pinned.managers.has(program))
2579
+ return null;
2580
+ const expected = [...pinned.managers];
2581
+ const only = expected.length === 1 ? expected[0] : undefined;
2582
+ const canRewrite = only !== undefined && isRewritable && assignments.every((word) => PLAIN_WORD.test(word));
2583
+ const translated = canRewrite ? translate(program, only, subcommand, rest) : null;
2584
+ const leading = piece.text.slice(0, piece.text.length - piece.text.trimStart().length);
2585
+ const trailing = piece.text.slice(piece.text.trimEnd().length);
2586
+ return {
2587
+ piece,
2588
+ rewrite: translated === null ? null : `${leading}${[...assignments, translated].join(" ")}${trailing}`,
2589
+ reason: `${pinned.dir} is pinned to ${expected.join(" or ")} by its lockfile, so \`${`${program} ${subcommand}`.trim()}\` would install with the wrong package manager.`
2590
+ };
2591
+ }
2592
+
2593
+ // src/git.ts
2594
+ var GLOBAL_VALUE_OPTIONS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env"]);
2595
+ var READ_ONLY_STASH = new Set(["list", "show"]);
2596
+ var WHOLE_TREE = new Set(["-A", "--all", "-u", "--update", "--no-ignore-removal", ".", "./", ":/", "*"]);
2597
+ var COMMIT_VALUE_SHORTS = new Set(["m", "F", "c", "C", "t"]);
2598
+ var COMMIT_VALUE_LONGS = new Set(["--message", "--file", "--reuse-message", "--reedit-message", "--template", "--author", "--date", "--fixup", "--squash", "--cleanup", "--trailer", "--pathspec-from-file"]);
2599
+ var SHORT_CLUSTER = /^-[A-Z]+$/i;
2600
+ var STAGES_ALL = /[Au]/;
2601
+ var ALL_TAGS = new Set(["--tags", "--follow-tags"]);
2602
+ var TOP_MAGIC = /^:(?:\/|\([^)]*\))/;
2603
+ var RISKY_CONFIG = /^(?:alias\.|core\.(?:sshcommand|hookspath|pager|editor|fsmonitor|askpass|gitproxy)|credential\.|diff\.external|sequence\.editor|pager\.|filter\.|gpg\..*program)/i;
2604
+ var RISKY_ENV = /^GIT_(?:CONFIG_(?:COUNT|PARAMETERS)|EXTERNAL_DIFF|ASKPASS|PROXY_COMMAND|PAGER)=/;
2605
+ var READS_CONFIG = new Set(["--get", "--get-all", "--get-regexp", "--list", "-l", "--unset", "--unset-all", "--show-origin", "--show-scope"]);
2606
+ var STAGE_BY_PATH = `Stage by path: the tree carries unrelated work and peer sessions edit it live. ${USE_GC}`;
2607
+ var STASH = "Never `git stash`: a pop with nothing saved applies someone else's old stash. To prove a test fails without your change, `proof --keep <test> -- <cmd>` runs it at HEAD in a temporary worktree and again here; `base -- <cmd>` runs any command at HEAD (`--ref <rev>` another commit), the working tree untouched. To set edits aside before a cherry-pick, a rebase or a checkout, commit them with `gc` first, or do the other work in `git worktree add`.";
2608
+ var ADD_ALL = `\`git add\` over the whole tree is refused. ${STAGE_BY_PATH}`;
2609
+ var COMMIT_ALL = `\`git commit -a\` stages the whole tree and is refused. ${STAGE_BY_PATH}`;
2610
+ var PUSH = "`git push` runs only when the user asked for a push in their latest prompt: say the commit is ready and let them ask.";
2611
+ var CONFIG_OVERRIDE = "Never set git config that runs a program or defines a command (`-c alias.*`, `--config-env`, `core.sshCommand`, `core.hooksPath`, `core.pager`, credential helpers, `git config alias.*`): it sidesteps every rule here. Run the git command itself.";
2612
+ var TAGS_APART = "A tag goes out with its branch in one `git push --atomic origin <branch> <tag>`, never a separate `git push --tags`.";
2613
+ function subcommandOf(args) {
2614
+ for (let i = 0;i < args.length; i++) {
2615
+ const arg = args[i] ?? "";
2616
+ if (GLOBAL_VALUE_OPTIONS.has(arg))
2617
+ i++;
2618
+ else if (!arg.startsWith("-"))
2619
+ return { name: arg, rest: args.slice(i + 1) };
2620
+ }
2621
+ return { name: "", rest: [] };
2622
+ }
2623
+ function overridesConfig(args) {
2624
+ for (let i = 0;i < args.length; i++) {
2625
+ const arg = args[i] ?? "";
2626
+ if (arg === "--config-env" || arg.startsWith("--config-env="))
2627
+ return true;
2628
+ if (arg === "-c" && RISKY_CONFIG.test(args[i + 1] ?? ""))
2629
+ return true;
2630
+ if (GLOBAL_VALUE_OPTIONS.has(arg))
2631
+ i++;
2632
+ else if (!arg.startsWith("-"))
2633
+ return false;
2634
+ }
2635
+ return false;
2636
+ }
2637
+ function isWholeTree(arg) {
2638
+ if (WHOLE_TREE.has(arg))
2639
+ return true;
2640
+ if (arg.startsWith("-"))
2641
+ return SHORT_CLUSTER.test(arg) && STAGES_ALL.test(arg);
2642
+ const parts = [];
2643
+ for (const part of arg.replace(TOP_MAGIC, "").split("/")) {
2644
+ if (part === ".." && parts.length > 0 && parts.at(-1) !== "..")
2645
+ parts.pop();
2646
+ else if (part !== "" && part !== ".")
2647
+ parts.push(part);
2648
+ }
2649
+ const path = parts.join("/");
2650
+ return path === "" || path === ".." || WHOLE_TREE.has(path);
2651
+ }
2652
+ function commitsAll(args) {
2653
+ for (let i = 0;i < args.length; i++) {
2654
+ const arg = args[i] ?? "";
2655
+ if (arg === "--")
2656
+ return false;
2657
+ if (arg === "--all")
2658
+ return true;
2659
+ if (COMMIT_VALUE_LONGS.has(arg)) {
2660
+ i++;
2661
+ continue;
2662
+ }
2663
+ if (!SHORT_CLUSTER.test(arg))
2664
+ continue;
2665
+ for (const [index, flag] of [...arg.slice(1)].entries()) {
2666
+ if (flag === "a")
2667
+ return true;
2668
+ if (!COMMIT_VALUE_SHORTS.has(flag))
2669
+ continue;
2670
+ if (index === arg.length - 2)
2671
+ i++;
2672
+ break;
2673
+ }
2674
+ }
2675
+ return false;
2676
+ }
2677
+ function gitViolation(command, isPushAsked = false) {
2678
+ for (const piece of splitCommand(command)) {
2679
+ const { program, args, assignments } = parseCommand(piece.command);
2680
+ if (assignments.some((assignment) => RISKY_ENV.test(assignment)))
2681
+ return CONFIG_OVERRIDE;
2682
+ if (program !== "git")
2683
+ continue;
2684
+ if (overridesConfig(args))
2685
+ return CONFIG_OVERRIDE;
2686
+ const { name, rest } = subcommandOf(args);
2687
+ if (name === "config" && rest.length > 1 && rest.some((arg) => RISKY_CONFIG.test(arg)) && !rest.some((arg) => READS_CONFIG.has(arg)))
2688
+ return CONFIG_OVERRIDE;
2689
+ if (name === "stash" && !READ_ONLY_STASH.has(rest[0] ?? ""))
2690
+ return STASH;
2691
+ if (name === "add" && rest.some(isWholeTree))
2692
+ return ADD_ALL;
2693
+ if (name === "commit" && commitsAll(rest))
2694
+ return COMMIT_ALL;
2695
+ if (name === "push" && !isPushAsked)
2696
+ return PUSH;
2697
+ if (name === "push" && rest.some((arg) => ALL_TAGS.has(arg)) && !rest.includes("--atomic"))
2698
+ return TAGS_APART;
2699
+ }
2700
+ return null;
2701
+ }
2702
+
2703
+ // src/commit.ts
2704
+ var REUSES = new Set(["c", "C", "--reuse-message", "--reedit-message", "--fixup", "--squash"]);
2705
+ var TRAILER_FLAGS = new Set(["--signoff", "--trailer"]);
2706
+ var LONG_VALUE = /=(.*)/s;
2707
+ var CAT_OPENER = /^\$\(cat <<-?[ \t]*(['"]?)([\w-]+)\1/;
2708
+ var GLOB = /[*?[]/;
2709
+ var PLAIN_COMMIT_OPTION = /^(?:-q?m.*|-q|--quiet|--message=.*)$/s;
2710
+ var HEREDOC_OPENER = /<<-?[ \t]*(['"]?)([\w-]+)\1/;
2711
+ var TICKET_LINE = /^(?:[\w.-]+\/[\w.-]+)?#\d+ - /;
2712
+ var CAT_CLOSER = /^\s*(?:\)\s*)?$/;
2713
+ var EXPANDS = /\$[({\w]|`/;
2714
+ function heredocBody(text, opener) {
2715
+ const found = opener.exec(text);
2716
+ const newline = found === null ? -1 : text.indexOf(`
2717
+ `, found.index + found[0].length);
2718
+ if (found === null || newline === -1)
2719
+ return;
2720
+ const lines = text.slice(newline + 1).split(`
2721
+ `);
2722
+ const end = lines.findIndex((line) => line.trim() === found[2] || line.trim() === `${found[2]})`);
2723
+ return end === -1 ? undefined : { body: lines.slice(0, end).join(`
2724
+ `), rest: lines.slice(end + 1).join(`
2725
+ `) };
2726
+ }
2727
+ function sourceOf(args, text) {
2728
+ const source = { parts: [], file: null, stdin: null, isReused: false, hasTrailerFlag: false };
2729
+ const take = (option, value) => {
2730
+ if (option === "m" || option === "--message")
2731
+ source.parts.push(value);
2732
+ if (option === "F" || option === "--file")
2733
+ source.file = value;
2734
+ if (REUSES.has(option))
2735
+ source.isReused = true;
2736
+ if (option === "--trailer")
2737
+ source.hasTrailerFlag = true;
2738
+ };
2739
+ for (let i = 0;i < args.length; i++) {
2740
+ const arg = args[i] ?? "";
2741
+ if (arg === "--")
2742
+ break;
2743
+ if (arg.startsWith("--")) {
2744
+ const [option = "", value] = arg.split(LONG_VALUE);
2745
+ if (TRAILER_FLAGS.has(option))
2746
+ source.hasTrailerFlag = true;
2747
+ if (REUSES.has(option))
2748
+ source.isReused = true;
2749
+ if (value !== undefined)
2750
+ take(option, value);
2751
+ else if (COMMIT_VALUE_LONGS.has(option))
2752
+ take(option, args[++i] ?? "");
2753
+ continue;
2754
+ }
2755
+ if (!SHORT_CLUSTER.test(arg))
2756
+ continue;
2757
+ for (const [index, flag] of [...arg.slice(1)].entries()) {
2758
+ if (flag === "s")
2759
+ source.hasTrailerFlag = true;
2760
+ if (!COMMIT_VALUE_SHORTS.has(flag))
2761
+ continue;
2762
+ take(flag, index === arg.length - 2 ? args[++i] ?? "" : arg.slice(index + 2));
2763
+ break;
2764
+ }
2765
+ }
2766
+ if (source.file === "-")
2767
+ source.stdin = heredocBody(text, HEREDOC_OPENER)?.body ?? null;
2768
+ return source;
2769
+ }
2770
+ function commitSources(command) {
2771
+ const sources = [];
2772
+ for (const piece of splitCommand(command)) {
2773
+ const { program, args } = parseCommand(piece.command);
2774
+ const { name, rest } = program === "git" ? subcommandOf(args) : { name: "", rest: [] };
2775
+ if (name === "commit")
2776
+ sources.push(sourceOf(rest, HEREDOC_OPENER.test(piece.text) ? command.slice(piece.start) : piece.text));
2777
+ }
2778
+ return sources;
2779
+ }
2780
+ function inlineMessage(parts) {
2781
+ const texts = [];
2782
+ for (const part of parts) {
2783
+ const found = heredocBody(part, CAT_OPENER);
2784
+ const body = found !== undefined && CAT_CLOSER.test(found.rest) ? found.body : undefined;
2785
+ if (body === undefined && EXPANDS.test(part))
2786
+ return null;
2787
+ texts.push(body ?? part);
2788
+ }
2789
+ return texts.join(`
2790
+
2791
+ `);
2792
+ }
2793
+ function addedPaths(command) {
2794
+ const paths = [];
2795
+ for (const piece of splitCommand(command)) {
2796
+ const { program, args } = parseCommand(piece.command);
2797
+ const { name, rest } = program === "git" ? subcommandOf(args) : { name: "", rest: [] };
2798
+ if (name !== "add")
2799
+ continue;
2800
+ const operands = rest.filter((arg) => arg !== "--");
2801
+ if (operands.length === 0 || operands.some((arg) => arg.startsWith("-") || GLOB.test(arg)))
2802
+ return null;
2803
+ paths.push(...operands);
2804
+ }
2805
+ return paths.length === 0 ? null : paths;
2806
+ }
2807
+ function isPlainChain(command) {
2808
+ for (const piece of splitCommand(command)) {
2809
+ const { program, args } = parseCommand(piece.command);
2810
+ if (program !== "git")
2811
+ continue;
2812
+ const { name, rest } = subcommandOf(args);
2813
+ if (args[0] !== name)
2814
+ return false;
2815
+ if (name !== "commit")
2816
+ continue;
2817
+ for (let i = 0;i < rest.length; i++) {
2818
+ const arg = rest[i] ?? "";
2819
+ if (arg === "-m" || arg === "-qm" || arg === "--message")
2820
+ i++;
2821
+ else if (!PLAIN_COMMIT_OPTION.test(arg))
2822
+ return false;
2823
+ }
2824
+ }
2825
+ return true;
2826
+ }
2827
+ function gcLine(command) {
2828
+ if (!isPlainChain(command))
2829
+ return null;
2830
+ const paths = addedPaths(command);
2831
+ const [source, ...others] = commitSources(command);
2832
+ if (paths === null || source === undefined || others.length > 0 || source.file !== null || source.isReused || source.hasTrailerFlag)
2833
+ return null;
2834
+ const lines = (inlineMessage(source.parts) ?? "").split(`
2835
+ `).map((line) => line.trim()).filter((line) => line !== "");
2836
+ const [title, ...rest] = lines;
2837
+ if (title === undefined)
2838
+ return null;
2839
+ const options = rest.map((line) => TICKET_LINE.test(line) ? `--ticket ${shellQuote(line)}` : `-m ${shellQuote(line)}`);
2840
+ return ["gc", shellQuote(title), ...options, "--", ...paths.map((path) => shellQuote(path))].join(" ");
2841
+ }
2842
+
2843
+ // src/remote.ts
2844
+ var SHELL_PROGRAMS = new Set(["ssh", "scp", "sftp", "mosh", "mosh-client", "autossh"]);
2845
+ var SOCKET_PROGRAMS = new Set(["nc", "ncat", "netcat", "telnet", "socat"]);
2846
+ var URL_PROGRAMS = new Set(["git", "docker", "docker-compose"]);
2847
+ var DECLARERS2 = new Set(["export", "declare", "typeset"]);
2848
+ var RSYNC_REMOTE = /^(?:[\w.-]+@)?[\w.-]{2,}:/;
2849
+ var SSH_URL = /^ssh:\/\//;
2850
+ var SSH_URL_WORD = /^(?:[\w-]+=)?ssh:\/\//;
2851
+ var LOOPBACK = /(?:^|[:=@[])(?:localhost|127(?:\.\d+){3}|::1)(?:[:\]/]|$)/;
2852
+ var LISTENS = /^-[A-KM-Z]*L[A-Z]*$/i;
2853
+ var DOCKER_VALUE_OPTIONS2 = new Set(["-c", "--context", "-H", "--host", "-l", "--log-level", "--config", "--tlscacert", "--tlscert", "--tlskey"]);
2854
+ var CONTEXT_CHANGES = new Set(["use", "create", "update", "import"]);
2855
+ var KUBECTL_SERVER = /^(?:--server(?:=|$)|-s$)/;
2856
+ var REMOTE_VARIABLE = /^GIT_SSH(?:_COMMAND)?=/;
2857
+ var REMOTE = "Remote servers are off limits (no SSH, no deploys, no remote commands). Hand the user the exact command to run themselves.";
2858
+ function dockerContext(args) {
2859
+ let context = null;
2860
+ for (let i = 0;i < args.length; i++) {
2861
+ const arg = args[i] ?? "";
2862
+ if (arg.startsWith("--context="))
2863
+ context = arg.slice("--context=".length);
2864
+ else if (arg === "-c" || arg === "--context")
2865
+ context = args[++i] ?? null;
2866
+ else if (DOCKER_VALUE_OPTIONS2.has(arg))
2867
+ i++;
2868
+ else if (!arg.startsWith("-"))
2869
+ return { context, name: arg, rest: args.slice(i + 1) };
2870
+ }
2871
+ return { context, name: "", rest: [] };
2872
+ }
2873
+ function isDockerRemote(args, assignments) {
2874
+ const { context, name, rest } = dockerContext(args);
2875
+ const fromEnv = assignments.find((assignment) => assignment.startsWith("DOCKER_CONTEXT="))?.slice("DOCKER_CONTEXT=".length);
2876
+ if ([context, fromEnv].some((each) => each !== null && each !== undefined && each !== "default"))
2877
+ return true;
2878
+ return name === "context" && CONTEXT_CHANGES.has(rest[0] ?? "");
2879
+ }
2880
+ function isSocketRemote(args) {
2881
+ return !args.some((arg) => LISTENS.test(arg) || LOOPBACK.test(arg));
2882
+ }
2883
+ function isRemote(text) {
2884
+ const { program, args, assignments } = parseCommand(text);
2885
+ const declared = DECLARERS2.has(program) ? args : [];
2886
+ if (SHELL_PROGRAMS.has(program))
2887
+ return true;
2888
+ if (SOCKET_PROGRAMS.has(program))
2889
+ return isSocketRemote(args);
2890
+ if (program === "rsync")
2891
+ return args.some((arg) => !arg.startsWith("-") && RSYNC_REMOTE.test(arg));
2892
+ if (program === "kubectl")
2893
+ return args.some((arg) => KUBECTL_SERVER.test(arg));
2894
+ if ([...assignments, ...declared].some((assignment) => REMOTE_VARIABLE.test(assignment)))
2895
+ return true;
2896
+ if ([...assignments, ...declared].some((assignment) => assignment.startsWith("DOCKER_HOST=") && SSH_URL.test(assignment.slice("DOCKER_HOST=".length))))
2897
+ return true;
2898
+ if (program === "docker" && isDockerRemote(args, assignments))
2899
+ return true;
2900
+ return URL_PROGRAMS.has(program) && tokenize(text).some((word) => SSH_URL_WORD.test(word));
2901
+ }
2902
+ function remoteViolation(command) {
2903
+ return splitCommand(command).some((piece) => isRemote(piece.command)) ? REMOTE : null;
2904
+ }
2905
+
2906
+ // src/replace.ts
2907
+ var PYTHON = /^python[\d.]*$/;
2908
+ var SCRIPT_RUNNERS = new Set(["bun", "node"]);
2909
+ var EVAL_FLAGS = new Set(["-e", "--eval", "-p", "--print"]);
2910
+ var WRITES = /\bwrite_text\(|\bBun\.write\(|\bwriteFileSync\(|\bwriteFile\(|\bopen\([^)\n]*,\s*['"](?:w|a|r\+)/;
2911
+ var REPLACE_CALL = /\.(replace|replaceAll)\(/g;
2912
+ var FILE_CALL = /\b(?:Path|open|Bun\.file|Bun\.write|readFileSync|writeFileSync|readFile|writeFile)\(\s*/g;
2913
+ var IDENTIFIER2 = /^[A-Z_$][\w$]*/i;
2914
+ var COUNT_CHECK = /\.count\(/g;
2915
+ var COUNT_EQUALS = /^\s*\)\s*==\s*(\d+)/;
2916
+ var PYTHON_COUNT = /^\s*,\s*(\d+)\s*\)/;
2917
+ var SPACE2 = /^\s*/;
2918
+ var COMMA = /^\s*,\s*/;
2919
+ var REGEX_FLAGS = /^[gm]*$/;
2920
+ var PLAIN_WORD2 = /^[\w@%+=:,./*?-]+$/;
2921
+ var SED_SEPARATORS = /^[\s;]*/;
2922
+ var SED_SEPARATOR = /[\s;]/;
2923
+ var BRE_ESCAPED = new Map([["(", "("], [")", ")"], ["{", "{"], ["}", "}"], ["+", "+"], ["?", "?"], ["|", "|"]]);
2924
+ var POSIX_CLASSES = new Map([["[:space:]", String.raw`\s`], ["[:digit:]", String.raw`\d`], ["[:alpha:]", "a-zA-Z"], ["[:alnum:]", "a-zA-Z0-9"], ["[:upper:]", "A-Z"], ["[:lower:]", "a-z"], ["[:blank:]", String.raw` \t`]]);
2925
+ var ESCAPES = new Map([["n", `
2926
+ `], ["t", "\t"]]);
2927
+ var BRE_METAS = new Set([".", "[", "]", "*", "^", "$"]);
2928
+ var ERE_METAS = new Set([...BRE_METAS, "+", "?", "(", ")", "{", "}", "|"]);
2929
+ var JS_SPECIALS = /[.*+?^${}()|[\]\\]/g;
2930
+ var WHY = "writes nothing unless each file matches as often as expected, where it rewrites files whatever it matched";
2931
+ var GENERIC = "Run `sub --from <text> --to <text> <file>...` instead (`--regex`, `--all`, `-n N`, `--dry-run --diff` to look first). For several replacements or multi-line text, pipe SEARCH/REPLACE blocks from a quoted heredoc, no escaping: `sub <file> <<'EOF'`, then `<<<<<<< SEARCH`, the old lines, `=======`, the new lines and `>>>>>>> REPLACE` each on its own line, then `EOF`; blocks apply in order, a line naming a file before a block makes it edit that file.";
2932
+ function literalAt(text, at, regex = false) {
2933
+ let start = at;
2934
+ const isRaw = text[start] === "r" || text[start] === "R";
2935
+ if (isRaw || text[start] === "b")
2936
+ start++;
2937
+ const quote = text[start] ?? "";
2938
+ if (regex && quote === "/")
2939
+ return regexAt(text, start);
2940
+ if (quote !== "'" && quote !== '"' && quote !== "`")
2941
+ return;
2942
+ const fence = text.startsWith(quote.repeat(3), start) ? quote.repeat(3) : quote;
2943
+ let value = "";
2944
+ for (let i = start + fence.length;i < text.length; i++) {
2945
+ const char = text[i] ?? "";
2946
+ if (text.startsWith(fence, i))
2947
+ return { value, end: i + fence.length };
2948
+ if (quote === "`" && text.startsWith("${", i))
2949
+ return;
2950
+ if (char === "\\" && !isRaw) {
2951
+ const next = text[++i] ?? "";
2952
+ value += ESCAPES.get(next) ?? (next === `
2953
+ ` ? "" : next);
2954
+ } else {
2955
+ value += char;
2956
+ }
2957
+ }
2958
+ return;
2959
+ }
2960
+ function regexAt(text, start) {
2961
+ let source = "";
2962
+ let inClass = false;
2963
+ for (let i = start + 1;i < text.length; i++) {
2964
+ const char = text[i] ?? "";
2965
+ if (char === `
2966
+ `)
2967
+ return;
2968
+ if (char === "\\") {
2969
+ source += char + (text[++i] ?? "");
2970
+ continue;
2971
+ }
2972
+ if (char === "/" && !inClass) {
2973
+ const flags = IDENTIFIER2.exec(text.slice(i + 1))?.[0] ?? "";
2974
+ return { value: source, end: i + 1 + flags.length, flags };
2975
+ }
2976
+ if (char === "[" || char === "]")
2977
+ inClass = char === "[";
2978
+ source += char;
2979
+ }
2980
+ return;
2981
+ }
2982
+ function skip(text, at, pattern) {
2983
+ const found = pattern.exec(text.slice(at));
2984
+ return found === null ? undefined : at + found[0].length;
2985
+ }
2986
+ function valueAt(script, at, regex = false) {
2987
+ const literal = literalAt(script, at, regex);
2988
+ const name = literal === undefined ? IDENTIFIER2.exec(script.slice(at))?.[0] : undefined;
2989
+ if (literal !== undefined || name === undefined)
2990
+ return literal;
2991
+ const assignments = [...script.slice(0, at).matchAll(new RegExp(String.raw`(?<![\w.$])${name.replaceAll("$", String.raw`\$`)}\s*=(?!=)\s*`, "g"))];
2992
+ const last = assignments.at(-1);
2993
+ const assigned = last === undefined ? undefined : literalAt(script, last.index + last[0].length, regex);
2994
+ return assigned === undefined ? undefined : { ...assigned, end: at + name.length };
2995
+ }
2996
+ function scriptPaths(script) {
2997
+ const paths = new Set;
2998
+ for (const call of script.matchAll(FILE_CALL)) {
2999
+ const path = valueAt(script, call.index + call[0].length)?.value;
3000
+ if (path !== undefined && path !== "")
3001
+ paths.add(path);
3002
+ }
3003
+ return [...paths];
3004
+ }
3005
+ function assertedCounts(script) {
3006
+ const counts = new Map;
3007
+ for (const call of script.matchAll(COUNT_CHECK)) {
3008
+ const text = valueAt(script, call.index + call[0].length);
3009
+ const equals = text === undefined ? null : COUNT_EQUALS.exec(script.slice(text.end));
3010
+ if (text !== undefined && equals !== null)
3011
+ counts.set(text.value, Number(equals[1]));
3012
+ }
3013
+ return counts;
3014
+ }
3015
+ function scriptPairs(script, isPython) {
3016
+ const pairs = [];
3017
+ const counts = isPython ? assertedCounts(script) : new Map;
3018
+ for (const call of script.matchAll(REPLACE_CALL)) {
3019
+ const from = valueAt(script, skip(script, call.index + call[0].length, SPACE2) ?? 0, !isPython);
3020
+ const comma = from === undefined ? undefined : skip(script, from.end, COMMA);
3021
+ const to = comma === undefined ? undefined : valueAt(script, comma);
3022
+ if (from === undefined || to === undefined)
3023
+ return;
3024
+ if (from.flags !== undefined) {
3025
+ if (!REGEX_FLAGS.test(from.flags))
3026
+ return;
3027
+ pairs.push({ from: from.value, to: to.value, regex: true, ...from.flags.includes("g") ? { all: true } : {} });
3028
+ continue;
3029
+ }
3030
+ const limit = isPython ? PYTHON_COUNT.exec(script.slice(to.end)) : null;
3031
+ const count = limit === null ? counts.get(from.value) : Number(limit[1]);
3032
+ const all = call[1] === "replaceAll" || isPython && count === undefined;
3033
+ const pair = { from: from.value, to: to.value };
3034
+ if (all)
3035
+ pair.all = true;
3036
+ else if (count !== undefined && count !== 1)
3037
+ pair.count = count;
3038
+ pairs.push(pair);
3039
+ }
3040
+ return pairs.length === 0 ? undefined : pairs;
3041
+ }
3042
+ function sedArgs(args) {
3043
+ const sed = { scripts: [], files: [], isExtended: false, isInPlace: false, isPlain: true };
3044
+ const operands = [];
3045
+ for (let i = 0;i < args.length; i++) {
3046
+ const arg = args[i] ?? "";
3047
+ if (arg === "--in-place" || arg.startsWith("--in-place="))
3048
+ sed.isInPlace = true;
3049
+ else if (arg === "--regexp-extended")
3050
+ sed.isExtended = true;
3051
+ else if (arg === "--expression")
3052
+ sed.scripts.push(args[++i] ?? "");
3053
+ else if (arg.startsWith("--expression="))
3054
+ sed.scripts.push(arg.slice("--expression=".length));
3055
+ else if (arg.startsWith("--"))
3056
+ sed.isPlain = false;
3057
+ else if (arg.startsWith("-") && arg.length > 1)
3058
+ i += sedCluster(arg, args[i + 1], sed);
3059
+ else
3060
+ operands.push(arg);
3061
+ }
3062
+ if (sed.scripts.length === 0)
3063
+ sed.scripts.push(operands.shift() ?? "");
3064
+ sed.files = operands;
3065
+ return sed;
3066
+ }
3067
+ function sedCluster(arg, next, sed) {
3068
+ for (const [index, flag] of [...arg.slice(1)].entries()) {
3069
+ if (flag === "i") {
3070
+ sed.isInPlace = true;
3071
+ return 0;
3072
+ }
3073
+ if (flag === "E" || flag === "r") {
3074
+ sed.isExtended = true;
3075
+ } else if (flag === "e") {
3076
+ const value = index === arg.length - 2 ? next : arg.slice(index + 2);
3077
+ sed.scripts.push(value ?? "");
3078
+ return index === arg.length - 2 ? 1 : 0;
3079
+ } else if (flag !== "s" && flag !== "u") {
3080
+ sed.isPlain = false;
3081
+ }
3082
+ }
3083
+ return 0;
3084
+ }
3085
+ function sedPart(script, at, delimiter) {
3086
+ for (let i = at;i < script.length; i++) {
3087
+ if (script[i] === "\\")
3088
+ i++;
3089
+ else if (script[i] === delimiter)
3090
+ return { part: script.slice(at, i), end: i + 1 };
3091
+ }
3092
+ return;
3093
+ }
3094
+ function sedLiteral(pattern, delimiter, metas) {
3095
+ let text = "";
3096
+ for (let i = 0;i < pattern.length; i++) {
3097
+ const char = pattern[i] ?? "";
3098
+ if (char !== "\\") {
3099
+ if (metas.has(char))
3100
+ return;
3101
+ text += char;
3102
+ continue;
3103
+ }
3104
+ const next = pattern[++i] ?? "";
3105
+ if (ESCAPES.has(next))
3106
+ text += ESCAPES.get(next);
3107
+ else if (next === delimiter || next === "\\" || BRE_METAS.has(next) || metas === ERE_METAS && ERE_METAS.has(next))
3108
+ text += next;
3109
+ else
3110
+ return;
3111
+ }
3112
+ return text;
3113
+ }
3114
+ function sedRegex(pattern, delimiter, isExtended) {
3115
+ let source = "";
3116
+ for (let i = 0;i < pattern.length; i++) {
3117
+ const char = pattern[i] ?? "";
3118
+ const posix = [...POSIX_CLASSES].find(([name]) => pattern.startsWith(name, i));
3119
+ if (posix !== undefined) {
3120
+ source += posix[1];
3121
+ i += posix[0].length - 1;
3122
+ } else if (char === "\\") {
3123
+ const next = pattern[++i] ?? "";
3124
+ if (next === delimiter)
3125
+ source += next.replaceAll(JS_SPECIALS, String.raw`\$&`);
3126
+ else
3127
+ source += !isExtended && BRE_ESCAPED.has(next) ? next : `\\${next}`;
3128
+ } else {
3129
+ source += !isExtended && BRE_ESCAPED.has(char) ? `\\${char}` : char;
3130
+ }
3131
+ }
3132
+ return source;
3133
+ }
3134
+ function sedReplacement(replacement, literal) {
3135
+ let text = "";
3136
+ for (let i = 0;i < replacement.length; i++) {
3137
+ const char = replacement[i] ?? "";
3138
+ if (char === "&") {
3139
+ text += literal ?? "$&";
3140
+ } else if (char === "$" && literal === undefined) {
3141
+ text += "$$";
3142
+ } else if (char === "\\") {
3143
+ const next = replacement[++i] ?? "";
3144
+ if (next >= "1" && next <= "9" && literal === undefined)
3145
+ text += `$${next}`;
3146
+ else if (next >= "0" && next <= "9")
3147
+ return;
3148
+ else
3149
+ text += ESCAPES.get(next) ?? (next === "$" && literal === undefined ? "$$" : next);
3150
+ } else {
3151
+ text += char;
3152
+ }
3153
+ }
3154
+ return text;
3155
+ }
3156
+ function sedPairs(script, isExtended) {
3157
+ const pairs = [];
3158
+ for (let at = 0;at < script.length; ) {
3159
+ at = skip(script, at, SED_SEPARATORS) ?? at;
3160
+ if (at >= script.length)
3161
+ break;
3162
+ const delimiter = script[at + 1] ?? "";
3163
+ if (script[at] !== "s" || delimiter === "" || delimiter === "\\" || delimiter === `
3164
+ `)
3165
+ return;
3166
+ const pattern = sedPart(script, at + 2, delimiter);
3167
+ const replacement = pattern === undefined ? undefined : sedPart(script, pattern.end, delimiter);
3168
+ if (pattern === undefined || replacement === undefined)
3169
+ return;
3170
+ const isGlobal = script[replacement.end] === "g";
3171
+ at = replacement.end + (isGlobal ? 1 : 0);
3172
+ if (at < script.length && !SED_SEPARATOR.test(script[at] ?? ""))
3173
+ return;
3174
+ const literal = sedLiteral(pattern.part, delimiter, isExtended ? ERE_METAS : BRE_METAS);
3175
+ const to = sedReplacement(replacement.part, literal);
3176
+ if (to === undefined)
3177
+ return;
3178
+ pairs.push({ from: literal ?? sedRegex(pattern.part, delimiter, isExtended), to, ...literal === undefined ? { regex: true } : {}, ...isGlobal ? { all: true } : {} });
3179
+ }
3180
+ return pairs.length === 0 ? undefined : pairs;
3181
+ }
3182
+ function fileWord(path) {
3183
+ return PLAIN_WORD2.test(path) ? path : shellQuote(path);
3184
+ }
3185
+ function flagsOf(pair) {
3186
+ return [pair.regex === true ? " --regex" : "", pair.all === true ? " --all" : "", pair.count === undefined ? "" : ` -n ${pair.count}`].join("");
3187
+ }
3188
+ function blocksOf(pairs) {
3189
+ const [first] = pairs;
3190
+ if (first === undefined || pairs.some((pair) => flagsOf(pair) !== flagsOf(first)))
3191
+ return;
3192
+ const lines = new Set(pairs.flatMap((pair) => [...pair.from.split(`
3193
+ `), ...pair.to.split(`
3194
+ `)]));
3195
+ if (lines.has("EOF"))
3196
+ return;
3197
+ let width = 7;
3198
+ while (lines.has("=".repeat(width)) || lines.has(`${">".repeat(width)} REPLACE`))
3199
+ width++;
3200
+ return pairs.map((pair) => `${"<".repeat(width)} SEARCH
3201
+ ${pair.from}
3202
+ ${"=".repeat(width)}
3203
+ ${pair.to}
3204
+ ${">".repeat(width)} REPLACE`).join(`
3205
+ `);
3206
+ }
3207
+ function subCommand(pairs, files) {
3208
+ const targets = files.length === 0 ? "<file>" : files.map(fileWord).join(" ");
3209
+ const [pair] = pairs;
3210
+ if (pairs.length === 1 && pair !== undefined && !pair.from.includes(`
3211
+ `) && !pair.to.includes(`
3212
+ `))
3213
+ return `sub --from ${shellQuote(pair.from)} --to ${shellQuote(pair.to)}${flagsOf(pair)} ${targets}`;
3214
+ const blocks = pair === undefined || pairs.some(({ from }) => from === "") ? undefined : blocksOf(pairs);
3215
+ if (blocks !== undefined)
3216
+ return `sub${pair === undefined ? "" : flagsOf(pair)} ${targets} <<'EOF'
3217
+ ${blocks}
3218
+ EOF`;
3219
+ return `sub --pairs - ${targets} <<'PAIRS'
3220
+ ${JSON.stringify(pairs)}
3221
+ PAIRS`;
3222
+ }
3223
+ function route(what, pairs, files) {
3224
+ return pairs === undefined ? `${what} ${GENERIC}` : `${what} Run this instead, which ${WHY}:
3225
+ ${subCommand(pairs, files)}`;
3226
+ }
3227
+ function inlineScript(program, args, text) {
3228
+ const flags = PYTHON.test(program) ? new Set(["-c"]) : EVAL_FLAGS;
3229
+ const flag = args.findIndex((arg) => flags.has(arg));
3230
+ if (flag !== -1)
3231
+ return args[flag + 1] ?? null;
3232
+ const reads = args.every((arg) => arg === "-" || arg.startsWith("<<") || program === "bun" && arg === "run");
3233
+ return reads ? heredocBody(text, HEREDOC_OPENER)?.body ?? null : null;
3234
+ }
3235
+ function replaceViolation(command) {
3236
+ for (const piece of splitCommand(command)) {
3237
+ const { program, args } = parseCommand(piece.command);
3238
+ if (program === "sed") {
3239
+ const sed = sedArgs(args);
3240
+ if (sed.isInPlace)
3241
+ return route("`sed -i` rewrites files without checking what it matched.", sed.isPlain && sed.scripts.length > 0 ? sedPairs(sed.scripts.join(`
3242
+ `), sed.isExtended) : undefined, sed.files);
3243
+ continue;
3244
+ }
3245
+ const isPython = PYTHON.test(program);
3246
+ const script = isPython || SCRIPT_RUNNERS.has(program) ? inlineScript(program, args, piece.text) : null;
3247
+ if (script === null || !WRITES.test(script) || script.search(REPLACE_CALL) === -1)
3248
+ continue;
3249
+ const pairs = scriptPairs(script, isPython);
3250
+ return route(`A ${isPython ? "python" : program} script replacing text in a file is what \`sub\` does with a match-count check.`, pairs, scriptPaths(script));
3251
+ }
3252
+ return null;
3253
+ }
3254
+
3255
+ // src/check.ts
3256
+ var UNREADABLE_MESSAGE = "The commit message cannot be read here (a variable, a substitution, a missing file or no heredoc on stdin), so it cannot be checked. Write it literally with `-m` or a `$(cat <<'EOF' ... EOF)` heredoc.";
3257
+ function absolute(path, cwd) {
3258
+ return path.startsWith("/") ? path : `${cwd}/${path}`;
3259
+ }
3260
+ function commitViolation(command, { cwd, read }) {
3261
+ for (const source of commitSources(command)) {
3262
+ if (source.hasTrailerFlag)
3263
+ return TRAILERS;
3264
+ if (source.isReused || source.file?.startsWith("/dev/") === true)
3265
+ continue;
3266
+ const { file } = source;
3267
+ let message = source.stdin;
3268
+ if (file === null)
3269
+ message = inlineMessage(source.parts);
3270
+ else if (file !== "-")
3271
+ message = read(absolute(file, cwd));
3272
+ if (message === null && (source.parts.length > 0 || file !== null))
3273
+ return UNREADABLE_MESSAGE;
3274
+ const violation = message === null ? null : commitMessageViolation(message);
3275
+ if (violation !== null)
3276
+ return violation;
3277
+ }
3278
+ return null;
3279
+ }
3280
+ function pinnedManagers(start, exists) {
3281
+ for (let dir = start;; dir = parentDir(dir)) {
3282
+ const managers = new Set(LOCKFILES.filter(([file]) => exists(`${dir}/${file}`)).map(([, manager]) => manager));
3283
+ if (managers.size > 0)
3284
+ return { dir, managers };
3285
+ if (dir === "/")
3286
+ return null;
3287
+ }
3288
+ }
3289
+ function mismatches(command, { cwd, home, exists }) {
3290
+ return installRequests(command, cwd, home).flatMap((request) => {
3291
+ const mismatch = mismatchFor(request, pinnedManagers(request.dir, exists));
3292
+ return mismatch === null ? [] : [mismatch];
3293
+ });
3294
+ }
3295
+ async function checkCommand(command, context) {
3296
+ const violations = [];
3297
+ const notes = [];
3298
+ const add = (rule, message) => {
3299
+ if (message !== null)
3300
+ violations.push({ rule, message });
3301
+ };
3302
+ const run = commandsRun(command);
3303
+ const first = (messages) => messages.find((message) => message !== null) ?? null;
3304
+ const guarded = async (rule, check) => {
3305
+ try {
3306
+ return await check();
3307
+ } catch (error) {
3308
+ context.onError?.(rule, error, command);
3309
+ return `The ${rule} rule crashed on this command (${error instanceof Error ? error.message : String(error)}), so it is refused. Simplify the command or run it yourself.`;
3310
+ }
3311
+ };
3312
+ const readSql = async (path) => Promise.resolve(context.read(absolute(path, context.cwd)));
3313
+ add("remote", await guarded("remote", () => first(run.map(remoteViolation))));
3314
+ add("git", await guarded("git", () => first(run.map((each) => gitViolation(each, context.isPushAsked)))));
3315
+ const commit = await guarded("commit", () => first(run.map((each) => commitViolation(each, context))));
3316
+ add("commit", commit === null ? null : `${commit} ${USE_GC}`);
3317
+ add("sql", await guarded("sql", async () => first(await Promise.all(run.map(async (each) => sqlViolation(each, readSql))))));
3318
+ add("env", await guarded("env", () => {
3319
+ const touching = run.flatMap((each) => touchingPieces(each, { hasTrackedEnv: context.hasTrackedEnv === true }));
3320
+ if (touching.length === 0)
3321
+ return null;
3322
+ return touching.some(isSearchCommand) ? `${USE_EV} ${USE_EV_SEARCH}` : USE_EV;
3323
+ }));
3324
+ add("edit", context.canSub ? await guarded("edit", () => first(run.map(replaceViolation))) : null);
3325
+ const found = mismatches(command, context);
3326
+ const refused = found.find((mismatch) => mismatch.rewrite === null || !context.canRewrite);
3327
+ const rewrite = refused?.rewrite ?? null;
3328
+ const route = rewrite === null ? "Run it with the pinned manager instead." : `Run \`${rewrite.trim()}\` instead.`;
3329
+ add("package-manager", refused === undefined ? null : `${refused.reason} ${route}`);
3330
+ let rewritten = command;
3331
+ if (refused === undefined && found.length > 0) {
3332
+ rewritten = replacePieces(command, new Map(found.map((mismatch) => [mismatch.piece, mismatch.rewrite ?? ""])));
3333
+ notes.push(...found.map((mismatch) => `${mismatch.reason} It ran as \`${mismatch.rewrite?.trim()}\` instead.`));
3334
+ }
3335
+ if (context.canRewrite && context.canWrap && shouldWrap(rewritten))
3336
+ rewritten = wrap(rewritten);
3337
+ return { violations, command: violations.length > 0 ? command : rewritten, notes: violations.length > 0 ? [] : notes, packages: [...new Set(run.flatMap(addedPackages))] };
3338
+ }
3339
+ function checkPath(path) {
3340
+ return reachesEnvFile(path) ? { rule: "env", message: USE_EV } : null;
3341
+ }
3342
+
3343
+ // src/bins.ts
3344
+ var BINS = {
3345
+ check: "`check`: runs the repo's check, typecheck, lint and test steps (package.json, composer.json and PHP tool configs, a Justfile, a Makefile) and prints only what failed, each full log saved to a file; a step runs inside the running compose service that mounts its folder (`--in <service>`, `--host`), never starting one; validate a change with it rather than chaining the scripts or `docker compose exec` by hand (`--only lint,test`, `--list`, `--slot`).",
3346
+ fix: "`fix`: runs the repo's fixers and formatters (its fix, lint:fix and format scripts, php-cs-fixer, just fmt, go fmt, cargo fmt, ruff), in the compose service like `check`, and lists the files they changed.",
3347
+ errs: "`errs [log]`, `errs -- <cmd>`: turns tsc, tsgo, eslint, bun check, bun test, vitest, playwright, phpunit, phpstan and php-cs-fixer output into one `file:line:col: message (rule)` line per error, counting the lines it did not recognise (`--json`); use it instead of reading raw type, lint or test logs.",
3348
+ db: '`db "<sql>"`: one read-only statement against the Postgres, MySQL or MariaDB in DATABASE_URL (`-e KEY` for another) or, without one, the compose project\'s running database service (`-s <service>`, `-c <container>` for any container, `-d <database>`), credentials never shown; a write runs on a database whose name ends in `_test` and is printed for the user to run otherwise; `db tables`, `db describe <table>`, `db dbs`; use it instead of `docker exec <container> psql` or `mysql`.',
3349
+ ev: "`ev`: .env files read and edited with values masked (`ev list`, `ev get KEY`, `ev grep <regex>`, `ev show <rev>:<file>`, `ev set`, `ev diff`, `ev missing`); `ev audit [dir]` finds env files others can read or git tracks, and compose files writing secrets out; `ev pins [dir]` lists the env vars reaching outside that the tests of an app leave unpinned.",
3350
+ redact: "`redact`: masks secrets in piped output, `<cmd> | redact`.",
3351
+ pkg: "`pkg <name>[@version]`: checks an npm package before it is added: whether the name exists or is a near miss of a popular one, the newest version at least two weeks old, licence, install scripts; `bun add`, `npm install`, `pnpm add` and `yarn add` run it first and are refused on what it flags. `pkg bump <@scope/lib> [version]` waits until the registry serves a release, then `bun add --exact`s it in every consumer under ~/Workspace (`--dry-run`), `pkg consumers <name>` lists them; use it instead of a `bun info` and sleep loop and a `bun add` per repo.",
3352
+ stack: "`stack port <name>`: the port a service name always hashes to, for every host port a compose file publishes; `stack audit [dir]` cross-checks release.config.ts against its compose files.",
3353
+ ft: "`ft`: Forgejo CI runs, logs and waits, releases, issue checklists and claims, milestones (`ft milestones`, `ft milestone <m>`, `ft new -m`), in a repo whose origin is on Forgejo.",
3354
+ sub: "`sub --from <text> --to <text> <file>...`: replaces text, writing nothing unless each match count is as expected (1, `-n N`, `--all`), `--regex`, `--dry-run --diff`; multi-line text goes as SEARCH/REPLACE blocks on stdin from a quoted heredoc (`sub <file> <<'EOF'`, see `sub --help`), no escaping; use it instead of sed -i, a bun -e or python editor.",
3355
+ base: "`base [--ref <rev>] [--keep <path>...] -- <cmd>`: runs a command at HEAD (or a ref) in a temporary worktree, removed afterwards, ignored env files and node_modules/vendor linked; use it instead of git stash to see whether a test fails without your change (`--keep` the new test).",
3356
+ proof: "`proof [--ref <rev>] [--keep <path>...] -- <cmd>`: runs the command at HEAD (or a ref) in a temporary worktree, then in the working tree, and exits 0 only when it fails before and passes now, printing the failing side's output; use it to prove a new test fails without your change (`--keep` the test).",
3357
+ gst: "`gst [--log N]`: branch, upstream, changed counts and HEAD in one line, then the changed paths by staged, unstaged and untracked; use it instead of `git status --short` and `git log --oneline`.",
3358
+ gc: "`gc <title> [-m <line>]... [--ticket <line>]... -- <path>...`: commits exactly those paths, refusing with nothing staged when the message breaks a commit rule, a path has no change or other files are already staged; use it instead of chaining git add, status and commit.",
3359
+ waitfor: "`waitfor --file <log> --until <regex> [--fail <regex>]`, `--port <n>`, `--url <url>`, `--pid <n>` (`-t 5m`): waits until the line shows, the port listens, the URL answers 2xx or the process exits, exits 1 on a --fail line with the lines around it, 2 on a timeout with the last lines; `waitfor task <id>` waits for a background Bash task and prints its exit code, last lines and failure lines; use it instead of sleep and tail, `until ! pgrep -f` or polling loops.",
3360
+ slot: "`slot [-l <lock>] -- <cmd>`: waits for one of the machine-wide slots shared by every session (half the CPUs), then runs the command; `--lock <name>` also holds a named lock for what must not run twice (a shared test database), `slot ls` lists holders and waiters; run heavy jobs (phpunit, playwright, vue-tsc, a full test suite) through it instead of a flock wrapper.",
3361
+ gl: "`gl ci [ref]` waits for the GitLab pipeline covering a commit and prints each failed job's tests (exit 0/1/2), `gl runs`, `gl logs <pipeline> [-j job] [--full]`; use it instead of `glab ci` or `glab api .../pipelines/<id>/jobs` polled in a sleep loop.",
3362
+ peek: "`peek <file:from-to>...` prints several spans with line numbers in one call, `peek --def <symbol>` a whole declaration, `--refs <symbol>` its usages by file, `--outline <file>` the declarations and members, `--around <regex> -C 3` the lines around matches; use it instead of `sed -n N,Mp`, `grep -n` chains and whole-file reads.",
3363
+ "todo-scan": "`todo-scan [path...]` lists the TODO, FIXME and owner/repo#N comments as `<file>:<line>: <comment>`, `--stale` only those whose issue is closed (exit 1), through ft; use it to find the workarounds a shipped fix lets you drop.",
3364
+ doctor: "`doctor`: checks this host's @kaynooo/cli-* install, one line per check with its fix: each bin's version against the registry, tea's login, the Claude Code hooks, the Bun floor (`--json`); run it when a bin lacks a command or a flag its docs name.",
3365
+ cli: "`cli list`: every @kaynooo/cli-* bin in one line, what it does and what it is reached for instead of, read from each bin's own --help (`--json` adds the synopsis and examples); run it to find the bin that fits a task.",
3366
+ hotspots: "`hotspots [dir] [--since <date>] [-n 20]`: ranks the source files by complexity times git churn (commits touching each in the window, 6 months by default), tests and generated files left out, `--json`; use it to pick which complex files are worth splitting first.",
3367
+ out: "`out -- <cmd>`: folds long output, keeping the errors and saving the full log; run noisy builds, installs, tests and linters through it.",
3368
+ changelog: "`changelog --dry`: the release notes since the last tag, grouped from the conventional commits, without publishing them; `changelog` publishes them as the Forgejo release of the tag at HEAD, `changelog undo [tag]` takes a release back."
3369
+ };
3370
+ function binsSection(installed) {
3371
+ const lines = Object.entries(BINS).filter(([bin]) => installed.has(bin)).map(([, line]) => `- ${line}`);
3372
+ return lines.length === 0 ? undefined : `# CLIs
3373
+
3374
+ CLIs installed on this machine for you to use over hand-rolled equivalents, \`<bin> --help\` for the options:
3375
+ ${lines.join(`
3376
+ `)}`;
3377
+ }
3378
+
3379
+ // src/hook.ts
3380
+ var EVENTS = ["pre-tool-use", "user-prompt-submit", "session-start"];
3381
+ var PUSH_WORD = /\b(?:push|pousser?|poussez)\b/i;
3382
+ var PUSH_NOUN = /\bpush[\s-]+(?:notifications?|messages?|tokens?|events?|services?|apis?|subscriptions?|workers?|servers?)\b/gi;
3383
+ var NOT_A_REQUEST = /\b(?:don'?t|do not|never|not|no|without|avoid|stop|can'?t|cannot|won'?t|shouldn'?t|did|didn'?t|does|doesn'?t|already|ne|pas|jamais|sans|surtout)\b/i;
3384
+ var CLAUSE_BREAKS = /[.!?;,\n]+/;
3385
+ var SESSION_ID = /^[\w-]+$/;
3386
+ var FILE_TOOLS = new Map([["Read", "file_path"], ["Edit", "file_path"], ["MultiEdit", "file_path"], ["Write", "file_path"], ["NotebookEdit", "notebook_path"], ["Grep", "path"], ["Glob", "path"]]);
3387
+ var GIT_WORD = /\bgit\b/;
3388
+ var GIT_PRINT_WORD = /\b(?:diff|log|show|whatchanged|format-patch|grep)\b/;
3389
+ var TRACKED_ENV = [":(glob)**/.env", ":(glob)**/.env.*", ":(glob)**/.envrc"];
3390
+ function asksForPush(prompt) {
3391
+ return prompt.split(CLAUSE_BREAKS).some((clause) => {
3392
+ const asked = clause.replace(PUSH_NOUN, "");
3393
+ return PUSH_WORD.test(asked) && !NOT_A_REQUEST.test(asked);
3394
+ });
3395
+ }
3396
+ function pushFile(sessionId, { stateDir }) {
3397
+ return sessionId !== undefined && SESSION_ID.test(sessionId) ? `${stateDir}/push-asked/${sessionId}` : null;
3398
+ }
3399
+ function deny(violations) {
3400
+ if (violations.length === 0)
3401
+ return null;
3402
+ return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: violations.map((each) => each.message).join(`
3403
+
3404
+ `) } };
3405
+ }
3406
+ async function bashCall(command, input, machine) {
3407
+ const answer = await checkedBashCall(command, input, machine);
3408
+ if (answer !== null)
3409
+ return answer;
3410
+ const line = gcLine(command);
3411
+ return line === null ? null : { hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: `This commit went through, but \`gc\` does the same in one call, checks the message first and is never held by the read-first gate: \`${line}\`` } };
3412
+ }
3413
+ async function checkedBashCall(command, input, machine) {
3414
+ const file = pushFile(input.session_id, machine);
3415
+ const cwd = input.cwd ?? machine.home;
3416
+ const verdict = await checkCommand(command, {
3417
+ cwd,
3418
+ home: machine.home,
3419
+ isPushAsked: file !== null && machine.exists(file),
3420
+ canRewrite: false,
3421
+ canWrap: false,
3422
+ canSub: machine.has("sub"),
3423
+ read: machine.read,
3424
+ exists: machine.exists,
3425
+ hasTrackedEnv: GIT_WORD.test(command) && GIT_PRINT_WORD.test(command) && await hasTrackedEnv(cwd, machine),
3426
+ onError: (rule, error, each) => machine.log?.(`${new Date().toISOString()} ${rule} crashed: ${error instanceof Error ? error.stack ?? error.message : String(error)}
3427
+ command: ${each}
3428
+ `)
3429
+ });
3430
+ if (verdict.violations.length > 0 || verdict.packages.length === 0 || !machine.has("pkg"))
3431
+ return deny(verdict.violations);
3432
+ const checked = await machine.run(["pkg", "check", ...verdict.packages], cwd);
3433
+ if (checked.code === 0)
3434
+ return null;
3435
+ const message = checked.code === 1 ? "pkg refused what this adds, so it was not run" : `pkg check failed (exit ${checked.code}), so what this adds was not checked and it was not run`;
3436
+ return deny([{ rule: "pkg", message: `${message}:
3437
+ ${checked.text.trim()}` }]);
3438
+ }
3439
+ async function hasTrackedEnv(cwd, machine) {
3440
+ const listed = await machine.run(["git", "ls-files", "-z", "--", ...TRACKED_ENV], cwd);
3441
+ return listed.code === 0 && listed.text.split("\x00").some(isEnvFile);
3442
+ }
3443
+ function preToolUse(input, machine) {
3444
+ const { tool_name: tool, tool_input: given = {} } = input;
3445
+ if (tool === "Bash" && typeof given.command === "string")
3446
+ return bashCall(given.command, input, machine);
3447
+ const field = tool === undefined ? undefined : FILE_TOOLS.get(tool);
3448
+ const paths = [field === undefined ? undefined : given[field], tool === "Grep" ? given.glob : undefined];
3449
+ return deny(paths.flatMap((path) => typeof path === "string" ? [checkPath(path)] : []).filter((each) => each !== null));
3450
+ }
3451
+ function userPromptSubmit(input, machine) {
3452
+ const file = pushFile(input.session_id, machine);
3453
+ if (file !== null && asksForPush(input.prompt ?? ""))
3454
+ machine.write(file, "");
3455
+ else if (file !== null)
3456
+ machine.remove(file);
3457
+ return null;
3458
+ }
3459
+ function sessionStart(machine) {
3460
+ const text = binsSection(new Set(Object.keys(BINS).filter(machine.has)));
3461
+ return text === undefined ? null : { hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: text } };
3462
+ }
3463
+ async function hook(event, input, machine) {
3464
+ if (event === "pre-tool-use")
3465
+ return preToolUse(input, machine);
3466
+ return event === "user-prompt-submit" ? userPromptSubmit(input, machine) : sessionStart(machine);
3467
+ }
3468
+
3469
+ // src/cli.ts
3470
+ var checkUsage = `guard check [options] [<command> | -]
3471
+
3472
+ Checks a shell command against the rules: remote machines, git (stash, whole-tree add and commit, push, tags), commit messages, SQL writes, env files, package managers and in-place edits (sed -i and replace scripts, pointed at sub).
3473
+ Prints each broken rule with the route to take instead and exits 1, prints nothing and exits 0 when the command is clean.
3474
+ The command is read from stdin with - or when none is given; a rule may rewrite it instead (the pinned package manager, a noisy run through out), printed as \`runs as: <command>\`.
3475
+
3476
+ Exits 0 when the command is clean, 1 when a rule is broken, 2 on a usage error.`;
3477
+ var checkOptions = {
3478
+ json: jsonOption("{violations, command, notes, packages} for a hook"),
3479
+ cwd: { type: "string", description: "the directory the command runs in (default: here)" },
3480
+ "push-asked": { type: "boolean", description: "the user asked for a push, so git push may run" },
3481
+ "no-wrap": { type: "boolean", description: "never route a noisy command through out" }
3482
+ };
3483
+ var pathUsage = `guard path [--json] <path>...
3484
+
3485
+ Checks the paths a file tool would read, edit or write: env files are refused.
3486
+
3487
+ Exits 0 when every path is clean, 1 when one is refused, 2 on a usage error.`;
3488
+ var pathOptions = {
3489
+ json: jsonOption("{violations} for a hook")
3490
+ };
3491
+ var hookUsage = `guard hook <${EVENTS.join("|")}>
3492
+
3493
+ Answers a Claude Code hook: reads the event JSON on stdin and prints the reply JSON, nothing when the call goes ahead untouched.
3494
+ pre-tool-use refuses a Bash call breaking a rule, an install pkg refuses (or fails to check), and a file tool (Read, Edit, MultiEdit, Write, NotebookEdit, Grep, Glob) reaching an env file; user-prompt-submit remembers whether the prompt asked for a push; session-start lists the installed @kaynooo/cli-* bins.
3495
+ A failure exits 1, which Claude Code reports without blocking the call.
3496
+
3497
+ Exits 0 when it answered, 1 on a failure or an unknown event (never 2, which would block the call).`;
3498
+ var MAX_READ = 1e6;
3499
+ function readText(path) {
3500
+ try {
3501
+ const stats = statSync(path, { throwIfNoEntry: false });
3502
+ return stats?.isFile() === true && stats.size <= MAX_READ ? readFileSync(path, "utf8") : null;
3503
+ } catch {
3504
+ return null;
3505
+ }
3506
+ }
3507
+ function report(violations) {
3508
+ for (const { rule, message } of violations)
3509
+ console.log(`${rule}: ${message}`);
3510
+ }
3511
+ async function check(args) {
3512
+ const parsed = parse(args, checkUsage, checkOptions);
3513
+ const { values, positionals } = parsed;
3514
+ if (positionals.length > 1)
3515
+ fail(`give the command as one argument, quoted
3516
+
3517
+ ${checkUsage}`);
3518
+ const given = positionals[0] ?? "-";
3519
+ const command = given === "-" ? await readInput("-", { noStdin: "give the command, or pipe it on stdin" }) : given;
3520
+ const context = {
3521
+ cwd: values.cwd ?? process7.cwd(),
3522
+ home: homedir(),
3523
+ isPushAsked: values["push-asked"] === true,
3524
+ canRewrite: true,
3525
+ canWrap: values["no-wrap"] !== true && Bun.which("out") !== null,
3526
+ canSub: Bun.which("sub") !== null,
3527
+ read: readText,
3528
+ exists: existsSync
3529
+ };
3530
+ const verdict = await checkCommand(command, context);
3531
+ if (values.json === true)
3532
+ console.log(JSON.stringify(verdict));
3533
+ else
3534
+ report(verdict.violations);
3535
+ if (values.json !== true && verdict.command !== command)
3536
+ console.log(`runs as: ${verdict.command}${verdict.notes.map((note) => `
3537
+ ${note}`).join("")}`);
3538
+ return verdict.violations.length > 0 ? 1 : 0;
3539
+ }
3540
+ function path(args) {
3541
+ const parsed = parse(args, pathUsage, pathOptions);
3542
+ if (parsed.positionals.length === 0)
3543
+ fail(`give at least one path
3544
+
3545
+ ${pathUsage}`);
3546
+ const violations = parsed.positionals.flatMap((each) => checkPath(each) ?? []);
3547
+ if (parsed.values.json === true)
3548
+ console.log(JSON.stringify({ violations }));
3549
+ else
3550
+ report(violations);
3551
+ return violations.length > 0 ? 1 : 0;
3552
+ }
3553
+ function machine() {
3554
+ const home = homedir();
3555
+ const stateDir = `${process7.env.XDG_STATE_HOME ?? `${home}/.local/state`}/guard`;
3556
+ return {
3557
+ home,
3558
+ stateDir,
3559
+ has: (bin) => Bun.which(bin) !== null,
3560
+ run: async (argv, cwd) => runCommand(argv, { cwd }),
3561
+ read: readText,
3562
+ exists: existsSync,
3563
+ write: (path, text) => {
3564
+ mkdirSync(dirname(path), { recursive: true });
3565
+ writeFileSync(path, text);
3566
+ },
3567
+ remove: (path) => rmSync(path, { force: true }),
3568
+ log: (text) => {
3569
+ try {
3570
+ mkdirSync(stateDir, { recursive: true });
3571
+ appendFileSync(`${stateDir}/errors.log`, text);
3572
+ } catch {}
3573
+ }
3574
+ };
3575
+ }
3576
+ async function hookCommand(args) {
3577
+ const parsed = parse(args, hookUsage, {});
3578
+ const event = parsed.positionals[0] ?? "";
3579
+ if (!EVENTS.includes(event))
3580
+ fail(`unknown event ${event}
3581
+
3582
+ ${hookUsage}`, 1);
3583
+ const reply = await hook(event, JSON.parse(await Bun.stdin.text()), machine());
3584
+ if (reply !== null)
3585
+ console.log(JSON.stringify(reply));
3586
+ return 0;
3587
+ }
3588
+ process7.exitCode = await runCli({
3589
+ name: "guard",
3590
+ version,
3591
+ about: "the safety rules a Claude Code Bash call is held to, each refusal naming the route",
3592
+ replaces: "a hook script per rule, each wording its own refusal",
3593
+ examples: [['guard check "git push --force"', "the rules a command breaks, with their routes"], ["guard path .env", "whether a file tool may open a path"]],
3594
+ commands: {
3595
+ check: { run: check, summary: "check a shell command, printing each broken rule with its route" },
3596
+ path: { run: async (args) => Promise.resolve(path(args)), summary: "check a path a file tool would open" },
3597
+ hook: { run: hookCommand, summary: "answer a Claude Code hook event, JSON in and out" }
3598
+ },
3599
+ defaultCommand: "check"
3600
+ });