@callstack/apex 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,4859 @@
1
+ #!/usr/bin/env node
2
+ import { isDeepStrictEqual, parseArgs, styleText } from "node:util";
3
+ import { spawn } from "node:child_process";
4
+ import { access, lstat, mkdir, open, readFile, rename, stat, unlink } from "node:fs/promises";
5
+ import { basename, delimiter, dirname, join, parse, resolve } from "node:path";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { constants } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import process$1, { stdin, stdout } from "node:process";
10
+ import l__default from "node:readline";
11
+
12
+ //#region \0rolldown/runtime.js
13
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
14
+
15
+ //#endregion
16
+ //#region node_modules/jsonc-parser/lib/esm/impl/scanner.js
17
+ /**
18
+ * Creates a JSON scanner on the given text.
19
+ * If ignoreTrivia is set, whitespaces or comments are ignored.
20
+ */
21
+ function createScanner(text, ignoreTrivia = false) {
22
+ const len = text.length;
23
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
24
+ function scanHexDigits(count, exact) {
25
+ let digits = 0;
26
+ let value = 0;
27
+ while (digits < count || !exact) {
28
+ let ch = text.charCodeAt(pos);
29
+ if (ch >= 48 && ch <= 57) value = value * 16 + ch - 48;
30
+ else if (ch >= 65 && ch <= 70) value = value * 16 + ch - 65 + 10;
31
+ else if (ch >= 97 && ch <= 102) value = value * 16 + ch - 97 + 10;
32
+ else break;
33
+ pos++;
34
+ digits++;
35
+ }
36
+ if (digits < count) value = -1;
37
+ return value;
38
+ }
39
+ function setPosition(newPosition) {
40
+ pos = newPosition;
41
+ value = "";
42
+ tokenOffset = 0;
43
+ token = 16;
44
+ scanError = 0;
45
+ }
46
+ function scanNumber() {
47
+ let start = pos;
48
+ if (text.charCodeAt(pos) === 48) pos++;
49
+ else {
50
+ pos++;
51
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
52
+ }
53
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
54
+ pos++;
55
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
56
+ pos++;
57
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
58
+ } else {
59
+ scanError = 3;
60
+ return text.substring(start, pos);
61
+ }
62
+ }
63
+ let end = pos;
64
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
65
+ pos++;
66
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++;
67
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
68
+ pos++;
69
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
70
+ end = pos;
71
+ } else scanError = 3;
72
+ }
73
+ return text.substring(start, end);
74
+ }
75
+ function scanString() {
76
+ let result = "", start = pos;
77
+ while (true) {
78
+ if (pos >= len) {
79
+ result += text.substring(start, pos);
80
+ scanError = 2;
81
+ break;
82
+ }
83
+ const ch = text.charCodeAt(pos);
84
+ if (ch === 34) {
85
+ result += text.substring(start, pos);
86
+ pos++;
87
+ break;
88
+ }
89
+ if (ch === 92) {
90
+ result += text.substring(start, pos);
91
+ pos++;
92
+ if (pos >= len) {
93
+ scanError = 2;
94
+ break;
95
+ }
96
+ switch (text.charCodeAt(pos++)) {
97
+ case 34:
98
+ result += "\"";
99
+ break;
100
+ case 92:
101
+ result += "\\";
102
+ break;
103
+ case 47:
104
+ result += "/";
105
+ break;
106
+ case 98:
107
+ result += "\b";
108
+ break;
109
+ case 102:
110
+ result += "\f";
111
+ break;
112
+ case 110:
113
+ result += "\n";
114
+ break;
115
+ case 114:
116
+ result += "\r";
117
+ break;
118
+ case 116:
119
+ result += " ";
120
+ break;
121
+ case 117:
122
+ const ch3 = scanHexDigits(4, true);
123
+ if (ch3 >= 0) result += String.fromCharCode(ch3);
124
+ else scanError = 4;
125
+ break;
126
+ default: scanError = 5;
127
+ }
128
+ start = pos;
129
+ continue;
130
+ }
131
+ if (ch >= 0 && ch <= 31) {
132
+ if (isLineBreak(ch)) {
133
+ result += text.substring(start, pos);
134
+ scanError = 2;
135
+ break;
136
+ } else scanError = 6;
137
+ }
138
+ pos++;
139
+ }
140
+ return result;
141
+ }
142
+ function scanNext() {
143
+ value = "";
144
+ scanError = 0;
145
+ tokenOffset = pos;
146
+ lineStartOffset = lineNumber;
147
+ prevTokenLineStartOffset = tokenLineStartOffset;
148
+ if (pos >= len) {
149
+ tokenOffset = len;
150
+ return token = 17;
151
+ }
152
+ let code = text.charCodeAt(pos);
153
+ if (isWhiteSpace(code)) {
154
+ do {
155
+ pos++;
156
+ value += String.fromCharCode(code);
157
+ code = text.charCodeAt(pos);
158
+ } while (isWhiteSpace(code));
159
+ return token = 15;
160
+ }
161
+ if (isLineBreak(code)) {
162
+ pos++;
163
+ value += String.fromCharCode(code);
164
+ if (code === 13 && text.charCodeAt(pos) === 10) {
165
+ pos++;
166
+ value += "\n";
167
+ }
168
+ lineNumber++;
169
+ tokenLineStartOffset = pos;
170
+ return token = 14;
171
+ }
172
+ switch (code) {
173
+ case 123:
174
+ pos++;
175
+ return token = 1;
176
+ case 125:
177
+ pos++;
178
+ return token = 2;
179
+ case 91:
180
+ pos++;
181
+ return token = 3;
182
+ case 93:
183
+ pos++;
184
+ return token = 4;
185
+ case 58:
186
+ pos++;
187
+ return token = 6;
188
+ case 44:
189
+ pos++;
190
+ return token = 5;
191
+ case 34:
192
+ pos++;
193
+ value = scanString();
194
+ return token = 10;
195
+ case 47:
196
+ const start = pos - 1;
197
+ if (text.charCodeAt(pos + 1) === 47) {
198
+ pos += 2;
199
+ while (pos < len) {
200
+ if (isLineBreak(text.charCodeAt(pos))) break;
201
+ pos++;
202
+ }
203
+ value = text.substring(start, pos);
204
+ return token = 12;
205
+ }
206
+ if (text.charCodeAt(pos + 1) === 42) {
207
+ pos += 2;
208
+ const safeLength = len - 1;
209
+ let commentClosed = false;
210
+ while (pos < safeLength) {
211
+ const ch = text.charCodeAt(pos);
212
+ if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
213
+ pos += 2;
214
+ commentClosed = true;
215
+ break;
216
+ }
217
+ pos++;
218
+ if (isLineBreak(ch)) {
219
+ if (ch === 13 && text.charCodeAt(pos) === 10) pos++;
220
+ lineNumber++;
221
+ tokenLineStartOffset = pos;
222
+ }
223
+ }
224
+ if (!commentClosed) {
225
+ pos++;
226
+ scanError = 1;
227
+ }
228
+ value = text.substring(start, pos);
229
+ return token = 13;
230
+ }
231
+ value += String.fromCharCode(code);
232
+ pos++;
233
+ return token = 16;
234
+ case 45:
235
+ value += String.fromCharCode(code);
236
+ pos++;
237
+ if (pos === len || !isDigit(text.charCodeAt(pos))) return token = 16;
238
+ case 48:
239
+ case 49:
240
+ case 50:
241
+ case 51:
242
+ case 52:
243
+ case 53:
244
+ case 54:
245
+ case 55:
246
+ case 56:
247
+ case 57:
248
+ value += scanNumber();
249
+ return token = 11;
250
+ default:
251
+ while (pos < len && isUnknownContentCharacter(code)) {
252
+ pos++;
253
+ code = text.charCodeAt(pos);
254
+ }
255
+ if (tokenOffset !== pos) {
256
+ value = text.substring(tokenOffset, pos);
257
+ switch (value) {
258
+ case "true": return token = 8;
259
+ case "false": return token = 9;
260
+ case "null": return token = 7;
261
+ }
262
+ return token = 16;
263
+ }
264
+ value += String.fromCharCode(code);
265
+ pos++;
266
+ return token = 16;
267
+ }
268
+ }
269
+ function isUnknownContentCharacter(code) {
270
+ if (isWhiteSpace(code) || isLineBreak(code)) return false;
271
+ switch (code) {
272
+ case 125:
273
+ case 93:
274
+ case 123:
275
+ case 91:
276
+ case 34:
277
+ case 58:
278
+ case 44:
279
+ case 47: return false;
280
+ }
281
+ return true;
282
+ }
283
+ function scanNextNonTrivia() {
284
+ let result;
285
+ do
286
+ result = scanNext();
287
+ while (result >= 12 && result <= 15);
288
+ return result;
289
+ }
290
+ return {
291
+ setPosition,
292
+ getPosition: () => pos,
293
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
294
+ getToken: () => token,
295
+ getTokenValue: () => value,
296
+ getTokenOffset: () => tokenOffset,
297
+ getTokenLength: () => pos - tokenOffset,
298
+ getTokenStartLine: () => lineStartOffset,
299
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
300
+ getTokenError: () => scanError
301
+ };
302
+ }
303
+ function isWhiteSpace(ch) {
304
+ return ch === 32 || ch === 9;
305
+ }
306
+ function isLineBreak(ch) {
307
+ return ch === 10 || ch === 13;
308
+ }
309
+ function isDigit(ch) {
310
+ return ch >= 48 && ch <= 57;
311
+ }
312
+ var CharacterCodes;
313
+ (function(CharacterCodes) {
314
+ CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
315
+ CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
316
+ CharacterCodes[CharacterCodes["space"] = 32] = "space";
317
+ CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
318
+ CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
319
+ CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
320
+ CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
321
+ CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
322
+ CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
323
+ CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
324
+ CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
325
+ CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
326
+ CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
327
+ CharacterCodes[CharacterCodes["a"] = 97] = "a";
328
+ CharacterCodes[CharacterCodes["b"] = 98] = "b";
329
+ CharacterCodes[CharacterCodes["c"] = 99] = "c";
330
+ CharacterCodes[CharacterCodes["d"] = 100] = "d";
331
+ CharacterCodes[CharacterCodes["e"] = 101] = "e";
332
+ CharacterCodes[CharacterCodes["f"] = 102] = "f";
333
+ CharacterCodes[CharacterCodes["g"] = 103] = "g";
334
+ CharacterCodes[CharacterCodes["h"] = 104] = "h";
335
+ CharacterCodes[CharacterCodes["i"] = 105] = "i";
336
+ CharacterCodes[CharacterCodes["j"] = 106] = "j";
337
+ CharacterCodes[CharacterCodes["k"] = 107] = "k";
338
+ CharacterCodes[CharacterCodes["l"] = 108] = "l";
339
+ CharacterCodes[CharacterCodes["m"] = 109] = "m";
340
+ CharacterCodes[CharacterCodes["n"] = 110] = "n";
341
+ CharacterCodes[CharacterCodes["o"] = 111] = "o";
342
+ CharacterCodes[CharacterCodes["p"] = 112] = "p";
343
+ CharacterCodes[CharacterCodes["q"] = 113] = "q";
344
+ CharacterCodes[CharacterCodes["r"] = 114] = "r";
345
+ CharacterCodes[CharacterCodes["s"] = 115] = "s";
346
+ CharacterCodes[CharacterCodes["t"] = 116] = "t";
347
+ CharacterCodes[CharacterCodes["u"] = 117] = "u";
348
+ CharacterCodes[CharacterCodes["v"] = 118] = "v";
349
+ CharacterCodes[CharacterCodes["w"] = 119] = "w";
350
+ CharacterCodes[CharacterCodes["x"] = 120] = "x";
351
+ CharacterCodes[CharacterCodes["y"] = 121] = "y";
352
+ CharacterCodes[CharacterCodes["z"] = 122] = "z";
353
+ CharacterCodes[CharacterCodes["A"] = 65] = "A";
354
+ CharacterCodes[CharacterCodes["B"] = 66] = "B";
355
+ CharacterCodes[CharacterCodes["C"] = 67] = "C";
356
+ CharacterCodes[CharacterCodes["D"] = 68] = "D";
357
+ CharacterCodes[CharacterCodes["E"] = 69] = "E";
358
+ CharacterCodes[CharacterCodes["F"] = 70] = "F";
359
+ CharacterCodes[CharacterCodes["G"] = 71] = "G";
360
+ CharacterCodes[CharacterCodes["H"] = 72] = "H";
361
+ CharacterCodes[CharacterCodes["I"] = 73] = "I";
362
+ CharacterCodes[CharacterCodes["J"] = 74] = "J";
363
+ CharacterCodes[CharacterCodes["K"] = 75] = "K";
364
+ CharacterCodes[CharacterCodes["L"] = 76] = "L";
365
+ CharacterCodes[CharacterCodes["M"] = 77] = "M";
366
+ CharacterCodes[CharacterCodes["N"] = 78] = "N";
367
+ CharacterCodes[CharacterCodes["O"] = 79] = "O";
368
+ CharacterCodes[CharacterCodes["P"] = 80] = "P";
369
+ CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
370
+ CharacterCodes[CharacterCodes["R"] = 82] = "R";
371
+ CharacterCodes[CharacterCodes["S"] = 83] = "S";
372
+ CharacterCodes[CharacterCodes["T"] = 84] = "T";
373
+ CharacterCodes[CharacterCodes["U"] = 85] = "U";
374
+ CharacterCodes[CharacterCodes["V"] = 86] = "V";
375
+ CharacterCodes[CharacterCodes["W"] = 87] = "W";
376
+ CharacterCodes[CharacterCodes["X"] = 88] = "X";
377
+ CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
378
+ CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
379
+ CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
380
+ CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
381
+ CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
382
+ CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
383
+ CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
384
+ CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
385
+ CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
386
+ CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
387
+ CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
388
+ CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
389
+ CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
390
+ CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
391
+ CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
392
+ CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
393
+ CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
394
+ })(CharacterCodes || (CharacterCodes = {}));
395
+
396
+ //#endregion
397
+ //#region node_modules/jsonc-parser/lib/esm/impl/string-intern.js
398
+ const cachedSpaces = new Array(20).fill(0).map((_, index) => {
399
+ return " ".repeat(index);
400
+ });
401
+ const maxCachedValues = 200;
402
+ const cachedBreakLinesWithSpaces = {
403
+ " ": {
404
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
405
+ return "\n" + " ".repeat(index);
406
+ }),
407
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
408
+ return "\r" + " ".repeat(index);
409
+ }),
410
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
411
+ return "\r\n" + " ".repeat(index);
412
+ })
413
+ },
414
+ " ": {
415
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
416
+ return "\n" + " ".repeat(index);
417
+ }),
418
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
419
+ return "\r" + " ".repeat(index);
420
+ }),
421
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
422
+ return "\r\n" + " ".repeat(index);
423
+ })
424
+ }
425
+ };
426
+ const supportedEols = [
427
+ "\n",
428
+ "\r",
429
+ "\r\n"
430
+ ];
431
+
432
+ //#endregion
433
+ //#region node_modules/jsonc-parser/lib/esm/impl/format.js
434
+ function format(documentText, range, options) {
435
+ let initialIndentLevel;
436
+ let formatText;
437
+ let formatTextStart;
438
+ let rangeStart;
439
+ let rangeEnd;
440
+ if (range) {
441
+ rangeStart = range.offset;
442
+ rangeEnd = rangeStart + range.length;
443
+ formatTextStart = rangeStart;
444
+ while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) formatTextStart--;
445
+ let endOffset = rangeEnd;
446
+ while (endOffset < documentText.length && !isEOL(documentText, endOffset)) endOffset++;
447
+ formatText = documentText.substring(formatTextStart, endOffset);
448
+ initialIndentLevel = computeIndentLevel(formatText, options);
449
+ } else {
450
+ formatText = documentText;
451
+ initialIndentLevel = 0;
452
+ formatTextStart = 0;
453
+ rangeStart = 0;
454
+ rangeEnd = documentText.length;
455
+ }
456
+ const eol = getEOL(options, documentText);
457
+ const eolFastPathSupported = supportedEols.includes(eol);
458
+ let numberLineBreaks = 0;
459
+ let indentLevel = 0;
460
+ let indentValue;
461
+ if (options.insertSpaces) indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);
462
+ else indentValue = " ";
463
+ const indentType = indentValue === " " ? " " : " ";
464
+ let scanner = createScanner(formatText, false);
465
+ let hasError = false;
466
+ function newLinesAndIndent() {
467
+ if (numberLineBreaks > 1) return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
468
+ const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);
469
+ if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) return eol + repeat(indentValue, initialIndentLevel + indentLevel);
470
+ if (amountOfSpaces <= 0) return eol;
471
+ return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];
472
+ }
473
+ function scanNext() {
474
+ let token = scanner.scan();
475
+ numberLineBreaks = 0;
476
+ while (token === 15 || token === 14) {
477
+ if (token === 14 && options.keepLines) numberLineBreaks += 1;
478
+ else if (token === 14) numberLineBreaks = 1;
479
+ token = scanner.scan();
480
+ }
481
+ hasError = token === 16 || scanner.getTokenError() !== 0;
482
+ return token;
483
+ }
484
+ const editOperations = [];
485
+ function addEdit(text, startOffset, endOffset) {
486
+ if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) editOperations.push({
487
+ offset: startOffset,
488
+ length: endOffset - startOffset,
489
+ content: text
490
+ });
491
+ }
492
+ let firstToken = scanNext();
493
+ if (options.keepLines && numberLineBreaks > 0) addEdit(repeat(eol, numberLineBreaks), 0, 0);
494
+ if (firstToken !== 17) {
495
+ let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
496
+ addEdit(indentValue.length * initialIndentLevel < 20 && options.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel), formatTextStart, firstTokenStart);
497
+ }
498
+ while (firstToken !== 17) {
499
+ let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
500
+ let secondToken = scanNext();
501
+ let replaceContent = "";
502
+ let needsLineBreak = false;
503
+ while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
504
+ let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
505
+ addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);
506
+ firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
507
+ needsLineBreak = secondToken === 12;
508
+ replaceContent = needsLineBreak ? newLinesAndIndent() : "";
509
+ secondToken = scanNext();
510
+ }
511
+ if (secondToken === 2) {
512
+ if (firstToken !== 1) indentLevel--;
513
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) replaceContent = newLinesAndIndent();
514
+ else if (options.keepLines) replaceContent = cachedSpaces[1];
515
+ } else if (secondToken === 4) {
516
+ if (firstToken !== 3) indentLevel--;
517
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) replaceContent = newLinesAndIndent();
518
+ else if (options.keepLines) replaceContent = cachedSpaces[1];
519
+ } else {
520
+ switch (firstToken) {
521
+ case 3:
522
+ case 1:
523
+ indentLevel++;
524
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent();
525
+ else replaceContent = cachedSpaces[1];
526
+ break;
527
+ case 5:
528
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent();
529
+ else replaceContent = cachedSpaces[1];
530
+ break;
531
+ case 12:
532
+ replaceContent = newLinesAndIndent();
533
+ break;
534
+ case 13:
535
+ if (numberLineBreaks > 0) replaceContent = newLinesAndIndent();
536
+ else if (!needsLineBreak) replaceContent = cachedSpaces[1];
537
+ break;
538
+ case 6:
539
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
540
+ else if (!needsLineBreak) replaceContent = cachedSpaces[1];
541
+ break;
542
+ case 10:
543
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
544
+ else if (secondToken === 6 && !needsLineBreak) replaceContent = "";
545
+ break;
546
+ case 7:
547
+ case 8:
548
+ case 9:
549
+ case 11:
550
+ case 2:
551
+ case 4:
552
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
553
+ else if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) replaceContent = cachedSpaces[1];
554
+ else if (secondToken !== 5 && secondToken !== 17) hasError = true;
555
+ break;
556
+ case 16: hasError = true;
557
+ }
558
+ if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) replaceContent = newLinesAndIndent();
559
+ }
560
+ if (secondToken === 17) {
561
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
562
+ else replaceContent = options.insertFinalNewline ? eol : "";
563
+ }
564
+ const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
565
+ addEdit(replaceContent, firstTokenEnd, secondTokenStart);
566
+ firstToken = secondToken;
567
+ }
568
+ return editOperations;
569
+ }
570
+ function repeat(s, count) {
571
+ let result = "";
572
+ for (let i = 0; i < count; i++) result += s;
573
+ return result;
574
+ }
575
+ function computeIndentLevel(content, options) {
576
+ let i = 0;
577
+ let nChars = 0;
578
+ const tabSize = options.tabSize || 4;
579
+ while (i < content.length) {
580
+ let ch = content.charAt(i);
581
+ if (ch === cachedSpaces[1]) nChars++;
582
+ else if (ch === " ") nChars += tabSize;
583
+ else break;
584
+ i++;
585
+ }
586
+ return Math.floor(nChars / tabSize);
587
+ }
588
+ function getEOL(options, text) {
589
+ for (let i = 0; i < text.length; i++) {
590
+ const ch = text.charAt(i);
591
+ if (ch === "\r") {
592
+ if (i + 1 < text.length && text.charAt(i + 1) === "\n") return "\r\n";
593
+ return "\r";
594
+ } else if (ch === "\n") return "\n";
595
+ }
596
+ return options && options.eol || "\n";
597
+ }
598
+ function isEOL(text, offset) {
599
+ return "\r\n".indexOf(text.charAt(offset)) !== -1;
600
+ }
601
+
602
+ //#endregion
603
+ //#region node_modules/jsonc-parser/lib/esm/impl/parser.js
604
+ var ParseOptions;
605
+ (function(ParseOptions) {
606
+ ParseOptions.DEFAULT = { allowTrailingComma: false };
607
+ })(ParseOptions || (ParseOptions = {}));
608
+ /**
609
+ * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
610
+ * Therefore always check the errors list to find out if the input was valid.
611
+ */
612
+ function parse$3(text, errors = [], options = ParseOptions.DEFAULT) {
613
+ let currentProperty = null;
614
+ let currentParent = [];
615
+ const previousParents = [];
616
+ function onValue(value) {
617
+ if (Array.isArray(currentParent)) currentParent.push(value);
618
+ else if (currentProperty !== null) currentParent[currentProperty] = value;
619
+ }
620
+ visit(text, {
621
+ onObjectBegin: () => {
622
+ const object = {};
623
+ onValue(object);
624
+ previousParents.push(currentParent);
625
+ currentParent = object;
626
+ currentProperty = null;
627
+ },
628
+ onObjectProperty: (name) => {
629
+ currentProperty = name;
630
+ },
631
+ onObjectEnd: () => {
632
+ currentParent = previousParents.pop();
633
+ },
634
+ onArrayBegin: () => {
635
+ const array = [];
636
+ onValue(array);
637
+ previousParents.push(currentParent);
638
+ currentParent = array;
639
+ currentProperty = null;
640
+ },
641
+ onArrayEnd: () => {
642
+ currentParent = previousParents.pop();
643
+ },
644
+ onLiteralValue: onValue,
645
+ onError: (error, offset, length) => {
646
+ errors.push({
647
+ error,
648
+ offset,
649
+ length
650
+ });
651
+ }
652
+ }, options);
653
+ return currentParent[0];
654
+ }
655
+ /**
656
+ * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
657
+ */
658
+ function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
659
+ let currentParent = {
660
+ type: "array",
661
+ offset: -1,
662
+ length: -1,
663
+ children: [],
664
+ parent: void 0
665
+ };
666
+ function ensurePropertyComplete(endOffset) {
667
+ if (currentParent.type === "property") {
668
+ currentParent.length = endOffset - currentParent.offset;
669
+ currentParent = currentParent.parent;
670
+ }
671
+ }
672
+ function onValue(valueNode) {
673
+ currentParent.children.push(valueNode);
674
+ return valueNode;
675
+ }
676
+ visit(text, {
677
+ onObjectBegin: (offset) => {
678
+ currentParent = onValue({
679
+ type: "object",
680
+ offset,
681
+ length: -1,
682
+ parent: currentParent,
683
+ children: []
684
+ });
685
+ },
686
+ onObjectProperty: (name, offset, length) => {
687
+ currentParent = onValue({
688
+ type: "property",
689
+ offset,
690
+ length: -1,
691
+ parent: currentParent,
692
+ children: []
693
+ });
694
+ currentParent.children.push({
695
+ type: "string",
696
+ value: name,
697
+ offset,
698
+ length,
699
+ parent: currentParent
700
+ });
701
+ },
702
+ onObjectEnd: (offset, length) => {
703
+ ensurePropertyComplete(offset + length);
704
+ currentParent.length = offset + length - currentParent.offset;
705
+ currentParent = currentParent.parent;
706
+ ensurePropertyComplete(offset + length);
707
+ },
708
+ onArrayBegin: (offset, length) => {
709
+ currentParent = onValue({
710
+ type: "array",
711
+ offset,
712
+ length: -1,
713
+ parent: currentParent,
714
+ children: []
715
+ });
716
+ },
717
+ onArrayEnd: (offset, length) => {
718
+ currentParent.length = offset + length - currentParent.offset;
719
+ currentParent = currentParent.parent;
720
+ ensurePropertyComplete(offset + length);
721
+ },
722
+ onLiteralValue: (value, offset, length) => {
723
+ onValue({
724
+ type: getNodeType(value),
725
+ offset,
726
+ length,
727
+ parent: currentParent,
728
+ value
729
+ });
730
+ ensurePropertyComplete(offset + length);
731
+ },
732
+ onSeparator: (sep, offset, length) => {
733
+ if (currentParent.type === "property") {
734
+ if (sep === ":") currentParent.colonOffset = offset;
735
+ else if (sep === ",") ensurePropertyComplete(offset);
736
+ }
737
+ },
738
+ onError: (error, offset, length) => {
739
+ errors.push({
740
+ error,
741
+ offset,
742
+ length
743
+ });
744
+ }
745
+ }, options);
746
+ const result = currentParent.children[0];
747
+ if (result) delete result.parent;
748
+ return result;
749
+ }
750
+ /**
751
+ * Finds the node at the given path in a JSON DOM.
752
+ */
753
+ function findNodeAtLocation(root, path) {
754
+ if (!root) return;
755
+ let node = root;
756
+ for (let segment of path) if (typeof segment === "string") {
757
+ if (node.type !== "object" || !Array.isArray(node.children)) return;
758
+ let found = false;
759
+ for (const propertyNode of node.children) if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
760
+ node = propertyNode.children[1];
761
+ found = true;
762
+ break;
763
+ }
764
+ if (!found) return;
765
+ } else {
766
+ const index = segment;
767
+ if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) return;
768
+ node = node.children[index];
769
+ }
770
+ return node;
771
+ }
772
+ /**
773
+ * Parses the given text and invokes the visitor functions for each object, array and literal reached.
774
+ */
775
+ function visit(text, visitor, options = ParseOptions.DEFAULT) {
776
+ const _scanner = createScanner(text, false);
777
+ const _jsonPath = [];
778
+ let suppressedCallbacks = 0;
779
+ function toNoArgVisit(visitFunction) {
780
+ return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
781
+ }
782
+ function toOneArgVisit(visitFunction) {
783
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
784
+ }
785
+ function toOneArgVisitWithPath(visitFunction) {
786
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
787
+ }
788
+ function toBeginVisit(visitFunction) {
789
+ return visitFunction ? () => {
790
+ if (suppressedCallbacks > 0) suppressedCallbacks++;
791
+ else if (visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) === false) suppressedCallbacks = 1;
792
+ } : () => true;
793
+ }
794
+ function toEndVisit(visitFunction) {
795
+ return visitFunction ? () => {
796
+ if (suppressedCallbacks > 0) suppressedCallbacks--;
797
+ if (suppressedCallbacks === 0) visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
798
+ } : () => true;
799
+ }
800
+ const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
801
+ const disallowComments = options && options.disallowComments;
802
+ const allowTrailingComma = options && options.allowTrailingComma;
803
+ function scanNext() {
804
+ while (true) {
805
+ const token = _scanner.scan();
806
+ switch (_scanner.getTokenError()) {
807
+ case 4:
808
+ handleError(14);
809
+ break;
810
+ case 5:
811
+ handleError(15);
812
+ break;
813
+ case 3:
814
+ handleError(13);
815
+ break;
816
+ case 1:
817
+ if (!disallowComments) handleError(11);
818
+ break;
819
+ case 2:
820
+ handleError(12);
821
+ break;
822
+ case 6: handleError(16);
823
+ }
824
+ switch (token) {
825
+ case 12:
826
+ case 13:
827
+ if (disallowComments) handleError(10);
828
+ else onComment();
829
+ break;
830
+ case 16:
831
+ handleError(1);
832
+ break;
833
+ case 15:
834
+ case 14: break;
835
+ default: return token;
836
+ }
837
+ }
838
+ }
839
+ function handleError(error, skipUntilAfter = [], skipUntil = []) {
840
+ onError(error);
841
+ if (skipUntilAfter.length + skipUntil.length > 0) {
842
+ let token = _scanner.getToken();
843
+ while (token !== 17) {
844
+ if (skipUntilAfter.indexOf(token) !== -1) {
845
+ scanNext();
846
+ break;
847
+ } else if (skipUntil.indexOf(token) !== -1) break;
848
+ token = scanNext();
849
+ }
850
+ }
851
+ }
852
+ function parseString(isValue) {
853
+ const value = _scanner.getTokenValue();
854
+ if (isValue) onLiteralValue(value);
855
+ else {
856
+ onObjectProperty(value);
857
+ _jsonPath.push(value);
858
+ }
859
+ scanNext();
860
+ return true;
861
+ }
862
+ function parseLiteral() {
863
+ switch (_scanner.getToken()) {
864
+ case 11:
865
+ const tokenValue = _scanner.getTokenValue();
866
+ let value = Number(tokenValue);
867
+ if (isNaN(value)) {
868
+ handleError(2);
869
+ value = 0;
870
+ }
871
+ onLiteralValue(value);
872
+ break;
873
+ case 7:
874
+ onLiteralValue(null);
875
+ break;
876
+ case 8:
877
+ onLiteralValue(true);
878
+ break;
879
+ case 9:
880
+ onLiteralValue(false);
881
+ break;
882
+ default: return false;
883
+ }
884
+ scanNext();
885
+ return true;
886
+ }
887
+ function parseProperty() {
888
+ if (_scanner.getToken() !== 10) {
889
+ handleError(3, [], [2, 5]);
890
+ return false;
891
+ }
892
+ parseString(false);
893
+ if (_scanner.getToken() === 6) {
894
+ onSeparator(":");
895
+ scanNext();
896
+ if (!parseValue()) handleError(4, [], [2, 5]);
897
+ } else handleError(5, [], [2, 5]);
898
+ _jsonPath.pop();
899
+ return true;
900
+ }
901
+ function parseObject() {
902
+ onObjectBegin();
903
+ scanNext();
904
+ let needsComma = false;
905
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
906
+ if (_scanner.getToken() === 5) {
907
+ if (!needsComma) handleError(4, [], []);
908
+ onSeparator(",");
909
+ scanNext();
910
+ if (_scanner.getToken() === 2 && allowTrailingComma) break;
911
+ } else if (needsComma) handleError(6, [], []);
912
+ if (!parseProperty()) handleError(4, [], [2, 5]);
913
+ needsComma = true;
914
+ }
915
+ onObjectEnd();
916
+ if (_scanner.getToken() !== 2) handleError(7, [2], []);
917
+ else scanNext();
918
+ return true;
919
+ }
920
+ function parseArray() {
921
+ onArrayBegin();
922
+ scanNext();
923
+ let isFirstElement = true;
924
+ let needsComma = false;
925
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
926
+ if (_scanner.getToken() === 5) {
927
+ if (!needsComma) handleError(4, [], []);
928
+ onSeparator(",");
929
+ scanNext();
930
+ if (_scanner.getToken() === 4 && allowTrailingComma) break;
931
+ } else if (needsComma) handleError(6, [], []);
932
+ if (isFirstElement) {
933
+ _jsonPath.push(0);
934
+ isFirstElement = false;
935
+ } else _jsonPath[_jsonPath.length - 1]++;
936
+ if (!parseValue()) handleError(4, [], [4, 5]);
937
+ needsComma = true;
938
+ }
939
+ onArrayEnd();
940
+ if (!isFirstElement) _jsonPath.pop();
941
+ if (_scanner.getToken() !== 4) handleError(8, [4], []);
942
+ else scanNext();
943
+ return true;
944
+ }
945
+ function parseValue() {
946
+ switch (_scanner.getToken()) {
947
+ case 3: return parseArray();
948
+ case 1: return parseObject();
949
+ case 10: return parseString(true);
950
+ default: return parseLiteral();
951
+ }
952
+ }
953
+ scanNext();
954
+ if (_scanner.getToken() === 17) {
955
+ if (options.allowEmptyContent) return true;
956
+ handleError(4, [], []);
957
+ return false;
958
+ }
959
+ if (!parseValue()) {
960
+ handleError(4, [], []);
961
+ return false;
962
+ }
963
+ if (_scanner.getToken() !== 17) handleError(9, [], []);
964
+ return true;
965
+ }
966
+ function getNodeType(value) {
967
+ switch (typeof value) {
968
+ case "boolean": return "boolean";
969
+ case "number": return "number";
970
+ case "string": return "string";
971
+ case "object":
972
+ if (!value) return "null";
973
+ else if (Array.isArray(value)) return "array";
974
+ return "object";
975
+ default: return "null";
976
+ }
977
+ }
978
+
979
+ //#endregion
980
+ //#region node_modules/jsonc-parser/lib/esm/impl/edit.js
981
+ function setProperty(text, originalPath, value, options) {
982
+ const path = originalPath.slice();
983
+ const root = parseTree(text, []);
984
+ let parent = void 0;
985
+ let lastSegment = void 0;
986
+ while (path.length > 0) {
987
+ lastSegment = path.pop();
988
+ parent = findNodeAtLocation(root, path);
989
+ if (parent === void 0 && value !== void 0) {
990
+ if (typeof lastSegment === "string") value = { [lastSegment]: value };
991
+ else value = [value];
992
+ } else break;
993
+ }
994
+ if (!parent) {
995
+ if (value === void 0) throw new Error("Can not delete in empty document");
996
+ return withFormatting(text, {
997
+ offset: root ? root.offset : 0,
998
+ length: root ? root.length : 0,
999
+ content: JSON.stringify(value)
1000
+ }, options);
1001
+ } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
1002
+ const existing = findNodeAtLocation(parent, [lastSegment]);
1003
+ if (existing !== void 0) {
1004
+ if (value === void 0) {
1005
+ if (!existing.parent) throw new Error("Malformed AST");
1006
+ const propertyIndex = parent.children.indexOf(existing.parent);
1007
+ let removeBegin;
1008
+ let removeEnd = existing.parent.offset + existing.parent.length;
1009
+ if (propertyIndex > 0) {
1010
+ let previous = parent.children[propertyIndex - 1];
1011
+ removeBegin = previous.offset + previous.length;
1012
+ } else {
1013
+ removeBegin = parent.offset + 1;
1014
+ if (parent.children.length > 1) removeEnd = parent.children[1].offset;
1015
+ }
1016
+ return withFormatting(text, {
1017
+ offset: removeBegin,
1018
+ length: removeEnd - removeBegin,
1019
+ content: ""
1020
+ }, options);
1021
+ } else return withFormatting(text, {
1022
+ offset: existing.offset,
1023
+ length: existing.length,
1024
+ content: JSON.stringify(value)
1025
+ }, options);
1026
+ } else {
1027
+ if (value === void 0) return [];
1028
+ const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
1029
+ const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
1030
+ let edit;
1031
+ if (index > 0) {
1032
+ let previous = parent.children[index - 1];
1033
+ edit = {
1034
+ offset: previous.offset + previous.length,
1035
+ length: 0,
1036
+ content: "," + newProperty
1037
+ };
1038
+ } else if (parent.children.length === 0) edit = {
1039
+ offset: parent.offset + 1,
1040
+ length: 0,
1041
+ content: newProperty
1042
+ };
1043
+ else edit = {
1044
+ offset: parent.offset + 1,
1045
+ length: 0,
1046
+ content: newProperty + ","
1047
+ };
1048
+ return withFormatting(text, edit, options);
1049
+ }
1050
+ } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
1051
+ const insertIndex = lastSegment;
1052
+ if (insertIndex === -1) {
1053
+ const newProperty = `${JSON.stringify(value)}`;
1054
+ let edit;
1055
+ if (parent.children.length === 0) edit = {
1056
+ offset: parent.offset + 1,
1057
+ length: 0,
1058
+ content: newProperty
1059
+ };
1060
+ else {
1061
+ const previous = parent.children[parent.children.length - 1];
1062
+ edit = {
1063
+ offset: previous.offset + previous.length,
1064
+ length: 0,
1065
+ content: "," + newProperty
1066
+ };
1067
+ }
1068
+ return withFormatting(text, edit, options);
1069
+ } else if (value === void 0 && parent.children.length >= 0) {
1070
+ const removalIndex = lastSegment;
1071
+ const toRemove = parent.children[removalIndex];
1072
+ let edit;
1073
+ if (parent.children.length === 1) edit = {
1074
+ offset: parent.offset + 1,
1075
+ length: parent.length - 2,
1076
+ content: ""
1077
+ };
1078
+ else if (parent.children.length - 1 === removalIndex) {
1079
+ let previous = parent.children[removalIndex - 1];
1080
+ let offset = previous.offset + previous.length;
1081
+ edit = {
1082
+ offset,
1083
+ length: parent.offset + parent.length - 2 - offset,
1084
+ content: ""
1085
+ };
1086
+ } else edit = {
1087
+ offset: toRemove.offset,
1088
+ length: parent.children[removalIndex + 1].offset - toRemove.offset,
1089
+ content: ""
1090
+ };
1091
+ return withFormatting(text, edit, options);
1092
+ } else if (value !== void 0) {
1093
+ let edit;
1094
+ const newProperty = `${JSON.stringify(value)}`;
1095
+ if (!options.isArrayInsertion && parent.children.length > lastSegment) {
1096
+ const toModify = parent.children[lastSegment];
1097
+ edit = {
1098
+ offset: toModify.offset,
1099
+ length: toModify.length,
1100
+ content: newProperty
1101
+ };
1102
+ } else if (parent.children.length === 0 || lastSegment === 0) edit = {
1103
+ offset: parent.offset + 1,
1104
+ length: 0,
1105
+ content: parent.children.length === 0 ? newProperty : newProperty + ","
1106
+ };
1107
+ else {
1108
+ const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
1109
+ const previous = parent.children[index - 1];
1110
+ edit = {
1111
+ offset: previous.offset + previous.length,
1112
+ length: 0,
1113
+ content: "," + newProperty
1114
+ };
1115
+ }
1116
+ return withFormatting(text, edit, options);
1117
+ } else throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
1118
+ } else throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
1119
+ }
1120
+ function withFormatting(text, edit, options) {
1121
+ if (!options.formattingOptions) return [edit];
1122
+ let newText = applyEdit(text, edit);
1123
+ let begin = edit.offset;
1124
+ let end = edit.offset + edit.content.length;
1125
+ if (edit.length === 0 || edit.content.length === 0) {
1126
+ while (begin > 0 && !isEOL(newText, begin - 1)) begin--;
1127
+ while (end < newText.length && !isEOL(newText, end)) end++;
1128
+ }
1129
+ const edits = format(newText, {
1130
+ offset: begin,
1131
+ length: end - begin
1132
+ }, {
1133
+ ...options.formattingOptions,
1134
+ keepLines: false
1135
+ });
1136
+ for (let i = edits.length - 1; i >= 0; i--) {
1137
+ const edit = edits[i];
1138
+ newText = applyEdit(newText, edit);
1139
+ begin = Math.min(begin, edit.offset);
1140
+ end = Math.max(end, edit.offset + edit.length);
1141
+ end += edit.content.length - edit.length;
1142
+ }
1143
+ const editLength = text.length - (newText.length - end) - begin;
1144
+ return [{
1145
+ offset: begin,
1146
+ length: editLength,
1147
+ content: newText.substring(begin, end)
1148
+ }];
1149
+ }
1150
+ function applyEdit(text, edit) {
1151
+ return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
1152
+ }
1153
+
1154
+ //#endregion
1155
+ //#region node_modules/jsonc-parser/lib/esm/main.js
1156
+ var ScanError;
1157
+ (function(ScanError) {
1158
+ ScanError[ScanError["None"] = 0] = "None";
1159
+ ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
1160
+ ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
1161
+ ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
1162
+ ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode";
1163
+ ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
1164
+ ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter";
1165
+ })(ScanError || (ScanError = {}));
1166
+ var SyntaxKind;
1167
+ (function(SyntaxKind) {
1168
+ SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken";
1169
+ SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken";
1170
+ SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken";
1171
+ SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken";
1172
+ SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken";
1173
+ SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken";
1174
+ SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword";
1175
+ SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword";
1176
+ SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword";
1177
+ SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
1178
+ SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral";
1179
+ SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia";
1180
+ SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
1181
+ SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia";
1182
+ SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia";
1183
+ SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown";
1184
+ SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF";
1185
+ })(SyntaxKind || (SyntaxKind = {}));
1186
+ /**
1187
+ * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
1188
+ * Therefore, always check the errors list to find out if the input was valid.
1189
+ */
1190
+ const parse$2 = parse$3;
1191
+ var ParseErrorCode;
1192
+ (function(ParseErrorCode) {
1193
+ ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol";
1194
+ ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
1195
+ ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected";
1196
+ ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected";
1197
+ ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected";
1198
+ ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected";
1199
+ ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected";
1200
+ ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected";
1201
+ ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected";
1202
+ ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken";
1203
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
1204
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
1205
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
1206
+ ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode";
1207
+ ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
1208
+ ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter";
1209
+ })(ParseErrorCode || (ParseErrorCode = {}));
1210
+ /**
1211
+ * Computes the edit operations needed to modify a value in the JSON document.
1212
+ *
1213
+ * @param documentText The input text
1214
+ * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
1215
+ * If the path points to an non-existing property or item, it will be created.
1216
+ * @param value The new value for the specified property or item. If the value is undefined,
1217
+ * the property or item will be removed.
1218
+ * @param options Options
1219
+ * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.
1220
+ * To apply the edit operations to the input, use {@linkcode applyEdits}.
1221
+ */
1222
+ function modify(text, path, value, options) {
1223
+ return setProperty(text, path, value, options);
1224
+ }
1225
+ /**
1226
+ * Applies edits to an input string.
1227
+ * @param text The input text
1228
+ * @param edits Edit operations following the format described in {@linkcode EditResult}.
1229
+ * @returns The text with the applied edits.
1230
+ * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.
1231
+ */
1232
+ function applyEdits(text, edits) {
1233
+ let sortedEdits = edits.slice(0).sort((a, b) => {
1234
+ const diff = a.offset - b.offset;
1235
+ if (diff === 0) return a.length - b.length;
1236
+ return diff;
1237
+ });
1238
+ let lastModifiedOffset = text.length;
1239
+ for (let i = sortedEdits.length - 1; i >= 0; i--) {
1240
+ let e = sortedEdits[i];
1241
+ if (e.offset + e.length <= lastModifiedOffset) text = applyEdit(text, e);
1242
+ else throw new Error("Overlapping edit");
1243
+ lastModifiedOffset = e.offset;
1244
+ }
1245
+ return text;
1246
+ }
1247
+
1248
+ //#endregion
1249
+ //#region node_modules/smol-toml/dist/error.js
1250
+ /*!
1251
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1252
+ * SPDX-License-Identifier: BSD-3-Clause
1253
+ *
1254
+ * Redistribution and use in source and binary forms, with or without
1255
+ * modification, are permitted provided that the following conditions are met:
1256
+ *
1257
+ * 1. Redistributions of source code must retain the above copyright notice, this
1258
+ * list of conditions and the following disclaimer.
1259
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1260
+ * this list of conditions and the following disclaimer in the
1261
+ * documentation and/or other materials provided with the distribution.
1262
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1263
+ * may be used to endorse or promote products derived from this software without
1264
+ * specific prior written permission.
1265
+ *
1266
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1267
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1268
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1269
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1270
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1271
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1272
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1273
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1274
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1275
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1276
+ */
1277
+ function getLineColFromPtr(string, ptr) {
1278
+ let lines = string.slice(0, ptr).split(/\r\n|\n|\r/g);
1279
+ return [lines.length, lines.pop().length + 1];
1280
+ }
1281
+ function makeCodeBlock(string, line, column) {
1282
+ let lines = string.split(/\r\n|\n|\r/g);
1283
+ let codeblock = "";
1284
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
1285
+ for (let i = line - 1; i <= line + 1; i++) {
1286
+ let l = lines[i - 1];
1287
+ if (!l) continue;
1288
+ codeblock += i.toString().padEnd(numberLen, " ");
1289
+ codeblock += ": ";
1290
+ codeblock += l;
1291
+ codeblock += "\n";
1292
+ if (i === line) {
1293
+ codeblock += " ".repeat(numberLen + column + 2);
1294
+ codeblock += "^\n";
1295
+ }
1296
+ }
1297
+ return codeblock;
1298
+ }
1299
+ var TomlError = class extends Error {
1300
+ line;
1301
+ column;
1302
+ codeblock;
1303
+ constructor(message, options) {
1304
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
1305
+ const codeblock = makeCodeBlock(options.toml, line, column);
1306
+ super(`Invalid TOML document: ${message}\n\n${codeblock}`, options);
1307
+ this.line = line;
1308
+ this.column = column;
1309
+ this.codeblock = codeblock;
1310
+ }
1311
+ };
1312
+
1313
+ //#endregion
1314
+ //#region node_modules/smol-toml/dist/util.js
1315
+ /*!
1316
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1317
+ * SPDX-License-Identifier: BSD-3-Clause
1318
+ *
1319
+ * Redistribution and use in source and binary forms, with or without
1320
+ * modification, are permitted provided that the following conditions are met:
1321
+ *
1322
+ * 1. Redistributions of source code must retain the above copyright notice, this
1323
+ * list of conditions and the following disclaimer.
1324
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1325
+ * this list of conditions and the following disclaimer in the
1326
+ * documentation and/or other materials provided with the distribution.
1327
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1328
+ * may be used to endorse or promote products derived from this software without
1329
+ * specific prior written permission.
1330
+ *
1331
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1332
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1333
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1334
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1335
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1336
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1337
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1338
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1339
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1340
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1341
+ */
1342
+ function isEscaped(str, ptr) {
1343
+ let i = 0;
1344
+ while (str[ptr - ++i] === "\\");
1345
+ return --i && i % 2;
1346
+ }
1347
+ function indexOfNewline(str, start = 0, end = str.length) {
1348
+ let idx = str.indexOf("\n", start);
1349
+ if (str[idx - 1] === "\r") idx--;
1350
+ return idx <= end ? idx : -1;
1351
+ }
1352
+ function skipComment(str, ptr) {
1353
+ for (let i = ptr; i < str.length; i++) {
1354
+ let c = str[i];
1355
+ if (c === "\n") return i;
1356
+ if (c === "\r" && str[i + 1] === "\n") return i + 1;
1357
+ if (c < " " && c !== " " || c === "") throw new TomlError("control characters are not allowed in comments", {
1358
+ toml: str,
1359
+ ptr
1360
+ });
1361
+ }
1362
+ return str.length;
1363
+ }
1364
+ function skipVoid(str, ptr, banNewLines, banComments) {
1365
+ let c;
1366
+ while ((c = str[ptr]) === " " || c === " " || !banNewLines && (c === "\n" || c === "\r" && str[ptr + 1] === "\n")) ptr++;
1367
+ return banComments || c !== "#" ? ptr : skipVoid(str, skipComment(str, ptr), banNewLines);
1368
+ }
1369
+ function skipUntil(str, ptr, sep, end, banNewLines = false) {
1370
+ if (!end) {
1371
+ ptr = indexOfNewline(str, ptr);
1372
+ return ptr < 0 ? str.length : ptr;
1373
+ }
1374
+ for (let i = ptr; i < str.length; i++) {
1375
+ let c = str[i];
1376
+ if (c === "#") i = indexOfNewline(str, i);
1377
+ else if (c === sep) return i + 1;
1378
+ else if (c === end || banNewLines && (c === "\n" || c === "\r" && str[i + 1] === "\n")) return i;
1379
+ }
1380
+ throw new TomlError("cannot find end of structure", {
1381
+ toml: str,
1382
+ ptr
1383
+ });
1384
+ }
1385
+ function getStringEnd(str, seek) {
1386
+ let first = str[seek];
1387
+ let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2] ? str.slice(seek, seek + 3) : first;
1388
+ seek += target.length - 1;
1389
+ do
1390
+ seek = str.indexOf(target, ++seek);
1391
+ while (seek > -1 && first !== "'" && isEscaped(str, seek));
1392
+ if (seek > -1) {
1393
+ seek += target.length;
1394
+ if (target.length > 1) {
1395
+ if (str[seek] === first) seek++;
1396
+ if (str[seek] === first) seek++;
1397
+ }
1398
+ }
1399
+ return seek;
1400
+ }
1401
+
1402
+ //#endregion
1403
+ //#region node_modules/smol-toml/dist/date.js
1404
+ /*!
1405
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1406
+ * SPDX-License-Identifier: BSD-3-Clause
1407
+ *
1408
+ * Redistribution and use in source and binary forms, with or without
1409
+ * modification, are permitted provided that the following conditions are met:
1410
+ *
1411
+ * 1. Redistributions of source code must retain the above copyright notice, this
1412
+ * list of conditions and the following disclaimer.
1413
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1414
+ * this list of conditions and the following disclaimer in the
1415
+ * documentation and/or other materials provided with the distribution.
1416
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1417
+ * may be used to endorse or promote products derived from this software without
1418
+ * specific prior written permission.
1419
+ *
1420
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1421
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1422
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1423
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1424
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1425
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1426
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1427
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1428
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1429
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1430
+ */
1431
+ let DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}:\d{2}(?:\.\d+)?)?(Z|[-+]\d{2}:\d{2})?$/i;
1432
+ var TomlDate = class TomlDate extends Date {
1433
+ #hasDate = false;
1434
+ #hasTime = false;
1435
+ #offset = null;
1436
+ constructor(date) {
1437
+ let hasDate = true;
1438
+ let hasTime = true;
1439
+ let offset = "Z";
1440
+ if (typeof date === "string") {
1441
+ let match = date.match(DATE_TIME_RE);
1442
+ if (match) {
1443
+ if (!match[1]) {
1444
+ hasDate = false;
1445
+ date = `0000-01-01T${date}`;
1446
+ }
1447
+ hasTime = !!match[2];
1448
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
1449
+ if (match[2] && +match[2] > 23) date = "";
1450
+ else {
1451
+ offset = match[3] || null;
1452
+ date = date.toUpperCase();
1453
+ if (!offset && hasTime) date += "Z";
1454
+ }
1455
+ } else date = "";
1456
+ }
1457
+ super(date);
1458
+ if (!isNaN(this.getTime())) {
1459
+ this.#hasDate = hasDate;
1460
+ this.#hasTime = hasTime;
1461
+ this.#offset = offset;
1462
+ }
1463
+ }
1464
+ isDateTime() {
1465
+ return this.#hasDate && this.#hasTime;
1466
+ }
1467
+ isLocal() {
1468
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
1469
+ }
1470
+ isDate() {
1471
+ return this.#hasDate && !this.#hasTime;
1472
+ }
1473
+ isTime() {
1474
+ return this.#hasTime && !this.#hasDate;
1475
+ }
1476
+ isValid() {
1477
+ return this.#hasDate || this.#hasTime;
1478
+ }
1479
+ toISOString() {
1480
+ let iso = super.toISOString();
1481
+ if (this.isDate()) return iso.slice(0, 10);
1482
+ if (this.isTime()) return iso.slice(11, 23);
1483
+ if (this.#offset === null) return iso.slice(0, -1);
1484
+ if (this.#offset === "Z") return iso;
1485
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
1486
+ offset = this.#offset[0] === "-" ? offset : -offset;
1487
+ return (/* @__PURE__ */ new Date(this.getTime() - offset * 6e4)).toISOString().slice(0, -1) + this.#offset;
1488
+ }
1489
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
1490
+ let date = new TomlDate(jsDate);
1491
+ date.#offset = offset;
1492
+ return date;
1493
+ }
1494
+ static wrapAsLocalDateTime(jsDate) {
1495
+ let date = new TomlDate(jsDate);
1496
+ date.#offset = null;
1497
+ return date;
1498
+ }
1499
+ static wrapAsLocalDate(jsDate) {
1500
+ let date = new TomlDate(jsDate);
1501
+ date.#hasTime = false;
1502
+ date.#offset = null;
1503
+ return date;
1504
+ }
1505
+ static wrapAsLocalTime(jsDate) {
1506
+ let date = new TomlDate(jsDate);
1507
+ date.#hasDate = false;
1508
+ date.#offset = null;
1509
+ return date;
1510
+ }
1511
+ };
1512
+
1513
+ //#endregion
1514
+ //#region node_modules/smol-toml/dist/primitive.js
1515
+ /*!
1516
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1517
+ * SPDX-License-Identifier: BSD-3-Clause
1518
+ *
1519
+ * Redistribution and use in source and binary forms, with or without
1520
+ * modification, are permitted provided that the following conditions are met:
1521
+ *
1522
+ * 1. Redistributions of source code must retain the above copyright notice, this
1523
+ * list of conditions and the following disclaimer.
1524
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1525
+ * this list of conditions and the following disclaimer in the
1526
+ * documentation and/or other materials provided with the distribution.
1527
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1528
+ * may be used to endorse or promote products derived from this software without
1529
+ * specific prior written permission.
1530
+ *
1531
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1532
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1533
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1534
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1535
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1536
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1537
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1538
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1539
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1540
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1541
+ */
1542
+ let INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/;
1543
+ let FLOAT_REGEX = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/;
1544
+ let LEADING_ZERO = /^[+-]?0[0-9_]/;
1545
+ let ESCAPE_REGEX = /^[0-9a-f]{4,8}$/i;
1546
+ let ESC_MAP = {
1547
+ b: "\b",
1548
+ t: " ",
1549
+ n: "\n",
1550
+ f: "\f",
1551
+ r: "\r",
1552
+ "\"": "\"",
1553
+ "\\": "\\"
1554
+ };
1555
+ function parseString(str, ptr = 0, endPtr = str.length) {
1556
+ let isLiteral = str[ptr] === "'";
1557
+ let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];
1558
+ if (isMultiline) {
1559
+ endPtr -= 2;
1560
+ if (str[ptr += 2] === "\r") ptr++;
1561
+ if (str[ptr] === "\n") ptr++;
1562
+ }
1563
+ let tmp = 0;
1564
+ let isEscape;
1565
+ let parsed = "";
1566
+ let sliceStart = ptr;
1567
+ while (ptr < endPtr - 1) {
1568
+ let c = str[ptr++];
1569
+ if (c === "\n" || c === "\r" && str[ptr] === "\n") {
1570
+ if (!isMultiline) throw new TomlError("newlines are not allowed in strings", {
1571
+ toml: str,
1572
+ ptr: ptr - 1
1573
+ });
1574
+ } else if (c < " " && c !== " " || c === "") throw new TomlError("control characters are not allowed in strings", {
1575
+ toml: str,
1576
+ ptr: ptr - 1
1577
+ });
1578
+ if (isEscape) {
1579
+ isEscape = false;
1580
+ if (c === "u" || c === "U") {
1581
+ let code = str.slice(ptr, ptr += c === "u" ? 4 : 8);
1582
+ if (!ESCAPE_REGEX.test(code)) throw new TomlError("invalid unicode escape", {
1583
+ toml: str,
1584
+ ptr: tmp
1585
+ });
1586
+ try {
1587
+ parsed += String.fromCodePoint(parseInt(code, 16));
1588
+ } catch {
1589
+ throw new TomlError("invalid unicode escape", {
1590
+ toml: str,
1591
+ ptr: tmp
1592
+ });
1593
+ }
1594
+ } else if (isMultiline && (c === "\n" || c === " " || c === " " || c === "\r")) {
1595
+ ptr = skipVoid(str, ptr - 1, true);
1596
+ if (str[ptr] !== "\n" && str[ptr] !== "\r") throw new TomlError("invalid escape: only line-ending whitespace may be escaped", {
1597
+ toml: str,
1598
+ ptr: tmp
1599
+ });
1600
+ ptr = skipVoid(str, ptr);
1601
+ } else if (c in ESC_MAP) parsed += ESC_MAP[c];
1602
+ else throw new TomlError("unrecognized escape sequence", {
1603
+ toml: str,
1604
+ ptr: tmp
1605
+ });
1606
+ sliceStart = ptr;
1607
+ } else if (!isLiteral && c === "\\") {
1608
+ tmp = ptr - 1;
1609
+ isEscape = true;
1610
+ parsed += str.slice(sliceStart, tmp);
1611
+ }
1612
+ }
1613
+ return parsed + str.slice(sliceStart, endPtr - 1);
1614
+ }
1615
+ function parseValue(value, toml, ptr, integersAsBigInt) {
1616
+ if (value === "true") return true;
1617
+ if (value === "false") return false;
1618
+ if (value === "-inf") return -Infinity;
1619
+ if (value === "inf" || value === "+inf") return Infinity;
1620
+ if (value === "nan" || value === "+nan" || value === "-nan") return NaN;
1621
+ if (value === "-0") return integersAsBigInt ? 0n : 0;
1622
+ let isInt = INT_REGEX.test(value);
1623
+ if (isInt || FLOAT_REGEX.test(value)) {
1624
+ if (LEADING_ZERO.test(value)) throw new TomlError("leading zeroes are not allowed", {
1625
+ toml,
1626
+ ptr
1627
+ });
1628
+ value = value.replace(/_/g, "");
1629
+ let numeric = +value;
1630
+ if (isNaN(numeric)) throw new TomlError("invalid number", {
1631
+ toml,
1632
+ ptr
1633
+ });
1634
+ if (isInt) {
1635
+ if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) throw new TomlError("integer value cannot be represented losslessly", {
1636
+ toml,
1637
+ ptr
1638
+ });
1639
+ if (isInt || integersAsBigInt === true) numeric = BigInt(value);
1640
+ }
1641
+ return numeric;
1642
+ }
1643
+ const date = new TomlDate(value);
1644
+ if (!date.isValid()) throw new TomlError("invalid value", {
1645
+ toml,
1646
+ ptr
1647
+ });
1648
+ return date;
1649
+ }
1650
+
1651
+ //#endregion
1652
+ //#region node_modules/smol-toml/dist/extract.js
1653
+ /*!
1654
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1655
+ * SPDX-License-Identifier: BSD-3-Clause
1656
+ *
1657
+ * Redistribution and use in source and binary forms, with or without
1658
+ * modification, are permitted provided that the following conditions are met:
1659
+ *
1660
+ * 1. Redistributions of source code must retain the above copyright notice, this
1661
+ * list of conditions and the following disclaimer.
1662
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1663
+ * this list of conditions and the following disclaimer in the
1664
+ * documentation and/or other materials provided with the distribution.
1665
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1666
+ * may be used to endorse or promote products derived from this software without
1667
+ * specific prior written permission.
1668
+ *
1669
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1670
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1671
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1672
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1673
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1674
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1675
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1676
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1677
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1678
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1679
+ */
1680
+ function sliceAndTrimEndOf(str, startPtr, endPtr, allowNewLines) {
1681
+ let value = str.slice(startPtr, endPtr);
1682
+ let commentIdx = value.indexOf("#");
1683
+ if (commentIdx > -1) {
1684
+ skipComment(str, commentIdx);
1685
+ value = value.slice(0, commentIdx);
1686
+ }
1687
+ let trimmed = value.trimEnd();
1688
+ if (!allowNewLines) {
1689
+ let newlineIdx = value.indexOf("\n", trimmed.length);
1690
+ if (newlineIdx > -1) throw new TomlError("newlines are not allowed in inline tables", {
1691
+ toml: str,
1692
+ ptr: startPtr + newlineIdx
1693
+ });
1694
+ }
1695
+ return [trimmed, commentIdx];
1696
+ }
1697
+ function extractValue(str, ptr, end, depth, integersAsBigInt) {
1698
+ if (depth === 0) throw new TomlError("document contains excessively nested structures. aborting.", {
1699
+ toml: str,
1700
+ ptr
1701
+ });
1702
+ let c = str[ptr];
1703
+ if (c === "[" || c === "{") {
1704
+ let [value, endPtr] = c === "[" ? parseArray(str, ptr, depth, integersAsBigInt) : parseInlineTable(str, ptr, depth, integersAsBigInt);
1705
+ let newPtr = end ? skipUntil(str, endPtr, ",", end) : endPtr;
1706
+ if (endPtr - newPtr && end === "}") {
1707
+ let nextNewLine = indexOfNewline(str, endPtr, newPtr);
1708
+ if (nextNewLine > -1) throw new TomlError("newlines are not allowed in inline tables", {
1709
+ toml: str,
1710
+ ptr: nextNewLine
1711
+ });
1712
+ }
1713
+ return [value, newPtr];
1714
+ }
1715
+ let endPtr;
1716
+ if (c === "\"" || c === "'") {
1717
+ endPtr = getStringEnd(str, ptr);
1718
+ let parsed = parseString(str, ptr, endPtr);
1719
+ if (end) {
1720
+ endPtr = skipVoid(str, endPtr, end !== "]");
1721
+ if (str[endPtr] && str[endPtr] !== "," && str[endPtr] !== end && str[endPtr] !== "\n" && str[endPtr] !== "\r") throw new TomlError("unexpected character encountered", {
1722
+ toml: str,
1723
+ ptr: endPtr
1724
+ });
1725
+ endPtr += +(str[endPtr] === ",");
1726
+ }
1727
+ return [parsed, endPtr];
1728
+ }
1729
+ endPtr = skipUntil(str, ptr, ",", end);
1730
+ let slice = sliceAndTrimEndOf(str, ptr, endPtr - +(str[endPtr - 1] === ","), end === "]");
1731
+ if (!slice[0]) throw new TomlError("incomplete key-value declaration: no value specified", {
1732
+ toml: str,
1733
+ ptr
1734
+ });
1735
+ if (end && slice[1] > -1) {
1736
+ endPtr = skipVoid(str, ptr + slice[1]);
1737
+ endPtr += +(str[endPtr] === ",");
1738
+ }
1739
+ return [parseValue(slice[0], str, ptr, integersAsBigInt), endPtr];
1740
+ }
1741
+
1742
+ //#endregion
1743
+ //#region node_modules/smol-toml/dist/struct.js
1744
+ /*!
1745
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1746
+ * SPDX-License-Identifier: BSD-3-Clause
1747
+ *
1748
+ * Redistribution and use in source and binary forms, with or without
1749
+ * modification, are permitted provided that the following conditions are met:
1750
+ *
1751
+ * 1. Redistributions of source code must retain the above copyright notice, this
1752
+ * list of conditions and the following disclaimer.
1753
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1754
+ * this list of conditions and the following disclaimer in the
1755
+ * documentation and/or other materials provided with the distribution.
1756
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1757
+ * may be used to endorse or promote products derived from this software without
1758
+ * specific prior written permission.
1759
+ *
1760
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1761
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1762
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1763
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1764
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1765
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1766
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1767
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1768
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1769
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1770
+ */
1771
+ let KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \t]*$/;
1772
+ function parseKey(str, ptr, end = "=") {
1773
+ let dot = ptr - 1;
1774
+ let parsed = [];
1775
+ let endPtr = str.indexOf(end, ptr);
1776
+ if (endPtr < 0) throw new TomlError("incomplete key-value: cannot find end of key", {
1777
+ toml: str,
1778
+ ptr
1779
+ });
1780
+ do {
1781
+ let c = str[ptr = ++dot];
1782
+ if (c !== " " && c !== " ") {
1783
+ if (c === "\"" || c === "'") {
1784
+ if (c === str[ptr + 1] && c === str[ptr + 2]) throw new TomlError("multiline strings are not allowed in keys", {
1785
+ toml: str,
1786
+ ptr
1787
+ });
1788
+ let eos = getStringEnd(str, ptr);
1789
+ if (eos < 0) throw new TomlError("unfinished string encountered", {
1790
+ toml: str,
1791
+ ptr
1792
+ });
1793
+ dot = str.indexOf(".", eos);
1794
+ let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);
1795
+ let newLine = indexOfNewline(strEnd);
1796
+ if (newLine > -1) throw new TomlError("newlines are not allowed in keys", {
1797
+ toml: str,
1798
+ ptr: ptr + dot + newLine
1799
+ });
1800
+ if (strEnd.trimStart()) throw new TomlError("found extra tokens after the string part", {
1801
+ toml: str,
1802
+ ptr: eos
1803
+ });
1804
+ if (endPtr < eos) {
1805
+ endPtr = str.indexOf(end, eos);
1806
+ if (endPtr < 0) throw new TomlError("incomplete key-value: cannot find end of key", {
1807
+ toml: str,
1808
+ ptr
1809
+ });
1810
+ }
1811
+ parsed.push(parseString(str, ptr, eos));
1812
+ } else {
1813
+ dot = str.indexOf(".", ptr);
1814
+ let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);
1815
+ if (!KEY_PART_RE.test(part)) throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys", {
1816
+ toml: str,
1817
+ ptr
1818
+ });
1819
+ parsed.push(part.trimEnd());
1820
+ }
1821
+ }
1822
+ } while (dot + 1 && dot < endPtr);
1823
+ return [parsed, skipVoid(str, endPtr + 1, true, true)];
1824
+ }
1825
+ function parseInlineTable(str, ptr, depth, integersAsBigInt) {
1826
+ let res = {};
1827
+ let seen = /* @__PURE__ */ new Set();
1828
+ let c;
1829
+ let comma = 0;
1830
+ ptr++;
1831
+ while ((c = str[ptr++]) !== "}" && c) {
1832
+ let err = {
1833
+ toml: str,
1834
+ ptr: ptr - 1
1835
+ };
1836
+ if (c === "\n") throw new TomlError("newlines are not allowed in inline tables", err);
1837
+ else if (c === "#") throw new TomlError("inline tables cannot contain comments", err);
1838
+ else if (c === ",") throw new TomlError("expected key-value, found comma", err);
1839
+ else if (c !== " " && c !== " ") {
1840
+ let k;
1841
+ let t = res;
1842
+ let hasOwn = false;
1843
+ let [key, keyEndPtr] = parseKey(str, ptr - 1);
1844
+ for (let i = 0; i < key.length; i++) {
1845
+ if (i) t = hasOwn ? t[k] : t[k] = {};
1846
+ k = key[i];
1847
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) throw new TomlError("trying to redefine an already defined value", {
1848
+ toml: str,
1849
+ ptr
1850
+ });
1851
+ if (!hasOwn && k === "__proto__") Object.defineProperty(t, k, {
1852
+ enumerable: true,
1853
+ configurable: true,
1854
+ writable: true
1855
+ });
1856
+ }
1857
+ if (hasOwn) throw new TomlError("trying to redefine an already defined value", {
1858
+ toml: str,
1859
+ ptr
1860
+ });
1861
+ let [value, valueEndPtr] = extractValue(str, keyEndPtr, "}", depth - 1, integersAsBigInt);
1862
+ seen.add(value);
1863
+ t[k] = value;
1864
+ ptr = valueEndPtr;
1865
+ comma = str[ptr - 1] === "," ? ptr - 1 : 0;
1866
+ }
1867
+ }
1868
+ if (comma) throw new TomlError("trailing commas are not allowed in inline tables", {
1869
+ toml: str,
1870
+ ptr: comma
1871
+ });
1872
+ if (!c) throw new TomlError("unfinished table encountered", {
1873
+ toml: str,
1874
+ ptr
1875
+ });
1876
+ return [res, ptr];
1877
+ }
1878
+ function parseArray(str, ptr, depth, integersAsBigInt) {
1879
+ let res = [];
1880
+ let c;
1881
+ ptr++;
1882
+ while ((c = str[ptr++]) !== "]" && c) if (c === ",") throw new TomlError("expected value, found comma", {
1883
+ toml: str,
1884
+ ptr: ptr - 1
1885
+ });
1886
+ else if (c === "#") ptr = skipComment(str, ptr);
1887
+ else if (c !== " " && c !== " " && c !== "\n" && c !== "\r") {
1888
+ let e = extractValue(str, ptr - 1, "]", depth - 1, integersAsBigInt);
1889
+ res.push(e[0]);
1890
+ ptr = e[1];
1891
+ }
1892
+ if (!c) throw new TomlError("unfinished array encountered", {
1893
+ toml: str,
1894
+ ptr
1895
+ });
1896
+ return [res, ptr];
1897
+ }
1898
+
1899
+ //#endregion
1900
+ //#region node_modules/smol-toml/dist/parse.js
1901
+ /*!
1902
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1903
+ * SPDX-License-Identifier: BSD-3-Clause
1904
+ *
1905
+ * Redistribution and use in source and binary forms, with or without
1906
+ * modification, are permitted provided that the following conditions are met:
1907
+ *
1908
+ * 1. Redistributions of source code must retain the above copyright notice, this
1909
+ * list of conditions and the following disclaimer.
1910
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1911
+ * this list of conditions and the following disclaimer in the
1912
+ * documentation and/or other materials provided with the distribution.
1913
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1914
+ * may be used to endorse or promote products derived from this software without
1915
+ * specific prior written permission.
1916
+ *
1917
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1918
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1919
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1920
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1921
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1922
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1923
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1924
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1925
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1926
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1927
+ */
1928
+ function peekTable(key, table, meta, type) {
1929
+ let t = table;
1930
+ let m = meta;
1931
+ let k;
1932
+ let hasOwn = false;
1933
+ let state;
1934
+ for (let i = 0; i < key.length; i++) {
1935
+ if (i) {
1936
+ t = hasOwn ? t[k] : t[k] = {};
1937
+ m = (state = m[k]).c;
1938
+ if (type === 0 && (state.t === 1 || state.t === 2)) return null;
1939
+ if (state.t === 2) {
1940
+ let l = t.length - 1;
1941
+ t = t[l];
1942
+ m = m[l].c;
1943
+ }
1944
+ }
1945
+ k = key[i];
1946
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) return null;
1947
+ if (!hasOwn) {
1948
+ if (k === "__proto__") {
1949
+ Object.defineProperty(t, k, {
1950
+ enumerable: true,
1951
+ configurable: true,
1952
+ writable: true
1953
+ });
1954
+ Object.defineProperty(m, k, {
1955
+ enumerable: true,
1956
+ configurable: true,
1957
+ writable: true
1958
+ });
1959
+ }
1960
+ m[k] = {
1961
+ t: i < key.length - 1 && type === 2 ? 3 : type,
1962
+ d: false,
1963
+ i: 0,
1964
+ c: {}
1965
+ };
1966
+ }
1967
+ }
1968
+ state = m[k];
1969
+ if (state.t !== type && !(type === 1 && state.t === 3)) return null;
1970
+ if (type === 2) {
1971
+ if (!state.d) {
1972
+ state.d = true;
1973
+ t[k] = [];
1974
+ }
1975
+ t[k].push(t = {});
1976
+ state.c[state.i++] = state = {
1977
+ t: 1,
1978
+ d: false,
1979
+ i: 0,
1980
+ c: {}
1981
+ };
1982
+ }
1983
+ if (state.d) return null;
1984
+ state.d = true;
1985
+ if (type === 1) t = hasOwn ? t[k] : t[k] = {};
1986
+ else if (type === 0 && hasOwn) return null;
1987
+ return [
1988
+ k,
1989
+ t,
1990
+ state.c
1991
+ ];
1992
+ }
1993
+ function parse$1(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
1994
+ let res = {};
1995
+ let meta = {};
1996
+ let tbl = res;
1997
+ let m = meta;
1998
+ for (let ptr = skipVoid(toml, 0); ptr < toml.length;) {
1999
+ if (toml[ptr] === "[") {
2000
+ let isTableArray = toml[++ptr] === "[";
2001
+ let k = parseKey(toml, ptr += +isTableArray, "]");
2002
+ if (isTableArray) {
2003
+ if (toml[k[1] - 1] !== "]") throw new TomlError("expected end of table declaration", {
2004
+ toml,
2005
+ ptr: k[1] - 1
2006
+ });
2007
+ k[1]++;
2008
+ }
2009
+ let p = peekTable(k[0], res, meta, isTableArray ? 2 : 1);
2010
+ if (!p) throw new TomlError("trying to redefine an already defined table or value", {
2011
+ toml,
2012
+ ptr
2013
+ });
2014
+ m = p[2];
2015
+ tbl = p[1];
2016
+ ptr = k[1];
2017
+ } else {
2018
+ let k = parseKey(toml, ptr);
2019
+ let p = peekTable(k[0], tbl, m, 0);
2020
+ if (!p) throw new TomlError("trying to redefine an already defined table or value", {
2021
+ toml,
2022
+ ptr
2023
+ });
2024
+ let v = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);
2025
+ p[1][p[0]] = v[0];
2026
+ ptr = v[1];
2027
+ }
2028
+ ptr = skipVoid(toml, ptr, true);
2029
+ if (toml[ptr] && toml[ptr] !== "\n" && toml[ptr] !== "\r") throw new TomlError("each key-value declaration must be followed by an end-of-line", {
2030
+ toml,
2031
+ ptr
2032
+ });
2033
+ ptr = skipVoid(toml, ptr);
2034
+ }
2035
+ return res;
2036
+ }
2037
+
2038
+ //#endregion
2039
+ //#region node_modules/smol-toml/dist/stringify.js
2040
+ /*!
2041
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2042
+ * SPDX-License-Identifier: BSD-3-Clause
2043
+ *
2044
+ * Redistribution and use in source and binary forms, with or without
2045
+ * modification, are permitted provided that the following conditions are met:
2046
+ *
2047
+ * 1. Redistributions of source code must retain the above copyright notice, this
2048
+ * list of conditions and the following disclaimer.
2049
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2050
+ * this list of conditions and the following disclaimer in the
2051
+ * documentation and/or other materials provided with the distribution.
2052
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2053
+ * may be used to endorse or promote products derived from this software without
2054
+ * specific prior written permission.
2055
+ *
2056
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2057
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2058
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2059
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2060
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2061
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2062
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2063
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2064
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2065
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2066
+ */
2067
+ let BARE_KEY = /^[a-z0-9-_]+$/i;
2068
+ function extendedTypeOf(obj) {
2069
+ let type = typeof obj;
2070
+ if (type === "object") {
2071
+ if (Array.isArray(obj)) return "array";
2072
+ if (obj instanceof Date) return "date";
2073
+ }
2074
+ return type;
2075
+ }
2076
+ function isArrayOfTables(obj) {
2077
+ for (let i = 0; i < obj.length; i++) if (extendedTypeOf(obj[i]) !== "object") return false;
2078
+ return obj.length != 0;
2079
+ }
2080
+ function formatString(s) {
2081
+ return JSON.stringify(s).replace(/\x7f/g, "\\u007f");
2082
+ }
2083
+ function stringifyValue(val, type, depth, numberAsFloat) {
2084
+ if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
2085
+ if (type === "number") {
2086
+ if (isNaN(val)) return "nan";
2087
+ if (val === Infinity) return "inf";
2088
+ if (val === -Infinity) return "-inf";
2089
+ if (numberAsFloat && Number.isInteger(val)) return val.toFixed(1);
2090
+ return val.toString();
2091
+ }
2092
+ if (type === "bigint" || type === "boolean") return val.toString();
2093
+ if (type === "string") return formatString(val);
2094
+ if (type === "date") {
2095
+ if (isNaN(val.getTime())) throw new TypeError("cannot serialize invalid date");
2096
+ return val.toISOString();
2097
+ }
2098
+ if (type === "object") return stringifyInlineTable(val, depth, numberAsFloat);
2099
+ if (type === "array") return stringifyArray(val, depth, numberAsFloat);
2100
+ }
2101
+ function stringifyInlineTable(obj, depth, numberAsFloat) {
2102
+ let keys = Object.keys(obj);
2103
+ if (keys.length === 0) return "{}";
2104
+ let res = "{ ";
2105
+ for (let i = 0; i < keys.length; i++) {
2106
+ let k = keys[i];
2107
+ if (i) res += ", ";
2108
+ res += BARE_KEY.test(k) ? k : formatString(k);
2109
+ res += " = ";
2110
+ res += stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat);
2111
+ }
2112
+ return res + " }";
2113
+ }
2114
+ function stringifyArray(array, depth, numberAsFloat) {
2115
+ if (array.length === 0) return "[]";
2116
+ let res = "[ ";
2117
+ for (let i = 0; i < array.length; i++) {
2118
+ if (i) res += ", ";
2119
+ if (array[i] === null || array[i] === void 0) throw new TypeError("arrays cannot contain null or undefined values");
2120
+ res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat);
2121
+ }
2122
+ return res + " ]";
2123
+ }
2124
+ function stringifyArrayTable(array, key, depth, numberAsFloat) {
2125
+ if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
2126
+ let res = "";
2127
+ for (let i = 0; i < array.length; i++) {
2128
+ res += `[[${key}]]\n`;
2129
+ res += stringifyTable(array[i], key, depth, numberAsFloat);
2130
+ res += "\n\n";
2131
+ }
2132
+ return res;
2133
+ }
2134
+ function stringifyTable(obj, prefix, depth, numberAsFloat) {
2135
+ if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
2136
+ let preamble = "";
2137
+ let tables = "";
2138
+ let keys = Object.keys(obj);
2139
+ for (let i = 0; i < keys.length; i++) {
2140
+ let k = keys[i];
2141
+ if (obj[k] !== null && obj[k] !== void 0) {
2142
+ let type = extendedTypeOf(obj[k]);
2143
+ if (type === "symbol" || type === "function") throw new TypeError(`cannot serialize values of type '${type}'`);
2144
+ let key = BARE_KEY.test(k) ? k : formatString(k);
2145
+ if (type === "array" && isArrayOfTables(obj[k])) tables += stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat);
2146
+ else if (type === "object") {
2147
+ let tblKey = prefix ? `${prefix}.${key}` : key;
2148
+ tables += `[${tblKey}]\n`;
2149
+ tables += stringifyTable(obj[k], tblKey, depth - 1, numberAsFloat);
2150
+ tables += "\n\n";
2151
+ } else {
2152
+ preamble += key;
2153
+ preamble += " = ";
2154
+ preamble += stringifyValue(obj[k], type, depth, numberAsFloat);
2155
+ preamble += "\n";
2156
+ }
2157
+ }
2158
+ }
2159
+ return `${preamble}\n${tables}`.trim();
2160
+ }
2161
+ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false } = {}) {
2162
+ if (extendedTypeOf(obj) !== "object") throw new TypeError("stringify can only be called with an object");
2163
+ return stringifyTable(obj, "", maxDepth, numbersAsFloat);
2164
+ }
2165
+
2166
+ //#endregion
2167
+ //#region src/config.js
2168
+ async function assertSafePath(path) {
2169
+ let current = parse(resolve(path)).root;
2170
+ for (const part of resolve(path).slice(current.length).split(/[\\/]/).filter(Boolean)) {
2171
+ current = join(current, part);
2172
+ try {
2173
+ if ((await lstat(current)).isSymbolicLink()) throw new Error(`Refusing symbolic link: ${current}`);
2174
+ } catch (error) {
2175
+ if (error.code !== "ENOENT") throw error;
2176
+ }
2177
+ }
2178
+ }
2179
+ async function readConfig(path) {
2180
+ await assertSafePath(path);
2181
+ try {
2182
+ return await readFile(path, "utf8");
2183
+ } catch (error) {
2184
+ if (error.code === "ENOENT") return null;
2185
+ throw error;
2186
+ }
2187
+ }
2188
+ function object(value) {
2189
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2190
+ }
2191
+ function parseJson(text, path) {
2192
+ const errors = [];
2193
+ const value = parse$2(text ?? "{}", errors, { allowTrailingComma: true });
2194
+ if (errors.length || !object(value)) throw new Error(`Invalid JSON/JSONC object in ${path}; nothing overwritten.`);
2195
+ return value;
2196
+ }
2197
+ function editJson(text, changes, path) {
2198
+ let next = text ?? "{}\n";
2199
+ for (const [keys, value] of changes) {
2200
+ let parent = parseJson(next, path);
2201
+ for (const key of keys.slice(0, -1)) {
2202
+ if (!Object.hasOwn(parent, key)) break;
2203
+ if (!object(parent[key])) throw new Error(`Expected object at ${keys.join(".")} in ${path}`);
2204
+ parent = parent[key];
2205
+ }
2206
+ next = applyEdits(next, modify(next, keys, value, { formattingOptions: {
2207
+ insertSpaces: true,
2208
+ tabSize: 2,
2209
+ eol: next.includes("\r\n") ? "\r\n" : "\n"
2210
+ } }));
2211
+ }
2212
+ parseJson(next, path);
2213
+ return next;
2214
+ }
2215
+ function addToml(text, desired, path) {
2216
+ let existing;
2217
+ try {
2218
+ existing = parse$1(text ?? "");
2219
+ } catch {
2220
+ throw new Error(`Invalid TOML in ${path}; nothing overwritten.`);
2221
+ }
2222
+ const missing = {};
2223
+ for (const [key, value] of Object.entries(desired)) if (!Object.hasOwn(existing, key)) missing[key] = value;
2224
+ else if (!isDeepStrictEqual(existing[key], value)) throw new Error(`Conflicting ${key} in ${path}. Review it manually; nothing overwritten.`);
2225
+ if (!Object.keys(missing).length) return text ?? "";
2226
+ const scalars = Object.fromEntries(Object.entries(missing).filter(([, value]) => !object(value)));
2227
+ const tables = Object.fromEntries(Object.entries(missing).filter(([, value]) => object(value)));
2228
+ const parts = [];
2229
+ if (Object.keys(scalars).length) parts.push(stringify(scalars));
2230
+ if ((text ?? "").trim()) parts.push(text);
2231
+ if (Object.keys(tables).length) parts.push(stringify(tables));
2232
+ const next = `${parts.map((part) => part.replace(/\s+$/, "")).join("\n\n")}\n`;
2233
+ parse$1(next);
2234
+ return next;
2235
+ }
2236
+ function sha256(text) {
2237
+ return createHash("sha256").update(text, "utf8").digest("hex");
2238
+ }
2239
+ async function writeAtomic(path, text, check = async () => {}) {
2240
+ await mkdir(dirname(path), {
2241
+ recursive: true,
2242
+ mode: 448
2243
+ });
2244
+ const temporary = `${path}.apex-tmp-${randomUUID().slice(0, 8)}`;
2245
+ try {
2246
+ const handle = await open(temporary, "wx", 384);
2247
+ try {
2248
+ await handle.writeFile(text);
2249
+ await handle.sync();
2250
+ } finally {
2251
+ await handle.close();
2252
+ }
2253
+ await check();
2254
+ await rename(temporary, path);
2255
+ } finally {
2256
+ await unlink(temporary).catch((error) => {
2257
+ if (error.code !== "ENOENT") throw error;
2258
+ });
2259
+ }
2260
+ }
2261
+ async function removeChange(change) {
2262
+ const { path, before } = change;
2263
+ if (await readConfig(path) !== before) throw new Error(`Configuration changed while planning: ${path}. Run undo again.`);
2264
+ await unlink(path);
2265
+ }
2266
+ async function writeChange(change) {
2267
+ const { path, before, after } = change;
2268
+ if (await readConfig(path) !== before) throw new Error(`Configuration changed while planning: ${path}. Run init again.`);
2269
+ const backup = before === null ? null : `${path}.apex-backup-${randomUUID().slice(0, 8)}`;
2270
+ if (backup) {
2271
+ const handle = await open(backup, "wx", 384);
2272
+ try {
2273
+ await handle.writeFile(before);
2274
+ } finally {
2275
+ await handle.close();
2276
+ }
2277
+ }
2278
+ await writeAtomic(path, after, async () => {
2279
+ if (await readConfig(path) !== before) throw new Error(`Configuration changed before saving: ${path}`);
2280
+ });
2281
+ return backup;
2282
+ }
2283
+
2284
+ //#endregion
2285
+ //#region src/assistants.js
2286
+ const MODEL = "callstack/Apex";
2287
+ const BASE_URL = "https://api.callstack.ai/v1";
2288
+ const GUIDE_URL = "https://app.notion.com/p/callstack/Apex-how-to-use-it-36d5d027c0f880e99d03d1c37a77382f";
2289
+ const IDS = [
2290
+ "opencode",
2291
+ "codex",
2292
+ "claude",
2293
+ "pi",
2294
+ "cursor",
2295
+ "copilot",
2296
+ "ai-sdk"
2297
+ ];
2298
+ const NAMES = {
2299
+ opencode: "OpenCode",
2300
+ codex: "Codex",
2301
+ claude: "Claude Code",
2302
+ pi: "Pi",
2303
+ cursor: "Cursor",
2304
+ copilot: "VS Code (Copilot)",
2305
+ "ai-sdk": "Vercel AI SDK / Eve"
2306
+ };
2307
+ const RUNNABLE = [
2308
+ "codex",
2309
+ "claude",
2310
+ "opencode",
2311
+ "pi"
2312
+ ];
2313
+ const CONTEXT_WINDOW = 262144;
2314
+ const MAX_INPUT = 24e4;
2315
+ const MAX_OUTPUT = 16384;
2316
+ const EFFORTS = [
2317
+ "none",
2318
+ "low",
2319
+ "medium",
2320
+ "xhigh"
2321
+ ];
2322
+ const OPENCODE_MODEL = {
2323
+ name: "Apex",
2324
+ reasoning: true,
2325
+ tool_call: true,
2326
+ attachment: true,
2327
+ modalities: {
2328
+ input: ["text", "image"],
2329
+ output: ["text"]
2330
+ },
2331
+ limit: {
2332
+ context: CONTEXT_WINDOW,
2333
+ input: MAX_INPUT,
2334
+ output: MAX_OUTPUT
2335
+ },
2336
+ options: { reasoningEffort: "medium" },
2337
+ variants: Object.fromEntries(EFFORTS.map((effort) => [effort, { reasoningEffort: effort }]))
2338
+ };
2339
+ const OPENCODE_V2_PROVIDER = {
2340
+ name: "callstack.ai",
2341
+ package: "@opencode/ai/providers/openai-compatible",
2342
+ settings: { baseURL: BASE_URL },
2343
+ models: { [MODEL]: {
2344
+ name: "Apex",
2345
+ capabilities: {
2346
+ tools: true,
2347
+ input: ["text", "image"],
2348
+ output: ["text"]
2349
+ },
2350
+ limit: {
2351
+ context: CONTEXT_WINDOW,
2352
+ input: MAX_INPUT,
2353
+ output: MAX_OUTPUT
2354
+ },
2355
+ settings: { reasoningEffort: "medium" },
2356
+ variants: EFFORTS.map((effort) => ({
2357
+ id: effort,
2358
+ settings: { reasoningEffort: effort }
2359
+ }))
2360
+ } }
2361
+ };
2362
+ const PI_MODEL = {
2363
+ id: MODEL,
2364
+ reasoning: true,
2365
+ input: ["text", "image"],
2366
+ thinkingLevelMap: {
2367
+ off: "none",
2368
+ minimal: null,
2369
+ low: "low",
2370
+ medium: "medium",
2371
+ high: null,
2372
+ xhigh: "xhigh",
2373
+ max: null
2374
+ },
2375
+ contextWindow: CONTEXT_WINDOW
2376
+ };
2377
+ async function exists(path) {
2378
+ try {
2379
+ await stat(path);
2380
+ return true;
2381
+ } catch (error) {
2382
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return false;
2383
+ throw error;
2384
+ }
2385
+ }
2386
+ async function executable(command, env = process.env, platform = process.platform) {
2387
+ const extensions = platform === "win32" ? (env.PATHEXT || ".EXE;.CMD;.BAT").split(";") : [""];
2388
+ for (const directory of (env.PATH || "").split(platform === "win32" ? ";" : delimiter).filter(Boolean)) for (const extension of extensions) {
2389
+ const path = join(directory, command + extension.toLowerCase());
2390
+ try {
2391
+ await access(path, platform === "win32" ? constants.F_OK : constants.X_OK);
2392
+ if ((await stat(path)).isFile()) return path;
2393
+ } catch (error) {
2394
+ if (![
2395
+ "ENOENT",
2396
+ "ENOTDIR",
2397
+ "EACCES"
2398
+ ].includes(error.code)) throw error;
2399
+ }
2400
+ }
2401
+ return null;
2402
+ }
2403
+ function locations(home = homedir(), env = process.env, platform = process.platform) {
2404
+ const config = env.XDG_CONFIG_HOME || join(home, ".config");
2405
+ const userData = platform === "darwin" ? join(home, "Library", "Application Support") : platform === "win32" ? env.APPDATA || join(home, "AppData", "Roaming") : config;
2406
+ return {
2407
+ opencode: join(config, "opencode"),
2408
+ codex: env.CODEX_HOME || join(home, ".codex"),
2409
+ claude: env.CLAUDE_CONFIG_DIR || join(home, ".claude"),
2410
+ pi: env.PI_CODING_AGENT_DIR || join(home, ".pi", "agent"),
2411
+ cursor: join(userData, "Cursor"),
2412
+ copilot: join(userData, "Code")
2413
+ };
2414
+ }
2415
+ async function aiSdkProject(cwd) {
2416
+ const path = join(cwd, "package.json");
2417
+ let pkg;
2418
+ try {
2419
+ pkg = JSON.parse(await readFile(path, "utf8"));
2420
+ } catch {
2421
+ return null;
2422
+ }
2423
+ const deps = {
2424
+ ...pkg?.dependencies,
2425
+ ...pkg?.devDependencies
2426
+ };
2427
+ return [
2428
+ "ai",
2429
+ "@ai-sdk/openai",
2430
+ "eve"
2431
+ ].some((name) => Object.hasOwn(deps, name)) ? path : null;
2432
+ }
2433
+ async function detect(options = {}) {
2434
+ const home = options.home ?? homedir();
2435
+ const env = options.env ?? process.env;
2436
+ const platform = options.platform ?? process.platform;
2437
+ const cwd = options.cwd ?? process.cwd();
2438
+ const paths = locations(home, env, platform);
2439
+ return Promise.all(IDS.map(async (id) => {
2440
+ if (id === "ai-sdk") {
2441
+ const evidence = await aiSdkProject(cwd);
2442
+ return {
2443
+ id,
2444
+ detected: Boolean(evidence),
2445
+ binary: null,
2446
+ evidence,
2447
+ directory: cwd
2448
+ };
2449
+ }
2450
+ const binary = await executable(id === "copilot" ? "code" : id, env, platform);
2451
+ const markers = [paths[id]];
2452
+ if (platform === "darwin" && ["cursor", "copilot"].includes(id)) {
2453
+ const name = id === "cursor" ? "Cursor.app" : "Visual Studio Code.app";
2454
+ markers.push(join("/Applications", name), join(home, "Applications", name));
2455
+ }
2456
+ if (id === "copilot") markers.push(join(home, ".vscode", "extensions"));
2457
+ const found = [];
2458
+ for (const path of markers) if (await exists(path)) found.push(path);
2459
+ return {
2460
+ id,
2461
+ detected: Boolean(binary || found.length),
2462
+ binary,
2463
+ evidence: binary || found[0],
2464
+ directory: paths[id],
2465
+ ...id === "opencode" ? { authFile: join(env.XDG_DATA_HOME || join(home, ".local", "share"), "opencode", "auth.json") } : {}
2466
+ };
2467
+ }));
2468
+ }
2469
+ async function openCodeHasKey(authFile) {
2470
+ if (!authFile) return false;
2471
+ try {
2472
+ return Object.hasOwn(JSON.parse(await readConfig(authFile) ?? "{}"), "callstack.ai");
2473
+ } catch {
2474
+ return false;
2475
+ }
2476
+ }
2477
+ const PI_PLACEHOLDER = "XXX";
2478
+ async function planAssistant(assistant) {
2479
+ const changes = [];
2480
+ const json = async (filename, updates) => {
2481
+ const path = join(assistant.directory, filename);
2482
+ const before = await readConfig(path);
2483
+ const after = editJson(before, typeof updates === "function" ? updates(parseJson(before, path)) : updates, path);
2484
+ changes.push({
2485
+ path,
2486
+ before,
2487
+ after,
2488
+ format: "json"
2489
+ });
2490
+ };
2491
+ switch (assistant.id) {
2492
+ case "opencode": {
2493
+ const hasJson = await exists(join(assistant.directory, "opencode.json"));
2494
+ const hasJsonc = await exists(join(assistant.directory, "opencode.jsonc"));
2495
+ if (hasJson && hasJsonc) throw new Error("Both opencode.json and opencode.jsonc exist. Consolidate them before init.");
2496
+ let v2 = false;
2497
+ const storedKey = await openCodeHasKey(assistant.authFile);
2498
+ await json(hasJsonc ? "opencode.jsonc" : "opencode.json", (existing) => {
2499
+ v2 = Object.hasOwn(existing, "providers");
2500
+ if (v2) return [[["providers", "callstack.ai"], OPENCODE_V2_PROVIDER]];
2501
+ return [
2502
+ [[
2503
+ "provider",
2504
+ "callstack.ai",
2505
+ "npm"
2506
+ ], "@ai-sdk/openai-compatible"],
2507
+ [[
2508
+ "provider",
2509
+ "callstack.ai",
2510
+ "name"
2511
+ ], "callstack.ai"],
2512
+ [[
2513
+ "provider",
2514
+ "callstack.ai",
2515
+ "options",
2516
+ "baseURL"
2517
+ ], BASE_URL],
2518
+ ...storedKey ? [] : [[[
2519
+ "provider",
2520
+ "callstack.ai",
2521
+ "options",
2522
+ "apiKey"
2523
+ ], "{env:CALLSTACK_AUTH_TOKEN}"]],
2524
+ [[
2525
+ "provider",
2526
+ "callstack.ai",
2527
+ "models",
2528
+ MODEL
2529
+ ], OPENCODE_MODEL]
2530
+ ];
2531
+ });
2532
+ if (v2) changes[0].steps = ["OpenCode 2 stores provider keys itself: run /connect in OpenCode, pick callstack.ai → \"Manually enter API Key\", and paste your Callstack key."];
2533
+ break;
2534
+ }
2535
+ case "pi":
2536
+ await json("models.json", (existing) => {
2537
+ const models = existing.providers?.callstack?.models ?? [];
2538
+ const key = existing.providers?.callstack?.apiKey;
2539
+ if (!Array.isArray(models) || models.some((model) => !model || typeof model.id !== "string")) throw new Error("Expected Pi models to be an array of model objects.");
2540
+ return [
2541
+ [[
2542
+ "providers",
2543
+ "callstack",
2544
+ "baseUrl"
2545
+ ], BASE_URL],
2546
+ [[
2547
+ "providers",
2548
+ "callstack",
2549
+ "api"
2550
+ ], "openai-completions"],
2551
+ ...key && key !== PI_PLACEHOLDER ? [] : [[[
2552
+ "providers",
2553
+ "callstack",
2554
+ "apiKey"
2555
+ ], "$CALLSTACK_AUTH_TOKEN"]],
2556
+ [[
2557
+ "providers",
2558
+ "callstack",
2559
+ "models"
2560
+ ], models.some((model) => model.id === "callstack/Apex") ? models.map((model) => model.id === "callstack/Apex" ? PI_MODEL : model) : [...models, PI_MODEL]]
2561
+ ];
2562
+ });
2563
+ break;
2564
+ case "claude":
2565
+ await json("settings.json", [[["env", "CLAUDE_CODE_ATTRIBUTION_HEADER"], "0"]]);
2566
+ break;
2567
+ case "codex": {
2568
+ const path = join(assistant.directory, "callstack_ai.config.toml");
2569
+ const before = await readConfig(path);
2570
+ const after = addToml(before, {
2571
+ model_provider: "callstack_ai",
2572
+ model: MODEL,
2573
+ model_context_window: CONTEXT_WINDOW,
2574
+ model_reasoning_effort: "medium",
2575
+ model_providers: { callstack_ai: {
2576
+ name: "callstack.ai",
2577
+ base_url: BASE_URL,
2578
+ env_key: "CALLSTACK_AUTH_TOKEN",
2579
+ wire_api: "responses",
2580
+ requires_openai_auth: false
2581
+ } }
2582
+ }, path);
2583
+ changes.push({
2584
+ path,
2585
+ before,
2586
+ after,
2587
+ format: "toml"
2588
+ });
2589
+ break;
2590
+ }
2591
+ }
2592
+ return changes;
2593
+ }
2594
+ function launchOptions(id, env = process.env) {
2595
+ const token = env.CALLSTACK_AUTH_TOKEN;
2596
+ if (!token?.trim()) throw new Error("Set CALLSTACK_AUTH_TOKEN in your environment before launching.");
2597
+ const childEnv = { ...env };
2598
+ switch (id) {
2599
+ case "opencode": return {
2600
+ args: ["--model", `callstack.ai/${MODEL}`],
2601
+ env: childEnv
2602
+ };
2603
+ case "codex": return {
2604
+ args: ["--profile", "callstack_ai"],
2605
+ env: childEnv
2606
+ };
2607
+ case "pi": return {
2608
+ args: [
2609
+ "--provider",
2610
+ "callstack",
2611
+ "--model",
2612
+ MODEL
2613
+ ],
2614
+ env: childEnv
2615
+ };
2616
+ case "claude":
2617
+ for (const key of [
2618
+ "ANTHROPIC_API_KEY",
2619
+ "CLAUDE_CODE_OAUTH_TOKEN",
2620
+ "CLAUDE_CODE_USE_BEDROCK",
2621
+ "CLAUDE_CODE_USE_VERTEX",
2622
+ "CLAUDE_CODE_USE_FOUNDRY"
2623
+ ]) delete childEnv[key];
2624
+ Object.assign(childEnv, {
2625
+ ANTHROPIC_BASE_URL: "https://api.callstack.ai",
2626
+ ANTHROPIC_AUTH_TOKEN: token,
2627
+ ANTHROPIC_MODEL: MODEL,
2628
+ CLAUDE_CODE_ATTRIBUTION_HEADER: "0",
2629
+ ANTHROPIC_DEFAULT_OPUS_MODEL: MODEL,
2630
+ ANTHROPIC_DEFAULT_SONNET_MODEL: MODEL,
2631
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: MODEL,
2632
+ CLAUDE_CODE_SUBAGENT_MODEL: MODEL
2633
+ });
2634
+ return {
2635
+ args: ["--model", MODEL],
2636
+ env: childEnv
2637
+ };
2638
+ default: throw new Error(`Cannot launch ${id}. Use the editor's model selector.`);
2639
+ }
2640
+ }
2641
+ const RUN_NOTE = { claude: "(ANTHROPIC_* gateway environment set)" };
2642
+ function runExpansion(id) {
2643
+ const { args } = launchOptions(id, { CALLSTACK_AUTH_TOKEN: "placeholder" });
2644
+ return [`${id} ${args.join(" ")}`, RUN_NOTE[id]].filter(Boolean).join(" ");
2645
+ }
2646
+ const COPILOT_MODEL = JSON.stringify({
2647
+ id: MODEL,
2648
+ name: "Apex",
2649
+ url: BASE_URL,
2650
+ toolCalling: true,
2651
+ vision: true,
2652
+ thinking: true,
2653
+ contextWindow: CONTEXT_WINDOW,
2654
+ maxOutputTokens: MAX_OUTPUT,
2655
+ supportsReasoningEffort: EFFORTS,
2656
+ reasoningEffortFormat: "chat-completions"
2657
+ }, null, 2);
2658
+ const AI_SDK_SNIPPET = [
2659
+ "import { createOpenAI } from '@ai-sdk/openai';",
2660
+ "",
2661
+ "const apex = createOpenAI({",
2662
+ " name: 'callstack',",
2663
+ ` baseURL: '${BASE_URL}',`,
2664
+ " apiKey: process.env.CALLSTACK_AUTH_TOKEN,",
2665
+ "});",
2666
+ `// apex('${MODEL}') with generateText / streamText.`,
2667
+ `// Reasoning effort (${EFFORTS.join(", ")}):`,
2668
+ "// providerOptions: { callstack: { reasoningEffort: 'medium' } }"
2669
+ ];
2670
+ const MANUAL = {
2671
+ cursor: [`Cursor: Settings → Models → API Keys → OpenAI API Key. Enter your Callstack key, override the base URL with ${BASE_URL}, add and enable ${MODEL}, then select it in Agent.`, "Cursor has no way to declare what a custom model can do (tool calling, vision, reasoning); it infers that itself."],
2672
+ copilot: [
2673
+ "Installation of Copilot itself is not verified: Copilot → model selector → Manage Models → Add Models → Custom Endpoint → name callstack.ai → enter your key → Chat Completions.",
2674
+ "Keep the generated apiKey secret reference; add this object to its models array:",
2675
+ ...COPILOT_MODEL.split("\n")
2676
+ ],
2677
+ "ai-sdk": [
2678
+ "Apex CLI never writes your key into a project. Keep it in CALLSTACK_AUTH_TOKEN (for example in a .env that git ignores) and create the provider with:",
2679
+ ...AI_SDK_SNIPPET,
2680
+ `Eve: set modelContextWindowTokens: ${CONTEXT_WINDOW} on defineAgent, or compaction will fail to compile.`
2681
+ ]
2682
+ };
2683
+ const MANUAL_IDS = Object.keys(MANUAL);
2684
+
2685
+ //#endregion
2686
+ //#region node_modules/fast-string-truncated-width/dist/utils.js
2687
+ const getCodePointsLength = (() => {
2688
+ const SURROGATE_PAIR_RE = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
2689
+ return (input) => {
2690
+ let surrogatePairsNr = 0;
2691
+ SURROGATE_PAIR_RE.lastIndex = 0;
2692
+ while (SURROGATE_PAIR_RE.test(input)) surrogatePairsNr += 1;
2693
+ return input.length - surrogatePairsNr;
2694
+ };
2695
+ })();
2696
+ const isFullWidth = (x) => {
2697
+ return x === 12288 || x >= 65281 && x <= 65376 || x >= 65504 && x <= 65510;
2698
+ };
2699
+ const isWideNotCJKTNotEmoji = (x) => {
2700
+ return x === 8987 || x === 9001 || x >= 12272 && x <= 12287 || x >= 12289 && x <= 12350 || x >= 12441 && x <= 12543 || x >= 12549 && x <= 12591 || x >= 12593 && x <= 12686 || x >= 12688 && x <= 12771 || x >= 12783 && x <= 12830 || x >= 12832 && x <= 12871 || x >= 12880 && x <= 19903 || x >= 65040 && x <= 65049 || x >= 65072 && x <= 65106 || x >= 65108 && x <= 65126 || x >= 65128 && x <= 65131 || x >= 127488 && x <= 127490 || x >= 127504 && x <= 127547 || x >= 127552 && x <= 127560 || x >= 131072 && x <= 196605 || x >= 196608 && x <= 262141;
2701
+ };
2702
+
2703
+ //#endregion
2704
+ //#region node_modules/fast-string-truncated-width/dist/index.js
2705
+ const ANSI_RE = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y;
2706
+ const CONTROL_RE = /[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y;
2707
+ const CJKT_WIDE_RE = /(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy;
2708
+ const TAB_RE = /\t{1,1000}/y;
2709
+ const EMOJI_RE = /[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy;
2710
+ const LATIN_RE = /(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y;
2711
+ const MODIFIER_RE = /\p{M}+/gu;
2712
+ const NO_TRUNCATION$1 = {
2713
+ limit: Infinity,
2714
+ ellipsis: ""
2715
+ };
2716
+ const getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {
2717
+ const LIMIT = truncationOptions.limit ?? Infinity;
2718
+ const ELLIPSIS = truncationOptions.ellipsis ?? "";
2719
+ const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION$1, widthOptions).width : 0);
2720
+ const ANSI_WIDTH = 0;
2721
+ const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;
2722
+ const TAB_WIDTH = widthOptions.tabWidth ?? 8;
2723
+ const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;
2724
+ const FULL_WIDTH_WIDTH = 2;
2725
+ const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;
2726
+ const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;
2727
+ const PARSE_BLOCKS = [
2728
+ [LATIN_RE, REGULAR_WIDTH],
2729
+ [ANSI_RE, ANSI_WIDTH],
2730
+ [CONTROL_RE, CONTROL_WIDTH],
2731
+ [TAB_RE, TAB_WIDTH],
2732
+ [EMOJI_RE, EMOJI_WIDTH],
2733
+ [CJKT_WIDE_RE, WIDE_WIDTH]
2734
+ ];
2735
+ let indexPrev = 0;
2736
+ let index = 0;
2737
+ let length = input.length;
2738
+ let lengthExtra = 0;
2739
+ let truncationEnabled = false;
2740
+ let truncationIndex = length;
2741
+ let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);
2742
+ let unmatchedStart = 0;
2743
+ let unmatchedEnd = 0;
2744
+ let width = 0;
2745
+ let widthExtra = 0;
2746
+ outer: while (true) {
2747
+ if (unmatchedEnd > unmatchedStart || index >= length && index > indexPrev) {
2748
+ const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);
2749
+ lengthExtra = 0;
2750
+ for (const char of unmatched.replaceAll(MODIFIER_RE, "")) {
2751
+ const codePoint = char.codePointAt(0) || 0;
2752
+ if (isFullWidth(codePoint)) widthExtra = FULL_WIDTH_WIDTH;
2753
+ else if (isWideNotCJKTNotEmoji(codePoint)) widthExtra = WIDE_WIDTH;
2754
+ else widthExtra = REGULAR_WIDTH;
2755
+ if (width + widthExtra > truncationLimit) truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);
2756
+ if (width + widthExtra > LIMIT) {
2757
+ truncationEnabled = true;
2758
+ break outer;
2759
+ }
2760
+ lengthExtra += char.length;
2761
+ width += widthExtra;
2762
+ }
2763
+ unmatchedStart = unmatchedEnd = 0;
2764
+ }
2765
+ if (index >= length) break outer;
2766
+ for (let i = 0, l = PARSE_BLOCKS.length; i < l; i++) {
2767
+ const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i];
2768
+ BLOCK_RE.lastIndex = index;
2769
+ if (BLOCK_RE.test(input)) {
2770
+ lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;
2771
+ widthExtra = lengthExtra * BLOCK_WIDTH;
2772
+ if (width + widthExtra > truncationLimit) truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));
2773
+ if (width + widthExtra > LIMIT) {
2774
+ truncationEnabled = true;
2775
+ break outer;
2776
+ }
2777
+ width += widthExtra;
2778
+ unmatchedStart = indexPrev;
2779
+ unmatchedEnd = index;
2780
+ index = indexPrev = BLOCK_RE.lastIndex;
2781
+ continue outer;
2782
+ }
2783
+ }
2784
+ index += 1;
2785
+ }
2786
+ return {
2787
+ width: truncationEnabled ? truncationLimit : width,
2788
+ index: truncationEnabled ? truncationIndex : length,
2789
+ truncated: truncationEnabled,
2790
+ ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH
2791
+ };
2792
+ };
2793
+
2794
+ //#endregion
2795
+ //#region node_modules/fast-string-width/dist/index.js
2796
+ const NO_TRUNCATION = {
2797
+ limit: Infinity,
2798
+ ellipsis: "",
2799
+ ellipsisWidth: 0
2800
+ };
2801
+ const fastStringWidth = (input, options = {}) => {
2802
+ return getStringTruncatedWidth(input, NO_TRUNCATION, options).width;
2803
+ };
2804
+
2805
+ //#endregion
2806
+ //#region node_modules/fast-wrap-ansi/lib/main.js
2807
+ const ESC = "\x1B";
2808
+ const CSI = "›";
2809
+ const END_CODE = 39;
2810
+ const ANSI_ESCAPE_BELL = "\x07";
2811
+ const ANSI_CSI = "[";
2812
+ const ANSI_OSC = "]";
2813
+ const ANSI_SGR_TERMINATOR = "m";
2814
+ const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
2815
+ const GROUP_REGEX = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, "y");
2816
+ const getClosingCode = (openingCode) => {
2817
+ if (openingCode >= 30 && openingCode <= 37) return 39;
2818
+ if (openingCode >= 90 && openingCode <= 97) return 39;
2819
+ if (openingCode >= 40 && openingCode <= 47) return 49;
2820
+ if (openingCode >= 100 && openingCode <= 107) return 49;
2821
+ if (openingCode === 1 || openingCode === 2) return 22;
2822
+ if (openingCode === 3) return 23;
2823
+ if (openingCode === 4) return 24;
2824
+ if (openingCode === 7) return 27;
2825
+ if (openingCode === 8) return 28;
2826
+ if (openingCode === 9) return 29;
2827
+ if (openingCode === 0) return 0;
2828
+ };
2829
+ const wrapAnsiCode = (code) => `${ESC}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
2830
+ const wrapAnsiHyperlink = (url) => `${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;
2831
+ const wrapWord = (rows, word, columns) => {
2832
+ const characters = word[Symbol.iterator]();
2833
+ let isInsideEscape = false;
2834
+ let isInsideLinkEscape = false;
2835
+ let lastRow = rows.at(-1);
2836
+ let visible = lastRow === void 0 ? 0 : fastStringWidth(lastRow);
2837
+ let currentCharacter = characters.next();
2838
+ let nextCharacter = characters.next();
2839
+ let rawCharacterIndex = 0;
2840
+ while (!currentCharacter.done) {
2841
+ const character = currentCharacter.value;
2842
+ const characterLength = fastStringWidth(character);
2843
+ if (visible + characterLength <= columns) rows[rows.length - 1] += character;
2844
+ else {
2845
+ rows.push(character);
2846
+ visible = 0;
2847
+ }
2848
+ if (character === ESC || character === CSI) {
2849
+ isInsideEscape = true;
2850
+ isInsideLinkEscape = word.startsWith(ANSI_ESCAPE_LINK, rawCharacterIndex + 1);
2851
+ }
2852
+ if (isInsideEscape) {
2853
+ if (isInsideLinkEscape) {
2854
+ if (character === ANSI_ESCAPE_BELL) {
2855
+ isInsideEscape = false;
2856
+ isInsideLinkEscape = false;
2857
+ }
2858
+ } else if (character === ANSI_SGR_TERMINATOR) isInsideEscape = false;
2859
+ } else {
2860
+ visible += characterLength;
2861
+ if (visible === columns && !nextCharacter.done) {
2862
+ rows.push("");
2863
+ visible = 0;
2864
+ }
2865
+ }
2866
+ currentCharacter = nextCharacter;
2867
+ nextCharacter = characters.next();
2868
+ rawCharacterIndex += character.length;
2869
+ }
2870
+ lastRow = rows.at(-1);
2871
+ if (!visible && lastRow !== void 0 && lastRow.length && rows.length > 1) rows[rows.length - 2] += rows.pop();
2872
+ };
2873
+ const stringVisibleTrimSpacesRight = (string) => {
2874
+ const words = string.split(" ");
2875
+ let last = words.length;
2876
+ while (last) {
2877
+ if (fastStringWidth(words[last - 1])) break;
2878
+ last--;
2879
+ }
2880
+ if (last === words.length) return string;
2881
+ return words.slice(0, last).join(" ") + words.slice(last).join("");
2882
+ };
2883
+ const exec = (string, columns, options = {}) => {
2884
+ if (options.trim !== false && string.trim() === "") return "";
2885
+ let returnValue = "";
2886
+ let escapeCode;
2887
+ let escapeUrl;
2888
+ const words = string.split(" ");
2889
+ let rows = [""];
2890
+ let rowLength = 0;
2891
+ for (let index = 0; index < words.length; index++) {
2892
+ const word = words[index];
2893
+ if (options.trim !== false) {
2894
+ const row = rows.at(-1) ?? "";
2895
+ const trimmed = row.trimStart();
2896
+ if (row.length !== trimmed.length) {
2897
+ rows[rows.length - 1] = trimmed;
2898
+ rowLength = fastStringWidth(trimmed);
2899
+ }
2900
+ }
2901
+ if (index !== 0) {
2902
+ if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
2903
+ rows.push("");
2904
+ rowLength = 0;
2905
+ }
2906
+ if (rowLength || options.trim === false) {
2907
+ rows[rows.length - 1] += " ";
2908
+ rowLength++;
2909
+ }
2910
+ }
2911
+ const wordLength = fastStringWidth(word);
2912
+ if (options.hard && wordLength > columns) {
2913
+ const remainingColumns = columns - rowLength;
2914
+ const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);
2915
+ if (Math.floor((wordLength - 1) / columns) < breaksStartingThisLine) rows.push("");
2916
+ wrapWord(rows, word, columns);
2917
+ rowLength = fastStringWidth(rows.at(-1) ?? "");
2918
+ continue;
2919
+ }
2920
+ if (rowLength + wordLength > columns && rowLength && wordLength) {
2921
+ if (options.wordWrap === false && rowLength < columns) {
2922
+ wrapWord(rows, word, columns);
2923
+ rowLength = fastStringWidth(rows.at(-1) ?? "");
2924
+ continue;
2925
+ }
2926
+ rows.push("");
2927
+ rowLength = 0;
2928
+ }
2929
+ if (rowLength + wordLength > columns && options.wordWrap === false) {
2930
+ wrapWord(rows, word, columns);
2931
+ rowLength = fastStringWidth(rows.at(-1) ?? "");
2932
+ continue;
2933
+ }
2934
+ rows[rows.length - 1] += word;
2935
+ rowLength += wordLength;
2936
+ }
2937
+ if (options.trim !== false) rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
2938
+ const preString = rows.join("\n");
2939
+ let inSurrogate = false;
2940
+ for (let i = 0; i < preString.length; i++) {
2941
+ const character = preString[i];
2942
+ returnValue += character;
2943
+ if (!inSurrogate) {
2944
+ inSurrogate = character >= "\ud800" && character <= "\udbff";
2945
+ if (inSurrogate) continue;
2946
+ } else inSurrogate = false;
2947
+ if (character === ESC || character === CSI) {
2948
+ GROUP_REGEX.lastIndex = i + 1;
2949
+ const groups = GROUP_REGEX.exec(preString)?.groups;
2950
+ if (groups?.code !== void 0) {
2951
+ const code = Number.parseFloat(groups.code);
2952
+ escapeCode = code === END_CODE ? void 0 : code;
2953
+ } else if (groups?.uri !== void 0) escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
2954
+ }
2955
+ if (preString[i + 1] === "\n") {
2956
+ if (escapeUrl) returnValue += wrapAnsiHyperlink("");
2957
+ const closingCode = escapeCode ? getClosingCode(escapeCode) : void 0;
2958
+ if (escapeCode && closingCode) returnValue += wrapAnsiCode(closingCode);
2959
+ } else if (character === "\n") {
2960
+ if (escapeCode && getClosingCode(escapeCode)) returnValue += wrapAnsiCode(escapeCode);
2961
+ if (escapeUrl) returnValue += wrapAnsiHyperlink(escapeUrl);
2962
+ }
2963
+ }
2964
+ return returnValue;
2965
+ };
2966
+ const CRLF_OR_LF = /\r?\n/;
2967
+ function wrapAnsi(string, columns, options) {
2968
+ return String(string).normalize().split(CRLF_OR_LF).map((line) => exec(line, columns, options)).join("\n");
2969
+ }
2970
+
2971
+ //#endregion
2972
+ //#region node_modules/sisteransi/src/index.js
2973
+ var require_src = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2974
+ const ESC = "\x1B";
2975
+ const CSI = `${ESC}[`;
2976
+ const beep = "\x07";
2977
+ const cursor = {
2978
+ to(x, y) {
2979
+ if (!y) return `${CSI}${x + 1}G`;
2980
+ return `${CSI}${y + 1};${x + 1}H`;
2981
+ },
2982
+ move(x, y) {
2983
+ let ret = "";
2984
+ if (x < 0) ret += `${CSI}${-x}D`;
2985
+ else if (x > 0) ret += `${CSI}${x}C`;
2986
+ if (y < 0) ret += `${CSI}${-y}A`;
2987
+ else if (y > 0) ret += `${CSI}${y}B`;
2988
+ return ret;
2989
+ },
2990
+ up: (count = 1) => `${CSI}${count}A`,
2991
+ down: (count = 1) => `${CSI}${count}B`,
2992
+ forward: (count = 1) => `${CSI}${count}C`,
2993
+ backward: (count = 1) => `${CSI}${count}D`,
2994
+ nextLine: (count = 1) => `${CSI}E`.repeat(count),
2995
+ prevLine: (count = 1) => `${CSI}F`.repeat(count),
2996
+ left: `${CSI}G`,
2997
+ hide: `${CSI}?25l`,
2998
+ show: `${CSI}?25h`,
2999
+ save: `${ESC}7`,
3000
+ restore: `${ESC}8`
3001
+ };
3002
+ const scroll = {
3003
+ up: (count = 1) => `${CSI}S`.repeat(count),
3004
+ down: (count = 1) => `${CSI}T`.repeat(count)
3005
+ };
3006
+ const erase = {
3007
+ screen: `${CSI}2J`,
3008
+ up: (count = 1) => `${CSI}1J`.repeat(count),
3009
+ down: (count = 1) => `${CSI}J`.repeat(count),
3010
+ line: `${CSI}2K`,
3011
+ lineEnd: `${CSI}K`,
3012
+ lineStart: `${CSI}1K`,
3013
+ lines(count) {
3014
+ let clear = "";
3015
+ for (let i = 0; i < count; i++) clear += this.line + (i < count - 1 ? cursor.up() : "");
3016
+ if (count) clear += cursor.left;
3017
+ return clear;
3018
+ }
3019
+ };
3020
+ module.exports = {
3021
+ cursor,
3022
+ scroll,
3023
+ erase,
3024
+ beep
3025
+ };
3026
+ }));
3027
+
3028
+ //#endregion
3029
+ //#region node_modules/@clack/core/dist/index.mjs
3030
+ var import_src = require_src();
3031
+ function findCursor(s, o, l) {
3032
+ if (!l.some((r) => !r.disabled)) return s;
3033
+ const t = s + o, n = Math.max(l.length - 1, 0), e = t < 0 ? n : t > n ? 0 : t;
3034
+ return l[e]?.disabled ? findCursor(e, o < 0 ? -1 : 1, l) : e;
3035
+ }
3036
+ const settings = {
3037
+ actions: /* @__PURE__ */ new Set([
3038
+ "up",
3039
+ "down",
3040
+ "left",
3041
+ "right",
3042
+ "space",
3043
+ "enter",
3044
+ "cancel"
3045
+ ]),
3046
+ aliases: /* @__PURE__ */ new Map([
3047
+ ["k", "up"],
3048
+ ["j", "down"],
3049
+ ["h", "left"],
3050
+ ["l", "right"],
3051
+ ["", "cancel"],
3052
+ ["escape", "cancel"]
3053
+ ]),
3054
+ messages: {
3055
+ cancel: "Canceled",
3056
+ error: "Something went wrong"
3057
+ },
3058
+ withGuide: true,
3059
+ accessible: void 0,
3060
+ date: {
3061
+ monthNames: [...[
3062
+ "January",
3063
+ "February",
3064
+ "March",
3065
+ "April",
3066
+ "May",
3067
+ "June",
3068
+ "July",
3069
+ "August",
3070
+ "September",
3071
+ "October",
3072
+ "November",
3073
+ "December"
3074
+ ]],
3075
+ messages: {
3076
+ required: "Please enter a valid date",
3077
+ invalidMonth: "There are only 12 months in a year",
3078
+ invalidDay: (n, e) => `There are only ${n} days in ${e}`,
3079
+ afterMin: (n) => `Date must be on or after ${n.toISOString().slice(0, 10)}`,
3080
+ beforeMax: (n) => `Date must be on or before ${n.toISOString().slice(0, 10)}`
3081
+ }
3082
+ }
3083
+ };
3084
+ function isAccessible(n) {
3085
+ if (n !== void 0) return n;
3086
+ if (settings.accessible !== void 0) return settings.accessible;
3087
+ const e = process.env.ACCESSIBLE;
3088
+ return e !== void 0 && e !== "" && e !== "0" && e !== "false";
3089
+ }
3090
+ function isActionKey(n, e) {
3091
+ if (typeof n == "string") return settings.aliases.get(n) === e;
3092
+ for (const s of n) if (s !== void 0 && isActionKey(s, e)) return true;
3093
+ return false;
3094
+ }
3095
+ function diffLines(i, s) {
3096
+ if (i === s) return;
3097
+ const e = i.split(`
3098
+ `), t = s.split(`
3099
+ `), r = Math.max(e.length, t.length), f = [];
3100
+ for (let n = 0; n < r; n++) e[n] !== t[n] && f.push(n);
3101
+ return {
3102
+ lines: f,
3103
+ numLinesBefore: e.length,
3104
+ numLinesAfter: t.length,
3105
+ numLines: r
3106
+ };
3107
+ }
3108
+ const R = globalThis.process.platform.startsWith("win");
3109
+ const CANCEL_SYMBOL = Symbol("clack:cancel");
3110
+ function isCancel(e) {
3111
+ return e === CANCEL_SYMBOL;
3112
+ }
3113
+ function setRawMode(e, r) {
3114
+ const o = e;
3115
+ o.isTTY && o.setRawMode(r);
3116
+ }
3117
+ const getColumns = (e) => "columns" in e && typeof e.columns == "number" ? e.columns : 80;
3118
+ const getRows = (e) => "rows" in e && typeof e.rows == "number" ? e.rows : 20;
3119
+ function wrapTextWithPrefix(e, r, o, n = o, s = o, t) {
3120
+ const f = getColumns(e ?? stdout);
3121
+ return wrapAnsi(r, f - o.length, {
3122
+ hard: true,
3123
+ trim: false
3124
+ }).split(`
3125
+ `).map((c, i, m) => {
3126
+ const d = t ? t(c, i) : c;
3127
+ return i === 0 ? `${n}${d}` : i === m.length - 1 ? `${s}${d}` : `${o}${d}`;
3128
+ }).join(`
3129
+ `);
3130
+ }
3131
+ function runValidation(e, a) {
3132
+ if ("~standard" in e) {
3133
+ const n = e["~standard"].validate(a);
3134
+ return n instanceof Promise ? n.then((r) => r.issues?.at(0)?.message) : n.issues?.at(0)?.message;
3135
+ }
3136
+ return e(a);
3137
+ }
3138
+ var y = class {
3139
+ input;
3140
+ output;
3141
+ _abortSignal;
3142
+ rl;
3143
+ opts;
3144
+ _render;
3145
+ _track = false;
3146
+ _prevFrame = "";
3147
+ _subscribers = /* @__PURE__ */ new Map();
3148
+ _cursor = 0;
3149
+ state = "initial";
3150
+ error = "";
3151
+ value;
3152
+ userInput = "";
3153
+ /**
3154
+ * Whether accessible (static, screen-reader friendly) output is enabled for
3155
+ * this prompt, resolved from the `accessible` option, the global setting,
3156
+ * and the `ACCESSIBLE` env var.
3157
+ */
3158
+ get accessible() {
3159
+ return isAccessible(this.opts.accessible);
3160
+ }
3161
+ constructor(t, e = true) {
3162
+ const { input: i = stdin, output: s = stdout, render: r, signal: n, ...o } = t;
3163
+ this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = r.bind(this), this._track = e, this._abortSignal = n, this.input = i, this.output = s;
3164
+ }
3165
+ /**
3166
+ * Unsubscribe all listeners
3167
+ */
3168
+ unsubscribe() {
3169
+ this._subscribers.clear();
3170
+ }
3171
+ /**
3172
+ * Set a subscriber with opts
3173
+ * @param event - The event name
3174
+ */
3175
+ setSubscriber(t, e) {
3176
+ const i = this._subscribers.get(t) ?? [];
3177
+ i.push(e), this._subscribers.set(t, i);
3178
+ }
3179
+ /**
3180
+ * Subscribe to an event
3181
+ * @param event - The event name
3182
+ * @param cb - The callback
3183
+ */
3184
+ on(t, e) {
3185
+ this.setSubscriber(t, { cb: e });
3186
+ }
3187
+ /**
3188
+ * Subscribe to an event once
3189
+ * @param event - The event name
3190
+ * @param cb - The callback
3191
+ */
3192
+ once(t, e) {
3193
+ this.setSubscriber(t, {
3194
+ cb: e,
3195
+ once: true
3196
+ });
3197
+ }
3198
+ /**
3199
+ * Emit an event with data
3200
+ * @param event - The event name
3201
+ * @param data - The data to pass to the callback
3202
+ */
3203
+ emit(t, ...e) {
3204
+ const i = this._subscribers.get(t) ?? [], s = [];
3205
+ for (const r of i) r.cb(...e), r.once && s.push(() => i.splice(i.indexOf(r), 1));
3206
+ for (const r of s) r();
3207
+ }
3208
+ prompt() {
3209
+ return new Promise((t) => {
3210
+ if (this._abortSignal) {
3211
+ if (this._abortSignal.aborted) return this.state = "cancel", this.close(), t(CANCEL_SYMBOL);
3212
+ this._abortSignal.addEventListener("abort", () => {
3213
+ this.state = "cancel", this.close();
3214
+ }, { once: true });
3215
+ }
3216
+ this.rl = l__default.createInterface({
3217
+ input: this.input,
3218
+ tabSize: 2,
3219
+ prompt: "",
3220
+ escapeCodeTimeout: 50,
3221
+ terminal: true
3222
+ }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on("keypress", this.onKeypress), setRawMode(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
3223
+ this.output.write(import_src.cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t(this.value);
3224
+ }), this.once("cancel", () => {
3225
+ this.output.write(import_src.cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t(CANCEL_SYMBOL);
3226
+ });
3227
+ });
3228
+ }
3229
+ _isActionKey(t, e) {
3230
+ return t === " ";
3231
+ }
3232
+ _shouldSubmit(t, e) {
3233
+ return true;
3234
+ }
3235
+ _setValue(t) {
3236
+ this.value = t, this.emit("value", this.value);
3237
+ }
3238
+ _setUserInput(t, e) {
3239
+ this.userInput = t ?? "", this.emit("userInput", this.userInput), e && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);
3240
+ }
3241
+ _clearUserInput() {
3242
+ this.rl?.write(null, {
3243
+ ctrl: true,
3244
+ name: "u"
3245
+ }), this._setUserInput("");
3246
+ }
3247
+ async onKeypress(t, e) {
3248
+ if (this.state !== "validating") {
3249
+ if (this._track && e.name !== "return" && (e.name && this._isActionKey(t, e) && this.rl?.write(null, {
3250
+ ctrl: true,
3251
+ name: "h"
3252
+ }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit("cursor", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit("cursor", e.name)), t && (t.toLowerCase() === "y" || t.toLowerCase() === "n") && this.emit("confirm", t.toLowerCase() === "y"), this.emit("key", t, e), e?.name === "return" && this._shouldSubmit(t, e)) {
3253
+ if (this.opts.validate) {
3254
+ const i = runValidation(this.opts.validate, this.value);
3255
+ let s;
3256
+ i instanceof Promise ? (this.state = "validating", this.render(), s = await i) : s = i, s && (this.error = s instanceof Error ? s.message : s, this.state = "error", this.rl?.write(this.userInput));
3257
+ }
3258
+ this.state !== "error" && (this.state = "submit");
3259
+ }
3260
+ isActionKey([
3261
+ t,
3262
+ e?.name,
3263
+ e?.sequence
3264
+ ], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
3265
+ }
3266
+ }
3267
+ close() {
3268
+ this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
3269
+ `), setRawMode(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
3270
+ }
3271
+ restoreCursor() {
3272
+ const t = wrapAnsi(this._prevFrame, process.stdout.columns, {
3273
+ hard: true,
3274
+ trim: false
3275
+ }).split(`
3276
+ `).length - 1;
3277
+ this.output.write(import_src.cursor.move(-999, t * -1));
3278
+ }
3279
+ render() {
3280
+ const t = wrapAnsi(this._render(this) ?? "", process.stdout.columns, {
3281
+ hard: true,
3282
+ trim: false
3283
+ });
3284
+ if (t !== this._prevFrame) {
3285
+ if (this.state === "initial") this.output.write(import_src.cursor.hide);
3286
+ else {
3287
+ const e = diffLines(this._prevFrame, t), i = getRows(this.output);
3288
+ if (this.restoreCursor(), e) {
3289
+ const s = Math.max(0, e.numLinesAfter - i), r = Math.max(0, e.numLinesBefore - i);
3290
+ let n = e.lines.find((o) => o >= s);
3291
+ if (n === void 0) {
3292
+ this._prevFrame = t;
3293
+ return;
3294
+ }
3295
+ if (e.lines.length === 1) {
3296
+ this.output.write(import_src.cursor.move(0, n - r)), this.output.write(import_src.erase.lines(1));
3297
+ const o = t.split(`
3298
+ `);
3299
+ this.output.write(o[n]), this._prevFrame = t, this.output.write(import_src.cursor.move(0, o.length - n - 1));
3300
+ return;
3301
+ } else if (e.lines.length > 1) {
3302
+ if (s < r) n = s;
3303
+ else {
3304
+ const h = n - r;
3305
+ h > 0 && this.output.write(import_src.cursor.move(0, h));
3306
+ }
3307
+ this.output.write(import_src.erase.down());
3308
+ const f = t.split(`
3309
+ `).slice(n);
3310
+ this.output.write(f.join(`
3311
+ `)), this._prevFrame = t;
3312
+ return;
3313
+ }
3314
+ }
3315
+ this.output.write(import_src.erase.down());
3316
+ }
3317
+ this.output.write(t), this.state === "initial" && (this.state = "active"), this._prevFrame = t;
3318
+ }
3319
+ }
3320
+ };
3321
+ var r = class extends y {
3322
+ get cursor() {
3323
+ return this.value ? 0 : 1;
3324
+ }
3325
+ get _value() {
3326
+ return this.cursor === 0;
3327
+ }
3328
+ constructor(t) {
3329
+ super(t, false), this.value = !!t.initialValue, this.on("userInput", () => {
3330
+ this.value = this._value;
3331
+ }), this.on("confirm", (i) => {
3332
+ this.output.write(import_src.cursor.move(0, -1)), this.value = i, this.state = "submit", this.close();
3333
+ }), this.on("cursor", () => {
3334
+ this.value = !this.value;
3335
+ });
3336
+ }
3337
+ };
3338
+ var a = class extends y {
3339
+ options;
3340
+ cursor = 0;
3341
+ get _value() {
3342
+ return this.options[this.cursor]?.value;
3343
+ }
3344
+ get _enabledOptions() {
3345
+ return this.options.filter((e) => e.disabled !== true);
3346
+ }
3347
+ toggleAll() {
3348
+ const e = this._enabledOptions, i = this.value !== void 0 && this.value.length === e.length;
3349
+ this.value = i ? [] : e.map((t) => t.value);
3350
+ }
3351
+ toggleInvert() {
3352
+ const e = this.value;
3353
+ if (!e) return;
3354
+ const i = this._enabledOptions.filter((t) => !e.includes(t.value));
3355
+ this.value = i.map((t) => t.value);
3356
+ }
3357
+ toggleValue() {
3358
+ this.value === void 0 && (this.value = []);
3359
+ const e = this.value.includes(this._value);
3360
+ this.value = e ? this.value.filter((i) => i !== this._value) : [...this.value, this._value];
3361
+ }
3362
+ constructor(e) {
3363
+ super(e, false), this.options = e.options, this.value = [...e.initialValues ?? []];
3364
+ const i = Math.max(this.options.findIndex(({ value: t }) => t === e.cursorAt), 0);
3365
+ this.cursor = this.options[i]?.disabled ? findCursor(i, 1, this.options) : i, this.on("key", (t, l) => {
3366
+ l.name === "a" && this.toggleAll(), l.name === "i" && this.toggleInvert();
3367
+ }), this.on("cursor", (t) => {
3368
+ switch (t) {
3369
+ case "left":
3370
+ case "up":
3371
+ this.cursor = findCursor(this.cursor, -1, this.options);
3372
+ break;
3373
+ case "down":
3374
+ case "right":
3375
+ this.cursor = findCursor(this.cursor, 1, this.options);
3376
+ break;
3377
+ case "space": this.toggleValue();
3378
+ }
3379
+ });
3380
+ }
3381
+ };
3382
+
3383
+ //#endregion
3384
+ //#region node_modules/@clack/prompts/dist/index.mjs
3385
+ function isUnicodeSupported() {
3386
+ if (process$1.platform !== "win32") return process$1.env.TERM !== "linux";
3387
+ return Boolean(process$1.env.CI) || Boolean(process$1.env.WT_SESSION) || Boolean(process$1.env.TERMINUS_SUBLIME) || process$1.env.ConEmuTask === "{cmd::Cmder}" || process$1.env.TERM_PROGRAM === "Terminus-Sublime" || process$1.env.TERM_PROGRAM === "vscode" || process$1.env.TERM === "xterm-256color" || process$1.env.TERM === "alacritty" || process$1.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
3388
+ }
3389
+ const unicode = isUnicodeSupported();
3390
+ const isTTY = (o) => o.isTTY === true;
3391
+ const unicodeOr = (o, e) => unicode ? o : e;
3392
+ const S_STEP_ACTIVE = unicodeOr("◆", "*");
3393
+ const S_STEP_CANCEL = unicodeOr("■", "x");
3394
+ const S_STEP_ERROR = unicodeOr("▲", "x");
3395
+ const S_STEP_SUBMIT = unicodeOr("◇", "o");
3396
+ const S_BAR_START = unicodeOr("┌", "T");
3397
+ const S_BAR = unicodeOr("│", "|");
3398
+ const S_BAR_END = unicodeOr("└", "—");
3399
+ const S_BAR_START_RIGHT = unicodeOr("┐", "T");
3400
+ const S_BAR_END_RIGHT = unicodeOr("┘", "—");
3401
+ const S_RADIO_ACTIVE = unicodeOr("●", ">");
3402
+ const S_RADIO_INACTIVE = unicodeOr("○", " ");
3403
+ const S_CHECKBOX_ACTIVE = unicodeOr("◻", "[•]");
3404
+ const S_CHECKBOX_SELECTED = unicodeOr("◼", "[+]");
3405
+ const S_CHECKBOX_INACTIVE = unicodeOr("◻", "[ ]");
3406
+ const S_PASSWORD_MASK = unicodeOr("▪", "•");
3407
+ const S_BAR_H = unicodeOr("─", "-");
3408
+ const S_CORNER_TOP_RIGHT = unicodeOr("╮", "+");
3409
+ const S_CONNECT_LEFT = unicodeOr("├", "+");
3410
+ const S_CORNER_BOTTOM_RIGHT = unicodeOr("╯", "+");
3411
+ const S_CORNER_BOTTOM_LEFT = unicodeOr("╰", "+");
3412
+ const S_CORNER_TOP_LEFT = unicodeOr("╭", "+");
3413
+ const S_INFO = unicodeOr("●", "•");
3414
+ const S_SUCCESS = unicodeOr("◆", "*");
3415
+ const S_WARN = unicodeOr("▲", "!");
3416
+ const S_ERROR = unicodeOr("■", "x");
3417
+ const symbol = (o) => {
3418
+ switch (o) {
3419
+ case "initial":
3420
+ case "active": return styleText("cyan", S_STEP_ACTIVE);
3421
+ case "cancel": return styleText("red", S_STEP_CANCEL);
3422
+ case "error": return styleText("yellow", S_STEP_ERROR);
3423
+ case "submit": return styleText("green", S_STEP_SUBMIT);
3424
+ case "validating": return styleText("dim", S_STEP_ACTIVE);
3425
+ }
3426
+ };
3427
+ const symbolBar = (o) => {
3428
+ switch (o) {
3429
+ case "initial":
3430
+ case "active": return styleText("cyan", S_BAR);
3431
+ case "cancel": return styleText("red", S_BAR);
3432
+ case "error": return styleText("yellow", S_BAR);
3433
+ case "submit": return styleText("green", S_BAR);
3434
+ }
3435
+ };
3436
+ function formatInstructionFooter(o, e) {
3437
+ const r = [`${e ? `${styleText("cyan", S_BAR)} ` : ""}${o.join(" • ")}`];
3438
+ return e && r.push(styleText("cyan", S_BAR_END)), r;
3439
+ }
3440
+ const I = (l, e, w, p, b, C = false) => {
3441
+ let r = e, O = 0;
3442
+ if (C) for (let i = p - 1; i >= w; i--) {
3443
+ const m = l[i];
3444
+ if (m && (r -= m.length), O++, r <= b) break;
3445
+ }
3446
+ else for (let i = w; i < p; i++) {
3447
+ const m = l[i];
3448
+ if (m && (r -= m.length), O++, r <= b) break;
3449
+ }
3450
+ return {
3451
+ lineCount: r,
3452
+ removals: O
3453
+ };
3454
+ };
3455
+ const limitOptions = ({ cursor: l, options: e, style: w, output: p = process.stdout, maxItems: b = Number.POSITIVE_INFINITY, columnPadding: C = 0, rowPadding: r = 4 }) => {
3456
+ const i = getColumns(p) - C, m = getRows(p), M = styleText("dim", "..."), v = Math.max(m - r, 0), a = Math.max(Math.min(b, v), 5);
3457
+ let f = 0;
3458
+ l >= a - 3 && (f = Math.max(Math.min(l - a + 3, e.length - a), 0));
3459
+ let d = a < e.length && f > 0, c = a < e.length && f + a < e.length;
3460
+ const W = Math.min(f + a, e.length), s = [];
3461
+ let g = 0;
3462
+ d && g++, c && g++;
3463
+ const T = f + (d ? 1 : 0), y = W - (c ? 1 : 0);
3464
+ for (let t = T; t < y; t++) {
3465
+ const n = e[t], o = n ? w(n, t === l) : "", h = wrapAnsi(o, i, {
3466
+ hard: true,
3467
+ trim: false
3468
+ }).split(`
3469
+ `);
3470
+ s.push(h), g += h.length;
3471
+ }
3472
+ if (g > v) {
3473
+ let t = 0, n = 0, o = g;
3474
+ const h = l - T;
3475
+ let u = v;
3476
+ const L = () => I(s, o, 0, h, u), E = () => I(s, o, h + 1, s.length, u, true);
3477
+ d ? ({lineCount: o, removals: t} = L(), o > u && (c || (u -= 1), {lineCount: o, removals: n} = E())) : (c || (u -= 1), {lineCount: o, removals: n} = E(), o > u && (u -= 1, {lineCount: o, removals: t} = L())), t > 0 && (d = true, s.splice(0, t)), n > 0 && (c = true, s.splice(s.length - n, n));
3478
+ }
3479
+ const x = [];
3480
+ d && x.push(M);
3481
+ for (const t of s) for (const n of t) x.push(n);
3482
+ return c && x.push(M), x;
3483
+ };
3484
+ const confirm = (e) => {
3485
+ const a = e.active ?? "Yes", o = e.inactive ?? "No";
3486
+ return new r({
3487
+ active: a,
3488
+ inactive: o,
3489
+ signal: e.signal,
3490
+ input: e.input,
3491
+ output: e.output,
3492
+ initialValue: e.initialValue ?? true,
3493
+ render() {
3494
+ const i = e.withGuide ?? settings.withGuide, u = `${symbol(this.state)} `, l = i ? `${styleText("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(e.output, e.message, l, u), s = `${i ? `${styleText("gray", S_BAR)}
3495
+ ` : ""}${f}
3496
+ `, c = this.value ? a : o;
3497
+ switch (this.state) {
3498
+ case "submit": return `${s}${i ? `${styleText("gray", S_BAR)} ` : ""}${styleText("dim", c)}`;
3499
+ case "cancel": return `${s}${i ? `${styleText("gray", S_BAR)} ` : ""}${styleText(["strikethrough", "dim"], c)}${i ? `
3500
+ ${styleText("gray", S_BAR)}` : ""}`;
3501
+ default: {
3502
+ const r = i ? `${styleText("cyan", S_BAR)} ` : "", g = i ? styleText("cyan", S_BAR_END) : "";
3503
+ return `${s}${r}${this.value ? `${styleText("green", S_RADIO_ACTIVE)} ${a}` : `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", a)}`}${e.vertical ? i ? `
3504
+ ${styleText("cyan", S_BAR)} ` : `
3505
+ ` : ` ${styleText("dim", "/")} `}${this.value ? `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", o)}` : `${styleText("green", S_RADIO_ACTIVE)} ${o}`}
3506
+ ${g}
3507
+ `;
3508
+ }
3509
+ }
3510
+ }
3511
+ }).prompt();
3512
+ };
3513
+ const MULTISELECT_INSTRUCTIONS = [
3514
+ `${styleText("dim", "↑/↓")} to navigate`,
3515
+ `${styleText("dim", "Space:")} select`,
3516
+ `${styleText("dim", "Enter:")} confirm`
3517
+ ];
3518
+ const m = (i, u) => i.split(`
3519
+ `).map((d) => u(d)).join(`
3520
+ `);
3521
+ const multiselect = (i) => {
3522
+ const u = (t, a) => {
3523
+ const r = t.label ?? String(t.value);
3524
+ return a === "disabled" ? `${styleText("gray", S_CHECKBOX_INACTIVE)} ${m(r, (o) => styleText(["strikethrough", "gray"], o))}${t.hint ? ` ${styleText("dim", `(${t.hint ?? "disabled"})`)}` : ""}` : a === "active" ? `${styleText("cyan", S_CHECKBOX_ACTIVE)} ${r}${t.hint ? ` ${styleText("dim", `(${t.hint})`)}` : ""}` : a === "selected" ? `${styleText("green", S_CHECKBOX_SELECTED)} ${m(r, (o) => styleText("dim", o))}${t.hint ? ` ${styleText("dim", `(${t.hint})`)}` : ""}` : a === "cancelled" ? `${m(r, (o) => styleText(["strikethrough", "dim"], o))}` : a === "active-selected" ? `${styleText("green", S_CHECKBOX_SELECTED)} ${r}${t.hint ? ` ${styleText("dim", `(${t.hint})`)}` : ""}` : a === "submitted" ? `${m(r, (o) => styleText("dim", o))}` : `${styleText("dim", S_CHECKBOX_INACTIVE)} ${m(r, (o) => styleText("dim", o))}`;
3525
+ }, d = i.required ?? true, x = i.showInstructions ?? true;
3526
+ return new a({
3527
+ options: i.options,
3528
+ signal: i.signal,
3529
+ input: i.input,
3530
+ output: i.output,
3531
+ initialValues: i.initialValues,
3532
+ required: d,
3533
+ cursorAt: i.cursorAt,
3534
+ validate(t) {
3535
+ if (d && (t === void 0 || t.length === 0)) return `Please select at least one option.
3536
+ ${styleText("reset", styleText("dim", `Press ${styleText([
3537
+ "gray",
3538
+ "bgWhite",
3539
+ "inverse"
3540
+ ], " space ")} to select, ${styleText("gray", styleText("bgWhite", styleText("inverse", " enter ")))} to submit`))}`;
3541
+ },
3542
+ render() {
3543
+ const t = i.withGuide ?? settings.withGuide, a = wrapTextWithPrefix(i.output, i.message, t ? `${symbolBar(this.state)} ` : "", `${symbol(this.state)} `), r = `${t ? `${styleText("gray", S_BAR)}
3544
+ ` : ""}${a}
3545
+ `, o = this.value ?? [], g = (n, l) => {
3546
+ if (n.disabled) return u(n, "disabled");
3547
+ const s = o.includes(n.value);
3548
+ return l && s ? u(n, "active-selected") : s ? u(n, "selected") : u(n, l ? "active" : "inactive");
3549
+ };
3550
+ switch (this.state) {
3551
+ case "submit": {
3552
+ const n = this.options.filter(({ value: s }) => o.includes(s)).map((s) => u(s, "submitted")).join(styleText("dim", ", ")) || styleText("dim", "none");
3553
+ return `${r}${wrapTextWithPrefix(i.output, n, t ? `${styleText("gray", S_BAR)} ` : "")}`;
3554
+ }
3555
+ case "cancel": {
3556
+ const n = this.options.filter(({ value: s }) => o.includes(s)).map((s) => u(s, "cancelled")).join(styleText("dim", ", "));
3557
+ if (n.trim() === "") return `${r}${styleText("gray", S_BAR)}`;
3558
+ return `${r}${wrapTextWithPrefix(i.output, n, t ? `${styleText("gray", S_BAR)} ` : "")}${t ? `
3559
+ ${styleText("gray", S_BAR)}` : ""}`;
3560
+ }
3561
+ case "error": {
3562
+ const n = t ? `${styleText("yellow", S_BAR)} ` : "", l = this.error.split(`
3563
+ `).map(($, v) => v === 0 ? `${t ? `${styleText("yellow", S_BAR_END)} ` : ""}${styleText("yellow", $)}` : ` ${$}`).join(`
3564
+ `), s = r.split(`
3565
+ `).length, h = l.split(`
3566
+ `).length + 1;
3567
+ return `${r}${n}${limitOptions({
3568
+ output: i.output,
3569
+ options: this.options,
3570
+ cursor: this.cursor,
3571
+ maxItems: i.maxItems,
3572
+ columnPadding: n.length,
3573
+ rowPadding: s + h,
3574
+ style: g
3575
+ }).join(`
3576
+ ${n}`)}
3577
+ ${l}
3578
+ `;
3579
+ }
3580
+ default: {
3581
+ const n = t ? `${styleText("cyan", S_BAR)} ` : "", l = r.split(`
3582
+ `).length, s = x ? formatInstructionFooter(MULTISELECT_INSTRUCTIONS, t) : t ? [styleText("cyan", S_BAR_END)] : [], h = s.join(`
3583
+ `), $ = s.length + 1;
3584
+ return `${r}${n}${limitOptions({
3585
+ output: i.output,
3586
+ options: this.options,
3587
+ cursor: this.cursor,
3588
+ maxItems: i.maxItems,
3589
+ columnPadding: n.length,
3590
+ rowPadding: l + $,
3591
+ style: g
3592
+ }).join(`
3593
+ ${n}`)}
3594
+ ${h}
3595
+ `;
3596
+ }
3597
+ }
3598
+ }
3599
+ }).prompt();
3600
+ };
3601
+ const cancel = (o = "", t) => {
3602
+ const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText("gray", S_BAR_END)} ` : "";
3603
+ i.write(`${e}${styleText("red", o)}
3604
+
3605
+ `);
3606
+ };
3607
+ const u = {
3608
+ light: unicodeOr("─", "-"),
3609
+ heavy: unicodeOr("━", "="),
3610
+ block: unicodeOr("█", "#")
3611
+ };
3612
+ const SELECT_INSTRUCTIONS = [`${styleText("dim", "↑/↓")} to navigate`, `${styleText("dim", "Enter:")} confirm`];
3613
+ const i = `${styleText("gray", S_BAR)} `;
3614
+
3615
+ //#endregion
3616
+ //#region src/secrets.js
3617
+ const REDACTED = "<redacted>";
3618
+ const MIN_TOKEN = 12;
3619
+ const containsSecret = (text, secret) => typeof text === "string" && typeof secret === "string" && secret.length >= MIN_TOKEN && text.includes(secret);
3620
+ const SECRET_KEY = /^(?:.*_)?(?:key|token|secret|password|passwd|credential|auth|authorization)s?$/;
3621
+ function isSecretKey(key) {
3622
+ const leaf = key.split(".").at(-1).replace(/([^A-Z_])([A-Z])/g, (_, before, after) => `${before}_${after}`).replaceAll("-", "_").toLowerCase();
3623
+ return SECRET_KEY.test(leaf);
3624
+ }
3625
+ function isEnvReference(value) {
3626
+ return typeof value === "string" && value.length <= 128 && /^(?:\{env:[A-Za-z0-9_]+\}|\$[A-Za-z0-9_]+|[A-Z][A-Z0-9_]{2,})$/.test(value);
3627
+ }
3628
+ const LITERAL = /^(?:true|false|null|-?\d+(?:\.\d+)?)$/;
3629
+ const hidesValue = (key, value) => isSecretKey(key) && !isEnvReference(value) && !LITERAL.test(value);
3630
+ function maskValue(key, value, secret) {
3631
+ if (typeof value !== "string") return value;
3632
+ if (containsSecret(value, secret)) return REDACTED;
3633
+ return hidesValue(key, value) ? REDACTED : value;
3634
+ }
3635
+ const unquote = (text) => text.replace(/^["']|["']$/g, "");
3636
+ const SECRET_PAIR = /("(?:[^"\n]*)"|'[^'\n]+'|[A-Za-z0-9_.-]+)(\s*[:=]\s*)("(?:[^"\\\n]*)"|'(?:[^'\\\n]*)'|\[[^\]]*\]|[^\s,}\]{\[][^,}\]\n{\[]*)/g;
3637
+ const QUOTED = /"(?:[^"\\\n]*)"|'[^'\\\n]*'/g;
3638
+ function redactPair(key, value) {
3639
+ if (!hidesValue(unquote(key), unquote(value))) return null;
3640
+ return value.startsWith("[") ? value.replace(QUOTED, REDACTED) : REDACTED;
3641
+ }
3642
+ function redactText(text, secret) {
3643
+ const redacted = text.replace(SECRET_PAIR, (whole, key, separator, value) => {
3644
+ const masked = redactPair(key, value);
3645
+ return masked === null ? whole : `${key}${separator}${masked}`;
3646
+ });
3647
+ return containsSecret(redacted, secret) ? redacted.replaceAll(secret, REDACTED) : redacted;
3648
+ }
3649
+ const maskChanges = (changes, secret) => changes.map((change) => ({
3650
+ op: change.op,
3651
+ key: change.key,
3652
+ value: maskValue(change.key, change.value, secret),
3653
+ ...change.op === "replace" ? { oldValue: maskValue(change.key, change.oldValue, secret) } : {}
3654
+ }));
3655
+
3656
+ //#endregion
3657
+ //#region src/diff.js
3658
+ function readValues(text, format) {
3659
+ if (format === "toml") try {
3660
+ return parse$1(text);
3661
+ } catch {
3662
+ throw new Error("Invalid TOML while reading values.");
3663
+ }
3664
+ return parseJson(text, "values");
3665
+ }
3666
+ function* leaves(value, prefix = []) {
3667
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) for (const [key, child] of Object.entries(value)) yield* leaves(child, [...prefix, key]);
3668
+ else yield [prefix.join("."), value];
3669
+ }
3670
+ function diffValues({ before, after, format = "json" }) {
3671
+ const previous = before === null ? {} : readValues(before, format);
3672
+ const next = after === null ? {} : readValues(after, format);
3673
+ const oldKeys = new Map(leaves(previous));
3674
+ const newKeys = new Map(leaves(next));
3675
+ const changes = [];
3676
+ for (const [key, value] of newKeys) if (!oldKeys.has(key)) changes.push({
3677
+ op: "add",
3678
+ key,
3679
+ value
3680
+ });
3681
+ else if (!isDeepStrictEqual(oldKeys.get(key), value)) changes.push({
3682
+ op: "replace",
3683
+ key,
3684
+ value,
3685
+ oldValue: oldKeys.get(key)
3686
+ });
3687
+ for (const [key, value] of oldKeys) if (!newKeys.has(key)) changes.push({
3688
+ op: "remove",
3689
+ key,
3690
+ value
3691
+ });
3692
+ return changes;
3693
+ }
3694
+ function formatValue(value) {
3695
+ if (value === null || value === void 0) return "null";
3696
+ if (typeof value === "string") return value === "" ? "\"\"" : value;
3697
+ if (typeof value === "object") {
3698
+ const inner = Array.isArray(value) ? value.map(formatValue).join(", ") : Object.entries(value).map(([key, child]) => `${key}: ${formatValue(child)}`).join(", ");
3699
+ return Array.isArray(value) ? `[ ${inner} ]` : `{ ${inner} }`;
3700
+ }
3701
+ return String(value);
3702
+ }
3703
+ function toLines(text) {
3704
+ if (text === null || text === "") return [];
3705
+ const lines = text.split("\n");
3706
+ return lines.length > 1 && lines.at(-1) === "" ? lines.slice(0, -1) : lines;
3707
+ }
3708
+ function align(oldLines, newLines) {
3709
+ if (oldLines.length * newLines.length > 25e4) return null;
3710
+ const rows = Array.from({ length: oldLines.length + 1 }, () => new Uint32Array(newLines.length + 1));
3711
+ for (let i = oldLines.length - 1; i >= 0; i -= 1) for (let j = newLines.length - 1; j >= 0; j -= 1) rows[i][j] = oldLines[i] === newLines[j] ? rows[i + 1][j + 1] + 1 : Math.max(rows[i + 1][j], rows[i][j + 1]);
3712
+ const ops = [];
3713
+ let i = 0;
3714
+ let j = 0;
3715
+ while (i < oldLines.length && j < newLines.length) if (oldLines[i] === newLines[j]) {
3716
+ ops.push([" ", i]);
3717
+ i += 1;
3718
+ j += 1;
3719
+ } else if (rows[i + 1][j] >= rows[i][j + 1]) {
3720
+ ops.push(["-", i]);
3721
+ i += 1;
3722
+ } else {
3723
+ ops.push(["+", j]);
3724
+ j += 1;
3725
+ }
3726
+ while (i < oldLines.length) ops.push(["-", i++]);
3727
+ while (j < newLines.length) ops.push(["+", j++]);
3728
+ return ops;
3729
+ }
3730
+ function unifiedDiff(path, before, after, secret) {
3731
+ const oldLines = toLines(before);
3732
+ const newLines = toLines(after);
3733
+ const ops = align(oldLines, newLines) ?? [...oldLines.map((_, index) => ["-", index]), ...newLines.map((_, index) => ["+", index])];
3734
+ if (ops.every(([mark]) => mark === " ")) return [];
3735
+ const CONTEXT = 3;
3736
+ const changed = ops.map(([mark], index) => mark === " " ? -1 : index).filter((index) => index >= 0);
3737
+ const hunks = [];
3738
+ for (const index of changed) {
3739
+ const last = hunks.at(-1);
3740
+ if (last && index - last.end <= 6) last.end = index;
3741
+ else hunks.push({
3742
+ start: index,
3743
+ end: index
3744
+ });
3745
+ }
3746
+ const prefix = [{
3747
+ old: 0,
3748
+ new: 0
3749
+ }];
3750
+ for (const [index, [mark]] of ops.entries()) {
3751
+ const prev = prefix[index];
3752
+ prefix.push({
3753
+ old: prev.old + (mark !== "+"),
3754
+ new: prev.new + (mark !== "-")
3755
+ });
3756
+ }
3757
+ const shown = (text) => toLines(text === null ? null : redactText(text, secret));
3758
+ const [oldShown, newShown] = [shown(before), shown(after)];
3759
+ const body = ops.map(([mark, index]) => `${mark}${(mark === "+" ? newShown : oldShown)[index]}`);
3760
+ const lines = [`--- ${before === null ? "/dev/null" : path}`, `+++ ${after === null ? "/dev/null" : path}`];
3761
+ for (const hunk of hunks) {
3762
+ const from = Math.max(0, hunk.start - CONTEXT);
3763
+ const to = Math.min(ops.length, hunk.end + 1 + CONTEXT);
3764
+ const oldCount = prefix[to].old - prefix[from].old;
3765
+ const newCount = prefix[to].new - prefix[from].new;
3766
+ const oldStart = oldCount ? prefix[from].old + 1 : 0;
3767
+ const newStart = newCount ? prefix[from].new + 1 : 0;
3768
+ lines.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`, ...body.slice(from, to));
3769
+ }
3770
+ return lines;
3771
+ }
3772
+
3773
+ //#endregion
3774
+ //#region src/paths.js
3775
+ const home = homedir();
3776
+ const shortPath = (text) => home ? String(text).replaceAll(`${home}/`, "~/") : String(text);
3777
+
3778
+ //#endregion
3779
+ //#region src/tty.js
3780
+ const interactive = () => isTTY(process.stdout) && isTTY(process.stdin);
3781
+
3782
+ //#endregion
3783
+ //#region src/ui.js
3784
+ const green = (text) => styleText("green", text);
3785
+ const red = (text) => styleText("red", text);
3786
+ const yellow = (text) => styleText("yellow", text);
3787
+ const magenta = (text) => styleText("magenta", text);
3788
+ const gray = (text) => styleText("gray", text);
3789
+ const dim = (text) => styleText("dim", text);
3790
+ const bold = (text) => styleText("bold", text);
3791
+ const underline = (text) => styleText("underline", text);
3792
+ const link = (text) => styleText(["blue", "underline"], text);
3793
+ if (!interactive()) settings.withGuide = false;
3794
+ const columns = () => process.stdout.columns || Number(process.env.COLUMNS) || 88;
3795
+ const width = () => Math.min(columns(), 96);
3796
+ const GUTTER = " ";
3797
+ const visible = (text) => text.replace(/\u001b\[[0-9;]*m/g, "");
3798
+ const unbreakable = (word) => /^[a-z][a-z0-9+.-]*:\/\//i.test(word);
3799
+ function pieces(text, limit) {
3800
+ return text.split(" ").flatMap((word) => unbreakable(word) || visible(word).length <= limit ? [word] : word.match(new RegExp(`.{1,${limit}}`, "g")));
3801
+ }
3802
+ function wrap(text, limit) {
3803
+ if (visible(text).length <= limit) return [text];
3804
+ const lines = [];
3805
+ let line = null;
3806
+ for (const word of pieces(text, limit)) if (line !== null && visible(`${line} ${word}`).length > limit) {
3807
+ lines.push(line);
3808
+ line = word;
3809
+ } else line = line === null ? word : `${line} ${word}`;
3810
+ if (line !== null) lines.push(line);
3811
+ return lines;
3812
+ }
3813
+ function displayValue(key, value, secret) {
3814
+ const safe = maskValue(key, value, secret);
3815
+ if (safe === "<redacted>") return {
3816
+ text: safe,
3817
+ color: yellow
3818
+ };
3819
+ if (isEnvReference(safe)) return {
3820
+ text: String(safe),
3821
+ color: magenta
3822
+ };
3823
+ return {
3824
+ text: formatValue(safe),
3825
+ color: (text) => text
3826
+ };
3827
+ }
3828
+ const OP = {
3829
+ add: {
3830
+ mark: "+",
3831
+ color: green
3832
+ },
3833
+ replace: {
3834
+ mark: "~",
3835
+ color: yellow
3836
+ },
3837
+ remove: {
3838
+ mark: "-",
3839
+ color: red
3840
+ }
3841
+ };
3842
+ const STATUS = {
3843
+ create: {
3844
+ word: "Create",
3845
+ color: green
3846
+ },
3847
+ update: {
3848
+ word: "Update",
3849
+ color: green
3850
+ },
3851
+ unchanged: {
3852
+ word: "Unchanged",
3853
+ color: gray
3854
+ },
3855
+ restore: {
3856
+ word: "Restore",
3857
+ color: yellow
3858
+ },
3859
+ remove: {
3860
+ word: "Delete",
3861
+ color: red
3862
+ }
3863
+ };
3864
+ const columnWidth = (values, gap = 2) => Math.max(...values.map((value) => visible(String(value)).length), 0) + gap;
3865
+ const pad = (text, column) => {
3866
+ const value = String(text);
3867
+ return value + " ".repeat(Math.max(1, column - visible(value).length));
3868
+ };
3869
+ const MODEL_PATTERN = new RegExp(`(?<![\\w/.-])${MODEL.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w-])`, "g");
3870
+ const model = (text) => String(text).replace(MODEL_PATTERN, (match) => green(match));
3871
+ const STATUS_COLUMN = columnWidth(Object.values(STATUS).map((status) => status.word));
3872
+ function clip(text, limit) {
3873
+ const visibleText = visible(text);
3874
+ if (visibleText.length <= limit) return text;
3875
+ const head = Math.max(Math.ceil((limit - 1) / 2), 1);
3876
+ const tail = Math.max(limit - 1 - head, 1);
3877
+ return `${visibleText.slice(0, head)}\u2026${visibleText.slice(-tail)}`;
3878
+ }
3879
+ function changeLines(changes, secret, limit) {
3880
+ const keyWidth = Math.min(columnWidth(changes.map((change) => change.key)), 45, Math.max(17, limit - 3 - 3 - 20));
3881
+ const rows = [];
3882
+ for (const change of changes) {
3883
+ const op = OP[change.op];
3884
+ const key = change.key.length > keyWidth ? `${change.key.slice(0, keyWidth - 1)}…` : change.key;
3885
+ const prefix = `${op.color(op.mark)} ${dim(model(pad(key, keyWidth)))}`;
3886
+ if (change.op === "replace") {
3887
+ const from = displayValue(change.key, change.oldValue, secret);
3888
+ const to = displayValue(change.key, change.value, secret);
3889
+ rows.push(prefix + dim(model(from.text)) + yellow(" → ") + to.color(model(to.text)));
3890
+ continue;
3891
+ }
3892
+ const value = displayValue(change.key, change.value, secret);
3893
+ const [first, ...rest] = wrap(value.text, Math.max(limit - 3 - 3 - keyWidth, 20));
3894
+ rows.push(prefix + value.color(model(first ?? "")));
3895
+ for (const line of rest) rows.push(dim(" ".repeat(2)) + " ".repeat(keyWidth) + value.color(model(line)));
3896
+ }
3897
+ return rows;
3898
+ }
3899
+ const DIFF_MARKS = [
3900
+ "+",
3901
+ "-",
3902
+ "@"
3903
+ ];
3904
+ function fileBlock(file, { secret }) {
3905
+ const status = STATUS[file.status];
3906
+ const limit = width() - 3;
3907
+ const path = clip(shortPath(file.path), limit - STATUS_COLUMN);
3908
+ const lines = [`${status.color(pad(status.word, STATUS_COLUMN))}${bold(path)}`];
3909
+ if (file.diff?.length) {
3910
+ for (const line of file.diff) {
3911
+ const mark = DIFF_MARKS.includes(line[0]) ? line[0] : " ";
3912
+ const color = mark === "+" ? green : mark === "-" ? red : mark === "@" ? magenta : dim;
3913
+ const [first, ...rest] = wrap(line, limit);
3914
+ lines.push(color(first));
3915
+ for (const folded of rest) lines.push(color(mark === "@" ? ` ${folded}` : `${mark}${folded}`));
3916
+ }
3917
+ return lines;
3918
+ }
3919
+ const shown = file.changes.slice(0, 12);
3920
+ lines.push(...changeLines(shown, secret, width()));
3921
+ if (file.changes.length > shown.length) lines.push(dim(`… ${file.changes.length - shown.length} more`));
3922
+ return lines;
3923
+ }
3924
+ const SECTION_GAP = 2;
3925
+ const write = (text) => process.stdout.write(`${text}\n`);
3926
+ function plain(text = "") {
3927
+ write(text === "" ? "" : `${GUTTER}${text}`);
3928
+ }
3929
+ function prose(text) {
3930
+ for (const line of wrap(text, width() - 3)) plain(line);
3931
+ }
3932
+ function heading(text, gap = SECTION_GAP) {
3933
+ for (let index = 0; index < gap; index += 1) write("");
3934
+ for (const line of wrap(text, width() - 3)) plain(bold(model(line)));
3935
+ }
3936
+ function renderPlan(title, files, options = {}) {
3937
+ heading(files.some((file) => file.status !== "unchanged") ? `${title}:` : `${title}: nothing to change`);
3938
+ plain("");
3939
+ for (const [index, file] of files.entries()) {
3940
+ for (const line of fileBlock(file, options)) plain(line);
3941
+ if (index < files.length - 1) plain("");
3942
+ }
3943
+ }
3944
+ function section(title, lines) {
3945
+ heading(title);
3946
+ plain("");
3947
+ for (const line of lines) for (const wrapped of wrap(line, width() - 3)) plain(model(wrapped));
3948
+ }
3949
+ function box(lines) {
3950
+ const left = " ".repeat(1);
3951
+ const inner = Math.max(...lines.map((line) => visible(line).length));
3952
+ const edge = "─".repeat(inner + 2);
3953
+ write(`${left}\u250c${edge}\u2510`);
3954
+ for (const line of lines) write(`${left}\u2502 ${line}${" ".repeat(inner - visible(line).length)} \u2502`);
3955
+ write(`${left}\u2514${edge}\u2518`);
3956
+ }
3957
+ function intro(title, subtitle) {
3958
+ const inner = Math.max(24, width() - 3 - 4);
3959
+ const lines = wrap(title, inner).map((line) => bold(model(line)));
3960
+ if (subtitle) lines.push("", ...wrap(subtitle, inner).map((line) => dim(line)));
3961
+ box(lines);
3962
+ }
3963
+ const outro = (message) => heading(message, 1);
3964
+ const MARK_WIDTH = 2;
3965
+ function bullet(marker, message) {
3966
+ wrap(message, width() - 3 - MARK_WIDTH).forEach((line, index) => {
3967
+ plain(`${index === 0 ? `${marker}${" ".repeat(Math.max(MARK_WIDTH - visible(marker).length, 1))}` : " ".repeat(MARK_WIDTH)}${line}`);
3968
+ });
3969
+ }
3970
+ const success = (message) => bullet(green("✔"), message);
3971
+ const warn = (message) => bullet(yellow("!"), message);
3972
+ const error = (message) => bullet(red("✖"), message);
3973
+ async function selectAssistants(options, initial) {
3974
+ const chosen = await multiselect({
3975
+ message: model(`Set up ${MODEL} for which assistants? ${dim("(space toggles, enter confirms)")}`),
3976
+ options,
3977
+ initialValues: initial,
3978
+ required: false,
3979
+ maxItems: 8
3980
+ });
3981
+ if (isCancel(chosen)) {
3982
+ cancel("Cancelled. Nothing was written.");
3983
+ return false;
3984
+ }
3985
+ return chosen;
3986
+ }
3987
+ async function confirmApply(question, hint) {
3988
+ if (hint) {
3989
+ plain("");
3990
+ plain(dim(hint));
3991
+ }
3992
+ const answer = await confirm({
3993
+ message: question,
3994
+ initialValue: false
3995
+ });
3996
+ if (isCancel(answer)) {
3997
+ cancel("Cancelled. Nothing was written.");
3998
+ return false;
3999
+ }
4000
+ if (!answer) warn("Cancelled. Nothing was written.");
4001
+ return answer;
4002
+ }
4003
+ async function ask(question) {
4004
+ plain("");
4005
+ return await confirm({
4006
+ message: question,
4007
+ initialValue: true
4008
+ }) === true;
4009
+ }
4010
+
4011
+ //#endregion
4012
+ //#region src/plan.js
4013
+ function resolveMode({ apply, nonInteractive }) {
4014
+ if (apply) return "apply";
4015
+ return nonInteractive || !interactive() ? "preview" : "prompt";
4016
+ }
4017
+ const MODE_NOTE = {
4018
+ preview: "Preview only. Pass --apply to write.",
4019
+ apply: "Writing now (--apply).",
4020
+ prompt: "Nothing is written until you confirm."
4021
+ };
4022
+ function describeFile(change, { secret, showDiff = true } = {}) {
4023
+ const status = change.before === change.after ? "unchanged" : change.before === null ? "create" : "update";
4024
+ const changes = status === "unchanged" ? [] : diffValues({
4025
+ before: change.before,
4026
+ after: change.after,
4027
+ format: change.format
4028
+ });
4029
+ return {
4030
+ path: change.path,
4031
+ status,
4032
+ changes,
4033
+ diff: status === "unchanged" || !showDiff ? [] : unifiedDiff(shortPath(change.path), change.before, change.after, secret),
4034
+ change
4035
+ };
4036
+ }
4037
+ async function runWrites({ title, files, options, mode, prompt, hint, pending, write }) {
4038
+ renderPlan(title, files, options);
4039
+ if (mode === "preview") {
4040
+ outro("Dry run complete. No files were changed.");
4041
+ return { applied: 0 };
4042
+ }
4043
+ if (!pending.length) {
4044
+ outro("Already configured. Nothing to write.");
4045
+ return { applied: 0 };
4046
+ }
4047
+ if (mode === "prompt" && !await confirmApply(prompt, hint)) return {
4048
+ applied: 0,
4049
+ declined: true
4050
+ };
4051
+ plain("");
4052
+ let applied = 0;
4053
+ for (const item of pending) {
4054
+ success(await write(item));
4055
+ applied += 1;
4056
+ }
4057
+ return { applied };
4058
+ }
4059
+
4060
+ //#endregion
4061
+ //#region src/journal.js
4062
+ function journalPath(env = process.env, home = homedir(), platform = process.platform) {
4063
+ if (env.APEX_STATE_DIR) return join(env.APEX_STATE_DIR, "journal.json");
4064
+ const state = env.XDG_STATE_HOME || (platform === "win32" ? join(env.APPDATA || join(home, "AppData", "Roaming"), "apex-state") : join(home, ".local", "state"));
4065
+ return join(state, "apex", "journal.json");
4066
+ }
4067
+ async function readJournal(path) {
4068
+ const text = await readConfig(path);
4069
+ if (text === null) return [];
4070
+ let entries;
4071
+ try {
4072
+ entries = JSON.parse(text);
4073
+ } catch {
4074
+ throw new Error(`Apex CLI journal is not valid JSON: ${path}\n Inspect or remove it manually; Apex CLI changed nothing.`);
4075
+ }
4076
+ const shaped = (entry) => typeof entry?.batch === "string" && typeof entry?.at === "string" && typeof entry?.path === "string" && typeof entry?.afterSha === "string" && (entry.backup === null || typeof entry.backup === "string");
4077
+ if (!Array.isArray(entries) || entries.some((entry) => !shaped(entry))) throw new Error(`Unrecognised Apex CLI journal: ${path}\n Inspect or remove it manually; Apex CLI changed nothing.`);
4078
+ return entries;
4079
+ }
4080
+ async function writeJournal(path, entries) {
4081
+ const keep = new Set(batchIds(entries).slice(-20));
4082
+ await writeAtomic(path, `${JSON.stringify(entries.filter((entry) => keep.has(entry.batch)), null, 2)}\n`);
4083
+ }
4084
+ const batchIds = (entries) => [...new Set(entries.map((entry) => entry.batch))];
4085
+ function newEntry(change, batch, backup) {
4086
+ return {
4087
+ batch,
4088
+ at: (/* @__PURE__ */ new Date()).toISOString(),
4089
+ path: change.path,
4090
+ format: change.format ?? "json",
4091
+ created: change.before === null,
4092
+ beforeSha: change.before === null ? null : sha256(change.before),
4093
+ afterSha: sha256(change.after),
4094
+ backup,
4095
+ undoneAt: null
4096
+ };
4097
+ }
4098
+ async function markUndone(journalFile, entry) {
4099
+ const entries = await readJournal(journalFile);
4100
+ const found = entries.find((candidate) => candidate.batch === entry.batch && candidate.path === entry.path && !candidate.undoneAt);
4101
+ if (!found) throw new Error(`Journal has no pending entry for ${entry.path}. That file was already reverted, so mark it undone by hand if you restored it yourself.`);
4102
+ found.undoneAt = (/* @__PURE__ */ new Date()).toISOString();
4103
+ await writeJournal(journalFile, entries);
4104
+ }
4105
+ async function appendEntry(journalFile, entry) {
4106
+ const entries = await readJournal(journalFile);
4107
+ entries.push(entry);
4108
+ await writeJournal(journalFile, entries);
4109
+ }
4110
+ function pendingBatches(entries) {
4111
+ return batchIds(entries).reverse().map((batch) => ({
4112
+ batch,
4113
+ at: entries.findLast((entry) => entry.batch === batch).at,
4114
+ items: entries.filter((entry) => entry.batch === batch && !entry.undoneAt)
4115
+ })).filter((batch) => batch.items.length);
4116
+ }
4117
+ async function planEntry(entry) {
4118
+ const current = await readConfig(entry.path);
4119
+ if (current === null) return {
4120
+ entry,
4121
+ action: "skip",
4122
+ reason: "file no longer exists"
4123
+ };
4124
+ if (sha256(current) !== entry.afterSha) return {
4125
+ entry,
4126
+ action: "skip",
4127
+ reason: `changed by something else since Apex CLI wrote it${entry.backup ? `. Restore ${entry.backup} manually` : ""}`
4128
+ };
4129
+ const format = entry.format ?? "json";
4130
+ if (entry.created) return {
4131
+ entry,
4132
+ action: "remove",
4133
+ change: {
4134
+ path: entry.path,
4135
+ before: current,
4136
+ after: null,
4137
+ format
4138
+ }
4139
+ };
4140
+ if (entry.backup === null) return {
4141
+ entry,
4142
+ action: "skip",
4143
+ reason: "original backup was never recorded for this file"
4144
+ };
4145
+ const stored = await readConfig(entry.backup);
4146
+ if (stored === null || sha256(stored) !== entry.beforeSha) return {
4147
+ entry,
4148
+ action: "skip",
4149
+ reason: `original backup is missing (${entry.backup})`
4150
+ };
4151
+ return {
4152
+ entry,
4153
+ action: "restore",
4154
+ change: {
4155
+ path: entry.path,
4156
+ before: current,
4157
+ after: stored,
4158
+ format
4159
+ }
4160
+ };
4161
+ }
4162
+ async function planUndo(entries) {
4163
+ let newest = null;
4164
+ for (const batch of pendingBatches(entries)) {
4165
+ const plan = {
4166
+ ...batch,
4167
+ planned: await Promise.all(batch.items.map(planEntry))
4168
+ };
4169
+ if (plan.planned.some((item) => item.action !== "skip")) return plan;
4170
+ newest ??= plan;
4171
+ }
4172
+ return newest;
4173
+ }
4174
+
4175
+ //#endregion
4176
+ //#region src/cli.js
4177
+ const FLAGS = {
4178
+ assistants: {
4179
+ type: "string",
4180
+ usage: "--assistants <ids>",
4181
+ hint: "assistant ids",
4182
+ text: `comma list of: ${IDS.join(", ")} (skips the picker)`
4183
+ },
4184
+ "no-interactive": {
4185
+ type: "boolean",
4186
+ usage: "--no-interactive",
4187
+ hint: "never prompt",
4188
+ text: "skip the questions and just print the plan"
4189
+ },
4190
+ apply: {
4191
+ type: "boolean",
4192
+ usage: "--apply",
4193
+ hint: "write without prompting",
4194
+ text: "write changes without prompting (scripts and CI)"
4195
+ },
4196
+ "no-diff": {
4197
+ type: "boolean",
4198
+ usage: "--no-diff",
4199
+ hint: "list settings instead of the file diff",
4200
+ text: "hide the raw file diff (it is shown by default, secrets redacted)"
4201
+ },
4202
+ json: {
4203
+ type: "boolean",
4204
+ usage: "--json",
4205
+ hint: "machine-readable output",
4206
+ text: "print machine-readable output instead of the human UI"
4207
+ },
4208
+ list: {
4209
+ type: "boolean",
4210
+ usage: "--list",
4211
+ hint: "list recorded setups",
4212
+ text: "show recorded setups instead of reverting one"
4213
+ },
4214
+ help: {
4215
+ type: "boolean",
4216
+ short: "h",
4217
+ usage: "--help, -h",
4218
+ hint: "show help",
4219
+ text: "show all commands"
4220
+ }
4221
+ };
4222
+ const COMMANDS = {
4223
+ init: {
4224
+ args: "[--assistants <ids>] [options]",
4225
+ summary: "configure assistants",
4226
+ flags: [
4227
+ "assistants",
4228
+ "no-interactive",
4229
+ "apply",
4230
+ "no-diff",
4231
+ "json",
4232
+ "help"
4233
+ ]
4234
+ },
4235
+ detect: {
4236
+ args: "[--json]",
4237
+ summary: "show what Apex CLI can see on this machine",
4238
+ flags: ["json", "help"]
4239
+ },
4240
+ undo: {
4241
+ args: "[--list] [options]",
4242
+ summary: "reverse the most recent Apex CLI setup",
4243
+ flags: [
4244
+ "no-interactive",
4245
+ "apply",
4246
+ "no-diff",
4247
+ "json",
4248
+ "list",
4249
+ "help"
4250
+ ]
4251
+ },
4252
+ run: {
4253
+ args: `<${RUNNABLE.join("|")}> [-- <args>]`,
4254
+ summary: "launch an assistant with the gateway set",
4255
+ flags: []
4256
+ },
4257
+ completion: {
4258
+ args: "<zsh|bash|fish>",
4259
+ summary: "print a shell completion script",
4260
+ flags: []
4261
+ },
4262
+ help: {
4263
+ args: "",
4264
+ summary: "show all commands",
4265
+ flags: []
4266
+ }
4267
+ };
4268
+ const SHELLS = [
4269
+ "zsh",
4270
+ "bash",
4271
+ "fish"
4272
+ ];
4273
+ const APEX = process.env.npm_command === "exec" ? "npx @callstack/apex" : "apex";
4274
+ const packageVersion = async () => JSON.parse(await readFile(new URL("../package.json", import.meta.url))).version;
4275
+ async function installApex() {
4276
+ if (!await ask("Install the apex command globally, so apex undo and apex run work later?")) return false;
4277
+ const npm = spawn("npm", [
4278
+ "install",
4279
+ "--global",
4280
+ `@callstack/apex@${await packageVersion()}`
4281
+ ], {
4282
+ stdio: [
4283
+ "ignore",
4284
+ "ignore",
4285
+ "inherit"
4286
+ ],
4287
+ shell: process.platform === "win32"
4288
+ });
4289
+ const code = await new Promise((resolve) => {
4290
+ npm.once("error", () => resolve(1));
4291
+ npm.once("exit", resolve);
4292
+ });
4293
+ if (code === 0) success("Installed. From now on, just type apex.");
4294
+ else warn("npm could not install it. Run npm install -g @callstack/apex yourself.");
4295
+ return code === 0;
4296
+ }
4297
+ const OPTIONS = Object.fromEntries(Object.entries(FLAGS).map(([name, flag]) => [name, {
4298
+ type: flag.type,
4299
+ ...flag.short ? { short: flag.short } : {}
4300
+ }]));
4301
+ const flagsOf = (command) => COMMANDS[command].flags;
4302
+ const commandsFor = (flag) => Object.keys(COMMANDS).filter((name) => COMMANDS[name].flags.includes(flag));
4303
+ const usageRows = Object.entries(COMMANDS).map(([name, command]) => [`apex ${name}${command.args ? ` ${command.args}` : ""}`, command.summary]);
4304
+ const optionRows = [[
4305
+ "(no flags)",
4306
+ "(init, undo)",
4307
+ "interactive: pick assistants, review every change and diff, then confirm"
4308
+ ], ...Object.entries(FLAGS).map(([name, flag]) => [
4309
+ flag.usage,
4310
+ `(${commandsFor(name).join(", ")})`,
4311
+ flag.text
4312
+ ])];
4313
+ const exampleRows = [
4314
+ ["apex init", "pick assistants, review, confirm"],
4315
+ ["apex init --assistants codex,pi", "preview two tools (agent and CI friendly)"],
4316
+ ["apex init --assistants codex,pi --apply", "write those two without asking"],
4317
+ ["apex undo", "preview the reversal"],
4318
+ ["apex undo --apply", "reverse the last setup without asking"],
4319
+ ["apex detect --json", "machine-readable inventory"]
4320
+ ];
4321
+ const environmentRows = [
4322
+ ["CALLSTACK_AUTH_TOKEN", "your callstack.ai key, needed by apex run and by every assistant you configure"],
4323
+ ["Config directories", "XDG_CONFIG_HOME, CODEX_HOME, CLAUDE_CONFIG_DIR, PI_CODING_AGENT_DIR"],
4324
+ ["Undo journal", "APEX_STATE_DIR, XDG_STATE_HOME (default ~/.local/state/apex)"]
4325
+ ];
4326
+ const installRows = [
4327
+ ["zsh", "apex completion zsh > \"${fpath[1]}/_apex\""],
4328
+ ["bash", "apex completion bash >> ~/.bashrc"],
4329
+ ["fish", "apex completion fish > ~/.config/fish/completions/apex.fish"]
4330
+ ];
4331
+ const INDENT = " ";
4332
+ const MIN_TEXT = 24;
4333
+ const helpHeading = (text) => bold(underline(text));
4334
+ const PLAIN = (text) => text;
4335
+ const rowColors = (lead, scope = PLAIN, text = PLAIN) => ({
4336
+ lead,
4337
+ scope,
4338
+ text
4339
+ });
4340
+ const optionColors = rowColors((text) => text.startsWith("--") ? green(text) : dim(text), dim, PLAIN);
4341
+ const commandLine = (line, index = 0) => index ? dim(line) : line.replace(/^(apex)( \S+)?(.*)$/, (_, apex, command = "", rest) => green(apex) + command + (rest && dim(rest)));
4342
+ function columnRows(rows, color, width) {
4343
+ const leadWidth = Math.min(columnWidth(rows.map(([lead]) => lead)), Math.floor(width / 2) - 2);
4344
+ const scopeWidth = rows.some(([, scope]) => scope) ? columnWidth(rows.map(([, scope]) => scope)) : 0;
4345
+ const textCol = 2 + leadWidth + scopeWidth;
4346
+ const stacked = width - textCol < MIN_TEXT;
4347
+ const lines = [];
4348
+ for (const [lead, scope, text] of rows) {
4349
+ const head = `${INDENT}${pad(color.lead(lead), leadWidth)}${scope ? pad(color.scope(scope), scopeWidth) : ""}`;
4350
+ if (stacked || lead.length + 1 > leadWidth) {
4351
+ const leadLines = wrap(lead, width - 2);
4352
+ leadLines.forEach((part, index) => lines.push(`${INDENT}${color.lead(part, index)}${index === leadLines.length - 1 && scope ? ` ${color.scope(scope)}` : ""}`));
4353
+ const below = `${INDENT} `;
4354
+ for (const line of wrap(text, width - below.length).map(color.text)) lines.push(below + line);
4355
+ continue;
4356
+ }
4357
+ const [first, ...rest] = wrap(text, width - textCol).map(color.text);
4358
+ lines.push((head + first).replace(/\s+$/, ""));
4359
+ for (const line of rest) lines.push(" ".repeat(textCol) + line);
4360
+ }
4361
+ return lines;
4362
+ }
4363
+ function helpText() {
4364
+ const width$1 = width();
4365
+ const section = (title, rows, color) => [
4366
+ helpHeading(title),
4367
+ ...columnRows(rows, color, width$1),
4368
+ ""
4369
+ ];
4370
+ return [
4371
+ ...wrap(`Apex CLI: point your coding assistants at ${MODEL}`, width$1).map((line) => bold(model(line))),
4372
+ "",
4373
+ ...section("Usage", usageRows.map(([lead, text]) => [
4374
+ lead,
4375
+ "",
4376
+ text
4377
+ ]), rowColors(commandLine)),
4378
+ ...section("Options", optionRows, optionColors),
4379
+ ...section("Examples", exampleRows.map(([lead, text]) => [
4380
+ lead,
4381
+ "",
4382
+ text
4383
+ ]), rowColors(commandLine, PLAIN, dim)),
4384
+ ...section("Environment", environmentRows.map(([lead, text]) => [
4385
+ lead,
4386
+ "",
4387
+ text
4388
+ ]), rowColors(yellow, PLAIN, PLAIN)),
4389
+ ...section("Install completions", installRows.map(([lead, text]) => [
4390
+ lead,
4391
+ "",
4392
+ text
4393
+ ]), rowColors(PLAIN, PLAIN, commandLine)),
4394
+ ...wrap("Restart the shell afterwards, or rehash zsh and re-source your bashrc.", width$1 - 2).map((line) => `${INDENT}${dim(line)}`),
4395
+ "",
4396
+ ...wrap("Node.js 22+ required. Codex profiles target 0.134.0+", width$1).map((line) => dim(line))
4397
+ ].join("\n");
4398
+ }
4399
+ const printHelp = () => console.log(helpText());
4400
+ function readFlags(rest, command) {
4401
+ const { values } = parseArgs({
4402
+ args: rest,
4403
+ options: OPTIONS,
4404
+ allowPositionals: false
4405
+ });
4406
+ const unsupported = Object.keys(values).filter((name) => !flagsOf(command).includes(name));
4407
+ if (unsupported.length) throw new Error(`--${unsupported[0]} is not valid for apex ${command}. See ${APEX} --help.`);
4408
+ const selected = values.assistants === void 0 ? null : [...new Set(values.assistants.split(",").map((id) => id.trim()))];
4409
+ if (selected?.includes("")) throw new Error("--assistants needs at least one id.");
4410
+ if (selected?.some((id) => !IDS.includes(id))) throw new Error(`Unknown assistant in --assistants. Choose from: ${IDS.join(", ")}`);
4411
+ const json = Boolean(values.json);
4412
+ return {
4413
+ selected,
4414
+ showDiff: !values["no-diff"],
4415
+ json,
4416
+ help: Boolean(values.help),
4417
+ list: Boolean(values.list),
4418
+ mode: resolveMode({
4419
+ apply: Boolean(values.apply),
4420
+ nonInteractive: Boolean(values["no-interactive"] || json)
4421
+ })
4422
+ };
4423
+ }
4424
+ async function planAll(assistants, options) {
4425
+ return Promise.all(assistants.map(async (assistant) => {
4426
+ const base = {
4427
+ id: assistant.id,
4428
+ name: NAMES[assistant.id],
4429
+ detected: assistant.detected,
4430
+ evidence: assistant.evidence || null,
4431
+ manual: MANUAL_IDS.includes(assistant.id),
4432
+ error: null,
4433
+ files: [],
4434
+ steps: []
4435
+ };
4436
+ try {
4437
+ base.files = (await planAssistant(assistant)).map((change) => describeFile(change, options));
4438
+ base.steps = base.files.flatMap((file) => file.change.steps ?? []);
4439
+ } catch (error) {
4440
+ base.error = error.message;
4441
+ }
4442
+ return base;
4443
+ }));
4444
+ }
4445
+ const token = () => process.env.CALLSTACK_AUTH_TOKEN?.trim() || void 0;
4446
+ const stamp = (iso) => iso.replace("T", " ").replace(/\.\d{3}Z$/, " UTC");
4447
+ const pendingOf = (entry) => entry.files.filter((file) => file.status !== "unchanged");
4448
+ async function applyAll(items, apply) {
4449
+ const applied = [];
4450
+ try {
4451
+ for (const item of items) applied.push(await apply(item));
4452
+ } catch (error) {
4453
+ return {
4454
+ applied,
4455
+ failure: error
4456
+ };
4457
+ }
4458
+ return {
4459
+ applied,
4460
+ failure: null
4461
+ };
4462
+ }
4463
+ const jsonFile = (file, secret) => ({
4464
+ path: file.path,
4465
+ status: file.status,
4466
+ changes: maskChanges(file.changes, secret)
4467
+ });
4468
+ const jsonAssistant = (entry, secret) => ({
4469
+ id: entry.id,
4470
+ name: entry.name,
4471
+ detected: entry.detected,
4472
+ evidence: entry.evidence,
4473
+ manual: entry.manual,
4474
+ ...entry.error ? { error: entry.error } : {},
4475
+ ...entry.steps.length ? { steps: entry.steps } : {},
4476
+ files: entry.files.map((file) => jsonFile(file, secret))
4477
+ });
4478
+ function pickerOptions(entries) {
4479
+ return entries.map((entry) => {
4480
+ const pending = pendingOf(entry).length;
4481
+ return {
4482
+ value: entry.id,
4483
+ label: entry.detected ? entry.name : `${entry.name} (not detected)`,
4484
+ hint: entry.manual ? "manual steps only" : entry.error ? "needs attention" : pending ? "not set up yet" : "already configured"
4485
+ };
4486
+ });
4487
+ }
4488
+ async function commandInit(rest) {
4489
+ const flags = readFlags(rest, "init");
4490
+ if (flags.help) {
4491
+ printHelp();
4492
+ return;
4493
+ }
4494
+ const secret = token();
4495
+ const options = {
4496
+ secret,
4497
+ showDiff: flags.showDiff && !flags.json
4498
+ };
4499
+ const journalFile = journalPath();
4500
+ if (flags.mode !== "preview") await readJournal(journalFile);
4501
+ const batch = randomUUID();
4502
+ const entries = await planAll(await detect(), options);
4503
+ let ids = flags.selected ?? entries.filter((entry) => entry.detected).map((entry) => entry.id);
4504
+ if (!flags.json) {
4505
+ intro("Apex CLI · Configure callstack/Apex for your favorite harness", MODE_NOTE[flags.mode]);
4506
+ if (flags.mode === "prompt" && !flags.selected) {
4507
+ const defaults = entries.filter((entry) => entry.detected && !entry.manual && !entry.error && pendingOf(entry).length).map((entry) => entry.id);
4508
+ const picked = await selectAssistants(pickerOptions(entries), defaults);
4509
+ if (picked === false) return;
4510
+ ids = picked;
4511
+ }
4512
+ }
4513
+ const chosen = ids.map((id) => entries.find((entry) => entry.id === id));
4514
+ const blocked = chosen.filter((entry) => entry.error);
4515
+ const manual = chosen.filter((entry) => entry.manual && !entry.error);
4516
+ const active = chosen.filter((entry) => !entry.manual && !entry.error);
4517
+ const files = active.flatMap((entry) => entry.files);
4518
+ const pending = files.filter((file) => file.status !== "unchanged").map((file) => file.change);
4519
+ const applyOne = async (change) => {
4520
+ const backup = await writeChange(change);
4521
+ await appendEntry(journalFile, newEntry(change, batch, backup));
4522
+ return backup;
4523
+ };
4524
+ if (flags.json) {
4525
+ const { applied, failure } = await applyAll(flags.mode === "apply" && !blocked.length ? pending : [], async (change) => {
4526
+ await applyOne(change);
4527
+ return change.path;
4528
+ });
4529
+ console.log(JSON.stringify({
4530
+ command: "init",
4531
+ mode: flags.mode,
4532
+ model: MODEL,
4533
+ endpoint: BASE_URL,
4534
+ applied: applied.length,
4535
+ appliedPaths: applied,
4536
+ ...failure ? { error: failure.message } : {},
4537
+ blocked: blocked.map((entry) => ({
4538
+ id: entry.id,
4539
+ error: entry.error
4540
+ })),
4541
+ manualSetup: manual.map((entry) => entry.id),
4542
+ assistants: chosen.map((entry) => jsonAssistant(entry, secret)),
4543
+ journal: journalFile,
4544
+ undo: `${APEX} undo`,
4545
+ envVar: "CALLSTACK_AUTH_TOKEN",
4546
+ nextSteps: active.filter((entry) => RUNNABLE.includes(entry.id)).map((entry) => `${APEX} run ${entry.id}`)
4547
+ }, null, 2));
4548
+ if (blocked.length || failure) process.exitCode = 1;
4549
+ return;
4550
+ }
4551
+ if (!ids.length) {
4552
+ outro(`No assistant selected, so nothing was written. Pick one with --assistants or run ${APEX} init interactively.`);
4553
+ return;
4554
+ }
4555
+ if (flags.mode !== "prompt") prose(`${gray("setup for:")} ${chosen.map((entry) => entry.name + (entry.detected ? "" : " (not detected)")).join(", ")}`);
4556
+ if (blocked.length) {
4557
+ plain("");
4558
+ for (const entry of blocked) error(`${entry.name}: ${shortPath(entry.error)}`);
4559
+ outro(`Blocked by the configuration problems above. Nothing was written. Fix those files and run ${APEX} init again.`);
4560
+ process.exitCode = 1;
4561
+ return;
4562
+ }
4563
+ let applied = 0;
4564
+ if (active.length) {
4565
+ const result = await runWrites({
4566
+ title: "Planned changes",
4567
+ files,
4568
+ options,
4569
+ mode: flags.mode,
4570
+ prompt: "Apply these changes?",
4571
+ hint: "Existing files get a .apex-backup-<id> copy first.",
4572
+ pending,
4573
+ write: async (change) => {
4574
+ const backup = await applyOne(change);
4575
+ return `${bold(shortPath(change.path))} ${dim(backup ? `backup: ${basename(backup)}` : "created")}`;
4576
+ }
4577
+ });
4578
+ if (result.declined) return;
4579
+ applied = result.applied;
4580
+ }
4581
+ const apex = APEX !== "apex" && flags.mode === "prompt" && await installApex() ? "apex" : APEX;
4582
+ for (const entry of active.filter((entry) => entry.steps.length)) section(`Finish setting up ${entry.name}`, entry.steps);
4583
+ for (const entry of manual) section(`Manual setup for ${entry.name}: Apex CLI writes nothing`, MANUAL[entry.id]);
4584
+ section("Environment", [
4585
+ ...secret ? [] : ["export CALLSTACK_AUTH_TOKEN=<your callstack.ai key>"],
4586
+ secret ? `${green("✓")} CALLSTACK_AUTH_TOKEN is set in this shell` : `${yellow("!")} CALLSTACK_AUTH_TOKEN is not set here yet`,
4587
+ dim("Apex CLI never reads, stores or logs the key itself.")
4588
+ ]);
4589
+ const runnable = active.map((entry) => entry.id).filter((id) => RUNNABLE.includes(id));
4590
+ const rows = runnable.map((id) => ({
4591
+ command: `${apex} run ${id}`,
4592
+ expansion: runExpansion(id)
4593
+ }));
4594
+ const commandWidth = columnWidth(rows.map((row) => row.command));
4595
+ section(runnable.length ? `Use these commands to run ${MODEL} with your selected harnesses:` : `Use ${MODEL} with your assistant:`, [
4596
+ ...rows.flatMap((row) => wrap(row.expansion, width() - 3 - commandWidth).map((part, index) => `${pad(index ? "" : row.command, commandWidth)}${dim(part)}`)),
4597
+ "",
4598
+ `...or pick "${MODEL}" from the UI when setting up manually.`,
4599
+ `For more instructions, visit: ${link(GUIDE_URL)}`,
4600
+ ...applied ? ["", `If you want to undo the changes, run ${bold(`${apex} undo`)}`] : [],
4601
+ ...apex === "apex" ? [] : ["", dim("For the short apex command: npm install -g @callstack/apex")]
4602
+ ]);
4603
+ }
4604
+ async function commandDetect(rest) {
4605
+ const flags = readFlags(rest, "detect");
4606
+ if (flags.help) {
4607
+ printHelp();
4608
+ return;
4609
+ }
4610
+ const secret = token();
4611
+ const entries = await planAll(await detect(), {
4612
+ secret,
4613
+ showDiff: false
4614
+ });
4615
+ if (flags.json) {
4616
+ console.log(JSON.stringify(entries.map((entry) => jsonAssistant(entry, secret)), null, 2));
4617
+ return;
4618
+ }
4619
+ intro("Apex CLI · What this machine has", "Read only: nothing is created, edited or removed.");
4620
+ const rows = entries.map((entry) => {
4621
+ const pending = pendingOf(entry).length;
4622
+ return {
4623
+ entry,
4624
+ text: entry.manual ? "manual setup" : entry.error ? "unreadable config" : pending ? "needs setup" : "already configured",
4625
+ shade: entry.manual ? dim : entry.error || pending ? yellow : gray
4626
+ };
4627
+ });
4628
+ const nameWidth = columnWidth(rows.map((row) => row.entry.name));
4629
+ const stateWidth = columnWidth(rows.map((row) => row.text));
4630
+ const lead = 8 + nameWidth + stateWidth;
4631
+ const room = width() - 3 - lead;
4632
+ for (const { entry, text, shade } of rows) {
4633
+ const found = entry.evidence ? shortPath(entry.evidence) : "no config found";
4634
+ const evidence = room >= 8 ? clip(found, room) : "";
4635
+ plain(`${pad(entry.detected ? green("found") : dim("absent"), 8)}${pad(entry.name, nameWidth)}${shade(evidence ? pad(text, stateWidth) : text)}${dim(evidence)}`);
4636
+ }
4637
+ outro(`Next: ${APEX} init`);
4638
+ }
4639
+ async function commandUndo(rest) {
4640
+ const flags = readFlags(rest, "undo");
4641
+ if (flags.help) {
4642
+ printHelp();
4643
+ return;
4644
+ }
4645
+ const secret = token();
4646
+ const options = {
4647
+ secret,
4648
+ showDiff: flags.showDiff && !flags.json
4649
+ };
4650
+ const journalFile = journalPath();
4651
+ const entries = await readJournal(journalFile);
4652
+ if (flags.list) {
4653
+ if (flags.json) {
4654
+ console.log(JSON.stringify({
4655
+ command: "undo",
4656
+ journal: journalFile,
4657
+ entries
4658
+ }, null, 2));
4659
+ return;
4660
+ }
4661
+ const batches = batchIds(entries);
4662
+ intro("Apex CLI · Setup history", "Only the journal is read here; configs stay untouched.");
4663
+ for (const batch of batches) {
4664
+ const items = entries.filter((entry) => entry.batch === batch);
4665
+ prose(`${gray(stamp(items[0].at))} ${bold(items.length === 1 ? "1 file" : `${items.length} files`)} ${items.every((item) => item.undoneAt) ? gray("undone") : yellow("pending")}`);
4666
+ for (const item of items) prose(`${dim(clip(shortPath(item.path), width() - 3))}${item.undoneAt ? gray(" (already undone)") : ""}`);
4667
+ }
4668
+ if (!batches.length) plain(dim("nothing recorded yet"));
4669
+ outro(`Journal: ${shortPath(journalFile)}`);
4670
+ return;
4671
+ }
4672
+ const plan = await planUndo(entries);
4673
+ const skipped = plan?.planned.filter((item) => item.action === "skip") ?? [];
4674
+ const restorable = [];
4675
+ const files = [];
4676
+ for (const item of plan?.planned.filter((entry) => entry.action !== "skip") ?? []) try {
4677
+ files.push({
4678
+ ...describeFile(item.change, options),
4679
+ status: item.action === "remove" ? "remove" : "restore"
4680
+ });
4681
+ restorable.push(item);
4682
+ } catch (error) {
4683
+ skipped.push({
4684
+ entry: item.entry,
4685
+ reason: `its stored contents cannot be read: ${error.message}`
4686
+ });
4687
+ }
4688
+ const applyOne = async (item) => {
4689
+ if (item.action === "remove") await removeChange(item.change);
4690
+ const backup = item.action === "restore" ? await writeChange(item.change) : null;
4691
+ await markUndone(journalFile, item.entry);
4692
+ return backup;
4693
+ };
4694
+ if (flags.json) {
4695
+ const { applied, failure } = await applyAll(flags.mode === "apply" ? restorable : [], async (item) => {
4696
+ await applyOne(item);
4697
+ return item.entry.path;
4698
+ });
4699
+ console.log(JSON.stringify({
4700
+ command: "undo",
4701
+ mode: flags.mode,
4702
+ journal: journalFile,
4703
+ batch: plan?.batch ?? null,
4704
+ at: plan?.at ?? null,
4705
+ applied: applied.length,
4706
+ appliedPaths: applied,
4707
+ ...failure ? { error: failure.message } : {},
4708
+ files: files.map((file) => jsonFile(file, secret)),
4709
+ skipped: skipped.map((item) => ({
4710
+ path: item.entry.path,
4711
+ reason: item.reason
4712
+ }))
4713
+ }, null, 2));
4714
+ if (failure) process.exitCode = 1;
4715
+ return;
4716
+ }
4717
+ intro("Apex CLI · Undo the last setup", MODE_NOTE[flags.mode]);
4718
+ if (!plan) {
4719
+ outro(entries.length ? `Everything Apex CLI has written here has already been undone. History: ${APEX} undo --list (journal: ${shortPath(journalFile)})` : `Nothing recorded yet, so nothing to undo. Journal: ${shortPath(journalFile)}`);
4720
+ return;
4721
+ }
4722
+ if (skipped.length) plain("");
4723
+ for (const item of skipped) warn(`${bold(shortPath(item.entry.path))} stays as it is: ${shortPath(item.reason)}`);
4724
+ if (!restorable.length) {
4725
+ outro("No file Apex CLI wrote can be restored safely. Nothing was written.");
4726
+ return;
4727
+ }
4728
+ if ((await runWrites({
4729
+ title: `Undo of the setup from ${stamp(plan.at)}`,
4730
+ files,
4731
+ options,
4732
+ mode: flags.mode,
4733
+ prompt: "Undo these changes?",
4734
+ hint: "Files Apex CLI created are deleted; edited files go back to their pre-setup contents.",
4735
+ pending: restorable,
4736
+ write: async (item) => {
4737
+ const backup = await applyOne(item);
4738
+ const path = bold(shortPath(item.entry.path));
4739
+ return item.action === "remove" ? `${path} ${dim("deleted (Apex CLI created it)")}` : `${path} ${dim(`restored; current contents kept as ${basename(backup)}`)}`;
4740
+ }
4741
+ })).applied) outro("Undone. Configs are back to how they were. Restart any open assistant to reload them.");
4742
+ }
4743
+ async function commandRun(rest) {
4744
+ const [id, ...passed] = rest;
4745
+ if (!RUNNABLE.includes(id)) throw new Error(`apex run needs one of: ${RUNNABLE.join(", ")}. See ${APEX} --help.`);
4746
+ const options = launchOptions(id);
4747
+ const binary = await executable(id);
4748
+ if (!binary) throw new Error(`${id} was not found on PATH. Install it first, then run ${APEX} init.`);
4749
+ if (process.platform === "win32" && /\.(cmd|bat)$/i.test(binary)) throw new Error("Windows .cmd/.bat launchers are not executed through a shell. Use WSL or launch the configured assistant directly.");
4750
+ const args = passed[0] === "--" ? passed.slice(1) : passed;
4751
+ const child = spawn(binary, [...options.args, ...args], {
4752
+ env: options.env,
4753
+ stdio: "inherit",
4754
+ shell: false
4755
+ });
4756
+ await new Promise((resolve, reject) => {
4757
+ child.once("error", reject);
4758
+ child.once("exit", (code, signal) => {
4759
+ process.exitCode = code ?? (signal === "SIGINT" ? 130 : 1);
4760
+ resolve();
4761
+ });
4762
+ });
4763
+ }
4764
+ const GLOBALS = [["--version", "print the version"], ["--help", "show all commands"]];
4765
+ const completionsFor = (command) => COMMANDS[command].flags.map((flag) => ({
4766
+ long: `--${flag}`,
4767
+ short: FLAGS[flag].short ? `-${FLAGS[flag].short}` : null,
4768
+ hint: FLAGS[flag].hint,
4769
+ ...command === "init" && flag === "assistants" ? { values: IDS } : {}
4770
+ }));
4771
+ const spellings = (entry) => [entry.long, entry.short].filter(Boolean);
4772
+ function completionScript(shell) {
4773
+ const taking = Object.keys(COMMANDS).filter((name) => COMMANDS[name].flags.length);
4774
+ const words = (list) => list.join(" ");
4775
+ if (shell === "zsh") return `#compdef apex
4776
+ _apex() {
4777
+ local -a commands assistants runnable${taking.length ? " " : ""}${words(taking.map((name) => `${name}_flags`))}
4778
+ commands=(${words([...Object.entries(COMMANDS).map(([name, command]) => `'${name}:${command.summary}'`), ...GLOBALS.map(([flag, text]) => `'${flag}:${text}'`)])})
4779
+ assistants=(${words(IDS)})
4780
+ runnable=(${words(RUNNABLE)})
4781
+ ${taking.map((name) => ` ${name}_flags=(${words(completionsFor(name).flatMap((entry) => spellings(entry).map((word) => `'${word}:${entry.hint}'`)))})`).join("\n")}
4782
+ if (( CURRENT == 2 )); then
4783
+ _describe -t commands 'apex command' commands
4784
+ elif [[ "\${words[CURRENT - 1]}" == --assistants ]]; then
4785
+ _describe -t assistants 'assistant' assistants
4786
+ else
4787
+ case "\${words[2]}" in
4788
+ ${taking.map((name) => ` ${name}) _describe -t flags 'option' ${name}_flags ;;`).join("\n")}
4789
+ run) (( CURRENT == 3 )) && _describe -t assistants 'assistant' runnable ;;
4790
+ completion) _describe -t shells 'shell' '(${words(SHELLS)})' ;;
4791
+ esac
4792
+ fi
4793
+ }
4794
+ # Autoloaded from $fpath, this file body is the first completion call, so it must complete too.
4795
+ if [[ "\${funcstack[1]}" == _apex ]]; then _apex "$@"; else compdef _apex apex; fi
4796
+ `;
4797
+ if (shell === "bash") return `_apex_completions() {
4798
+ local sub="\${COMP_WORDS[1]}" prev="\${COMP_WORDS[COMP_CWORD - 1]}" current="\${COMP_WORDS[COMP_CWORD]}"
4799
+ if [[ "$prev" == --assistants ]]; then COMPREPLY=( $(compgen -W "${words(IDS)}" -- "$current") ); return; fi
4800
+ if (( COMP_CWORD == 1 )); then
4801
+ COMPREPLY=( $(compgen -W "${words([...Object.keys(COMMANDS), ...GLOBALS.map(([flag]) => flag)])}" -- "$current") )
4802
+ return
4803
+ fi
4804
+ case "$sub" in
4805
+ ${taking.map((name) => ` ${name}) COMPREPLY=( $(compgen -W "${words(completionsFor(name).flatMap(spellings))}" -- "$current") ) ;;`).join("\n")}
4806
+ run) (( COMP_CWORD == 2 )) && COMPREPLY=( $(compgen -W "${words(RUNNABLE)}" -- "$current") ) ;;
4807
+ completion) (( COMP_CWORD == 2 )) && COMPREPLY=( $(compgen -W "${words(SHELLS)}" -- "$current") ) ;;
4808
+ esac
4809
+ }
4810
+ complete -F _apex_completions apex
4811
+ `;
4812
+ const fish = (condition, { long, short, hint, values }) => `complete -c apex -f -n "${condition}" -l ${long.slice(2)}${short ? ` -s ${short.slice(1)}` : ""}${values ? ` -a "${words(values)}"` : ""} -d '${hint}'`;
4813
+ return [
4814
+ ...Object.entries(COMMANDS).map(([name, command]) => `complete -c apex -f -n "__fish_use_subcommand" -a ${name} -d '${command.summary}'`),
4815
+ ...GLOBALS.map(([flag, hint]) => `complete -c apex -f -n "__fish_use_subcommand" -l ${flag.slice(2)} -d '${hint}'`),
4816
+ ...taking.flatMap((name) => completionsFor(name).map((entry) => fish(`__fish_seen_subcommand_from ${name}`, entry))),
4817
+ ...RUNNABLE.map((id) => `complete -c apex -f -n "__fish_seen_subcommand_from run" -a ${id} -d 'assistant'`),
4818
+ ...SHELLS.map((name) => `complete -c apex -f -n "__fish_seen_subcommand_from completion" -a ${name} -d 'shell'`)
4819
+ ].join("\n") + "\n";
4820
+ }
4821
+ function commandCompletion(rest) {
4822
+ const [shell] = rest;
4823
+ if (!SHELLS.includes(shell)) throw new Error(`apex completion needs one of: ${SHELLS.join(", ")}.`);
4824
+ process.stdout.write(completionScript(shell));
4825
+ }
4826
+ async function main(argv) {
4827
+ const [command, ...rest] = argv;
4828
+ if (!command || [
4829
+ "--help",
4830
+ "-h",
4831
+ "help"
4832
+ ].includes(command)) {
4833
+ printHelp();
4834
+ return;
4835
+ }
4836
+ if (["--version", "-v"].includes(command)) {
4837
+ console.log(await packageVersion());
4838
+ return;
4839
+ }
4840
+ if (command === "completion") return commandCompletion(rest);
4841
+ if (command === "run") return commandRun(rest);
4842
+ if (command === "init") return commandInit(rest);
4843
+ if (command === "detect") return commandDetect(rest);
4844
+ if (command === "undo") return commandUndo(rest);
4845
+ throw new Error(`Unknown command: ${command}. See apex --help.`);
4846
+ }
4847
+ main(process.argv.slice(2)).catch((error) => {
4848
+ const line = `Apex CLI: ${error.message}`;
4849
+ if (interactive()) console.error(styleText("red", line));
4850
+ else console.error(line);
4851
+ process.exitCode = 1;
4852
+ });
4853
+ for (const stream of [process.stdout, process.stderr]) stream.on("error", (error) => {
4854
+ if (error.code === "EPIPE") process.exit(process.exitCode ?? 0);
4855
+ throw error;
4856
+ });
4857
+
4858
+ //#endregion
4859
+ export { };