punchlist-axi 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3535 @@
1
+ #!/usr/bin/env node
2
+ // Generated from src/ by `pnpm build` - do not edit.
3
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
11
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
12
+ }) : x)(function(x) {
13
+ if (typeof require !== "undefined") return require.apply(this, arguments);
14
+ throw Error('Dynamic require of "' + x + '" is not supported');
15
+ });
16
+ var __commonJS = (cb, mod) => function __require2() {
17
+ try {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ } catch (e) {
20
+ throw mod = 0, e;
21
+ }
22
+ };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (let key of __getOwnPropNames(from))
26
+ if (!__hasOwnProp.call(to, key) && key !== except)
27
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
+ }
29
+ return to;
30
+ };
31
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
32
+ // If the importer is in node compatibility mode or this is not an ESM
33
+ // file that has been converted to a CommonJS file using a Babel-
34
+ // compatible transform (i.e. "__esModule" has not been set), then set
35
+ // "default" to the CommonJS "module.exports" for node compatibility.
36
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
37
+ mod
38
+ ));
39
+
40
+ // node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
41
+ var require_picocolors = __commonJS({
42
+ "node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports, module) {
43
+ var p = process || {};
44
+ var argv = p.argv || [];
45
+ var env = p.env || {};
46
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
47
+ var formatter = (open, close, replace = open) => (input) => {
48
+ let string = "" + input, index = string.indexOf(close, open.length);
49
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
50
+ };
51
+ var replaceClose = (string, close, replace, index) => {
52
+ let result = "", cursor = 0;
53
+ do {
54
+ result += string.substring(cursor, index) + replace;
55
+ cursor = index + close.length;
56
+ index = string.indexOf(close, cursor);
57
+ } while (~index);
58
+ return result + string.substring(cursor);
59
+ };
60
+ var createColors = (enabled = isColorSupported) => {
61
+ let f = enabled ? formatter : () => String;
62
+ return {
63
+ isColorSupported: enabled,
64
+ reset: f("\x1B[0m", "\x1B[0m"),
65
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
66
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
67
+ italic: f("\x1B[3m", "\x1B[23m"),
68
+ underline: f("\x1B[4m", "\x1B[24m"),
69
+ inverse: f("\x1B[7m", "\x1B[27m"),
70
+ hidden: f("\x1B[8m", "\x1B[28m"),
71
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
72
+ black: f("\x1B[30m", "\x1B[39m"),
73
+ red: f("\x1B[31m", "\x1B[39m"),
74
+ green: f("\x1B[32m", "\x1B[39m"),
75
+ yellow: f("\x1B[33m", "\x1B[39m"),
76
+ blue: f("\x1B[34m", "\x1B[39m"),
77
+ magenta: f("\x1B[35m", "\x1B[39m"),
78
+ cyan: f("\x1B[36m", "\x1B[39m"),
79
+ white: f("\x1B[37m", "\x1B[39m"),
80
+ gray: f("\x1B[90m", "\x1B[39m"),
81
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
82
+ bgRed: f("\x1B[41m", "\x1B[49m"),
83
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
84
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
85
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
86
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
87
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
88
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
89
+ blackBright: f("\x1B[90m", "\x1B[39m"),
90
+ redBright: f("\x1B[91m", "\x1B[39m"),
91
+ greenBright: f("\x1B[92m", "\x1B[39m"),
92
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
93
+ blueBright: f("\x1B[94m", "\x1B[39m"),
94
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
95
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
96
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
97
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
98
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
99
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
100
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
101
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
102
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
103
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
104
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
105
+ };
106
+ };
107
+ module.exports = createColors();
108
+ module.exports.createColors = createColors;
109
+ }
110
+ });
111
+
112
+ // node_modules/.pnpm/shell-quote@1.12.0/node_modules/shell-quote/quote.js
113
+ var require_quote = __commonJS({
114
+ "node_modules/.pnpm/shell-quote@1.12.0/node_modules/shell-quote/quote.js"(exports, module) {
115
+ "use strict";
116
+ var OPS = (
117
+ /** @type {const} */
118
+ [
119
+ "||",
120
+ "&&",
121
+ ";;&",
122
+ ";;",
123
+ ";&",
124
+ "|&",
125
+ "<(",
126
+ ">(",
127
+ "<<<",
128
+ "<<-",
129
+ "<<",
130
+ ">>",
131
+ ">&",
132
+ ">|",
133
+ "&>>",
134
+ "&>",
135
+ "<&",
136
+ "<>",
137
+ "&",
138
+ ";",
139
+ "(",
140
+ ")",
141
+ "|",
142
+ "<",
143
+ ">"
144
+ ]
145
+ );
146
+ var LINE_TERMINATORS = /[\n\r\u2028\u2029]/;
147
+ var GLOB_SHELL_SPECIAL = /[\s#!"$&'():;<=>@\\^`|~]/g;
148
+ module.exports = function quote(xs) {
149
+ var sawComment = false;
150
+ return xs.map(function(s) {
151
+ if (sawComment && typeof s === "string" && LINE_TERMINATORS.test(s)) {
152
+ throw new TypeError("a token after a `comment` must not contain line terminators");
153
+ }
154
+ if (s === "") {
155
+ return (
156
+ /** @type {const} */
157
+ "''"
158
+ );
159
+ }
160
+ if (s && typeof s === "object") {
161
+ if ("op" in s && s.op === "glob") {
162
+ if (typeof s.pattern !== "string") {
163
+ throw new TypeError("glob token requires a string `pattern`");
164
+ }
165
+ if (LINE_TERMINATORS.test(s.pattern)) {
166
+ throw new TypeError("glob `pattern` must not contain line terminators");
167
+ }
168
+ if (s.pattern === "") {
169
+ return (
170
+ /** @type {const} */
171
+ "''"
172
+ );
173
+ }
174
+ return s.pattern.replace(GLOB_SHELL_SPECIAL, "\\$&");
175
+ }
176
+ if ("op" in s && typeof s.op === "string") {
177
+ if (OPS.indexOf(s.op) < 0) {
178
+ throw new TypeError("invalid `op` value: " + JSON.stringify(s.op));
179
+ }
180
+ return s.op.replace(/[\s\S]/g, "\\$&");
181
+ }
182
+ if ("comment" in s && typeof s.comment === "string") {
183
+ if (LINE_TERMINATORS.test(s.comment)) {
184
+ throw new TypeError("`comment` must not contain line terminators");
185
+ }
186
+ sawComment = true;
187
+ return "#" + s.comment;
188
+ }
189
+ throw new TypeError("unrecognized object token shape");
190
+ }
191
+ if (/'/.test(s) && /!/.test(s)) {
192
+ return "'" + s.replace(/'/g, `'"'"'`) + "'";
193
+ }
194
+ if (/["\s\\]/.test(s) && !/'/.test(s)) {
195
+ return "'" + s + "'";
196
+ }
197
+ if (/["'\s]/.test(s)) {
198
+ return '"' + s.replace(/(["\\$`])/g, "\\$1") + '"';
199
+ }
200
+ return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g, "$1\\$2");
201
+ }).join(" ");
202
+ };
203
+ }
204
+ });
205
+
206
+ // node_modules/.pnpm/shell-quote@1.12.0/node_modules/shell-quote/parse.js
207
+ var require_parse = __commonJS({
208
+ "node_modules/.pnpm/shell-quote@1.12.0/node_modules/shell-quote/parse.js"(exports, module) {
209
+ "use strict";
210
+ var CONTROL = (
211
+ /** @type {const} */
212
+ "(?:" + /** @type {const} */
213
+ [
214
+ "\\|\\|",
215
+ "\\&(?:\\&|>>?)",
216
+ // `&&`, `&>`, and `&>>`
217
+ ";;\\&?",
218
+ // `;;` and `;;&`
219
+ "[;|]\\&",
220
+ // `;&` and `|&`
221
+ "\\<\\(",
222
+ "\\<\\<\\<",
223
+ "\\<\\<-",
224
+ "\\<\\<(?!\\()",
225
+ // `<<(` stays `<` and `<(`, as zsh reads it; other shells reject it
226
+ ">>",
227
+ ">[&|(]",
228
+ // `>&`, `>|`, and `>(`
229
+ "<[&>]",
230
+ // `<&` and `<>`
231
+ "[&;()|<>]"
232
+ ].join(
233
+ /** @type {const} */
234
+ "|"
235
+ ) + /** @type {const} */
236
+ ")"
237
+ );
238
+ var controlRE = new RegExp("^" + CONTROL + "$");
239
+ var META = (
240
+ /** @type {const} */
241
+ "|&;()<> \\t"
242
+ );
243
+ var SINGLE_QUOTE = (
244
+ /** @type {const} */
245
+ "'([^']*?)'"
246
+ );
247
+ var ANSI_C_BODY = "(?:\\\\[\\s\\S]|[^\\\\'])*?";
248
+ var ANSI_C_QUOTE = "\\$'" + ANSI_C_BODY + "'";
249
+ var ansiCAt = new RegExp("\\$'" + ANSI_C_BODY + "(?:(')|\\\\?$)", "g");
250
+ var ANSI_C_LETTERS = "abeEfnrtv";
251
+ var ANSI_C_CHARS = "\x07\b\x1B\x1B\f\n\r \v";
252
+ var hash = /^#$/;
253
+ var SQ = (
254
+ /** @type {const} */
255
+ "'"
256
+ );
257
+ var DQ = (
258
+ /** @type {const} */
259
+ '"'
260
+ );
261
+ var DS = (
262
+ /** @type {const} */
263
+ "$"
264
+ );
265
+ var TOKEN = "";
266
+ var mult = (
267
+ /** @type {const} */
268
+ 4294967296
269
+ );
270
+ for (i = 0; i < 4; i++) {
271
+ TOKEN += (mult * Math.random()).toString(16);
272
+ }
273
+ var i;
274
+ var startsWithToken = new RegExp("^" + TOKEN);
275
+ function matchAll(s, r) {
276
+ var origIndex = r.lastIndex;
277
+ var matches = [];
278
+ var matchObj;
279
+ while (matchObj = r.exec(s)) {
280
+ matches[matches.length] = matchObj;
281
+ if (r.lastIndex === matchObj.index) {
282
+ r.lastIndex += 1;
283
+ }
284
+ }
285
+ r.lastIndex = origIndex;
286
+ return matches;
287
+ }
288
+ function getVar(env, pre, key) {
289
+ var r = typeof env === "function" ? env(key) : env[key];
290
+ if (typeof r === "undefined" && key != "") {
291
+ r = "";
292
+ } else if (typeof r === "undefined") {
293
+ r = "$";
294
+ }
295
+ if (typeof r === "object") {
296
+ return pre + TOKEN + JSON.stringify(r) + TOKEN;
297
+ }
298
+ return pre + r;
299
+ }
300
+ var ansiCEscape = /\\([0-7]{1,3}|x[\dA-Fa-f]{1,2}|u[\dA-Fa-f]{1,4}|U[\dA-Fa-f]{1,8}|c(?:\\\\|[\s\S])|[abeEfnrtv\\'"?])/g;
301
+ function expandAnsiCEscape(m, escape) {
302
+ var kind = escape.charAt(0);
303
+ if (kind === "c") {
304
+ var ctrl = escape.charAt(1);
305
+ return ctrl === "?" ? "\x7F" : String.fromCharCode(ctrl.charCodeAt(0) & 31);
306
+ }
307
+ if (kind === "x" || kind === "u" || kind === "U") {
308
+ var cp = parseInt(escape.slice(1), 16);
309
+ if (cp > 1114111) {
310
+ return m;
311
+ }
312
+ return String.fromCharCode.apply(null, cp > 65535 ? [55232 + (cp >> 10), 56320 + (cp & 1023)] : [cp]);
313
+ }
314
+ if (kind >= "0" && kind <= "7") {
315
+ return String.fromCharCode(parseInt(escape, 8) & 255);
316
+ }
317
+ var letter = ANSI_C_LETTERS.indexOf(escape);
318
+ return letter < 0 ? escape : ANSI_C_CHARS.charAt(letter);
319
+ }
320
+ function expandAnsiC(body) {
321
+ return body.replace(ansiCEscape, expandAnsiCEscape).split("\0")[0];
322
+ }
323
+ function closesAnsiC(s, i2) {
324
+ ansiCAt.lastIndex = i2;
325
+ return !!/** @type {RegExpExecArray} */
326
+ ansiCAt.exec(s)[1];
327
+ }
328
+ function parseInternal(string, env, opts) {
329
+ if (!opts) {
330
+ opts = {};
331
+ }
332
+ var BS = opts.escape || "\\";
333
+ var ifs = opts.splitUnquoted === true ? " \n" : typeof opts.splitUnquoted === "string" ? opts.splitUnquoted : "";
334
+ var BAREWORD = "(\\" + BS + `['"$\\` + BS + META + "]|\\$\\$|\\$(?!" + ANSI_C_QUOTE.slice(2) + `)|[^\\s'"$` + META + "])+";
335
+ var DOUBLE_QUOTE = '"(?:\\' + BS + '[\\s\\S]|[^"\\' + BS + '])*"';
336
+ var chunker = new RegExp([
337
+ "(" + CONTROL + ")",
338
+ // control chars
339
+ "(" + ANSI_C_QUOTE + "|" + BAREWORD + "|" + DOUBLE_QUOTE + "|" + SINGLE_QUOTE + ")+"
340
+ ].join("|"), "g");
341
+ var matches = matchAll(string, chunker);
342
+ if (matches.length === 0) {
343
+ return [];
344
+ }
345
+ if (!env) {
346
+ env = {};
347
+ }
348
+ var commented = false;
349
+ return matches.map(function(match) {
350
+ var s = match[0];
351
+ if (!s || commented) {
352
+ return void 0;
353
+ }
354
+ if (controlRE.test(s)) {
355
+ return (
356
+ /** @type {ControlOperator} */
357
+ { op: s }
358
+ );
359
+ }
360
+ var quote = false;
361
+ var esc = false;
362
+ var out = "";
363
+ var words = [];
364
+ var sawQuote = false;
365
+ var pendingNw = null;
366
+ var isGlob = false;
367
+ var i2;
368
+ function parseEnvVar() {
369
+ i2 += 1;
370
+ var varend;
371
+ var varname;
372
+ var char = s.charAt(i2);
373
+ if (char === "{") {
374
+ i2 += 1;
375
+ if (s.charAt(i2) === "}") {
376
+ throw new Error("Bad substitution: " + s.slice(i2 - 2, i2 + 1));
377
+ }
378
+ var depth = 1;
379
+ varend = i2;
380
+ while (depth > 0 && varend < s.length) {
381
+ if (s.charAt(varend) === "{" && s.charAt(varend - 1) === "$") {
382
+ depth += 1;
383
+ } else if (s.charAt(varend) === "}") {
384
+ depth -= 1;
385
+ }
386
+ varend += 1;
387
+ }
388
+ if (depth !== 0) {
389
+ throw new Error("Bad substitution: " + s.slice(i2));
390
+ }
391
+ varend -= 1;
392
+ varname = s.slice(i2, varend);
393
+ i2 = varend;
394
+ } else if (/[*@#?$!-]/.test(char)) {
395
+ varname = char;
396
+ } else {
397
+ var slicedFromI = s.slice(i2);
398
+ varend = slicedFromI.match(/[^\w\d_]/);
399
+ if (!varend) {
400
+ varname = slicedFromI;
401
+ i2 = s.length;
402
+ } else {
403
+ varname = slicedFromI.slice(0, varend.index);
404
+ i2 += /** @type {number} */
405
+ varend.index - 1;
406
+ }
407
+ }
408
+ return getVar(
409
+ /** @type {NonNullable<typeof env>} */
410
+ env,
411
+ "",
412
+ varname
413
+ );
414
+ }
415
+ function flushRun() {
416
+ if (pendingNw === null) {
417
+ return;
418
+ }
419
+ if (pendingNw === 0) {
420
+ if (out !== "") {
421
+ words[words.length] = out;
422
+ out = "";
423
+ }
424
+ } else {
425
+ words[words.length] = out;
426
+ out = "";
427
+ for (var fe = 1; fe < pendingNw; fe += 1) {
428
+ words[words.length] = "";
429
+ }
430
+ }
431
+ pendingNw = null;
432
+ }
433
+ for (i2 = 0; i2 < s.length; i2++) {
434
+ var c = s.charAt(i2);
435
+ if (ifs && c !== DS) {
436
+ flushRun();
437
+ }
438
+ isGlob = isGlob || !quote && (c === "*" || c === "?");
439
+ if (esc) {
440
+ out += c;
441
+ esc = false;
442
+ } else if (quote) {
443
+ if (c === quote) {
444
+ quote = false;
445
+ } else if (quote == SQ) {
446
+ out += c;
447
+ } else {
448
+ if (c === BS) {
449
+ i2 += 1;
450
+ c = s.charAt(i2);
451
+ if (c === DQ || c === BS || c === DS) {
452
+ out += c;
453
+ } else {
454
+ out += BS + c;
455
+ }
456
+ } else if (c === DS) {
457
+ out += parseEnvVar();
458
+ } else {
459
+ out += c;
460
+ }
461
+ }
462
+ } else if (c === DQ || c === SQ) {
463
+ quote = c;
464
+ sawQuote = true;
465
+ } else if (controlRE.test(c)) {
466
+ return (
467
+ /** @type {ControlOperator} */
468
+ { op: s }
469
+ );
470
+ } else if (hash.test(c)) {
471
+ commented = true;
472
+ var commentObj = { comment: string.slice(match.index + i2 + 1) };
473
+ if (out.length) {
474
+ return (
475
+ /** @type {const} */
476
+ [out, commentObj]
477
+ );
478
+ }
479
+ return (
480
+ /** @type {const} */
481
+ [commentObj]
482
+ );
483
+ } else if (c === BS) {
484
+ esc = true;
485
+ } else if (c === DS && s.charAt(i2 + 1) === SQ && closesAnsiC(s, i2)) {
486
+ flushRun();
487
+ sawQuote = true;
488
+ out += expandAnsiC(s.slice(i2 + 2, ansiCAt.lastIndex - 1));
489
+ i2 = ansiCAt.lastIndex - 1;
490
+ } else if (c === DS) {
491
+ var value = parseEnvVar();
492
+ if (!ifs) {
493
+ out += value;
494
+ } else {
495
+ for (var vi = 0; vi < value.length; vi += 1) {
496
+ var vc = value.charAt(vi);
497
+ if (ifs.indexOf(vc) < 0) {
498
+ flushRun();
499
+ out += vc;
500
+ } else if (pendingNw === null) {
501
+ pendingNw = vc === " " || vc === " " || vc === "\n" ? 0 : 1;
502
+ } else if (vc !== " " && vc !== " " && vc !== "\n") {
503
+ pendingNw += 1;
504
+ }
505
+ }
506
+ }
507
+ } else {
508
+ out += c;
509
+ }
510
+ }
511
+ if (isGlob) {
512
+ return (
513
+ /** @type {GlobPattern} */
514
+ { op: "glob", pattern: out }
515
+ );
516
+ }
517
+ if (ifs) {
518
+ if (pendingNw !== null && pendingNw > 0) {
519
+ words[words.length] = out;
520
+ out = "";
521
+ for (var te = 1; te < pendingNw; te += 1) {
522
+ words[words.length] = "";
523
+ }
524
+ }
525
+ if (out !== "" || sawQuote && words.length === 0) {
526
+ words[words.length] = out;
527
+ }
528
+ return words;
529
+ }
530
+ return out;
531
+ }).reduce(
532
+ function(prev, arg) {
533
+ if (typeof arg === "undefined") {
534
+ return prev;
535
+ }
536
+ [].concat(arg).forEach(function(entry) {
537
+ prev[prev.length] = entry;
538
+ });
539
+ return prev;
540
+ },
541
+ /** @type {ParseEntry[]} */
542
+ []
543
+ );
544
+ }
545
+ module.exports = function parse(s, env, opts) {
546
+ var mapped = parseInternal(s, env, opts);
547
+ if (typeof env !== "function") {
548
+ return mapped;
549
+ }
550
+ return mapped.reduce(
551
+ function(acc, s2) {
552
+ if (typeof s2 === "object") {
553
+ acc[acc.length] = s2;
554
+ return acc;
555
+ }
556
+ var xs = s2.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
557
+ if (xs.length === 1) {
558
+ acc[acc.length] = xs[0];
559
+ return acc;
560
+ }
561
+ xs.filter(Boolean).forEach(function(x) {
562
+ acc[acc.length] = startsWithToken.test(x) ? JSON.parse(x.split(TOKEN)[1]) : x;
563
+ });
564
+ return acc;
565
+ },
566
+ /** @type {ParseEntry[]} */
567
+ []
568
+ );
569
+ };
570
+ }
571
+ });
572
+
573
+ // node_modules/.pnpm/shell-quote@1.12.0/node_modules/shell-quote/index.js
574
+ var require_shell_quote = __commonJS({
575
+ "node_modules/.pnpm/shell-quote@1.12.0/node_modules/shell-quote/index.js"(exports) {
576
+ "use strict";
577
+ exports.quote = require_quote();
578
+ exports.parse = require_parse();
579
+ }
580
+ });
581
+
582
+ // node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/editor-info/macos.js
583
+ var require_macos = __commonJS({
584
+ "node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/editor-info/macos.js"(exports, module) {
585
+ module.exports = {
586
+ "/Applications/Atom.app/Contents/MacOS/Atom": "atom",
587
+ "/Applications/Atom Beta.app/Contents/MacOS/Atom Beta": "/Applications/Atom Beta.app/Contents/MacOS/Atom Beta",
588
+ "/Applications/Brackets.app/Contents/MacOS/Brackets": "brackets",
589
+ "/Applications/Sublime Text.app/Contents/MacOS/Sublime Text": "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl",
590
+ "/Applications/Sublime Text.app/Contents/MacOS/sublime_text": "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl",
591
+ "/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2": "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl",
592
+ "/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text": "/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl",
593
+ "/Applications/Visual Studio Code.app/Contents/MacOS/Code": "code",
594
+ "/Applications/Visual Studio Code.app/Contents/MacOS/Electron": "code",
595
+ "/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Code - Insiders": "code-insiders",
596
+ "/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron": "code-insiders",
597
+ "/Applications/VSCodium.app/Contents/MacOS/Electron": "codium",
598
+ "/Applications/Cursor.app/Contents/MacOS/Cursor": "cursor",
599
+ "/Applications/Trae.app/Contents/MacOS/Electron": "trae",
600
+ "/Applications/Antigravity.app/Contents/MacOS/Electron": "antigravity",
601
+ "/Applications/AppCode.app/Contents/MacOS/appcode": "/Applications/AppCode.app/Contents/MacOS/appcode",
602
+ "/Applications/CLion.app/Contents/MacOS/clion": "/Applications/CLion.app/Contents/MacOS/clion",
603
+ "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea",
604
+ "/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea",
605
+ "/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea",
606
+ "/Applications/PhpStorm.app/Contents/MacOS/phpstorm": "/Applications/PhpStorm.app/Contents/MacOS/phpstorm",
607
+ "/Applications/PyCharm.app/Contents/MacOS/pycharm": "/Applications/PyCharm.app/Contents/MacOS/pycharm",
608
+ "/Applications/PyCharm CE.app/Contents/MacOS/pycharm": "/Applications/PyCharm CE.app/Contents/MacOS/pycharm",
609
+ "/Applications/RubyMine.app/Contents/MacOS/rubymine": "/Applications/RubyMine.app/Contents/MacOS/rubymine",
610
+ "/Applications/WebStorm.app/Contents/MacOS/webstorm": "/Applications/WebStorm.app/Contents/MacOS/webstorm",
611
+ "/Applications/MacVim.app/Contents/MacOS/MacVim": "mvim",
612
+ "/Applications/GoLand.app/Contents/MacOS/goland": "/Applications/GoLand.app/Contents/MacOS/goland",
613
+ "/Applications/Rider.app/Contents/MacOS/rider": "/Applications/Rider.app/Contents/MacOS/rider",
614
+ "/Applications/Zed.app/Contents/MacOS/zed": "zed"
615
+ };
616
+ }
617
+ });
618
+
619
+ // node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/editor-info/linux.js
620
+ var require_linux = __commonJS({
621
+ "node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/editor-info/linux.js"(exports, module) {
622
+ module.exports = {
623
+ atom: "atom",
624
+ Brackets: "brackets",
625
+ "code-insiders": "code-insiders",
626
+ code: "code",
627
+ vscodium: "vscodium",
628
+ codium: "codium",
629
+ cursor: "cursor",
630
+ trae: "trae",
631
+ antigravity: "antigravity",
632
+ emacs: "emacs",
633
+ gvim: "gvim",
634
+ idea: "idea",
635
+ "idea.sh": "idea",
636
+ phpstorm: "phpstorm",
637
+ "phpstorm.sh": "phpstorm",
638
+ pycharm: "pycharm",
639
+ "pycharm.sh": "pycharm",
640
+ rubymine: "rubymine",
641
+ "rubymine.sh": "rubymine",
642
+ sublime_text: "subl",
643
+ vim: "vim",
644
+ webstorm: "webstorm",
645
+ "webstorm.sh": "webstorm",
646
+ goland: "goland",
647
+ "goland.sh": "goland",
648
+ rider: "rider",
649
+ "rider.sh": "rider",
650
+ zed: "zed"
651
+ };
652
+ }
653
+ });
654
+
655
+ // node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/editor-info/windows.js
656
+ var require_windows = __commonJS({
657
+ "node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/editor-info/windows.js"(exports, module) {
658
+ module.exports = [
659
+ "Brackets.exe",
660
+ "Code.exe",
661
+ "Code - Insiders.exe",
662
+ "VSCodium.exe",
663
+ "Cursor.exe",
664
+ "atom.exe",
665
+ "sublime_text.exe",
666
+ "notepad++.exe",
667
+ "clion.exe",
668
+ "clion64.exe",
669
+ "idea.exe",
670
+ "idea64.exe",
671
+ "phpstorm.exe",
672
+ "phpstorm64.exe",
673
+ "pycharm.exe",
674
+ "pycharm64.exe",
675
+ "rubymine.exe",
676
+ "rubymine64.exe",
677
+ "webstorm.exe",
678
+ "webstorm64.exe",
679
+ "goland.exe",
680
+ "goland64.exe",
681
+ "rider.exe",
682
+ "rider64.exe",
683
+ "Trae.exe",
684
+ "zed.exe",
685
+ "Antigravity.exe"
686
+ ];
687
+ }
688
+ });
689
+
690
+ // node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/guess.js
691
+ var require_guess = __commonJS({
692
+ "node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/guess.js"(exports, module) {
693
+ var path2 = __require("path");
694
+ var shellQuote = require_shell_quote();
695
+ var childProcess = __require("child_process");
696
+ var COMMON_EDITORS_MACOS = require_macos();
697
+ var COMMON_EDITORS_LINUX = require_linux();
698
+ var COMMON_EDITORS_WIN = require_windows();
699
+ function getEditorFromMacProcesses(output) {
700
+ const processNames = Object.keys(COMMON_EDITORS_MACOS);
701
+ const processList = output.split("\n");
702
+ for (let i = 0; i < processNames.length; i++) {
703
+ const processName = processNames[i];
704
+ if (processList.includes(processName)) {
705
+ return COMMON_EDITORS_MACOS[processName];
706
+ }
707
+ const processNameWithoutApplications = processName.replace("/Applications", "");
708
+ if (output.indexOf(processNameWithoutApplications) !== -1) {
709
+ if (processName !== COMMON_EDITORS_MACOS[processName]) {
710
+ return COMMON_EDITORS_MACOS[processName];
711
+ }
712
+ const runningProcess = processList.find(
713
+ (procName) => procName.endsWith(processNameWithoutApplications)
714
+ );
715
+ if (runningProcess !== void 0) {
716
+ return runningProcess;
717
+ }
718
+ }
719
+ }
720
+ return void 0;
721
+ }
722
+ function getEditorFromWindowsProcesses(output) {
723
+ const runningProcesses = output.split("\r\n");
724
+ for (let i = 0; i < runningProcesses.length; i++) {
725
+ const fullProcessPath = runningProcesses[i].trim();
726
+ const shortProcessName = path2.win32.basename(fullProcessPath);
727
+ if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) {
728
+ return fullProcessPath;
729
+ }
730
+ }
731
+ return void 0;
732
+ }
733
+ function getEditorFromLinuxProcesses(output) {
734
+ const processNames = Object.keys(COMMON_EDITORS_LINUX);
735
+ for (let i = 0; i < processNames.length; i++) {
736
+ const processName = processNames[i];
737
+ if (output.indexOf(processName) !== -1) {
738
+ return COMMON_EDITORS_LINUX[processName];
739
+ }
740
+ }
741
+ return void 0;
742
+ }
743
+ function guessEditor(specifiedEditor) {
744
+ if (specifiedEditor) {
745
+ return shellQuote.parse(specifiedEditor);
746
+ }
747
+ if (process.env.LAUNCH_EDITOR) {
748
+ return [process.env.LAUNCH_EDITOR];
749
+ }
750
+ if (process.versions.webcontainer) {
751
+ return [process.env.EDITOR || "code"];
752
+ }
753
+ try {
754
+ if (process.platform === "darwin") {
755
+ const output = childProcess.execSync("ps x -o comm=", {
756
+ stdio: ["pipe", "pipe", "ignore"]
757
+ }).toString();
758
+ const editor = getEditorFromMacProcesses(output);
759
+ if (editor !== void 0) {
760
+ return [editor];
761
+ }
762
+ } else if (process.platform === "win32") {
763
+ const output = childProcess.execSync(
764
+ 'powershell -NoProfile -Command "[Console]::OutputEncoding=[Text.Encoding]::UTF8;Get-CimInstance -Query \\"select executablepath from win32_process where executablepath is not null\\" | % { $_.ExecutablePath }"',
765
+ {
766
+ stdio: ["pipe", "pipe", "ignore"]
767
+ }
768
+ ).toString();
769
+ const editor = getEditorFromWindowsProcesses(output);
770
+ if (editor !== void 0) {
771
+ return [editor];
772
+ }
773
+ } else if (process.platform === "linux") {
774
+ const output = childProcess.execSync("ps x --no-heading -o comm --sort=comm", {
775
+ stdio: ["pipe", "pipe", "ignore"]
776
+ }).toString();
777
+ const editor = getEditorFromLinuxProcesses(output);
778
+ if (editor !== void 0) {
779
+ return [editor];
780
+ }
781
+ }
782
+ } catch (ignoreError) {
783
+ }
784
+ if (process.env.VISUAL) {
785
+ return [process.env.VISUAL];
786
+ } else if (process.env.EDITOR) {
787
+ return [process.env.EDITOR];
788
+ }
789
+ return [null];
790
+ }
791
+ module.exports = guessEditor;
792
+ module.exports.getEditorFromMacProcesses = getEditorFromMacProcesses;
793
+ module.exports.getEditorFromWindowsProcesses = getEditorFromWindowsProcesses;
794
+ module.exports.getEditorFromLinuxProcesses = getEditorFromLinuxProcesses;
795
+ }
796
+ });
797
+
798
+ // node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/get-args.js
799
+ var require_get_args = __commonJS({
800
+ "node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/get-args.js"(exports, module) {
801
+ var os2 = __require("os");
802
+ var path2 = __require("path");
803
+ module.exports = function getArgumentsForFile(editor, fileName, lineNumber, columnNumber = 1) {
804
+ fileName = path2.resolve(fileName);
805
+ if (process.platform === "linux" && fileName.startsWith("/mnt/") && /Microsoft/i.test(os2.release())) {
806
+ fileName = `./${path2.relative("", fileName)}`;
807
+ }
808
+ if (!lineNumber) {
809
+ return [fileName];
810
+ }
811
+ const editorBasename = path2.basename(editor).replace(/\.(exe|cmd|bat)$/i, "");
812
+ switch (editorBasename) {
813
+ case "atom":
814
+ case "Atom":
815
+ case "Atom Beta":
816
+ case "subl":
817
+ case "sublime":
818
+ case "sublime_text":
819
+ case "wstorm":
820
+ case "charm":
821
+ case "zed":
822
+ return [`${fileName}:${lineNumber}:${columnNumber}`];
823
+ case "notepad++":
824
+ return ["-n" + lineNumber, "-c" + columnNumber, fileName];
825
+ case "vim":
826
+ case "mvim":
827
+ return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName];
828
+ case "joe":
829
+ case "gvim":
830
+ return [`+${lineNumber}`, fileName];
831
+ case "emacs":
832
+ case "emacsclient":
833
+ return [`+${lineNumber}:${columnNumber}`, fileName];
834
+ case "rmate":
835
+ case "mate":
836
+ case "mine":
837
+ return ["--line", lineNumber, fileName];
838
+ case "code":
839
+ case "Code":
840
+ case "code-insiders":
841
+ case "Code - Insiders":
842
+ case "codium":
843
+ case "trae":
844
+ case "antigravity":
845
+ case "cursor":
846
+ case "vscodium":
847
+ case "VSCodium":
848
+ return ["-r", "-g", `${fileName}:${lineNumber}:${columnNumber}`];
849
+ case "appcode":
850
+ case "clion":
851
+ case "clion64":
852
+ case "idea":
853
+ case "idea64":
854
+ case "phpstorm":
855
+ case "phpstorm64":
856
+ case "pycharm":
857
+ case "pycharm64":
858
+ case "rubymine":
859
+ case "rubymine64":
860
+ case "webstorm":
861
+ case "webstorm64":
862
+ case "goland":
863
+ case "goland64":
864
+ case "rider":
865
+ case "rider64":
866
+ return ["--line", lineNumber, "--column", columnNumber, fileName];
867
+ }
868
+ if (process.env.LAUNCH_EDITOR) {
869
+ return [fileName, lineNumber, columnNumber];
870
+ }
871
+ return [fileName];
872
+ };
873
+ }
874
+ });
875
+
876
+ // node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/construct-windows-launch-command.js
877
+ var require_construct_windows_launch_command = __commonJS({
878
+ "node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/construct-windows-launch-command.js"(exports, module) {
879
+ function escapeCmdArgs(cmdArgs) {
880
+ return cmdArgs.replace(/([&|<>,;=^])/g, "^$1");
881
+ }
882
+ function doubleQuoteIfNeeded(str) {
883
+ if (str.includes("^")) {
884
+ return `^"${str}^"`;
885
+ } else if (str.includes(" ")) {
886
+ return `"${str}"`;
887
+ }
888
+ return str;
889
+ }
890
+ function constructWindowsLaunchCommand(editor, args) {
891
+ if (args.some((arg) => /[\r\n]/.test(arg))) {
892
+ throw new Error("Cannot launch an editor with an argument containing a line break");
893
+ }
894
+ if (args.some((arg) => arg.includes("%"))) {
895
+ throw new Error('Cannot launch an editor with an argument containing "%"');
896
+ }
897
+ return [editor, ...args.map(escapeCmdArgs)].map(doubleQuoteIfNeeded).join(" ");
898
+ }
899
+ module.exports = constructWindowsLaunchCommand;
900
+ }
901
+ });
902
+
903
+ // node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/parse-file.js
904
+ var require_parse_file = __commonJS({
905
+ "node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/parse-file.js"(exports, module) {
906
+ var path2 = __require("path");
907
+ var positionRE = /:(\d+)(:(\d+))?$/;
908
+ module.exports = function parseFile(file) {
909
+ if (file.startsWith("file://")) {
910
+ file = __require("url").fileURLToPath(file);
911
+ }
912
+ const unresolvedFileName = file.replace(positionRE, "");
913
+ const fileName = unresolvedFileName ? path2.resolve(unresolvedFileName) : "";
914
+ const match = file.match(positionRE);
915
+ const lineNumber = match && match[1];
916
+ const columnNumber = match && match[3];
917
+ return {
918
+ fileName,
919
+ lineNumber,
920
+ columnNumber
921
+ };
922
+ };
923
+ }
924
+ });
925
+
926
+ // node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/index.js
927
+ var require_launch_editor = __commonJS({
928
+ "node_modules/.pnpm/launch-editor@2.14.2/node_modules/launch-editor/index.js"(exports, module) {
929
+ var fs2 = __require("fs");
930
+ var path2 = __require("path");
931
+ var colors = require_picocolors();
932
+ var childProcess = __require("child_process");
933
+ var guessEditor = require_guess();
934
+ var getArgumentsForFile = require_get_args();
935
+ var constructWindowsLaunchCommand = require_construct_windows_launch_command();
936
+ var parseFile = require_parse_file();
937
+ function wrapErrorCallback(cb) {
938
+ return (fileName, errorMessage) => {
939
+ console.log();
940
+ console.log(colors.red("Could not open " + path2.basename(fileName) + " in the editor."));
941
+ if (errorMessage) {
942
+ if (errorMessage[errorMessage.length - 1] !== ".") {
943
+ errorMessage += ".";
944
+ }
945
+ console.log(colors.red("The editor process exited with an error: " + errorMessage));
946
+ }
947
+ console.log();
948
+ if (cb) cb(fileName, errorMessage);
949
+ };
950
+ }
951
+ function isTerminalEditor(editor) {
952
+ switch (editor) {
953
+ case "vim":
954
+ case "emacs":
955
+ case "nano":
956
+ return true;
957
+ }
958
+ return false;
959
+ }
960
+ var currentChildProcess = null;
961
+ function launchEditor2(file, specifiedEditor, onErrorCallback) {
962
+ const { fileName, lineNumber, columnNumber } = parseFile(file);
963
+ if (typeof specifiedEditor === "function") {
964
+ onErrorCallback = specifiedEditor;
965
+ specifiedEditor = void 0;
966
+ }
967
+ onErrorCallback = wrapErrorCallback(onErrorCallback);
968
+ if (process.platform === "win32" && fileName.startsWith("\\\\")) {
969
+ return onErrorCallback(
970
+ fileName,
971
+ "UNC paths are not supported on Windows to avoid security issues. See https://github.com/vitejs/launch-editor/tree/main/packages/launch-editor#unc-paths-on-windows for details."
972
+ );
973
+ }
974
+ if (!fs2.existsSync(fileName)) {
975
+ return;
976
+ }
977
+ const [editor, ...args] = guessEditor(specifiedEditor);
978
+ if (!editor) {
979
+ onErrorCallback(fileName, null);
980
+ return;
981
+ }
982
+ const extraArgs = getArgumentsForFile(editor, fileName, lineNumber, columnNumber);
983
+ args.push.apply(args, extraArgs);
984
+ let launchCommand;
985
+ if (process.platform === "win32") {
986
+ try {
987
+ launchCommand = constructWindowsLaunchCommand(editor, args);
988
+ } catch (error) {
989
+ onErrorCallback(fileName, error.message);
990
+ return;
991
+ }
992
+ }
993
+ if (currentChildProcess && isTerminalEditor(editor)) {
994
+ currentChildProcess.kill("SIGKILL");
995
+ }
996
+ if (process.platform === "win32") {
997
+ currentChildProcess = childProcess.exec(launchCommand, {
998
+ stdio: "inherit",
999
+ shell: true
1000
+ });
1001
+ } else {
1002
+ currentChildProcess = childProcess.spawn(editor, args, { stdio: "inherit" });
1003
+ }
1004
+ currentChildProcess.on("exit", function(errorCode) {
1005
+ currentChildProcess = null;
1006
+ if (errorCode) {
1007
+ onErrorCallback(fileName, "(code " + errorCode + ")");
1008
+ }
1009
+ });
1010
+ currentChildProcess.on("error", function(error) {
1011
+ let { code, message } = error;
1012
+ if ("ENOENT" === code) {
1013
+ message = `${message} ('${editor}' command does not exist in 'PATH')`;
1014
+ }
1015
+ onErrorCallback(fileName, message);
1016
+ });
1017
+ }
1018
+ module.exports = launchEditor2;
1019
+ }
1020
+ });
1021
+
1022
+ // src/cli.mjs
1023
+ import http from "node:http";
1024
+ import https from "node:https";
1025
+ import net from "node:net";
1026
+ import tls from "node:tls";
1027
+ import zlib from "node:zlib";
1028
+ import fs from "node:fs";
1029
+ import os from "node:os";
1030
+ import path from "node:path";
1031
+ import crypto from "node:crypto";
1032
+ import { execFileSync, spawn as spawn2 } from "node:child_process";
1033
+ import { fileURLToPath } from "node:url";
1034
+
1035
+ // node_modules/.pnpm/axi-sdk-js@0.1.13/node_modules/axi-sdk-js/dist/cli.js
1036
+ import { basename as basename2 } from "node:path";
1037
+
1038
+ // node_modules/.pnpm/axi-sdk-js@0.1.13/node_modules/axi-sdk-js/dist/errors.js
1039
+ var AxiError = class extends Error {
1040
+ code;
1041
+ suggestions;
1042
+ constructor(message, code, suggestions = []) {
1043
+ super(message);
1044
+ this.code = code;
1045
+ this.suggestions = suggestions;
1046
+ this.name = "AxiError";
1047
+ }
1048
+ };
1049
+ function exitCodeForError(error) {
1050
+ if (error instanceof AxiError && error.code === "VALIDATION_ERROR") {
1051
+ return 2;
1052
+ }
1053
+ return 1;
1054
+ }
1055
+
1056
+ // node_modules/.pnpm/axi-sdk-js@0.1.13/node_modules/axi-sdk-js/dist/output.js
1057
+ import { homedir } from "node:os";
1058
+
1059
+ // node_modules/.pnpm/@toon-format+toon@2.3.1/node_modules/@toon-format/toon/dist/index.mjs
1060
+ var NULL_LITERAL = "null";
1061
+ var DELIMITERS = {
1062
+ comma: ",",
1063
+ tab: " ",
1064
+ pipe: "|"
1065
+ };
1066
+ var DEFAULT_DELIMITER = DELIMITERS.comma;
1067
+ function escapeString(value) {
1068
+ return value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`).replace(/\n/g, `\\n`).replace(/\r/g, `\\r`).replace(/\t/g, `\\t`).replace(/[\u0000-\u001F]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
1069
+ }
1070
+ function isBooleanOrNullLiteral(token) {
1071
+ return token === "true" || token === "false" || token === "null";
1072
+ }
1073
+ function setOwnProperty(target, key, value) {
1074
+ if (key === "__proto__") {
1075
+ Object.defineProperty(target, key, {
1076
+ value,
1077
+ enumerable: true,
1078
+ writable: true,
1079
+ configurable: true
1080
+ });
1081
+ return;
1082
+ }
1083
+ target[key] = value;
1084
+ }
1085
+ function normalizeValue(value) {
1086
+ if (value === null) return null;
1087
+ if (typeof value === "object" && value !== null && "toJSON" in value && typeof value.toJSON === "function") {
1088
+ const next = value.toJSON();
1089
+ if (next !== value) return normalizeValue(next);
1090
+ }
1091
+ if (typeof value === "string" || typeof value === "boolean") return value;
1092
+ if (typeof value === "number") {
1093
+ if (Object.is(value, -0)) return 0;
1094
+ if (!Number.isFinite(value)) return null;
1095
+ return value;
1096
+ }
1097
+ if (typeof value === "bigint") {
1098
+ if (value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER) return Number(value);
1099
+ return value.toString();
1100
+ }
1101
+ if (value instanceof Date) return value.toISOString();
1102
+ if (Array.isArray(value)) return value.map(normalizeValue);
1103
+ if (value instanceof Set) return Array.from(value).map(normalizeValue);
1104
+ if (value instanceof Map) return Object.fromEntries(Array.from(value, ([k, v]) => [String(k), normalizeValue(v)]));
1105
+ if (isPlainObject(value)) {
1106
+ const encodedValues = {};
1107
+ for (const key in value) if (Object.hasOwn(value, key)) setOwnProperty(encodedValues, key, normalizeValue(value[key]));
1108
+ return encodedValues;
1109
+ }
1110
+ return null;
1111
+ }
1112
+ function isJsonPrimitive(value) {
1113
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
1114
+ }
1115
+ function isJsonArray(value) {
1116
+ return Array.isArray(value);
1117
+ }
1118
+ function isJsonObject(value) {
1119
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1120
+ }
1121
+ function isEmptyObject(value) {
1122
+ return Object.keys(value).length === 0;
1123
+ }
1124
+ function isPlainObject(value) {
1125
+ if (value === null || typeof value !== "object") return false;
1126
+ const prototype = Object.getPrototypeOf(value);
1127
+ return prototype === null || prototype === Object.prototype;
1128
+ }
1129
+ function isArrayOfPrimitives(value) {
1130
+ return value.length === 0 || value.every((item) => isJsonPrimitive(item));
1131
+ }
1132
+ function isArrayOfArrays(value) {
1133
+ return value.length === 0 || value.every((item) => isJsonArray(item));
1134
+ }
1135
+ function isArrayOfObjects(value) {
1136
+ return value.length === 0 || value.every((item) => isJsonObject(item));
1137
+ }
1138
+ var NUMERIC_LIKE_PATTERN = /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;
1139
+ var LEADING_ZERO_PATTERN = /^0\d+$/;
1140
+ function isValidUnquotedKey(key) {
1141
+ return /^[A-Z_][\w.]*$/i.test(key);
1142
+ }
1143
+ function isIdentifierSegment(key) {
1144
+ return /^[A-Z_]\w*$/i.test(key);
1145
+ }
1146
+ function isSafeUnquoted(value, delimiter2 = DEFAULT_DELIMITER) {
1147
+ if (!value) return false;
1148
+ if (value !== value.trim()) return false;
1149
+ if (isBooleanOrNullLiteral(value) || isNumericLike(value)) return false;
1150
+ if (value.includes(":")) return false;
1151
+ if (value.includes('"') || value.includes("\\")) return false;
1152
+ if (/[[\]{}]/.test(value)) return false;
1153
+ if (/[\u0000-\u001F]/.test(value)) return false;
1154
+ if (value.includes(delimiter2)) return false;
1155
+ if (value.startsWith("-")) return false;
1156
+ return true;
1157
+ }
1158
+ function isNumericLike(value) {
1159
+ return NUMERIC_LIKE_PATTERN.test(value) || LEADING_ZERO_PATTERN.test(value);
1160
+ }
1161
+ function tryFoldKeyChain(key, value, siblings, options, rootLiteralKeys, pathPrefix, flattenDepth) {
1162
+ if (options.keyFolding !== "safe") return;
1163
+ if (!isJsonObject(value)) return;
1164
+ const { segments, tail, leafValue } = collectSingleKeyChain(key, value, flattenDepth ?? options.flattenDepth);
1165
+ if (segments.length < 2) return;
1166
+ if (!segments.every((seg) => isIdentifierSegment(seg))) return;
1167
+ const foldedKey = buildFoldedKey(segments);
1168
+ const absolutePath = pathPrefix ? `${pathPrefix}.${foldedKey}` : foldedKey;
1169
+ if (siblings.includes(foldedKey)) return;
1170
+ if (rootLiteralKeys && rootLiteralKeys.has(absolutePath)) return;
1171
+ return {
1172
+ foldedKey,
1173
+ remainder: tail,
1174
+ leafValue,
1175
+ segmentCount: segments.length
1176
+ };
1177
+ }
1178
+ function collectSingleKeyChain(startKey, startValue, maxDepth) {
1179
+ const segments = [startKey];
1180
+ let currentValue = startValue;
1181
+ while (segments.length < maxDepth) {
1182
+ if (!isJsonObject(currentValue)) break;
1183
+ const keys = Object.keys(currentValue);
1184
+ if (keys.length !== 1) break;
1185
+ const nextKey = keys[0];
1186
+ const nextValue = currentValue[nextKey];
1187
+ segments.push(nextKey);
1188
+ currentValue = nextValue;
1189
+ }
1190
+ if (!isJsonObject(currentValue) || isEmptyObject(currentValue)) return {
1191
+ segments,
1192
+ tail: void 0,
1193
+ leafValue: currentValue
1194
+ };
1195
+ return {
1196
+ segments,
1197
+ tail: currentValue,
1198
+ leafValue: currentValue
1199
+ };
1200
+ }
1201
+ function buildFoldedKey(segments) {
1202
+ return segments.join(".");
1203
+ }
1204
+ function encodePrimitive(value, delimiter2) {
1205
+ if (value === null) return NULL_LITERAL;
1206
+ if (typeof value === "boolean") return String(value);
1207
+ if (typeof value === "number") return String(value);
1208
+ return encodeStringLiteral(value, delimiter2);
1209
+ }
1210
+ function encodeStringLiteral(value, delimiter2 = DEFAULT_DELIMITER) {
1211
+ if (isSafeUnquoted(value, delimiter2)) return value;
1212
+ return `"${escapeString(value)}"`;
1213
+ }
1214
+ function encodeKey(key) {
1215
+ if (isValidUnquotedKey(key)) return key;
1216
+ return `"${escapeString(key)}"`;
1217
+ }
1218
+ function encodeAndJoinPrimitives(values, delimiter2 = DEFAULT_DELIMITER) {
1219
+ return values.map((v) => encodePrimitive(v, delimiter2)).join(delimiter2);
1220
+ }
1221
+ function formatHeader(length, options) {
1222
+ const key = options?.key;
1223
+ const fields = options?.fields;
1224
+ const delimiter2 = options?.delimiter ?? ",";
1225
+ let header = "";
1226
+ if (key != null) header += encodeKey(key);
1227
+ header += `[${length}${delimiter2 !== DEFAULT_DELIMITER ? delimiter2 : ""}]`;
1228
+ if (fields) {
1229
+ const quotedFields = fields.map((f) => encodeKey(f));
1230
+ header += `{${quotedFields.join(delimiter2)}}`;
1231
+ }
1232
+ header += ":";
1233
+ return header;
1234
+ }
1235
+ function* encodeJsonValue(value, options, depth) {
1236
+ if (isJsonPrimitive(value)) {
1237
+ const encodedPrimitive = encodePrimitive(value, options.delimiter);
1238
+ if (encodedPrimitive !== "") yield encodedPrimitive;
1239
+ return;
1240
+ }
1241
+ if (isJsonArray(value)) yield* encodeArrayLines(void 0, value, depth, options);
1242
+ else if (isJsonObject(value)) yield* encodeObjectLines(value, depth, options);
1243
+ }
1244
+ function* encodeObjectLines(value, depth, options, rootLiteralKeys, pathPrefix, remainingDepth) {
1245
+ const keys = Object.keys(value);
1246
+ if (depth === 0 && !rootLiteralKeys) rootLiteralKeys = new Set(keys.filter((k) => k.includes(".")));
1247
+ const effectiveFlattenDepth = remainingDepth ?? options.flattenDepth;
1248
+ for (const [key, val] of Object.entries(value)) yield* encodeKeyValuePairLines(key, val, depth, options, keys, rootLiteralKeys, pathPrefix, effectiveFlattenDepth);
1249
+ }
1250
+ function* encodeKeyValuePairLines(key, value, depth, options, siblings, rootLiteralKeys, pathPrefix, flattenDepth) {
1251
+ const currentPath = pathPrefix ? `${pathPrefix}.${key}` : key;
1252
+ const effectiveFlattenDepth = flattenDepth ?? options.flattenDepth;
1253
+ if (options.keyFolding === "safe" && siblings) {
1254
+ const foldResult = tryFoldKeyChain(key, value, siblings, options, rootLiteralKeys, pathPrefix, effectiveFlattenDepth);
1255
+ if (foldResult) {
1256
+ const { foldedKey, remainder, leafValue, segmentCount } = foldResult;
1257
+ const encodedFoldedKey = encodeKey(foldedKey);
1258
+ if (remainder === void 0) {
1259
+ if (isJsonPrimitive(leafValue)) {
1260
+ yield indentedLine(depth, `${encodedFoldedKey}: ${encodePrimitive(leafValue, options.delimiter)}`, options.indent);
1261
+ return;
1262
+ } else if (isJsonArray(leafValue)) {
1263
+ yield* encodeArrayLines(foldedKey, leafValue, depth, options);
1264
+ return;
1265
+ } else if (isJsonObject(leafValue) && isEmptyObject(leafValue)) {
1266
+ yield indentedLine(depth, `${encodedFoldedKey}:`, options.indent);
1267
+ return;
1268
+ }
1269
+ }
1270
+ if (isJsonObject(remainder)) {
1271
+ yield indentedLine(depth, `${encodedFoldedKey}:`, options.indent);
1272
+ const remainingDepth = effectiveFlattenDepth - segmentCount;
1273
+ const foldedPath = pathPrefix ? `${pathPrefix}.${foldedKey}` : foldedKey;
1274
+ yield* encodeObjectLines(remainder, depth + 1, options, rootLiteralKeys, foldedPath, remainingDepth);
1275
+ return;
1276
+ }
1277
+ }
1278
+ }
1279
+ const encodedKey = encodeKey(key);
1280
+ if (isJsonPrimitive(value)) yield indentedLine(depth, `${encodedKey}: ${encodePrimitive(value, options.delimiter)}`, options.indent);
1281
+ else if (isJsonArray(value)) yield* encodeArrayLines(key, value, depth, options);
1282
+ else if (isJsonObject(value)) {
1283
+ yield indentedLine(depth, `${encodedKey}:`, options.indent);
1284
+ if (!isEmptyObject(value)) yield* encodeObjectLines(value, depth + 1, options, rootLiteralKeys, currentPath, effectiveFlattenDepth);
1285
+ }
1286
+ }
1287
+ function* encodeArrayLines(key, value, depth, options) {
1288
+ if (value.length === 0) {
1289
+ yield indentedLine(depth, key != null ? `${encodeKey(key)}: []` : "[]", options.indent);
1290
+ return;
1291
+ }
1292
+ if (isArrayOfPrimitives(value)) {
1293
+ yield indentedLine(depth, encodeInlineArrayLine(value, options.delimiter, key), options.indent);
1294
+ return;
1295
+ }
1296
+ if (isArrayOfArrays(value)) {
1297
+ if (value.every((arr) => isArrayOfPrimitives(arr))) {
1298
+ yield* encodeArrayOfArraysAsListItemsLines(key, value, depth, options);
1299
+ return;
1300
+ }
1301
+ }
1302
+ if (isArrayOfObjects(value)) {
1303
+ const header = extractTabularHeader(value);
1304
+ if (header) yield* encodeArrayOfObjectsAsTabularLines(key, value, header, depth, options);
1305
+ else yield* encodeMixedArrayAsListItemsLines(key, value, depth, options);
1306
+ return;
1307
+ }
1308
+ yield* encodeMixedArrayAsListItemsLines(key, value, depth, options);
1309
+ }
1310
+ function* encodeArrayOfArraysAsListItemsLines(prefix, values, depth, options) {
1311
+ yield indentedLine(depth, formatHeader(values.length, {
1312
+ key: prefix,
1313
+ delimiter: options.delimiter
1314
+ }), options.indent);
1315
+ for (const arr of values) if (isArrayOfPrimitives(arr)) {
1316
+ const arrayLine = encodeInlineArrayLine(arr, options.delimiter);
1317
+ yield indentedListItem(depth + 1, arrayLine, options.indent);
1318
+ }
1319
+ }
1320
+ function encodeInlineArrayLine(values, delimiter2, prefix) {
1321
+ const header = formatHeader(values.length, {
1322
+ key: prefix,
1323
+ delimiter: delimiter2
1324
+ });
1325
+ const joinedValue = encodeAndJoinPrimitives(values, delimiter2);
1326
+ if (values.length === 0) return header;
1327
+ return `${header} ${joinedValue}`;
1328
+ }
1329
+ function* encodeArrayOfObjectsAsTabularLines(prefix, rows, header, depth, options) {
1330
+ yield indentedLine(depth, formatHeader(rows.length, {
1331
+ key: prefix,
1332
+ fields: header,
1333
+ delimiter: options.delimiter
1334
+ }), options.indent);
1335
+ yield* writeTabularRowsLines(rows, header, depth + 1, options);
1336
+ }
1337
+ function extractTabularHeader(rows) {
1338
+ if (rows.length === 0) return;
1339
+ const firstRow = rows[0];
1340
+ const firstKeys = Object.keys(firstRow);
1341
+ if (firstKeys.length === 0) return;
1342
+ if (isTabularArray(rows, firstKeys)) return firstKeys;
1343
+ }
1344
+ function isTabularArray(rows, header) {
1345
+ for (const row of rows) {
1346
+ if (Object.keys(row).length !== header.length) return false;
1347
+ for (const key of header) {
1348
+ if (!Object.hasOwn(row, key)) return false;
1349
+ if (!isJsonPrimitive(row[key])) return false;
1350
+ }
1351
+ }
1352
+ return true;
1353
+ }
1354
+ function* writeTabularRowsLines(rows, header, depth, options) {
1355
+ for (const row of rows) yield indentedLine(depth, encodeAndJoinPrimitives(header.map((key) => row[key]), options.delimiter), options.indent);
1356
+ }
1357
+ function* encodeMixedArrayAsListItemsLines(prefix, items, depth, options) {
1358
+ yield indentedLine(depth, formatHeader(items.length, {
1359
+ key: prefix,
1360
+ delimiter: options.delimiter
1361
+ }), options.indent);
1362
+ for (const item of items) yield* encodeListItemValueLines(item, depth + 1, options);
1363
+ }
1364
+ function* encodeObjectAsListItemLines(obj, depth, options) {
1365
+ if (isEmptyObject(obj)) {
1366
+ yield indentedLine(depth, "-", options.indent);
1367
+ return;
1368
+ }
1369
+ const entries = Object.entries(obj);
1370
+ const [firstKey, firstValue] = entries[0];
1371
+ const restEntries = entries.slice(1);
1372
+ if (isJsonArray(firstValue) && isArrayOfObjects(firstValue)) {
1373
+ const header = extractTabularHeader(firstValue);
1374
+ if (header) {
1375
+ yield indentedListItem(depth, formatHeader(firstValue.length, {
1376
+ key: firstKey,
1377
+ fields: header,
1378
+ delimiter: options.delimiter
1379
+ }), options.indent);
1380
+ yield* writeTabularRowsLines(firstValue, header, depth + 2, options);
1381
+ if (restEntries.length > 0) yield* encodeObjectLines(Object.fromEntries(restEntries), depth + 1, options);
1382
+ return;
1383
+ }
1384
+ }
1385
+ const encodedKey = encodeKey(firstKey);
1386
+ if (isJsonPrimitive(firstValue)) yield indentedListItem(depth, `${encodedKey}: ${encodePrimitive(firstValue, options.delimiter)}`, options.indent);
1387
+ else if (isJsonArray(firstValue)) if (firstValue.length === 0) yield indentedListItem(depth, `${encodedKey}: []`, options.indent);
1388
+ else if (isArrayOfPrimitives(firstValue)) yield indentedListItem(depth, `${encodedKey}${encodeInlineArrayLine(firstValue, options.delimiter)}`, options.indent);
1389
+ else {
1390
+ yield indentedListItem(depth, `${encodedKey}${formatHeader(firstValue.length, { delimiter: options.delimiter })}`, options.indent);
1391
+ for (const item of firstValue) yield* encodeListItemValueLines(item, depth + 2, options);
1392
+ }
1393
+ else if (isJsonObject(firstValue)) {
1394
+ yield indentedListItem(depth, `${encodedKey}:`, options.indent);
1395
+ if (!isEmptyObject(firstValue)) yield* encodeObjectLines(firstValue, depth + 2, options);
1396
+ }
1397
+ if (restEntries.length > 0) yield* encodeObjectLines(Object.fromEntries(restEntries), depth + 1, options);
1398
+ }
1399
+ function* encodeListItemValueLines(value, depth, options) {
1400
+ if (isJsonPrimitive(value)) yield indentedListItem(depth, encodePrimitive(value, options.delimiter), options.indent);
1401
+ else if (isJsonArray(value)) if (isArrayOfPrimitives(value)) yield indentedListItem(depth, encodeInlineArrayLine(value, options.delimiter), options.indent);
1402
+ else {
1403
+ yield indentedListItem(depth, formatHeader(value.length, { delimiter: options.delimiter }), options.indent);
1404
+ for (const item of value) yield* encodeListItemValueLines(item, depth + 1, options);
1405
+ }
1406
+ else if (isJsonObject(value)) yield* encodeObjectAsListItemLines(value, depth, options);
1407
+ }
1408
+ function indentedLine(depth, content, indentSize) {
1409
+ return " ".repeat(indentSize * depth) + content;
1410
+ }
1411
+ function indentedListItem(depth, content, indentSize) {
1412
+ return indentedLine(depth, "- " + content, indentSize);
1413
+ }
1414
+ function applyReplacer(root, replacer) {
1415
+ const replacedRoot = replacer("", root, []);
1416
+ if (replacedRoot === void 0) return transformChildren(root, replacer, []);
1417
+ return transformChildren(normalizeValue(replacedRoot), replacer, []);
1418
+ }
1419
+ function transformChildren(value, replacer, path2) {
1420
+ if (isJsonObject(value)) return transformObject(value, replacer, path2);
1421
+ if (isJsonArray(value)) return transformArray(value, replacer, path2);
1422
+ return value;
1423
+ }
1424
+ function transformObject(obj, replacer, path2) {
1425
+ const result = {};
1426
+ for (const [key, value] of Object.entries(obj)) {
1427
+ const childPath = [...path2, key];
1428
+ const replacedValue = replacer(key, value, childPath);
1429
+ if (replacedValue === void 0) continue;
1430
+ setOwnProperty(result, key, transformChildren(normalizeValue(replacedValue), replacer, childPath));
1431
+ }
1432
+ return result;
1433
+ }
1434
+ function transformArray(arr, replacer, path2) {
1435
+ const result = [];
1436
+ for (let i = 0; i < arr.length; i++) {
1437
+ const value = arr[i];
1438
+ const childPath = [...path2, i];
1439
+ const replacedValue = replacer(String(i), value, childPath);
1440
+ if (replacedValue === void 0) continue;
1441
+ const normalizedValue = normalizeValue(replacedValue);
1442
+ result.push(transformChildren(normalizedValue, replacer, childPath));
1443
+ }
1444
+ return result;
1445
+ }
1446
+ function encode(input, options) {
1447
+ return Array.from(encodeLines(input, options)).join("\n");
1448
+ }
1449
+ function encodeLines(input, options) {
1450
+ const normalizedValue = normalizeValue(input);
1451
+ const resolvedOptions = resolveOptions(options);
1452
+ return encodeJsonValue(resolvedOptions.replacer ? applyReplacer(normalizedValue, resolvedOptions.replacer) : normalizedValue, resolvedOptions, 0);
1453
+ }
1454
+ function resolveOptions(options) {
1455
+ return {
1456
+ indent: options?.indent ?? 2,
1457
+ delimiter: options?.delimiter ?? DEFAULT_DELIMITER,
1458
+ keyFolding: options?.keyFolding ?? "off",
1459
+ flattenDepth: options?.flattenDepth ?? Number.POSITIVE_INFINITY,
1460
+ replacer: options?.replacer
1461
+ };
1462
+ }
1463
+
1464
+ // node_modules/.pnpm/axi-sdk-js@0.1.13/node_modules/axi-sdk-js/dist/output.js
1465
+ function collapseHomeDirectory(path2, homeDir = homedir()) {
1466
+ if (!path2.startsWith(homeDir)) {
1467
+ return path2;
1468
+ }
1469
+ return `~${path2.slice(homeDir.length)}`;
1470
+ }
1471
+ function homeHeaderOutput(options) {
1472
+ return {
1473
+ bin: collapseHomeDirectory(options.execPath ?? process.argv[1] ?? "", options.homeDir),
1474
+ description: options.description
1475
+ };
1476
+ }
1477
+ function errorOutput(message, code, suggestions = []) {
1478
+ const output = {
1479
+ error: message,
1480
+ code
1481
+ };
1482
+ if (suggestions.length > 0) {
1483
+ output.help = suggestions;
1484
+ }
1485
+ return output;
1486
+ }
1487
+ function renderOutput(output) {
1488
+ if (typeof output === "string") {
1489
+ return output;
1490
+ }
1491
+ return encode(output);
1492
+ }
1493
+ function renderError(message, code, suggestions = []) {
1494
+ return renderOutput(errorOutput(message, code, suggestions));
1495
+ }
1496
+
1497
+ // node_modules/.pnpm/axi-sdk-js@0.1.13/node_modules/axi-sdk-js/dist/update.js
1498
+ import { spawn } from "node:child_process";
1499
+ import { execFile } from "node:child_process";
1500
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
1501
+ import { basename, dirname, join } from "node:path";
1502
+ import { promisify } from "node:util";
1503
+ var execFileAsync = promisify(execFile);
1504
+ var REGISTRY_BASE = "https://registry.npmjs.org";
1505
+ var REGISTRY_FETCH_TIMEOUT_MS = 2e4;
1506
+ function parseSemver(version2) {
1507
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-.]+))?(?:\+[0-9A-Za-z-.]+)?$/.exec(version2.trim());
1508
+ if (!match) {
1509
+ return null;
1510
+ }
1511
+ return {
1512
+ major: Number(match[1]),
1513
+ minor: Number(match[2]),
1514
+ patch: Number(match[3]),
1515
+ prerelease: match[4] ? match[4].split(".") : []
1516
+ };
1517
+ }
1518
+ function comparePrerelease(a, b) {
1519
+ if (a.length === 0 && b.length === 0)
1520
+ return 0;
1521
+ if (a.length === 0)
1522
+ return 1;
1523
+ if (b.length === 0)
1524
+ return -1;
1525
+ const length = Math.max(a.length, b.length);
1526
+ for (let index = 0; index < length; index += 1) {
1527
+ if (index >= a.length)
1528
+ return -1;
1529
+ if (index >= b.length)
1530
+ return 1;
1531
+ const left = a[index];
1532
+ const right = b[index];
1533
+ const leftNumeric = /^\d+$/.test(left);
1534
+ const rightNumeric = /^\d+$/.test(right);
1535
+ if (leftNumeric && rightNumeric) {
1536
+ const delta = Number(left) - Number(right);
1537
+ if (delta !== 0)
1538
+ return delta < 0 ? -1 : 1;
1539
+ } else if (leftNumeric) {
1540
+ return -1;
1541
+ } else if (rightNumeric) {
1542
+ return 1;
1543
+ } else if (left !== right) {
1544
+ return left < right ? -1 : 1;
1545
+ }
1546
+ }
1547
+ return 0;
1548
+ }
1549
+ function compareSemver(a, b) {
1550
+ const parsedA = parseSemver(a);
1551
+ const parsedB = parseSemver(b);
1552
+ if (!parsedA || !parsedB) {
1553
+ if (a === b)
1554
+ return 0;
1555
+ return a < b ? -1 : 1;
1556
+ }
1557
+ if (parsedA.major !== parsedB.major) {
1558
+ return parsedA.major < parsedB.major ? -1 : 1;
1559
+ }
1560
+ if (parsedA.minor !== parsedB.minor) {
1561
+ return parsedA.minor < parsedB.minor ? -1 : 1;
1562
+ }
1563
+ if (parsedA.patch !== parsedB.patch) {
1564
+ return parsedA.patch < parsedB.patch ? -1 : 1;
1565
+ }
1566
+ return comparePrerelease(parsedA.prerelease, parsedB.prerelease);
1567
+ }
1568
+ function isUpdateAvailable(current, latest) {
1569
+ return compareSemver(latest, current) > 0;
1570
+ }
1571
+ var nodeFs = {
1572
+ existsSync,
1573
+ readFileSync: (path2, encoding) => readFileSync(path2, encoding)
1574
+ };
1575
+ function readNearestPackageJson(startPath, fs2 = nodeFs) {
1576
+ let dir = dirname(startPath);
1577
+ let previous = "";
1578
+ while (dir !== previous) {
1579
+ const packageJsonPath = join(dir, "package.json");
1580
+ if (fs2.existsSync(packageJsonPath)) {
1581
+ try {
1582
+ const parsed = JSON.parse(fs2.readFileSync(packageJsonPath, "utf-8"));
1583
+ if (typeof parsed.name === "string" && parsed.name.length > 0) {
1584
+ return {
1585
+ packageName: parsed.name,
1586
+ version: typeof parsed.version === "string" ? parsed.version : void 0,
1587
+ packageJsonPath
1588
+ };
1589
+ }
1590
+ } catch {
1591
+ }
1592
+ }
1593
+ previous = dir;
1594
+ dir = dirname(dir);
1595
+ }
1596
+ return {};
1597
+ }
1598
+ function detectInstallMethod(options) {
1599
+ const env = options.env ?? process.env;
1600
+ const path2 = options.entry.replaceAll("\\", "/");
1601
+ if (path2.includes("/_npx/") || /\/dlx-[^/]+\//.test(path2) || path2.includes("/pnpm/dlx/") || path2.includes("/bun/install/cache/")) {
1602
+ return { kind: "npx" };
1603
+ }
1604
+ const homebrewFormula = homebrewFormulaFromPath(path2, env);
1605
+ if (homebrewFormula) {
1606
+ return { kind: "homebrew", formula: homebrewFormula };
1607
+ }
1608
+ const pnpmHome = normalizePathRoot(env.PNPM_HOME);
1609
+ if (isPathInsideRoot(path2, pnpmHome) || isKnownPnpmGlobalStore(path2, env)) {
1610
+ return { kind: "pnpm-global" };
1611
+ }
1612
+ if (isKnownNpmGlobalInstall(path2, env)) {
1613
+ return { kind: "npm-global" };
1614
+ }
1615
+ return { kind: "unknown" };
1616
+ }
1617
+ function normalizePathRoot(path2) {
1618
+ const normalized = path2?.replaceAll("\\", "/").replace(/\/+$/, "");
1619
+ return normalized && normalized.length > 0 ? normalized : void 0;
1620
+ }
1621
+ function isPathInsideRoot(path2, root) {
1622
+ return root !== void 0 && (path2 === root || path2.startsWith(`${root}/`));
1623
+ }
1624
+ function homebrewFormulaFromPath(path2, env) {
1625
+ for (const root of homebrewCellarRoots(env)) {
1626
+ if (!isPathInsideRoot(path2, root)) {
1627
+ continue;
1628
+ }
1629
+ const relative = path2.slice(root.length).replace(/^\/+/, "");
1630
+ const formula = relative.split("/")[0];
1631
+ if (formula) {
1632
+ return formula;
1633
+ }
1634
+ }
1635
+ return null;
1636
+ }
1637
+ function homebrewCellarRoots(env) {
1638
+ const roots = [];
1639
+ const explicitCellar = normalizePathRoot(env.HOMEBREW_CELLAR);
1640
+ if (explicitCellar) {
1641
+ roots.push(explicitCellar);
1642
+ }
1643
+ const prefixes = [
1644
+ env.HOMEBREW_PREFIX,
1645
+ "/opt/homebrew",
1646
+ "/usr/local",
1647
+ "/home/linuxbrew/.linuxbrew"
1648
+ ];
1649
+ for (const prefix of prefixes) {
1650
+ const normalized = normalizePathRoot(prefix);
1651
+ if (normalized) {
1652
+ roots.push(`${normalized}/Cellar`);
1653
+ }
1654
+ }
1655
+ return [...new Set(roots)];
1656
+ }
1657
+ function isKnownPnpmGlobalStore(path2, env) {
1658
+ return pnpmGlobalStoreRoots(env).some((root) => {
1659
+ if (!isPathInsideRoot(path2, root)) {
1660
+ return false;
1661
+ }
1662
+ const relative = path2.slice(root.length).replace(/^\/+/, "");
1663
+ return /^\d+\/\.pnpm\//.test(relative);
1664
+ });
1665
+ }
1666
+ function pnpmGlobalStoreRoots(env) {
1667
+ const roots = [];
1668
+ const home2 = normalizePathRoot(env.HOME ?? env.USERPROFILE);
1669
+ if (home2) {
1670
+ roots.push(`${home2}/Library/pnpm/global`);
1671
+ roots.push(`${home2}/.local/share/pnpm/global`);
1672
+ roots.push(`${home2}/AppData/Local/pnpm/global`);
1673
+ }
1674
+ const localAppData = normalizePathRoot(env.LOCALAPPDATA);
1675
+ if (localAppData) {
1676
+ roots.push(`${localAppData}/pnpm/global`);
1677
+ }
1678
+ return [...new Set(roots)];
1679
+ }
1680
+ function isKnownNpmGlobalInstall(path2, env) {
1681
+ return npmGlobalNodeModulesRoots(env).some((root) => isPathInsideRoot(path2, root)) || isKnownVersionManagerNpmGlobal(path2, env);
1682
+ }
1683
+ function npmGlobalNodeModulesRoots(env) {
1684
+ const roots = [
1685
+ "/usr/local/lib/node_modules",
1686
+ "/usr/lib/node_modules",
1687
+ "/opt/homebrew/lib/node_modules",
1688
+ "/opt/local/lib/node_modules"
1689
+ ];
1690
+ const prefixes = [env.npm_config_prefix, env.NPM_CONFIG_PREFIX];
1691
+ for (const prefix of prefixes) {
1692
+ const normalized = normalizePathRoot(prefix);
1693
+ if (normalized) {
1694
+ roots.push(`${normalized}/lib/node_modules`, `${normalized}/node_modules`);
1695
+ }
1696
+ }
1697
+ const appData = normalizePathRoot(env.APPDATA);
1698
+ if (appData) {
1699
+ roots.push(`${appData}/npm/node_modules`);
1700
+ }
1701
+ const home2 = normalizePathRoot(env.HOME ?? env.USERPROFILE);
1702
+ if (home2) {
1703
+ roots.push(`${home2}/.npm-global/lib/node_modules`, `${home2}/.npm-packages/lib/node_modules`);
1704
+ }
1705
+ return [...new Set(roots)];
1706
+ }
1707
+ function isKnownVersionManagerNpmGlobal(path2, env) {
1708
+ return versionManagerNodeRoots(env).some((root) => isPathInsideRoot(path2, root) && path2.includes("/lib/node_modules/"));
1709
+ }
1710
+ function versionManagerNodeRoots(env) {
1711
+ const roots = [];
1712
+ const home2 = normalizePathRoot(env.HOME ?? env.USERPROFILE);
1713
+ if (home2) {
1714
+ roots.push(`${home2}/.nvm/versions/node`, `${home2}/.local/share/fnm/node-versions`, `${home2}/.asdf/installs/nodejs`, `${home2}/.nodenv/versions`, `${home2}/.local/share/mise/installs/node`, `${home2}/.volta/tools/image/node`);
1715
+ }
1716
+ const nvmDir = normalizePathRoot(env.NVM_DIR);
1717
+ if (nvmDir) {
1718
+ roots.push(`${nvmDir}/versions/node`);
1719
+ }
1720
+ const fnmDir = normalizePathRoot(env.FNM_DIR);
1721
+ if (fnmDir) {
1722
+ roots.push(`${fnmDir}/node-versions`);
1723
+ }
1724
+ return [...new Set(roots)];
1725
+ }
1726
+ function planUpgrade(method, packageName) {
1727
+ switch (method.kind) {
1728
+ case "npm-global":
1729
+ return {
1730
+ method: method.kind,
1731
+ command: `npm install -g ${packageName}@latest`,
1732
+ argv: ["npm", "install", "-g", `${packageName}@latest`]
1733
+ };
1734
+ case "pnpm-global":
1735
+ return {
1736
+ method: method.kind,
1737
+ command: `pnpm add -g ${packageName}@latest`,
1738
+ argv: ["pnpm", "add", "-g", `${packageName}@latest`]
1739
+ };
1740
+ case "homebrew":
1741
+ if (method.formula) {
1742
+ return {
1743
+ method: method.kind,
1744
+ command: `brew upgrade ${method.formula}`,
1745
+ argv: ["brew", "upgrade", method.formula]
1746
+ };
1747
+ }
1748
+ return {
1749
+ method: method.kind,
1750
+ command: `brew upgrade ${packageName}`,
1751
+ argv: null,
1752
+ note: "Could not determine the Homebrew formula automatically"
1753
+ };
1754
+ case "npx":
1755
+ return {
1756
+ method: method.kind,
1757
+ command: `npx -y ${packageName}@latest`,
1758
+ argv: null,
1759
+ note: "npx always runs the latest published version, so no install is needed"
1760
+ };
1761
+ case "unknown":
1762
+ return {
1763
+ method: method.kind,
1764
+ command: `npm install -g ${packageName}@latest`,
1765
+ argv: null,
1766
+ note: "Could not determine how this tool was installed"
1767
+ };
1768
+ }
1769
+ }
1770
+ function packageManagerExecutable(command, platform) {
1771
+ if (platform === "win32" && (command === "npm" || command === "pnpm" || command === "npx")) {
1772
+ return `${command}.cmd`;
1773
+ }
1774
+ return command;
1775
+ }
1776
+ function shouldUseWindowsPackageManagerShell(command, platform) {
1777
+ return platform === "win32" && (command === "npm" || command === "pnpm" || command === "npx");
1778
+ }
1779
+ async function npmViewVersion(packageName, platform = process.platform) {
1780
+ try {
1781
+ const command = packageManagerExecutable("npm", platform);
1782
+ const { stdout } = await execFileAsync(command, ["view", packageName, "version"], {
1783
+ timeout: 2e4,
1784
+ shell: shouldUseWindowsPackageManagerShell("npm", platform)
1785
+ });
1786
+ const version2 = stdout.trim();
1787
+ return version2.length > 0 ? version2 : null;
1788
+ } catch {
1789
+ return null;
1790
+ }
1791
+ }
1792
+ function registryPath(packageName) {
1793
+ return packageName.startsWith("@") ? packageName.replace("/", "%2f") : packageName;
1794
+ }
1795
+ function notPublishedError(packageName) {
1796
+ return new AxiError(`${packageName} is not published to the npm registry`, "UPDATE_ERROR", [
1797
+ "Confirm the package name is correct",
1798
+ `Run \`npm view ${packageName} version\` to check manually`
1799
+ ]);
1800
+ }
1801
+ var RegistryNotFoundError = class extends Error {
1802
+ };
1803
+ async function withRegistryTimeout(timeoutMs, operation) {
1804
+ const controller = new AbortController();
1805
+ let timer;
1806
+ const timeout = new Promise((_resolve, reject) => {
1807
+ timer = setTimeout(() => {
1808
+ controller.abort();
1809
+ reject(new Error(`Registry fetch timed out after ${timeoutMs}ms`));
1810
+ }, timeoutMs);
1811
+ timer.unref?.();
1812
+ });
1813
+ try {
1814
+ return await Promise.race([operation(controller.signal), timeout]);
1815
+ } finally {
1816
+ if (timer) {
1817
+ clearTimeout(timer);
1818
+ }
1819
+ }
1820
+ }
1821
+ async function fetchRegistryVersion(fetchImpl, packageName, timeoutMs) {
1822
+ return withRegistryTimeout(timeoutMs, async (signal) => {
1823
+ const response = await fetchImpl(`${REGISTRY_BASE}/${registryPath(packageName)}/latest`, { headers: { accept: "application/json" }, signal });
1824
+ if (response.ok) {
1825
+ const data = await response.json();
1826
+ if (typeof data.version === "string" && data.version.length > 0) {
1827
+ return data.version;
1828
+ }
1829
+ } else if (response.status === 404) {
1830
+ throw new RegistryNotFoundError();
1831
+ }
1832
+ return null;
1833
+ });
1834
+ }
1835
+ async function fetchLatestVersion(packageName, options = {}) {
1836
+ const fetchImpl = options.fetchImpl === void 0 ? globalThis.fetch : options.fetchImpl ?? void 0;
1837
+ let registryNotFound = false;
1838
+ if (typeof fetchImpl === "function") {
1839
+ try {
1840
+ const version2 = await fetchRegistryVersion(fetchImpl, packageName, options.fetchTimeoutMs ?? REGISTRY_FETCH_TIMEOUT_MS);
1841
+ if (version2) {
1842
+ return version2;
1843
+ }
1844
+ } catch (error) {
1845
+ if (error instanceof RegistryNotFoundError) {
1846
+ registryNotFound = true;
1847
+ } else if (error instanceof AxiError) {
1848
+ throw error;
1849
+ }
1850
+ }
1851
+ }
1852
+ const viewed = await (options.npmView ?? ((name) => npmViewVersion(name, options.platform)))(packageName);
1853
+ if (viewed) {
1854
+ return viewed;
1855
+ }
1856
+ if (registryNotFound) {
1857
+ throw notPublishedError(packageName);
1858
+ }
1859
+ throw new AxiError(`Could not reach the npm registry to check for updates to ${packageName}`, "UPDATE_ERROR", [
1860
+ "Check your network connection and try again",
1861
+ `Run \`npm view ${packageName} version\` to check manually`
1862
+ ]);
1863
+ }
1864
+ async function defaultRunInstall(plan, stdout, context) {
1865
+ const argv = plan.argv;
1866
+ if (!argv || argv.length === 0) {
1867
+ return { ok: false, message: "No runnable upgrade command" };
1868
+ }
1869
+ stdout.write(`running: ${plan.command}
1870
+ `);
1871
+ return new Promise((resolve2) => {
1872
+ const [command, ...args] = argv;
1873
+ const child = spawn(packageManagerExecutable(command, context.platform), args, {
1874
+ stdio: ["ignore", "pipe", "pipe"],
1875
+ shell: shouldUseWindowsPackageManagerShell(command, context.platform)
1876
+ });
1877
+ child.stdout?.on("data", (chunk) => {
1878
+ process.stderr.write(chunk);
1879
+ });
1880
+ child.stderr?.on("data", (chunk) => {
1881
+ process.stderr.write(chunk);
1882
+ });
1883
+ child.on("error", (error) => {
1884
+ resolve2({ ok: false, message: error.message });
1885
+ });
1886
+ child.on("close", (code) => {
1887
+ resolve2(code === 0 ? { ok: true } : { ok: false, message: `${plan.command} exited with code ${code}` });
1888
+ });
1889
+ });
1890
+ }
1891
+ function binNameFromArgv(invokedAs) {
1892
+ return basename(invokedAs ?? "tool") || "tool";
1893
+ }
1894
+ function resolveEntry(invokedAs, realpath) {
1895
+ if (!invokedAs) {
1896
+ return void 0;
1897
+ }
1898
+ try {
1899
+ return realpath(invokedAs);
1900
+ } catch {
1901
+ return invokedAs;
1902
+ }
1903
+ }
1904
+ function resolveInstalledVersion(invokedAs, realpath, fs2) {
1905
+ const installedEntry = resolveEntry(invokedAs, realpath);
1906
+ return installedEntry ? readNearestPackageJson(installedEntry, fs2).version : void 0;
1907
+ }
1908
+ function homebrewUpgradeOutput(options) {
1909
+ const update = {
1910
+ package: options.packageName,
1911
+ previous: options.current,
1912
+ latest: options.latest
1913
+ };
1914
+ if (options.installedVersion) {
1915
+ update.installed = options.installedVersion;
1916
+ update.available = isUpdateAvailable(options.installedVersion, options.latest);
1917
+ } else {
1918
+ update.action = "upgrade-command-ran";
1919
+ update.result = "installed version unknown";
1920
+ }
1921
+ return {
1922
+ update,
1923
+ command: options.command
1924
+ };
1925
+ }
1926
+ function parseUpdateArgs(args, binName) {
1927
+ if (args.length === 0) {
1928
+ return "install";
1929
+ }
1930
+ if (args.length === 1 && (args[0] === "--check" || args[0] === "--dry-run")) {
1931
+ return "check";
1932
+ }
1933
+ const unknown = args.find((arg) => arg !== "--check" && arg !== "--dry-run");
1934
+ throw new AxiError(unknown ? `Unknown update option: ${unknown}` : "Invalid update arguments", "VALIDATION_ERROR", [
1935
+ `Run \`${binName} update --help\``,
1936
+ `Use \`${binName} update --check\` to check without installing`
1937
+ ]);
1938
+ }
1939
+ async function runUpdate(options) {
1940
+ const invokedAs = options.invokedAs ?? process.argv[1];
1941
+ const binName = binNameFromArgv(invokedAs);
1942
+ const mode = parseUpdateArgs(options.args, binName);
1943
+ const platform = options.platform ?? process.platform;
1944
+ const realpath = options.realpath ?? ((path2) => realpathSync(path2));
1945
+ const entry = resolveEntry(invokedAs, realpath);
1946
+ const fs2 = options.fs ?? nodeFs;
1947
+ const fromPackageJson = entry ? readNearestPackageJson(entry, fs2) : {};
1948
+ const packageName = options.packageName ?? fromPackageJson.packageName;
1949
+ const current = options.version ?? fromPackageJson.version;
1950
+ if (!packageName) {
1951
+ throw new AxiError("Could not determine the package name to update", "UPDATE_ERROR", [
1952
+ "Reinstall the tool from npm so its package.json is available",
1953
+ "Tool authors can pass `packageName` to runAxiCli()"
1954
+ ]);
1955
+ }
1956
+ if (!current) {
1957
+ throw new AxiError(`Could not determine the current version of ${packageName}`, "UPDATE_ERROR", [
1958
+ "Reinstall the tool from npm so its version is available",
1959
+ "Tool authors can pass `version` to runAxiCli()"
1960
+ ]);
1961
+ }
1962
+ const fetchLatest = options.fetchLatest ?? ((name) => fetchLatestVersion(name, { platform }));
1963
+ const latest = await fetchLatest(packageName);
1964
+ const available = isUpdateAvailable(current, latest);
1965
+ if (mode === "check") {
1966
+ const output = {
1967
+ update: { package: packageName, current, latest, available }
1968
+ };
1969
+ if (available) {
1970
+ output.help = [`Run \`${binName} update\` to upgrade`];
1971
+ }
1972
+ return output;
1973
+ }
1974
+ if (!available) {
1975
+ return {
1976
+ update: `${packageName} is already on the latest version (${current})`
1977
+ };
1978
+ }
1979
+ const method = entry ? detectInstallMethod({ entry, env: options.env }) : { kind: "unknown" };
1980
+ const plan = planUpgrade(method, packageName);
1981
+ if (!plan.argv) {
1982
+ const help = method.kind === "npx" ? `Re-run with \`${plan.command}\` to use the latest version` : `Run \`${plan.command}\` to upgrade`;
1983
+ return {
1984
+ update: {
1985
+ package: packageName,
1986
+ current,
1987
+ latest,
1988
+ available: true,
1989
+ action: "manual",
1990
+ ...plan.note ? { reason: plan.note } : {},
1991
+ run: plan.command
1992
+ },
1993
+ help: [help]
1994
+ };
1995
+ }
1996
+ const runInstall = options.runInstall ?? defaultRunInstall;
1997
+ const result = await runInstall(plan, options.stdout, { platform });
1998
+ if (!result.ok) {
1999
+ throw new AxiError(`Failed to upgrade ${packageName}`, "UPDATE_ERROR", [
2000
+ `Run \`${plan.command}\` manually`,
2001
+ ...result.message ? [result.message] : []
2002
+ ]);
2003
+ }
2004
+ if (method.kind === "homebrew") {
2005
+ return homebrewUpgradeOutput({
2006
+ packageName,
2007
+ current,
2008
+ latest,
2009
+ installedVersion: resolveInstalledVersion(invokedAs, realpath, fs2),
2010
+ command: plan.command
2011
+ });
2012
+ }
2013
+ return {
2014
+ update: `${packageName} upgraded ${current} -> ${latest}`,
2015
+ command: plan.command
2016
+ };
2017
+ }
2018
+
2019
+ // node_modules/.pnpm/axi-sdk-js@0.1.13/node_modules/axi-sdk-js/dist/cli.js
2020
+ var stdoutWithErrorHandler = /* @__PURE__ */ new WeakSet();
2021
+ function defaultFormatError(error) {
2022
+ if (error instanceof AxiError) {
2023
+ return {
2024
+ output: `${renderError(error.message, error.code, error.suggestions)}
2025
+ `,
2026
+ exitCode: exitCodeForError(error)
2027
+ };
2028
+ }
2029
+ const message = error instanceof Error ? error.message : String(error);
2030
+ return {
2031
+ output: `${renderError(message, "UNKNOWN")}
2032
+ `,
2033
+ exitCode: 1
2034
+ };
2035
+ }
2036
+ function defaultUnknownCommand(command) {
2037
+ return `${renderError(`Unknown command: ${command}`, "VALIDATION_ERROR", [
2038
+ "Run `--help` to see available commands"
2039
+ ])}
2040
+ `;
2041
+ }
2042
+ async function runAxiCli(options) {
2043
+ const stdout = options.stdout ?? process.stdout;
2044
+ handleStdoutErrors(stdout);
2045
+ try {
2046
+ await options.initialize?.();
2047
+ } catch (error) {
2048
+ writeFormattedError(error, stdout, options);
2049
+ return;
2050
+ }
2051
+ const argv = options.argv ?? process.argv.slice(2);
2052
+ if (argv.length === 1 && argv[0] === "--help") {
2053
+ stdout.write(options.topLevelHelp);
2054
+ if (!options.commands.update) {
2055
+ if (options.topLevelHelp.length > 0 && !options.topLevelHelp.endsWith("\n")) {
2056
+ stdout.write("\n");
2057
+ }
2058
+ stdout.write(builtinCommandsHelp());
2059
+ }
2060
+ return;
2061
+ }
2062
+ if (argv.length === 1 && isVersionFlag(argv[0])) {
2063
+ if (!options.version) {
2064
+ stdout.write(`${renderError("Version is not configured for this tool", "VALIDATION_ERROR")}
2065
+ `);
2066
+ process.exitCode = 2;
2067
+ return;
2068
+ }
2069
+ stdout.write(`${options.version}
2070
+ `);
2071
+ return;
2072
+ }
2073
+ const command = argv[0];
2074
+ if (!command) {
2075
+ await runHandler(options.home, [], { command: void 0, args: [] }, stdout, options, true);
2076
+ return;
2077
+ }
2078
+ if (command.startsWith("-")) {
2079
+ stdout.write(renderLeadingFlagError(command));
2080
+ process.exitCode = 2;
2081
+ return;
2082
+ }
2083
+ const args = argv.slice(1);
2084
+ if (command === "update" && !options.commands.update) {
2085
+ await runBuiltinUpdate(args, stdout, options);
2086
+ return;
2087
+ }
2088
+ if (args.includes("--help")) {
2089
+ const help = options.getCommandHelp?.(command);
2090
+ if (help) {
2091
+ stdout.write(help);
2092
+ return;
2093
+ }
2094
+ }
2095
+ const handler2 = options.commands[command];
2096
+ if (!handler2) {
2097
+ stdout.write((options.renderUnknownCommand ?? defaultUnknownCommand)(command));
2098
+ process.exitCode = 2;
2099
+ return;
2100
+ }
2101
+ await runHandler(handler2, args, { command, args }, stdout, options, false);
2102
+ }
2103
+ function handleStdoutErrors(stdout) {
2104
+ const errorObservable = stdout;
2105
+ if (typeof errorObservable.on !== "function" || stdoutWithErrorHandler.has(stdout)) {
2106
+ return;
2107
+ }
2108
+ stdoutWithErrorHandler.add(stdout);
2109
+ errorObservable.on("error", (error) => {
2110
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EPIPE") {
2111
+ process.exitCode = 0;
2112
+ return;
2113
+ }
2114
+ throw error;
2115
+ });
2116
+ }
2117
+ async function runHandler(handler2, args, contextInput, stdout, options, isHomeView) {
2118
+ try {
2119
+ const context = await options.resolveContext?.(contextInput);
2120
+ const output = await handler2(args, context);
2121
+ stdout.write(`${renderCommandOutput(output, options, isHomeView)}
2122
+ `);
2123
+ } catch (error) {
2124
+ writeFormattedError(error, stdout, options);
2125
+ }
2126
+ }
2127
+ async function runBuiltinUpdate(args, stdout, options) {
2128
+ if (args.length === 1 && args[0] === "--help") {
2129
+ stdout.write(builtinUpdateHelp());
2130
+ return;
2131
+ }
2132
+ try {
2133
+ const output = await runUpdate({
2134
+ args,
2135
+ stdout,
2136
+ packageName: options.packageName,
2137
+ version: options.version
2138
+ });
2139
+ stdout.write(`${renderOutput(output)}
2140
+ `);
2141
+ } catch (error) {
2142
+ writeFormattedError(error, stdout, options);
2143
+ }
2144
+ }
2145
+ function writeFormattedError(error, stdout, options) {
2146
+ const formatted = (options.formatError ?? defaultFormatError)(error);
2147
+ stdout.write(formatted.output);
2148
+ process.exitCode = formatted.exitCode;
2149
+ }
2150
+ function resolveBinName() {
2151
+ return basename2(process.argv[1] ?? "tool") || "tool";
2152
+ }
2153
+ function builtinCommandsHelp() {
2154
+ const bin = resolveBinName();
2155
+ return `${renderOutput({
2156
+ "built-in": {
2157
+ update: `Upgrade \`${bin}\` to the latest published version`,
2158
+ "update --check": "Report current vs latest without installing"
2159
+ }
2160
+ })}
2161
+ `;
2162
+ }
2163
+ function builtinUpdateHelp() {
2164
+ const bin = resolveBinName();
2165
+ return `${renderOutput({
2166
+ command: "update",
2167
+ description: `Upgrade \`${bin}\` to the latest published npm version`,
2168
+ flags: {
2169
+ "--check": "Report current vs latest and exit without installing"
2170
+ },
2171
+ examples: [`${bin} update`, `${bin} update --check`]
2172
+ })}
2173
+ `;
2174
+ }
2175
+ function renderLeadingFlagError(flag) {
2176
+ const bin = basename2(process.argv[1] ?? "tool") || "tool";
2177
+ return `${renderError("Flags must come after the command", "VALIDATION_ERROR", [
2178
+ `Run \`${bin} <command> [args] [flags]\``,
2179
+ `Move \`${flag}\` after the command instead of before it`
2180
+ ])}
2181
+ `;
2182
+ }
2183
+ function isVersionFlag(flag) {
2184
+ return flag === "-v" || flag === "-V" || flag === "--version";
2185
+ }
2186
+ function renderCommandOutput(output, options, isHomeView) {
2187
+ if (!isHomeView) {
2188
+ return renderOutput(output);
2189
+ }
2190
+ const header = homeHeaderOutput({ description: options.description });
2191
+ if (typeof output === "string") {
2192
+ return `${renderOutput(header)}
2193
+ ${output}`;
2194
+ }
2195
+ return renderOutput(mergeHomeHeader(header, output));
2196
+ }
2197
+ function mergeHomeHeader(header, output) {
2198
+ const rest = { ...output };
2199
+ delete rest.bin;
2200
+ delete rest.description;
2201
+ return {
2202
+ ...header,
2203
+ ...rest
2204
+ };
2205
+ }
2206
+
2207
+ // node_modules/.pnpm/axi-sdk-js@0.1.13/node_modules/axi-sdk-js/dist/hooks.js
2208
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, rmSync, statSync, writeFileSync } from "node:fs";
2209
+ import { homedir as homedir2 } from "node:os";
2210
+ import { basename as basename3, delimiter, dirname as dirname2, join as join2, resolve } from "node:path";
2211
+ var OPENCODE_PLUGIN_MANAGED_PREFIX = "axi-sdk-js managed opencode plugin:";
2212
+ function isManagedHook(hook, marker) {
2213
+ return typeof hook?.command === "string" && hook.command.includes(marker);
2214
+ }
2215
+ function computeSessionStartHookUpdate(settings, spec) {
2216
+ const updated = structuredClone(settings);
2217
+ let changed = false;
2218
+ if (!updated.hooks) {
2219
+ updated.hooks = {};
2220
+ changed = true;
2221
+ }
2222
+ if (Array.isArray(updated.hooks.session_start)) {
2223
+ const legacyHooks = updated.hooks.session_start.filter((hook) => !isManagedHook(hook, spec.marker));
2224
+ if (legacyHooks.length !== updated.hooks.session_start.length) {
2225
+ changed = true;
2226
+ if (legacyHooks.length === 0) {
2227
+ delete updated.hooks.session_start;
2228
+ } else {
2229
+ updated.hooks.session_start = legacyHooks;
2230
+ }
2231
+ }
2232
+ }
2233
+ if (!Array.isArray(updated.hooks.SessionStart)) {
2234
+ updated.hooks.SessionStart = [];
2235
+ changed = true;
2236
+ }
2237
+ for (const group of updated.hooks.SessionStart) {
2238
+ if (!Array.isArray(group.hooks)) {
2239
+ continue;
2240
+ }
2241
+ for (const hook of group.hooks) {
2242
+ if (!isManagedHook(hook, spec.marker)) {
2243
+ continue;
2244
+ }
2245
+ const timeout = spec.timeoutSeconds ?? 10;
2246
+ const isCorrect = hook.command === spec.command && hook.type === "command" && hook.timeout === timeout;
2247
+ if (isCorrect && !changed) {
2248
+ return [settings, false];
2249
+ }
2250
+ hook.command = spec.command;
2251
+ hook.type = "command";
2252
+ hook.timeout = timeout;
2253
+ return [updated, true];
2254
+ }
2255
+ }
2256
+ updated.hooks.SessionStart.push({
2257
+ matcher: "",
2258
+ hooks: [
2259
+ {
2260
+ type: "command",
2261
+ command: spec.command,
2262
+ timeout: spec.timeoutSeconds ?? 10
2263
+ }
2264
+ ]
2265
+ });
2266
+ return [updated, true];
2267
+ }
2268
+ function computeSessionStartHookRemoval(settings, marker) {
2269
+ if (!settings.hooks) {
2270
+ return [settings, false];
2271
+ }
2272
+ const updated = structuredClone(settings);
2273
+ const hooks = updated.hooks;
2274
+ if (!hooks) {
2275
+ return [settings, false];
2276
+ }
2277
+ let changed = false;
2278
+ if (Array.isArray(hooks.session_start)) {
2279
+ const remaining = hooks.session_start.filter((hook) => !isManagedHook(hook, marker));
2280
+ if (remaining.length !== hooks.session_start.length) {
2281
+ changed = true;
2282
+ if (remaining.length === 0) {
2283
+ delete hooks.session_start;
2284
+ } else {
2285
+ hooks.session_start = remaining;
2286
+ }
2287
+ }
2288
+ }
2289
+ if (Array.isArray(hooks.SessionStart)) {
2290
+ const remainingGroups = [];
2291
+ let sessionStartChanged = false;
2292
+ for (const group of hooks.SessionStart) {
2293
+ if (!Array.isArray(group.hooks)) {
2294
+ remainingGroups.push(group);
2295
+ continue;
2296
+ }
2297
+ const remainingHooks = group.hooks.filter((hook) => !isManagedHook(hook, marker));
2298
+ if (remainingHooks.length === group.hooks.length) {
2299
+ remainingGroups.push(group);
2300
+ continue;
2301
+ }
2302
+ sessionStartChanged = true;
2303
+ if (remainingHooks.length > 0) {
2304
+ remainingGroups.push({ ...group, hooks: remainingHooks });
2305
+ }
2306
+ }
2307
+ if (sessionStartChanged) {
2308
+ changed = true;
2309
+ if (remainingGroups.length > 0) {
2310
+ hooks.SessionStart = remainingGroups;
2311
+ } else {
2312
+ delete hooks.SessionStart;
2313
+ }
2314
+ }
2315
+ }
2316
+ if (Object.keys(hooks).length === 0) {
2317
+ delete updated.hooks;
2318
+ }
2319
+ return changed ? [updated, true] : [settings, false];
2320
+ }
2321
+ function computeCodexConfigUpdate(content) {
2322
+ const newline = content.includes("\r\n") ? "\r\n" : "\n";
2323
+ const normalized = content.length === 0 ? "" : content;
2324
+ if (normalized.trim().length === 0) {
2325
+ return [`[features]${newline}hooks = true${newline}`, true];
2326
+ }
2327
+ const lines = normalized.split(/\r?\n/);
2328
+ const updated = [...lines];
2329
+ let inFeatures = false;
2330
+ let sawFeatures = false;
2331
+ for (let index = 0; index < updated.length; index++) {
2332
+ const line = updated[index];
2333
+ const section = line.match(/^\s*(\[{1,2})([^\]]+)(\]{1,2})\s*(?:#.*)?$/);
2334
+ if (section) {
2335
+ const isTableHeader = section[1] === "[" && section[3] === "]" || section[1] === "[[" && section[3] === "]]";
2336
+ if (!isTableHeader) {
2337
+ continue;
2338
+ }
2339
+ const sectionName = section[2].trim();
2340
+ if (inFeatures) {
2341
+ updated.splice(index, 0, "hooks = true");
2342
+ return [updated.join(newline), true];
2343
+ }
2344
+ inFeatures = sectionName === "features";
2345
+ sawFeatures ||= inFeatures;
2346
+ continue;
2347
+ }
2348
+ if (!inFeatures) {
2349
+ continue;
2350
+ }
2351
+ const flag = line.match(/^\s*hooks\s*=\s*(true|false)\s*(?:#.*)?$/);
2352
+ if (!flag) {
2353
+ continue;
2354
+ }
2355
+ if (flag[1] === "true") {
2356
+ return [content, false];
2357
+ }
2358
+ updated[index] = line.replace(/false/, "true");
2359
+ return [updated.join(newline), true];
2360
+ }
2361
+ if (sawFeatures) {
2362
+ const suffix = normalized.endsWith(newline) ? "" : newline;
2363
+ return [`${normalized}${suffix}hooks = true${newline}`, true];
2364
+ }
2365
+ const separator = normalized.endsWith(newline) ? newline : `${newline}${newline}`;
2366
+ return [
2367
+ `${normalized}${separator}[features]${newline}hooks = true${newline}`,
2368
+ true
2369
+ ];
2370
+ }
2371
+ function openCodePluginId(marker) {
2372
+ return `axi-${marker.replace(/[^A-Za-z0-9._-]+/g, "_")}`;
2373
+ }
2374
+ function buildOpenCodeAmbientPluginSource(marker, command, timeoutSeconds) {
2375
+ const managedMarker = `${OPENCODE_PLUGIN_MANAGED_PREFIX} ${marker}`;
2376
+ return `// ${managedMarker}
2377
+ // This file is generated by axi-sdk-js. It is safe to edit only if you remove the managed marker above.
2378
+ import { spawn } from "node:child_process";
2379
+
2380
+ const command = ${JSON.stringify(command)};
2381
+ const marker = ${JSON.stringify(marker)};
2382
+ const ambientHeader = ${JSON.stringify(`## AXI ambient context: ${marker}`)};
2383
+ const timeoutMs = ${JSON.stringify(timeoutSeconds * 1e3)};
2384
+
2385
+ function runAxiHomeView(cwd) {
2386
+ return new Promise((resolve) => {
2387
+ const child = spawn(command, [], {
2388
+ cwd: directoryOrFallback(cwd),
2389
+ env: process.env,
2390
+ shell: false,
2391
+ stdio: ["ignore", "pipe", "pipe"],
2392
+ });
2393
+
2394
+ let stdout = "";
2395
+ let stderr = "";
2396
+ let settled = false;
2397
+
2398
+ const timer = setTimeout(() => {
2399
+ if (settled) return;
2400
+ settled = true;
2401
+ child.kill("SIGTERM");
2402
+ resolve("error: " + marker + " ambient context timed out after " + timeoutMs + "ms");
2403
+ }, timeoutMs);
2404
+
2405
+ child.stdout?.setEncoding("utf-8");
2406
+ child.stderr?.setEncoding("utf-8");
2407
+ child.stdout?.on("data", (chunk) => {
2408
+ stdout += chunk;
2409
+ });
2410
+ child.stderr?.on("data", (chunk) => {
2411
+ stderr += chunk;
2412
+ });
2413
+ child.on("error", (error) => {
2414
+ if (settled) return;
2415
+ settled = true;
2416
+ clearTimeout(timer);
2417
+ resolve("error: " + marker + " ambient context failed: " + error.message);
2418
+ });
2419
+ child.on("close", (code) => {
2420
+ if (settled) return;
2421
+ settled = true;
2422
+ clearTimeout(timer);
2423
+ if (code === 0) {
2424
+ resolve(stdout.trim());
2425
+ return;
2426
+ }
2427
+ const message = (stderr || stdout || marker + " exited with code " + code).trim();
2428
+ resolve("error: " + marker + " ambient context failed: " + message);
2429
+ });
2430
+ });
2431
+ }
2432
+
2433
+ function directoryOrFallback(directory) {
2434
+ return typeof directory === "string" && directory.length > 0
2435
+ ? directory
2436
+ : process.cwd();
2437
+ }
2438
+
2439
+ // Returns the session's ambient context text, running the AXI home view once per session.
2440
+ function ambientContextFor(directory) {
2441
+ const sessionCache = new Map();
2442
+
2443
+ return async (sessionID) => {
2444
+ const key = sessionID ?? "__global__";
2445
+ let homeView = sessionCache.get(key);
2446
+ if (homeView === undefined) {
2447
+ homeView = await runAxiHomeView(directory);
2448
+ sessionCache.set(key, homeView);
2449
+ }
2450
+ return homeView.length === 0 ? "" : ambientHeader + "\\n" + homeView;
2451
+ };
2452
+ }
2453
+
2454
+ export default {
2455
+ id: ${JSON.stringify(openCodePluginId(marker))},
2456
+ // OpenCode 2 entrypoint.
2457
+ async setup(ctx) {
2458
+ const ambientContext = ambientContextFor(ctx.location.directory);
2459
+ await ctx.session.hook("context", async (event) => {
2460
+ const text = await ambientContext(event.sessionID);
2461
+ if (text) event.system.push({ type: "text", text });
2462
+ });
2463
+ },
2464
+ // OpenCode 1 entrypoint.
2465
+ async server({ directory }) {
2466
+ const ambientContext = ambientContextFor(directory);
2467
+ return {
2468
+ "experimental.chat.system.transform": async (input, output) => {
2469
+ const text = await ambientContext(input.sessionID);
2470
+ if (text) output.system.push(text);
2471
+ },
2472
+ };
2473
+ },
2474
+ };
2475
+ `;
2476
+ }
2477
+ function openCodePluginFileName(marker) {
2478
+ return `${openCodePluginId(marker)}.js`;
2479
+ }
2480
+ function openCodePluginDir(scope, home2, root) {
2481
+ return scope === "project" ? join2(root, ".opencode", "plugins") : join2(home2, ".config", "opencode", "plugins");
2482
+ }
2483
+ function resolveHookScopeTargets(marker, options) {
2484
+ const home2 = options.homeDir ?? homedir2();
2485
+ const scope = options.scope ?? "user";
2486
+ const root = scope === "project" ? resolve(options.projectDir ?? process.cwd()) : home2;
2487
+ return {
2488
+ scope,
2489
+ home: home2,
2490
+ root,
2491
+ claudeSettingsPath: join2(root, ".claude", "settings.json"),
2492
+ codexHooksPath: join2(root, ".codex", "hooks.json"),
2493
+ codexConfigPath: join2(home2, ".codex", "config.toml"),
2494
+ openCodePluginPath: join2(openCodePluginDir(scope, home2, root), openCodePluginFileName(marker))
2495
+ };
2496
+ }
2497
+ function installOpenCodeAmbientPlugin(pluginPath, marker, command, timeoutSeconds, onError) {
2498
+ const managedMarker = `${OPENCODE_PLUGIN_MANAGED_PREFIX} ${marker}`;
2499
+ const next = buildOpenCodeAmbientPluginSource(marker, command, timeoutSeconds);
2500
+ try {
2501
+ mkdirSync(dirname2(pluginPath), { recursive: true });
2502
+ const current = existsSync2(pluginPath) ? readFileSync2(pluginPath, "utf-8") : void 0;
2503
+ if (current !== void 0 && !current.includes(managedMarker)) {
2504
+ onError?.(`${pluginPath}: refusing to overwrite unmanaged OpenCode plugin`);
2505
+ return;
2506
+ }
2507
+ if (current !== next) {
2508
+ writeFileSync(pluginPath, next, "utf-8");
2509
+ }
2510
+ } catch (error) {
2511
+ const message = error instanceof Error ? error.message : String(error);
2512
+ onError?.(`${pluginPath}: ${message}`);
2513
+ }
2514
+ }
2515
+ function resolvePortableHookCommand(execPath, binaryNames, marker, context) {
2516
+ if (binaryNames.length === 0) {
2517
+ return execPath;
2518
+ }
2519
+ const resolvedExec = context.resolveRealPath(execPath);
2520
+ if (!resolvedExec) {
2521
+ return execPath;
2522
+ }
2523
+ for (const name of binaryNames) {
2524
+ if (!name.includes(marker)) {
2525
+ continue;
2526
+ }
2527
+ for (const dir of context.pathEntries) {
2528
+ if (!dir)
2529
+ continue;
2530
+ for (const ext of context.pathExtensions) {
2531
+ const candidate = join2(dir, `${name}${ext}`);
2532
+ const resolvedCandidate = context.resolveRealPath(candidate);
2533
+ if (resolvedCandidate && resolvedCandidate === resolvedExec) {
2534
+ return name;
2535
+ }
2536
+ const shimTarget = context.resolveShimTarget?.(candidate);
2537
+ if (shimTarget && shimTarget === resolvedExec) {
2538
+ return name;
2539
+ }
2540
+ }
2541
+ }
2542
+ }
2543
+ return execPath;
2544
+ }
2545
+ var NPM_SHIM_SCRIPT_PATTERNS = [
2546
+ // Git Bash / POSIX shim: exec node "$basedir/node_modules/<pkg>/.../cli.js"
2547
+ /"\$basedir\/([^"]+\.[cm]?js)"/,
2548
+ // Windows .cmd shim: "%dp0%\node_modules\<pkg>\...\cli.js"
2549
+ /%~?dp0%?[\\/]([^"\r\n]+\.[cm]?js)/i
2550
+ ];
2551
+ function extractNpmShimScriptPath(content) {
2552
+ for (const pattern of NPM_SHIM_SCRIPT_PATTERNS) {
2553
+ const match = content.match(pattern);
2554
+ if (match?.[1]) {
2555
+ return match[1];
2556
+ }
2557
+ }
2558
+ return void 0;
2559
+ }
2560
+ function buildDefaultPortableCommandContext() {
2561
+ const rawPath = process.env.PATH ?? process.env.Path ?? "";
2562
+ const pathEntries = rawPath.split(delimiter).filter(Boolean);
2563
+ const pathExtensions = process.platform === "win32" ? (
2564
+ // Git Bash resolves the extensionless shim, which PATHEXT omits.
2565
+ ["", ...(process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";")]
2566
+ ) : [""];
2567
+ return {
2568
+ pathEntries,
2569
+ pathExtensions,
2570
+ resolveRealPath: (absolutePath) => {
2571
+ try {
2572
+ const stat = statSync(absolutePath);
2573
+ if (!stat.isFile()) {
2574
+ return void 0;
2575
+ }
2576
+ return realpathSync2(absolutePath);
2577
+ } catch {
2578
+ return void 0;
2579
+ }
2580
+ },
2581
+ resolveShimTarget: (shimPath) => {
2582
+ try {
2583
+ const relative = extractNpmShimScriptPath(readFileSync2(shimPath, "utf-8"));
2584
+ if (!relative) {
2585
+ return void 0;
2586
+ }
2587
+ return realpathSync2(resolve(dirname2(shimPath), relative));
2588
+ } catch {
2589
+ return void 0;
2590
+ }
2591
+ }
2592
+ };
2593
+ }
2594
+ function shouldInstallHooksForNodeAxiExecPath(execPath, policy) {
2595
+ const normalized = resolve(execPath).replaceAll("\\", "/");
2596
+ if (!normalized.includes(policy.marker) || normalized.endsWith(".ts")) {
2597
+ return false;
2598
+ }
2599
+ const fileName = basename3(normalized);
2600
+ if (policy.binaryNames?.includes(fileName)) {
2601
+ return true;
2602
+ }
2603
+ return policy.distEntrypoints?.some((entrypoint) => normalized.endsWith(entrypoint.replaceAll("\\", "/"))) ?? false;
2604
+ }
2605
+ function inferHookOptions(execPath) {
2606
+ if (!execPath) {
2607
+ return void 0;
2608
+ }
2609
+ const normalized = execPath.replaceAll("\\", "/");
2610
+ const match = normalized.match(/(?:^|\/)dist\/bin\/([^/]+)\.js$/);
2611
+ if (match?.[1]) {
2612
+ const marker = match[1];
2613
+ return {
2614
+ execPath,
2615
+ marker,
2616
+ binaryNames: [marker],
2617
+ distEntrypoints: [`dist/bin/${marker}.js`]
2618
+ };
2619
+ }
2620
+ const fileName = normalized.split("/").pop() ?? "";
2621
+ if (!fileName || fileName.includes(".") || fileName === "node") {
2622
+ return void 0;
2623
+ }
2624
+ return {
2625
+ execPath,
2626
+ marker: fileName,
2627
+ binaryNames: [fileName],
2628
+ distEntrypoints: [`dist/bin/${fileName}.js`]
2629
+ };
2630
+ }
2631
+ function buildInferredHookInstallPolicy(marker, options, inferred) {
2632
+ const binaryNames = options.binaryNames ?? inferred.binaryNames;
2633
+ const distEntrypoints = options.distEntrypoints ?? inferred.distEntrypoints;
2634
+ return (execPath) => shouldInstallHooksForNodeAxiExecPath(execPath, {
2635
+ marker,
2636
+ binaryNames,
2637
+ distEntrypoints
2638
+ });
2639
+ }
2640
+ function installSessionStartHooks(options = {}) {
2641
+ const inferred = inferHookOptions(options.execPath ?? process.argv[1]);
2642
+ const marker = options.marker ?? inferred?.marker;
2643
+ if (!marker) {
2644
+ return;
2645
+ }
2646
+ const execPath = resolve(options.execPath ?? inferred?.execPath ?? process.argv[1] ?? "");
2647
+ if (!execPath) {
2648
+ return;
2649
+ }
2650
+ const defaultPolicyOptions = inferred ?? {
2651
+ execPath,
2652
+ marker,
2653
+ binaryNames: [marker],
2654
+ distEntrypoints: [`dist/bin/${marker}.js`]
2655
+ };
2656
+ const shouldInstall = options.shouldInstall ?? buildInferredHookInstallPolicy(marker, options, defaultPolicyOptions);
2657
+ if (shouldInstall && !shouldInstall(execPath)) {
2658
+ return;
2659
+ }
2660
+ const binaryNames = options.binaryNames ?? inferred?.binaryNames ?? [];
2661
+ const command = resolvePortableHookCommand(execPath, binaryNames, marker, buildDefaultPortableCommandContext());
2662
+ const targets = resolveHookScopeTargets(marker, options);
2663
+ const jsonTargets = [targets.claudeSettingsPath, targets.codexHooksPath];
2664
+ const codexConfigPath = targets.codexConfigPath;
2665
+ installOpenCodeAmbientPlugin(targets.openCodePluginPath, marker, command, options.timeoutSeconds ?? 10, options.onError);
2666
+ for (const target of jsonTargets) {
2667
+ try {
2668
+ mkdirSync(dirname2(target), { recursive: true });
2669
+ const current = existsSync2(target) ? JSON.parse(readFileSync2(target, "utf-8")) : {};
2670
+ const [updated, changed] = computeSessionStartHookUpdate(current, {
2671
+ marker,
2672
+ command,
2673
+ timeoutSeconds: options.timeoutSeconds
2674
+ });
2675
+ if (changed) {
2676
+ writeFileSync(target, `${JSON.stringify(updated, null, 2)}
2677
+ `, "utf-8");
2678
+ }
2679
+ } catch (error) {
2680
+ const message = error instanceof Error ? error.message : String(error);
2681
+ options.onError?.(`${target}: ${message}`);
2682
+ }
2683
+ }
2684
+ try {
2685
+ mkdirSync(dirname2(codexConfigPath), { recursive: true });
2686
+ const current = existsSync2(codexConfigPath) ? readFileSync2(codexConfigPath, "utf-8") : "";
2687
+ const [updated, changed] = computeCodexConfigUpdate(current);
2688
+ if (changed) {
2689
+ writeFileSync(codexConfigPath, updated, "utf-8");
2690
+ }
2691
+ } catch (error) {
2692
+ const message = error instanceof Error ? error.message : String(error);
2693
+ options.onError?.(`${codexConfigPath}: ${message}`);
2694
+ }
2695
+ }
2696
+ function resolveStatusMarker(options, callerName) {
2697
+ const inferred = inferHookOptions(options.execPath ?? process.argv[1]);
2698
+ const marker = options.marker ?? inferred?.marker;
2699
+ if (!marker) {
2700
+ throw new Error(`${callerName}: unable to infer a hook marker from the current process; pass { marker } explicitly`);
2701
+ }
2702
+ return marker;
2703
+ }
2704
+ function hasManagedJsonHookEntry(path2, marker) {
2705
+ if (!existsSync2(path2)) {
2706
+ return false;
2707
+ }
2708
+ try {
2709
+ const settings = JSON.parse(readFileSync2(path2, "utf-8"));
2710
+ const groups = settings.hooks?.SessionStart ?? [];
2711
+ const inGroups = groups.some((group) => (group.hooks ?? []).some((hook) => isManagedHook(hook, marker)));
2712
+ const legacy = settings.hooks?.session_start ?? [];
2713
+ return inGroups || legacy.some((hook) => isManagedHook(hook, marker));
2714
+ } catch {
2715
+ return false;
2716
+ }
2717
+ }
2718
+ function hasManagedOpenCodePlugin(path2, marker) {
2719
+ if (!existsSync2(path2)) {
2720
+ return false;
2721
+ }
2722
+ try {
2723
+ return readFileSync2(path2, "utf-8").includes(`${OPENCODE_PLUGIN_MANAGED_PREFIX} ${marker}`);
2724
+ } catch {
2725
+ return false;
2726
+ }
2727
+ }
2728
+ function isCodexHooksFeatureEnabled(path2) {
2729
+ if (!existsSync2(path2)) {
2730
+ return false;
2731
+ }
2732
+ try {
2733
+ const [, changed] = computeCodexConfigUpdate(readFileSync2(path2, "utf-8"));
2734
+ return !changed;
2735
+ } catch {
2736
+ return false;
2737
+ }
2738
+ }
2739
+ function sessionStartHookStatus(options = {}) {
2740
+ const marker = resolveStatusMarker(options, "sessionStartHookStatus");
2741
+ const targets = resolveHookScopeTargets(marker, options);
2742
+ return {
2743
+ marker,
2744
+ scope: targets.scope,
2745
+ claude: {
2746
+ installed: hasManagedJsonHookEntry(targets.claudeSettingsPath, marker),
2747
+ path: targets.claudeSettingsPath
2748
+ },
2749
+ codex: {
2750
+ installed: hasManagedJsonHookEntry(targets.codexHooksPath, marker),
2751
+ path: targets.codexHooksPath,
2752
+ userFeatureEnabled: isCodexHooksFeatureEnabled(targets.codexConfigPath),
2753
+ userFeaturePath: targets.codexConfigPath
2754
+ },
2755
+ opencode: {
2756
+ installed: hasManagedOpenCodePlugin(targets.openCodePluginPath, marker),
2757
+ path: targets.openCodePluginPath
2758
+ }
2759
+ };
2760
+ }
2761
+ function uninstallSessionStartHooks(options = {}) {
2762
+ const inferred = inferHookOptions(options.execPath ?? process.argv[1]);
2763
+ const marker = options.marker ?? inferred?.marker;
2764
+ if (!marker) {
2765
+ return;
2766
+ }
2767
+ const targets = resolveHookScopeTargets(marker, options);
2768
+ for (const target of [targets.claudeSettingsPath, targets.codexHooksPath]) {
2769
+ try {
2770
+ if (!existsSync2(target)) {
2771
+ continue;
2772
+ }
2773
+ const current = JSON.parse(readFileSync2(target, "utf-8"));
2774
+ const [updated, changed] = computeSessionStartHookRemoval(current, marker);
2775
+ if (changed) {
2776
+ writeFileSync(target, `${JSON.stringify(updated, null, 2)}
2777
+ `, "utf-8");
2778
+ }
2779
+ } catch (error) {
2780
+ const message = error instanceof Error ? error.message : String(error);
2781
+ options.onError?.(`${target}: ${message}`);
2782
+ }
2783
+ }
2784
+ const pluginPath = targets.openCodePluginPath;
2785
+ try {
2786
+ if (existsSync2(pluginPath)) {
2787
+ const managedMarker = `${OPENCODE_PLUGIN_MANAGED_PREFIX} ${marker}`;
2788
+ if (readFileSync2(pluginPath, "utf-8").includes(managedMarker)) {
2789
+ rmSync(pluginPath, { force: true });
2790
+ } else {
2791
+ options.onError?.(`${pluginPath}: refusing to remove unmanaged OpenCode plugin`);
2792
+ }
2793
+ }
2794
+ } catch (error) {
2795
+ const message = error instanceof Error ? error.message : String(error);
2796
+ options.onError?.(`${pluginPath}: ${message}`);
2797
+ }
2798
+ }
2799
+
2800
+ // src/cli.mjs
2801
+ var import_launch_editor = __toESM(require_launch_editor(), 1);
2802
+
2803
+ // package.json
2804
+ var version = "0.1.0";
2805
+
2806
+ // src/version.mjs
2807
+ var VERSION = version;
2808
+
2809
+ // src/cli.mjs
2810
+ var DIR = path.dirname(fileURLToPath(import.meta.url));
2811
+ var SCRIPT = path.join(DIR, "punchlist-axi.mjs");
2812
+ var STATE_DIR = path.join(os.tmpdir(), "punchlist");
2813
+ var PREFIX = "/__pe";
2814
+ var COOKIE = "__pe_auth";
2815
+ var SERVE_FLAGS = { target: "v", port: "v", host: "v", "no-auth": "b", token: "v" };
2816
+ var FLAGS = {
2817
+ start: SERVE_FLAGS,
2818
+ serve: SERVE_FLAGS,
2819
+ wait: { port: "v", timeout: "v", json: "b" },
2820
+ show: { port: "v", full: "b" },
2821
+ done: { port: "v", failed: "b", open: "v" },
2822
+ status: { port: "v" },
2823
+ stop: { port: "v" },
2824
+ setup: { project: "b", remove: "b" }
2825
+ };
2826
+ function usageError(msg, cmd, extra = []) {
2827
+ const flags = Object.keys(FLAGS[cmd]).map((f) => `--${f}`).join(", ");
2828
+ return new AxiError(msg, "VALIDATION_ERROR", [...extra, `Valid flags for \`${cmd}\`: ${flags} (--help always allowed)`]);
2829
+ }
2830
+ function parseArgs(cmd, argv) {
2831
+ const spec = FLAGS[cmd], args = { _: [] };
2832
+ for (let i = 0; i < argv.length; i++) {
2833
+ const a = argv[i];
2834
+ if (!a.startsWith("--")) {
2835
+ args._.push(a);
2836
+ continue;
2837
+ }
2838
+ const eq = a.indexOf("=");
2839
+ const k = eq > -1 ? a.slice(2, eq) : a.slice(2);
2840
+ let v = eq > -1 ? a.slice(eq + 1) : void 0;
2841
+ if (!spec[k]) throw usageError(`unknown flag --${k} for \`${cmd}\``, cmd);
2842
+ if (spec[k] === "b") {
2843
+ if (v !== void 0) throw usageError(`--${k} takes no value`, cmd);
2844
+ args[k] = true;
2845
+ continue;
2846
+ }
2847
+ if (v === void 0) {
2848
+ v = argv[++i];
2849
+ if (v === void 0 || v.startsWith("--")) throw usageError(`--${k} needs a value`, cmd);
2850
+ }
2851
+ args[k] = v;
2852
+ }
2853
+ return args;
2854
+ }
2855
+ function normalizeTarget(t) {
2856
+ if (!t) throw usageError("--target is required (dev server port or URL)", "start", [`Run \`${PE} start --target 5173\` or \`--target http://localhost:3000\``]);
2857
+ t = String(t);
2858
+ if (/^\d+$/.test(t)) return `http://localhost:${t}`;
2859
+ if (!/^https?:\/\//.test(t)) return `http://${t}`;
2860
+ return t.replace(/\/+$/, "");
2861
+ }
2862
+ function statePath(port) {
2863
+ return path.join(STATE_DIR, `${port}.json`);
2864
+ }
2865
+ function loadState(args) {
2866
+ if (args.port) {
2867
+ const p = statePath(args.port);
2868
+ if (!fs.existsSync(p)) throw notRunning(`no proxy running on port ${args.port}`, args.port);
2869
+ return JSON.parse(fs.readFileSync(p, "utf8"));
2870
+ }
2871
+ const files = fs.existsSync(STATE_DIR) ? fs.readdirSync(STATE_DIR).filter((f) => f.endsWith(".json")) : [];
2872
+ if (!files.length) throw notRunning("no proxy running");
2873
+ files.sort((a, b) => fs.statSync(path.join(STATE_DIR, b)).mtimeMs - fs.statSync(path.join(STATE_DIR, a)).mtimeMs);
2874
+ return JSON.parse(fs.readFileSync(path.join(STATE_DIR, files[0]), "utf8"));
2875
+ }
2876
+ function notRunning(msg, port) {
2877
+ return new AxiError(msg, "NOT_RUNNING", [`Run \`${PE} start --target <port|url>${port ? ` --port ${port}` : ""}\``]);
2878
+ }
2879
+ async function api(st, p, opts = {}) {
2880
+ try {
2881
+ return await fetch(`${apiBase(st)}${p}`, { ...opts, headers: { "x-pe-token": st.token, ...opts.headers } });
2882
+ } catch {
2883
+ throw new AxiError(`proxy on port ${st.port} is not responding`, "NOT_RESPONDING", [`Run \`${PE} start --target ${st.target} --port ${st.port}\` to restart it`]);
2884
+ }
2885
+ }
2886
+ function apiBase(st) {
2887
+ const h = ["0.0.0.0", "::", ""].includes(st.host) ? "127.0.0.1" : st.host;
2888
+ return `http://${h.includes(":") ? `[${h}]` : h}:${st.port}${PREFIX}`;
2889
+ }
2890
+ function readBody(req, limit = 2e6) {
2891
+ return new Promise((resolve2, reject) => {
2892
+ let size = 0;
2893
+ const chunks = [];
2894
+ req.on("data", (c) => {
2895
+ size += c.length;
2896
+ if (size > limit) {
2897
+ reject(new Error("body too large"));
2898
+ req.destroy();
2899
+ } else chunks.push(c);
2900
+ });
2901
+ req.on("end", () => resolve2(Buffer.concat(chunks).toString("utf8")));
2902
+ req.on("error", reject);
2903
+ });
2904
+ }
2905
+ function json(res, status, obj) {
2906
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
2907
+ res.end(JSON.stringify(obj));
2908
+ }
2909
+ function getCookie(header, name) {
2910
+ for (const part of (header || "").split(";")) {
2911
+ const [k, ...v] = part.trim().split("=");
2912
+ if (k === name) return v.join("=");
2913
+ }
2914
+ return null;
2915
+ }
2916
+ function stripCookie(header, name) {
2917
+ if (!header) return header;
2918
+ const kept = header.split(";").map((s) => s.trim()).filter((s) => s && !s.startsWith(name + "="));
2919
+ return kept.length ? kept.join("; ") : void 0;
2920
+ }
2921
+ function tailscaleName() {
2922
+ try {
2923
+ const out = execFileSync("tailscale", ["status", "--json"], { stdio: ["ignore", "pipe", "ignore"], timeout: 3e3 });
2924
+ return JSON.parse(out).Self?.DNSName?.replace(/\.$/, "") || null;
2925
+ } catch {
2926
+ return null;
2927
+ }
2928
+ }
2929
+ function alive(pid) {
2930
+ try {
2931
+ process.kill(pid, 0);
2932
+ return true;
2933
+ } catch {
2934
+ return false;
2935
+ }
2936
+ }
2937
+ function printInfo(st) {
2938
+ const authPath = st.auth === false ? "/" : `${PREFIX}/auth?token=${st.token}`;
2939
+ const ts = tailscaleName();
2940
+ console.log(`punchlist: proxying ${st.target}`);
2941
+ console.log(` Local: http://${st.host === "0.0.0.0" ? "127.0.0.1" : st.host}:${st.port}${authPath}`);
2942
+ if (ts) {
2943
+ console.log(` Tailscale: run \`tailscale serve --bg ${st.port}\`, then open`);
2944
+ console.log(` https://${ts}${authPath}`);
2945
+ }
2946
+ console.log(` Agent: node ${SCRIPT} wait --port ${st.port}`);
2947
+ }
2948
+ function links(st) {
2949
+ const authPath = st.auth === false ? "/" : `${PREFIX}/auth?token=${st.token}`;
2950
+ const ts = tailscaleName();
2951
+ return { local: `http://${st.host === "0.0.0.0" ? "127.0.0.1" : st.host}:${st.port}${authPath}`, ...ts ? { tailscale: `https://${ts}${authPath}` } : {} };
2952
+ }
2953
+ function startOutput(st, state) {
2954
+ const l = links(st);
2955
+ return {
2956
+ proxy: { target: st.target, port: st.port, pid: st.pid, state },
2957
+ links: l,
2958
+ help: [
2959
+ "Paste the full local link into your reply text - the user does not see command output, and the link token sets the access cookie",
2960
+ "Tell the user: press \u25CE (Alt+Shift+E), tap an element or drag a box, write a note, repeat, then press Send. With \u25CE off, selecting text shows an Annotate button. \u23F8 (Alt+Shift+P) pauses animations, \u{1F5D2} lists notes, and notes survive reloads until sent. \u2197 Open in the note panel opens the source file in their editor; when no file is known, \u{1F50E} Locate asks you to find it",
2961
+ ...l.tailscale ? [`For phone access the user runs \`tailscale serve --bg ${st.port}\` and opens the tailscale link (never \`tailscale funnel\`)`] : [],
2962
+ `Then run \`${PE} wait --port ${st.port}\` to receive the notes - in the background if your harness notifies you when a background command ends (Claude Code: run_in_background), so your reply with the link reaches the user first. Never end your turn without a wait running`
2963
+ ]
2964
+ };
2965
+ }
2966
+ async function cmdStart(args) {
2967
+ const target = new URL(normalizeTarget(args.target ?? args._[0])).origin;
2968
+ const port = Number(args.port ?? 4e3);
2969
+ const p = statePath(port);
2970
+ const old = fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, "utf8")) : null;
2971
+ if (old && alive(old.pid)) {
2972
+ if (old.target !== target) throw new AxiError(`port ${port} already proxies ${old.target}`, "PORT_BUSY", [`Run \`${PE} stop --port ${port}\` first, or pick another --port`]);
2973
+ return startOutput(old, "already running");
2974
+ }
2975
+ fs.mkdirSync(STATE_DIR, { recursive: true });
2976
+ fs.rmSync(p, { force: true });
2977
+ const logFile = path.join(STATE_DIR, `${port}.log`);
2978
+ const fd = fs.openSync(logFile, "w");
2979
+ const child = spawn2(process.execPath, [SCRIPT, "serve", ...process.argv.slice(3)], { detached: true, stdio: ["ignore", fd, fd] });
2980
+ child.unref();
2981
+ fs.closeSync(fd);
2982
+ let exited = false;
2983
+ child.on("exit", () => {
2984
+ exited = true;
2985
+ });
2986
+ for (let i = 0; i < 100 && !exited; i++) {
2987
+ await new Promise((r) => setTimeout(r, 100));
2988
+ const st = fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, "utf8")) : null;
2989
+ if (st?.pid === child.pid) return startOutput(st, "started");
2990
+ }
2991
+ if (!exited) child.kill();
2992
+ const log = fs.readFileSync(logFile, "utf8").trim().slice(-1e3);
2993
+ throw new AxiError(`proxy did not start: ${log || "no output"}`, "START_FAILED", [`Full log: ${logFile}`]);
2994
+ }
2995
+ function cmdServe(args) {
2996
+ const target = new URL(normalizeTarget(args.target ?? args._[0]));
2997
+ const port = Number(args.port ?? 4e3);
2998
+ const host = args.host ?? "127.0.0.1";
2999
+ const noAuth = args["no-auth"] === true;
3000
+ const token = String(args.token ?? crypto.randomBytes(12).toString("base64url"));
3001
+ const targetPort = target.port || (target.protocol === "https:" ? 443 : 80);
3002
+ const lib = target.protocol === "https:" ? https : http;
3003
+ const selfOrigins = [target.origin];
3004
+ if (["localhost", "127.0.0.1", "[::1]"].includes(target.hostname)) {
3005
+ for (const h of ["localhost", "127.0.0.1", "[::1]"]) selfOrigins.push(`${target.protocol}//${h}:${targetPort}`);
3006
+ }
3007
+ const origins = [...new Set(selfOrigins)];
3008
+ const items = [];
3009
+ const waiters = /* @__PURE__ */ new Set();
3010
+ const sse = /* @__PURE__ */ new Set();
3011
+ let seq = 0;
3012
+ const summarize = (p) => {
3013
+ const n = p.notes.length;
3014
+ return { label: n === 1 ? p.notes[0].comment.slice(0, 60) : `${n} notes`, prompt: p.notes.map((x) => x.comment).join(" | ") };
3015
+ };
3016
+ const publicItem = (it) => ({ id: it.id, ...it.payload.kind ? { kind: it.payload.kind } : {}, status: it.status, message: it.message, ...summarize(it.payload) });
3017
+ const broadcast = (obj) => {
3018
+ const line = `data: ${JSON.stringify(obj)}
3019
+
3020
+ `;
3021
+ for (const r of sse) r.write(line);
3022
+ };
3023
+ function dispatch() {
3024
+ for (const w of waiters) {
3025
+ const it = items.find((i) => i.status === "pending");
3026
+ if (!it) return;
3027
+ it.status = "working";
3028
+ waiters.delete(w);
3029
+ clearTimeout(w.timer);
3030
+ json(w.res, 200, it);
3031
+ broadcast({ type: "update", item: publicItem(it) });
3032
+ }
3033
+ }
3034
+ function authed(req) {
3035
+ if (noAuth) return true;
3036
+ return getCookie(req.headers.cookie, COOKIE) === token || req.headers["x-pe-token"] === token;
3037
+ }
3038
+ function upstreamHeaders(req) {
3039
+ const h = { ...req.headers };
3040
+ h.host = target.host;
3041
+ if (h.origin) h.origin = target.origin;
3042
+ if (h.referer) {
3043
+ try {
3044
+ const u = new URL(h.referer);
3045
+ h.referer = target.origin + u.pathname + u.search;
3046
+ } catch {
3047
+ }
3048
+ }
3049
+ for (const k of Object.keys(h)) if (k.startsWith("x-forwarded-") || k === "forwarded" || k === "x-pe-token") delete h[k];
3050
+ delete h["accept-encoding"];
3051
+ const c = stripCookie(h.cookie, COOKIE);
3052
+ if (c) h.cookie = c;
3053
+ else delete h.cookie;
3054
+ return h;
3055
+ }
3056
+ function rewriteLocation(loc) {
3057
+ for (const o of origins) if (loc === o || loc.startsWith(o + "/") || loc.startsWith(o + "?")) return loc.slice(o.length) || "/";
3058
+ return loc;
3059
+ }
3060
+ function injectHtml(html) {
3061
+ for (const o of origins) html = html.split(o + "/").join("/").split(o).join("/");
3062
+ const tag = `<script src="${PREFIX}/client.js" defer data-pe></script>`;
3063
+ if (/<\/head>/i.test(html)) return html.replace(/<\/head>/i, tag + "</head>");
3064
+ if (/<body[^>]*>/i.test(html)) return html.replace(/<body[^>]*>/i, (m) => m + tag);
3065
+ return html + tag;
3066
+ }
3067
+ function proxy(req, res) {
3068
+ const upReq = lib.request({
3069
+ hostname: target.hostname.replace(/^\[|\]$/g, ""),
3070
+ port: targetPort,
3071
+ method: req.method,
3072
+ path: req.url,
3073
+ headers: upstreamHeaders(req),
3074
+ rejectUnauthorized: false
3075
+ }, (upRes) => {
3076
+ const h = { ...upRes.headers };
3077
+ delete h["content-security-policy"];
3078
+ delete h["content-security-policy-report-only"];
3079
+ if (h.location) h.location = rewriteLocation(h.location);
3080
+ if (h["set-cookie"]) h["set-cookie"] = h["set-cookie"].map((c) => c.replace(/;\s*domain=[^;]*/i, ""));
3081
+ const isHtml = /text\/html/i.test(h["content-type"] || "");
3082
+ if (!isHtml || req.method === "HEAD" || upRes.statusCode === 204 || upRes.statusCode === 304) {
3083
+ res.writeHead(upRes.statusCode, h);
3084
+ upRes.pipe(res);
3085
+ return;
3086
+ }
3087
+ let stream = upRes;
3088
+ const enc = String(h["content-encoding"] || "").toLowerCase();
3089
+ if (enc === "gzip") stream = upRes.pipe(zlib.createGunzip());
3090
+ else if (enc === "br") stream = upRes.pipe(zlib.createBrotliDecompress());
3091
+ else if (enc === "deflate") stream = upRes.pipe(zlib.createInflate());
3092
+ const chunks = [];
3093
+ stream.on("data", (c) => chunks.push(c));
3094
+ stream.on("error", (e) => {
3095
+ if (!res.headersSent) res.writeHead(502);
3096
+ res.end(`punchlist: decode error ${e.message}`);
3097
+ });
3098
+ stream.on("end", () => {
3099
+ const body = Buffer.from(injectHtml(Buffer.concat(chunks).toString("utf8")), "utf8");
3100
+ delete h["content-encoding"];
3101
+ delete h["transfer-encoding"];
3102
+ h["content-length"] = String(body.length);
3103
+ res.writeHead(upRes.statusCode, h);
3104
+ res.end(body);
3105
+ });
3106
+ });
3107
+ upReq.on("error", (e) => {
3108
+ if (!res.headersSent) res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
3109
+ res.end(`punchlist: cannot reach ${target.origin} (${e.code || e.message}). Is the dev server running?`);
3110
+ });
3111
+ req.pipe(upReq);
3112
+ }
3113
+ async function api2(req, res, url) {
3114
+ const p = url.pathname.slice(PREFIX.length);
3115
+ if (p === "/client.js") {
3116
+ res.writeHead(200, { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-store" });
3117
+ return res.end(fs.readFileSync(path.join(DIR, "client.js"), "utf8"));
3118
+ }
3119
+ if (p === "/requests" && req.method === "POST") {
3120
+ let payload;
3121
+ try {
3122
+ payload = JSON.parse(await readBody(req));
3123
+ } catch (e) {
3124
+ return json(res, 400, { error: e.message });
3125
+ }
3126
+ if (!Array.isArray(payload.notes) || !payload.notes.length || payload.notes.some((n) => !n.comment?.trim() || !n.elements?.length))
3127
+ return json(res, 400, { error: "expected { notes: [{ comment, elements: [...] }] }" });
3128
+ const it = { id: `r${++seq}`, status: "pending", createdAt: (/* @__PURE__ */ new Date()).toISOString(), payload, message: null };
3129
+ items.push(it);
3130
+ log(`received ${it.id}: ${summarize(payload).prompt.slice(0, 100)}`);
3131
+ broadcast({ type: "update", item: publicItem(it) });
3132
+ dispatch();
3133
+ return json(res, 201, publicItem(it));
3134
+ }
3135
+ if (p === "/requests" && req.method === "GET") return json(res, 200, items.map(publicItem));
3136
+ let m;
3137
+ if ((m = p.match(/^\/requests\/([\w-]+)$/)) && req.method === "GET") {
3138
+ const it = items.find((i) => i.id === m[1]);
3139
+ return it ? json(res, 200, it) : json(res, 404, { error: "unknown id" });
3140
+ }
3141
+ if ((m = p.match(/^\/requests\/([\w-]+)\/done$/)) && req.method === "POST") {
3142
+ const it = items.find((i) => i.id === m[1]);
3143
+ if (!it) return json(res, 404, { error: "unknown id" });
3144
+ let body = {};
3145
+ try {
3146
+ body = JSON.parse(await readBody(req) || "{}");
3147
+ } catch {
3148
+ }
3149
+ it.status = body.status === "failed" ? "failed" : "done";
3150
+ it.message = body.message || null;
3151
+ log(`${it.status} ${it.id}${it.message ? `: ${it.message}` : ""}`);
3152
+ broadcast({ type: "update", item: publicItem(it) });
3153
+ return json(res, 200, publicItem(it));
3154
+ }
3155
+ if (p === "/open" && req.method === "POST") {
3156
+ let body;
3157
+ try {
3158
+ body = JSON.parse(await readBody(req));
3159
+ } catch (e) {
3160
+ return json(res, 400, { error: e.message });
3161
+ }
3162
+ if (typeof body.file !== "string" || !body.file) return json(res, 400, { error: "expected { file, line?, column? }" });
3163
+ const r = openInEditor(body.file, Number(body.line) || 0, Number(body.column) || 0);
3164
+ return json(res, r.status, r.status === 200 ? { file: r.file } : { error: r.error });
3165
+ }
3166
+ if (p === "/next" && req.method === "GET") {
3167
+ const timeout = Math.min(Number(url.searchParams.get("timeout")) || 25e3, 6e4);
3168
+ const w = { res };
3169
+ w.timer = setTimeout(() => {
3170
+ waiters.delete(w);
3171
+ res.writeHead(204);
3172
+ res.end();
3173
+ }, timeout);
3174
+ req.on("close", () => {
3175
+ clearTimeout(w.timer);
3176
+ waiters.delete(w);
3177
+ });
3178
+ waiters.add(w);
3179
+ return dispatch();
3180
+ }
3181
+ if (p === "/events") {
3182
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
3183
+ res.write(`data: ${JSON.stringify({ type: "snapshot", items: items.map(publicItem) })}
3184
+
3185
+ `);
3186
+ sse.add(res);
3187
+ const ka = setInterval(() => res.write(": ka\n\n"), 25e3);
3188
+ req.on("close", () => {
3189
+ clearInterval(ka);
3190
+ sse.delete(res);
3191
+ });
3192
+ return;
3193
+ }
3194
+ json(res, 404, { error: "not found" });
3195
+ }
3196
+ const server = http.createServer((req, res) => {
3197
+ const url = new URL(req.url, "http://x");
3198
+ if (url.pathname === `${PREFIX}/auth`) {
3199
+ const next = url.searchParams.get("next");
3200
+ const dest = next && next.startsWith("/") && !next.startsWith("//") ? next : "/";
3201
+ if (noAuth || url.searchParams.get("token") === token) {
3202
+ res.writeHead(302, { "set-cookie": `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000`, location: dest });
3203
+ } else res.writeHead(403, { "content-type": "text/plain" });
3204
+ return res.end(res.statusCode === 403 ? "punchlist: bad token" : "");
3205
+ }
3206
+ if (!authed(req)) {
3207
+ res.writeHead(401, { "content-type": "text/plain; charset=utf-8" });
3208
+ return res.end("punchlist: open the link printed by `punchlist start` (it carries the access token).");
3209
+ }
3210
+ if (url.pathname.startsWith(PREFIX + "/")) return api2(req, res, url).catch((e) => json(res, 500, { error: e.message }));
3211
+ proxy(req, res);
3212
+ });
3213
+ server.on("upgrade", (req, socket, head) => {
3214
+ if (!authed(req)) return socket.end("HTTP/1.1 401 Unauthorized\r\n\r\n");
3215
+ const opts = { host: target.hostname.replace(/^\[|\]$/g, ""), port: targetPort, servername: target.hostname, rejectUnauthorized: false };
3216
+ const up = (target.protocol === "https:" ? tls : net).connect(opts, () => {
3217
+ let raw = `${req.method} ${req.url} HTTP/1.1\r
3218
+ `;
3219
+ const h = upstreamHeaders(req);
3220
+ for (const [k, v] of Object.entries(h)) for (const vv of [].concat(v)) raw += `${k}: ${vv}\r
3221
+ `;
3222
+ up.write(raw + "\r\n");
3223
+ if (head?.length) up.write(head);
3224
+ up.pipe(socket);
3225
+ socket.pipe(up);
3226
+ });
3227
+ up.on("error", () => socket.destroy());
3228
+ socket.on("error", () => up.destroy());
3229
+ });
3230
+ function openInEditor(file, line, column) {
3231
+ const root = process.cwd();
3232
+ const inside = (dir, f) => f === dir || f.startsWith(dir + path.sep);
3233
+ const abs = path.resolve(root, file);
3234
+ if (!inside(root, abs)) return { status: 403, error: "file is outside the project" };
3235
+ let real;
3236
+ try {
3237
+ real = fs.realpathSync(abs);
3238
+ } catch {
3239
+ return { status: 404, error: `${file} not found in ${root}` };
3240
+ }
3241
+ if (!inside(fs.realpathSync(root), real)) return { status: 403, error: "file is outside the project" };
3242
+ let failed = null;
3243
+ (0, import_launch_editor.default)(abs + (line ? `:${line}${column ? `:${column}` : ""}` : ""), (f, msg) => {
3244
+ failed = msg || "no editor found (set LAUNCH_EDITOR or EDITOR)";
3245
+ });
3246
+ if (failed) return { status: 500, error: failed };
3247
+ const rel = path.relative(root, abs);
3248
+ log(`opened ${rel}${line ? `:${line}` : ""} in the editor`);
3249
+ return { status: 200, file: rel };
3250
+ }
3251
+ function log(msg) {
3252
+ console.log(`[punchlist ${(/* @__PURE__ */ new Date()).toLocaleTimeString()}] ${msg}`);
3253
+ }
3254
+ server.listen(port, host, () => {
3255
+ fs.mkdirSync(STATE_DIR, { recursive: true });
3256
+ const st = { port, host, target: target.origin, token, auth: !noAuth, pid: process.pid, cwd: process.cwd() };
3257
+ fs.writeFileSync(statePath(port), JSON.stringify(st));
3258
+ printInfo(st);
3259
+ });
3260
+ server.on("error", (e) => {
3261
+ console.error(e.code === "EADDRINUSE" ? `port ${port} is in use (pick another with --port)` : e.message);
3262
+ process.exit(1);
3263
+ });
3264
+ const cleanup = () => {
3265
+ try {
3266
+ fs.unlinkSync(statePath(port));
3267
+ } catch {
3268
+ }
3269
+ process.exit(0);
3270
+ };
3271
+ process.on("SIGINT", cleanup);
3272
+ process.on("SIGTERM", cleanup);
3273
+ return new Promise(() => {
3274
+ });
3275
+ }
3276
+ var HTML_LIMIT = 600;
3277
+ function requestView(it, port, full = false) {
3278
+ const { notes, viewport } = it.payload;
3279
+ const kinds = new Set(notes.map((n) => n.kind));
3280
+ let cut = false;
3281
+ const noHint = [];
3282
+ const view = {
3283
+ request: { id: it.id, status: it.status, notes: notes.length, ...viewport ? { viewport: `${viewport.w}x${viewport.h}` } : {} },
3284
+ notes: notes.map((n, i) => ({
3285
+ key: String(i + 1),
3286
+ kind: n.kind,
3287
+ comment: n.comment,
3288
+ page: n.path,
3289
+ ...n.frozen ? { frozen: "captured with animations paused" } : {},
3290
+ ...n.kind === "text" ? { selected: n.text } : {},
3291
+ ...n.kind === "area" ? { area: `${Math.round(n.area.width)}x${Math.round(n.area.height)} at page (${Math.round(n.area.x)}, ${Math.round(n.area.y)})` } : {},
3292
+ targets: n.elements.map((e, j) => {
3293
+ const key = n.elements.length > 1 ? `${i + 1}${"abcdef"[j]}` : String(i + 1);
3294
+ const h = e.hints || {};
3295
+ const hints = Object.fromEntries(["svelte", "rails", "react", "vue"].filter((k) => h[k]?.length).map((k) => [k, h[k].join(k === "rails" ? " > " : k === "svelte" ? ", " : " < ")]));
3296
+ if (!Object.keys(hints).length) noHint.push(key);
3297
+ let html = e.html || "";
3298
+ if (!full && html.length > HTML_LIMIT) {
3299
+ html = `${html.slice(0, HTML_LIMIT)}... (truncated, ${html.length} chars total)`;
3300
+ cut = true;
3301
+ }
3302
+ return {
3303
+ key,
3304
+ label: e.label,
3305
+ ...Object.keys(hints).length ? { hints } : {},
3306
+ ...e.text ? { text: e.text } : {},
3307
+ html,
3308
+ ...full ? {
3309
+ selector: e.selector,
3310
+ ...e.ancestors?.length ? { inside: e.ancestors.join(" > ") } : {},
3311
+ ...e.styles ? { styles: e.styles } : {},
3312
+ ...e.rect ? { box: `${Math.round(e.rect.width)}x${Math.round(e.rect.height)} at page (${Math.round(e.rect.x)}, ${Math.round(e.rect.y)})` } : {}
3313
+ } : {}
3314
+ };
3315
+ })
3316
+ }))
3317
+ };
3318
+ if (it.payload.kind === "locate") return { ...view, request: { ...view.request, kind: "locate" }, help: [
3319
+ "The user wants to open the source of this target in their editor: find the file (and line) that renders it. Lookup only - do not edit anything",
3320
+ "Use the hints first (a component name: grep for its definition), then visible text, ids, data-* attributes or uncommon classes",
3321
+ `Run \`${PE} done ${it.id} --open <file>[:line[:col]] --port ${port}\` to open it (a path relative to the project); --failed "<why>" if you cannot find it`
3322
+ ] };
3323
+ const help = ["Handle every note (notes may touch the same file), then report once"];
3324
+ if (kinds.has("elements")) help.push("kind elements: apply the comment to every target; they often share one partial or component");
3325
+ if (kinds.has("text")) help.push("kind text: change exactly the selected text; it may live in an i18n file (config/locales, src/lib/i18n)");
3326
+ if (kinds.has("area")) help.push("kind area: the user boxed empty space; the change belongs at that spot inside the target");
3327
+ if (noHint.length) help.push(`No source hint for [${noHint.join("], [")}]: grep for the visible text, ids, data-* attributes or uncommon classes; the page path tells you the route`);
3328
+ if (cut || !full) help.push(`Run \`${PE} show ${it.id} --full --port ${port}\` for selectors, computed styles${cut ? " and the full HTML" : ""}`);
3329
+ help.push(`Run \`${PE} done ${it.id} "<one line per note, e.g. 1: ... 2: ...>" --port ${port}\` when finished (--failed if nothing could be done)`);
3330
+ return { ...view, help };
3331
+ }
3332
+ async function cmdWait(args) {
3333
+ const st = loadState(args);
3334
+ const secs = Number(args.timeout ?? 540);
3335
+ if (!(secs > 0)) throw usageError("--timeout must be a number of seconds", "wait");
3336
+ const deadline = Date.now() + secs * 1e3;
3337
+ while (Date.now() < deadline) {
3338
+ const left = Math.max(1e3, Math.min(25e3, deadline - Date.now()));
3339
+ const r = await api(st, `/next?timeout=${left}`);
3340
+ if (r.status === 200) {
3341
+ const it = await r.json();
3342
+ return args.json ? JSON.stringify(it, null, 2) : requestView(it, st.port);
3343
+ }
3344
+ if (r.status !== 204) throw new AxiError(`unexpected ${r.status} from the proxy: ${(await r.text()).slice(0, 300)}`, "PROXY_ERROR");
3345
+ }
3346
+ return { request: `none (waited ${secs}s)`, help: [listenHelp(st.port)] };
3347
+ }
3348
+ async function cmdShow(args) {
3349
+ const id = args._[0];
3350
+ if (!id) throw usageError("request id is required", "show", [`Run \`${PE} show <id> [--full]\``]);
3351
+ const st = loadState(args);
3352
+ const r = await api(st, `/requests/${encodeURIComponent(id)}`);
3353
+ if (r.status === 404) throw new AxiError(`no request ${id} on port ${st.port}`, "NOT_FOUND", [`Run \`${PE} status --port ${st.port}\` to list requests`]);
3354
+ return requestView(await r.json(), st.port, args.full === true);
3355
+ }
3356
+ async function cmdDone(args) {
3357
+ const id = args._[0];
3358
+ if (!id) throw usageError("request id is required", "done", [`Run \`${PE} done <id> "<one line per note>"\``]);
3359
+ const st = loadState(args);
3360
+ const status = args.failed ? "failed" : "done";
3361
+ let message = args._.slice(1).join(" ") || null;
3362
+ if (args.open && !args.failed) {
3363
+ const [, file, line, column] = args.open.match(/^(.+?)(?::(\d+))?(?::(\d+))?$/);
3364
+ const o = await api(st, "/open", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ file, line, column }) });
3365
+ const b = await o.json().catch(() => ({}));
3366
+ if (!o.ok) throw new AxiError(`could not open ${args.open}: ${b.error || o.status}`, "OPEN_FAILED", [`Fix the path and run \`${PE} done ${id} --open <file>[:line[:col]] --port ${st.port}\` again`]);
3367
+ message ??= `opened ${b.file}${line ? `:${line}${column ? `:${column}` : ""}` : ""}`;
3368
+ }
3369
+ const r = await api(st, `/requests/${encodeURIComponent(id)}/done`, {
3370
+ method: "POST",
3371
+ headers: { "content-type": "application/json" },
3372
+ body: JSON.stringify({ status, message })
3373
+ });
3374
+ if (r.status === 404) throw new AxiError(`no request ${id} on port ${st.port}`, "NOT_FOUND", [`Run \`${PE} status --port ${st.port}\` to list requests`]);
3375
+ if (!r.ok) throw new AxiError(`proxy refused: ${r.status} ${(await r.text()).slice(0, 300)}`, "PROXY_ERROR");
3376
+ return { request: { id, status }, help: [listenHelp(st.port)] };
3377
+ }
3378
+ async function cmdStatus(args) {
3379
+ const st = loadState(args);
3380
+ const list = await (await api(st, "/requests")).json();
3381
+ const by = (s) => list.filter((i) => i.status === s).length;
3382
+ return {
3383
+ proxy: { target: st.target, port: st.port, pid: st.pid },
3384
+ count: list.length ? `${list.length} request${list.length === 1 ? "" : "s"} (${by("pending")} pending, ${by("working")} working, ${by("done")} done, ${by("failed")} failed)` : "0 requests - the user has not sent anything yet",
3385
+ ...list.length ? { requests: list.map((i) => ({ id: i.id, status: i.status, prompt: i.prompt })) } : {},
3386
+ help: [`Run \`${PE} wait --port ${st.port}\` to receive the next batch`]
3387
+ };
3388
+ }
3389
+ function cmdStop(args) {
3390
+ const port = args.port;
3391
+ const p = port ? statePath(port) : null;
3392
+ if (p && !fs.existsSync(p) || !p && !runningProxies().length) return { stop: `no proxy running${port ? ` on port ${port}` : ""} (no-op)` };
3393
+ const st = loadState(args);
3394
+ try {
3395
+ process.kill(st.pid, "SIGTERM");
3396
+ } catch {
3397
+ fs.rmSync(statePath(st.port), { force: true });
3398
+ }
3399
+ return { stop: `stopped the proxy on port ${st.port}` };
3400
+ }
3401
+ function runningProxies() {
3402
+ if (!fs.existsSync(STATE_DIR)) return [];
3403
+ return fs.readdirSync(STATE_DIR).filter((f) => f.endsWith(".json")).map((f) => {
3404
+ try {
3405
+ return JSON.parse(fs.readFileSync(path.join(STATE_DIR, f), "utf8"));
3406
+ } catch {
3407
+ return null;
3408
+ }
3409
+ }).filter((st) => st && alive(st.pid));
3410
+ }
3411
+ async function home() {
3412
+ const here = process.cwd();
3413
+ const mine = (st) => st.cwd && (here === st.cwd || here.startsWith(st.cwd + path.sep));
3414
+ const sts = runningProxies(), local = sts.filter(mine), others = sts.length - local.length;
3415
+ const proxies = await Promise.all(local.map(async (st) => {
3416
+ let pending = "?";
3417
+ try {
3418
+ pending = (await (await api(st, "/requests", { signal: AbortSignal.timeout(1500) })).json()).filter((i) => i.status === "pending").length;
3419
+ } catch {
3420
+ }
3421
+ return { port: st.port, target: st.target, pending };
3422
+ }));
3423
+ return {
3424
+ proxies: proxies.length ? proxies : "0 running for this directory",
3425
+ ...others ? { other_proxies: `${others} (started from other directories; see \`${PE} status --port <port>\`)` } : {},
3426
+ help: proxies.length ? [`Run \`${PE} wait --port <port>\` to receive notes`, `Run \`${PE} status --port <port>\` to list requests`, `Run \`${PE} --help\` for commands and the loop`] : [`Run \`${PE} start --target <port|url>\` to proxy a dev server`, `Run \`${PE} --help\` for commands and the loop`]
3427
+ };
3428
+ }
3429
+ async function cmdSetup(args) {
3430
+ if (args._[0] !== "hooks" || args._.length > 1) throw usageError("unknown setup target", "setup", [`Run \`${PE} setup hooks [--project] [--remove]\``]);
3431
+ const scope = args.project ? "project" : "user";
3432
+ const identity = { marker: "punchlist-axi", execPath: SCRIPT, scope };
3433
+ const problems = [];
3434
+ if (args.remove) await uninstallSessionStartHooks({ ...identity, onError: (m) => problems.push(m) });
3435
+ else await installSessionStartHooks({ ...identity, binaryNames: ["punchlist-axi"], shouldInstall: () => true, onError: (m) => problems.push(m) });
3436
+ const st = sessionStartHookStatus(identity);
3437
+ const row = (agent, a) => ({ agent, installed: a.installed, path: a.path.replace(os.homedir(), "~") });
3438
+ return {
3439
+ setup: `${args.remove ? "removed" : "installed or already up to date"}: SessionStart hooks (${scope} scope)`,
3440
+ agents: [row("claude", st.claude), row("codex", st.codex), row("opencode", st.opencode)],
3441
+ ...problems.length ? { warnings: problems } : {},
3442
+ help: args.remove ? [`Run \`${PE} setup hooks${args.project ? " --project" : ""}\` to install them again`] : ["Each new agent session now starts with the proxies running for its directory", `Run \`${PE} setup hooks --remove${args.project ? " --project" : ""}\` to undo`]
3443
+ };
3444
+ }
3445
+ var PE = `node ${SCRIPT}`;
3446
+ var listenHelp = (port) => `Run \`${PE} wait --port ${port}\` as a background command (Claude Code: Bash with run_in_background: true), so new notes reach you without the user asking. Never end your turn without a wait running`;
3447
+ var GUIDE = `punchlist - click-to-edit for any running web app. A local proxy injects a picker into every
3448
+ page; the user marks elements and presses Send; you pull the notes, edit the source, report back.
3449
+
3450
+ commands:
3451
+ start proxy a dev server in the background and print the link for the user
3452
+ wait block until the user sends notes, then print them
3453
+ show print a request again (--full: selectors, styles, full HTML)
3454
+ done report a request back to the browser
3455
+ status list requests on a proxy
3456
+ stop stop a proxy
3457
+ setup add a SessionStart hook so new agent sessions see running proxies
3458
+ serve run the proxy in the foreground (debugging)
3459
+
3460
+ loop: start -> send the user the link -> wait (in the background) -> edit the source -> done -> wait ...
3461
+ Every output ends with help lines that name the next command.
3462
+ Run \`${PE} <command> --help\` for flags, examples and guidance.`;
3463
+ var HELP = {
3464
+ start: `start --target <port|url> [--port 4000] [--host 127.0.0.1] [--no-auth]
3465
+ Start the proxy in the background and print the link for the user. Safe to re-run.
3466
+ Find the dev server port from running processes, Procfile.dev, bin/dev, package.json scripts or
3467
+ the conversation; ask the user only if it is unclear.
3468
+ --target dev server port or URL (required)
3469
+ --port proxy port (default 4000)
3470
+ --host listen address (default 127.0.0.1; 0.0.0.0 = all interfaces)
3471
+ --no-auth no access token (purely local use only)
3472
+ examples:
3473
+ ${PE} start --target 5173
3474
+ ${PE} start --target http://localhost:3000 --port 4001`,
3475
+ serve: `serve --target <port|url> [same flags as start]
3476
+ Run the proxy in the foreground (debugging). Agents use start.`,
3477
+ wait: `wait [--port 4000] [--timeout 540] [--json]
3478
+ Block until the user presses Send, then print the batch of notes.
3479
+ Prints \`request: none\` (exit 0) when nothing arrives in time: run it again.
3480
+ --port proxy port (default: most recently started proxy)
3481
+ --timeout seconds to wait (default 540, under most shell-tool limits)
3482
+ --json raw request JSON instead of the formatted view
3483
+ Run wait as a background command so you stay free and your harness tells you when it exits:
3484
+ Claude Code: Bash with run_in_background: true. Other harnesses: any background job that
3485
+ reports its exit. No background support: run it in the foreground. Notes queue on the proxy,
3486
+ so none are lost between runs. Run wait again after every done and every timeout, without
3487
+ commentary, until the user tells you to stop: you hear the user only while wait runs.
3488
+ In the background a longer --timeout (e.g. 3600) means fewer empty wake-ups.
3489
+ finding the source (in this order):
3490
+ 1. svelte file:line:col (or React _debugSource) - open it directly
3491
+ 2. rails templates - the last entry is the innermost partial. Needs
3492
+ config.action_view.annotate_rendered_view_with_filenames = true in development; suggest it
3493
+ once for Rails apps, never add it without the user's consent
3494
+ 3. react/vue component names - grep for the definition
3495
+ 4. no hints - grep for visible text (also i18n files), ids, data-* attributes, rare classes
3496
+ The HTML is rendered output, not source. Make the smallest change; if a target comes from a
3497
+ shared partial or component, say in done that every use changes.
3498
+ examples:
3499
+ ${PE} wait --port 4000`,
3500
+ show: `show <id> [--full] [--port 4000]
3501
+ Print one request again. --full adds selectors, ancestors, computed styles, boxes and untruncated HTML.
3502
+ examples:
3503
+ ${PE} show r1 --full --port 4000`,
3504
+ done: `done <id> "<one line per note>" [--failed] [--open <file[:line[:col]]>] [--port 4000]
3505
+ Report a request back to the browser (shown as a toast). Run it once per request.
3506
+ If some notes fail, still do the others and name the failed ones in the message.
3507
+ --failed nothing could be done; the message says why
3508
+ --open open this project file in the user's editor first (answers a locate request)
3509
+ examples:
3510
+ ${PE} done r1 "1: CTA larger 2: doors time -> 18:00" --port 4000
3511
+ ${PE} done r2 "need the new copy for the hero" --failed
3512
+ ${PE} done r3 --open app/assets/javascripts/components/hero.js.jsx:12`,
3513
+ status: `status [--port 4000]
3514
+ List the requests on a proxy with counts by state.`,
3515
+ stop: `stop [--port 4000]
3516
+ Stop a proxy. No-op when nothing runs.`,
3517
+ setup: `setup hooks [--project] [--remove]
3518
+ Add a SessionStart hook to Claude Code, Codex and OpenCode: each session starts with the
3519
+ proxies running for its directory (the no-args home view). Safe to re-run.
3520
+ --project write the project's config (.claude/settings.json, ...) instead of the user's
3521
+ --remove take the hooks out again
3522
+ examples:
3523
+ ${PE} setup hooks
3524
+ ${PE} setup hooks --remove`
3525
+ };
3526
+ var handler = (fn) => (cmd) => (argv) => fn(parseArgs(cmd, argv));
3527
+ var cmds = Object.fromEntries(Object.entries({ start: cmdStart, serve: cmdServe, wait: cmdWait, show: cmdShow, done: cmdDone, status: cmdStatus, stop: cmdStop, setup: cmdSetup }).map(([k, fn]) => [k, handler(fn)(k)]));
3528
+ await runAxiCli({
3529
+ description: "Click-to-edit for running web apps: the user marks UI in the browser, you pull the notes and edit the source",
3530
+ version: VERSION,
3531
+ topLevelHelp: GUIDE + "\n",
3532
+ home,
3533
+ commands: cmds,
3534
+ getCommandHelp: (c) => HELP[c] ? HELP[c] + "\n" : null
3535
+ });