nim-sync 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1989 @@
1
+ // src/plugin/nim-sync.ts
2
+ import crypto from "crypto";
3
+ import path2 from "path";
4
+
5
+ // src/types/index.ts
6
+ var NVIDIAApiError = class extends Error {
7
+ constructor(statusCode, statusText) {
8
+ super(`NVIDIA API error: ${statusCode} ${statusText}`);
9
+ this.statusCode = statusCode;
10
+ this.statusText = statusText;
11
+ this.name = "NVIDIAApiError";
12
+ }
13
+ };
14
+
15
+ // src/types/schema.ts
16
+ function validateOpenCodeConfig(config) {
17
+ if (typeof config !== "object" || config === null) {
18
+ return { valid: false, errors: ["Configuration must be an object"] };
19
+ }
20
+ const typedConfig = config;
21
+ const errors = [];
22
+ if (typedConfig.provider && typeof typedConfig.provider === "object") {
23
+ const provider = typedConfig.provider;
24
+ if (provider.nim && typeof provider.nim === "object") {
25
+ const nim = provider.nim;
26
+ if (typeof nim.npm !== "string") {
27
+ errors.push("provider.nim.npm must be a string");
28
+ }
29
+ if (typeof nim.name !== "string") {
30
+ errors.push("provider.nim.name must be a string");
31
+ }
32
+ if (nim.models && typeof nim.models === "object") {
33
+ const models = nim.models;
34
+ for (const [modelId, modelData] of Object.entries(models)) {
35
+ if (typeof modelData !== "object" || modelData === null) {
36
+ errors.push(`provider.nim.models.${modelId} must be an object`);
37
+ } else {
38
+ const model = modelData;
39
+ if (typeof model.name !== "string") {
40
+ errors.push(`provider.nim.models.${modelId}.name must be a string`);
41
+ }
42
+ }
43
+ }
44
+ }
45
+ }
46
+ }
47
+ if (typedConfig.model !== void 0 && typeof typedConfig.model !== "string") {
48
+ errors.push("model must be a string if provided");
49
+ }
50
+ if (typedConfig.small_model !== void 0 && typeof typedConfig.small_model !== "string") {
51
+ errors.push("small_model must be a string if provided");
52
+ }
53
+ return {
54
+ valid: errors.length === 0,
55
+ errors: errors.length > 0 ? errors : void 0
56
+ };
57
+ }
58
+
59
+ // src/lib/retry.ts
60
+ var DEFAULT_OPTIONS = {
61
+ maxRetries: 3,
62
+ initialDelay: 1e3,
63
+ maxDelay: 1e4,
64
+ retryOnNetworkError: true,
65
+ retryStatusCodes: [429, 500, 502, 503, 504]
66
+ };
67
+ async function withRetry(fn, options = {}) {
68
+ const opts = { ...DEFAULT_OPTIONS, ...options };
69
+ let lastError = null;
70
+ for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
71
+ try {
72
+ return await fn();
73
+ } catch (error) {
74
+ lastError = error instanceof Error ? error : new Error(String(error));
75
+ const shouldRetry = shouldRetryError(error, opts);
76
+ if (!shouldRetry || attempt === opts.maxRetries) {
77
+ throw lastError;
78
+ }
79
+ const delay = Math.min(
80
+ opts.initialDelay * Math.pow(2, attempt),
81
+ opts.maxDelay
82
+ );
83
+ await new Promise((resolve) => setTimeout(resolve, delay));
84
+ }
85
+ }
86
+ throw lastError || new Error("Retry logic failed unexpectedly");
87
+ }
88
+ function shouldRetryError(error, options) {
89
+ if (options.retryOnNetworkError && isNetworkError(error)) {
90
+ return true;
91
+ }
92
+ if (isHttpError(error)) {
93
+ const statusCode = getStatusCode(error);
94
+ return options.retryStatusCodes.includes(statusCode);
95
+ }
96
+ return false;
97
+ }
98
+ function isNetworkError(error) {
99
+ if (!(error instanceof Error)) {
100
+ return false;
101
+ }
102
+ const networkErrorPatterns = [
103
+ "network",
104
+ "timeout",
105
+ "connection",
106
+ "fetch",
107
+ "abort",
108
+ "ECONNREFUSED",
109
+ "ETIMEDOUT"
110
+ ];
111
+ const message = error.message.toLowerCase();
112
+ const name = error.name.toLowerCase();
113
+ return networkErrorPatterns.some(
114
+ (pattern) => message.includes(pattern) || name.includes(pattern)
115
+ );
116
+ }
117
+ function isHttpError(error) {
118
+ return typeof error === "object" && error !== null && "statusCode" in error && typeof error.statusCode === "number";
119
+ }
120
+ function getStatusCode(error) {
121
+ if (isHttpError(error)) {
122
+ return error.statusCode;
123
+ }
124
+ return 0;
125
+ }
126
+
127
+ // src/lib/file-utils.ts
128
+ import fs from "fs/promises";
129
+ import path from "path";
130
+
131
+ // node_modules/jsonc-parser/lib/esm/impl/scanner.js
132
+ function createScanner(text, ignoreTrivia = false) {
133
+ const len = text.length;
134
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
135
+ function scanHexDigits(count, exact) {
136
+ let digits = 0;
137
+ let value2 = 0;
138
+ while (digits < count || !exact) {
139
+ let ch = text.charCodeAt(pos);
140
+ if (ch >= 48 && ch <= 57) {
141
+ value2 = value2 * 16 + ch - 48;
142
+ } else if (ch >= 65 && ch <= 70) {
143
+ value2 = value2 * 16 + ch - 65 + 10;
144
+ } else if (ch >= 97 && ch <= 102) {
145
+ value2 = value2 * 16 + ch - 97 + 10;
146
+ } else {
147
+ break;
148
+ }
149
+ pos++;
150
+ digits++;
151
+ }
152
+ if (digits < count) {
153
+ value2 = -1;
154
+ }
155
+ return value2;
156
+ }
157
+ function setPosition(newPosition) {
158
+ pos = newPosition;
159
+ value = "";
160
+ tokenOffset = 0;
161
+ token = 16;
162
+ scanError = 0;
163
+ }
164
+ function scanNumber() {
165
+ let start = pos;
166
+ if (text.charCodeAt(pos) === 48) {
167
+ pos++;
168
+ } else {
169
+ pos++;
170
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
171
+ pos++;
172
+ }
173
+ }
174
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
175
+ pos++;
176
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
177
+ pos++;
178
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
179
+ pos++;
180
+ }
181
+ } else {
182
+ scanError = 3;
183
+ return text.substring(start, pos);
184
+ }
185
+ }
186
+ let end = pos;
187
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
188
+ pos++;
189
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
190
+ pos++;
191
+ }
192
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
193
+ pos++;
194
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
195
+ pos++;
196
+ }
197
+ end = pos;
198
+ } else {
199
+ scanError = 3;
200
+ }
201
+ }
202
+ return text.substring(start, end);
203
+ }
204
+ function scanString() {
205
+ let result = "", start = pos;
206
+ while (true) {
207
+ if (pos >= len) {
208
+ result += text.substring(start, pos);
209
+ scanError = 2;
210
+ break;
211
+ }
212
+ const ch = text.charCodeAt(pos);
213
+ if (ch === 34) {
214
+ result += text.substring(start, pos);
215
+ pos++;
216
+ break;
217
+ }
218
+ if (ch === 92) {
219
+ result += text.substring(start, pos);
220
+ pos++;
221
+ if (pos >= len) {
222
+ scanError = 2;
223
+ break;
224
+ }
225
+ const ch2 = text.charCodeAt(pos++);
226
+ switch (ch2) {
227
+ case 34:
228
+ result += '"';
229
+ break;
230
+ case 92:
231
+ result += "\\";
232
+ break;
233
+ case 47:
234
+ result += "/";
235
+ break;
236
+ case 98:
237
+ result += "\b";
238
+ break;
239
+ case 102:
240
+ result += "\f";
241
+ break;
242
+ case 110:
243
+ result += "\n";
244
+ break;
245
+ case 114:
246
+ result += "\r";
247
+ break;
248
+ case 116:
249
+ result += " ";
250
+ break;
251
+ case 117:
252
+ const ch3 = scanHexDigits(4, true);
253
+ if (ch3 >= 0) {
254
+ result += String.fromCharCode(ch3);
255
+ } else {
256
+ scanError = 4;
257
+ }
258
+ break;
259
+ default:
260
+ scanError = 5;
261
+ }
262
+ start = pos;
263
+ continue;
264
+ }
265
+ if (ch >= 0 && ch <= 31) {
266
+ if (isLineBreak(ch)) {
267
+ result += text.substring(start, pos);
268
+ scanError = 2;
269
+ break;
270
+ } else {
271
+ scanError = 6;
272
+ }
273
+ }
274
+ pos++;
275
+ }
276
+ return result;
277
+ }
278
+ function scanNext() {
279
+ value = "";
280
+ scanError = 0;
281
+ tokenOffset = pos;
282
+ lineStartOffset = lineNumber;
283
+ prevTokenLineStartOffset = tokenLineStartOffset;
284
+ if (pos >= len) {
285
+ tokenOffset = len;
286
+ return token = 17;
287
+ }
288
+ let code = text.charCodeAt(pos);
289
+ if (isWhiteSpace(code)) {
290
+ do {
291
+ pos++;
292
+ value += String.fromCharCode(code);
293
+ code = text.charCodeAt(pos);
294
+ } while (isWhiteSpace(code));
295
+ return token = 15;
296
+ }
297
+ if (isLineBreak(code)) {
298
+ pos++;
299
+ value += String.fromCharCode(code);
300
+ if (code === 13 && text.charCodeAt(pos) === 10) {
301
+ pos++;
302
+ value += "\n";
303
+ }
304
+ lineNumber++;
305
+ tokenLineStartOffset = pos;
306
+ return token = 14;
307
+ }
308
+ switch (code) {
309
+ // tokens: []{}:,
310
+ case 123:
311
+ pos++;
312
+ return token = 1;
313
+ case 125:
314
+ pos++;
315
+ return token = 2;
316
+ case 91:
317
+ pos++;
318
+ return token = 3;
319
+ case 93:
320
+ pos++;
321
+ return token = 4;
322
+ case 58:
323
+ pos++;
324
+ return token = 6;
325
+ case 44:
326
+ pos++;
327
+ return token = 5;
328
+ // strings
329
+ case 34:
330
+ pos++;
331
+ value = scanString();
332
+ return token = 10;
333
+ // comments
334
+ case 47:
335
+ const start = pos - 1;
336
+ if (text.charCodeAt(pos + 1) === 47) {
337
+ pos += 2;
338
+ while (pos < len) {
339
+ if (isLineBreak(text.charCodeAt(pos))) {
340
+ break;
341
+ }
342
+ pos++;
343
+ }
344
+ value = text.substring(start, pos);
345
+ return token = 12;
346
+ }
347
+ if (text.charCodeAt(pos + 1) === 42) {
348
+ pos += 2;
349
+ const safeLength = len - 1;
350
+ let commentClosed = false;
351
+ while (pos < safeLength) {
352
+ const ch = text.charCodeAt(pos);
353
+ if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
354
+ pos += 2;
355
+ commentClosed = true;
356
+ break;
357
+ }
358
+ pos++;
359
+ if (isLineBreak(ch)) {
360
+ if (ch === 13 && text.charCodeAt(pos) === 10) {
361
+ pos++;
362
+ }
363
+ lineNumber++;
364
+ tokenLineStartOffset = pos;
365
+ }
366
+ }
367
+ if (!commentClosed) {
368
+ pos++;
369
+ scanError = 1;
370
+ }
371
+ value = text.substring(start, pos);
372
+ return token = 13;
373
+ }
374
+ value += String.fromCharCode(code);
375
+ pos++;
376
+ return token = 16;
377
+ // numbers
378
+ case 45:
379
+ value += String.fromCharCode(code);
380
+ pos++;
381
+ if (pos === len || !isDigit(text.charCodeAt(pos))) {
382
+ return token = 16;
383
+ }
384
+ // found a minus, followed by a number so
385
+ // we fall through to proceed with scanning
386
+ // numbers
387
+ case 48:
388
+ case 49:
389
+ case 50:
390
+ case 51:
391
+ case 52:
392
+ case 53:
393
+ case 54:
394
+ case 55:
395
+ case 56:
396
+ case 57:
397
+ value += scanNumber();
398
+ return token = 11;
399
+ // literals and unknown symbols
400
+ default:
401
+ while (pos < len && isUnknownContentCharacter(code)) {
402
+ pos++;
403
+ code = text.charCodeAt(pos);
404
+ }
405
+ if (tokenOffset !== pos) {
406
+ value = text.substring(tokenOffset, pos);
407
+ switch (value) {
408
+ case "true":
409
+ return token = 8;
410
+ case "false":
411
+ return token = 9;
412
+ case "null":
413
+ return token = 7;
414
+ }
415
+ return token = 16;
416
+ }
417
+ value += String.fromCharCode(code);
418
+ pos++;
419
+ return token = 16;
420
+ }
421
+ }
422
+ function isUnknownContentCharacter(code) {
423
+ if (isWhiteSpace(code) || isLineBreak(code)) {
424
+ return false;
425
+ }
426
+ switch (code) {
427
+ case 125:
428
+ case 93:
429
+ case 123:
430
+ case 91:
431
+ case 34:
432
+ case 58:
433
+ case 44:
434
+ case 47:
435
+ return false;
436
+ }
437
+ return true;
438
+ }
439
+ function scanNextNonTrivia() {
440
+ let result;
441
+ do {
442
+ result = scanNext();
443
+ } while (result >= 12 && result <= 15);
444
+ return result;
445
+ }
446
+ return {
447
+ setPosition,
448
+ getPosition: () => pos,
449
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
450
+ getToken: () => token,
451
+ getTokenValue: () => value,
452
+ getTokenOffset: () => tokenOffset,
453
+ getTokenLength: () => pos - tokenOffset,
454
+ getTokenStartLine: () => lineStartOffset,
455
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
456
+ getTokenError: () => scanError
457
+ };
458
+ }
459
+ function isWhiteSpace(ch) {
460
+ return ch === 32 || ch === 9;
461
+ }
462
+ function isLineBreak(ch) {
463
+ return ch === 10 || ch === 13;
464
+ }
465
+ function isDigit(ch) {
466
+ return ch >= 48 && ch <= 57;
467
+ }
468
+ var CharacterCodes;
469
+ (function(CharacterCodes2) {
470
+ CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
471
+ CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
472
+ CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
473
+ CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
474
+ CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
475
+ CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
476
+ CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
477
+ CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
478
+ CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
479
+ CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
480
+ CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
481
+ CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
482
+ CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
483
+ CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
484
+ CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
485
+ CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
486
+ CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
487
+ CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
488
+ CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
489
+ CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
490
+ CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
491
+ CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
492
+ CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
493
+ CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
494
+ CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
495
+ CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
496
+ CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
497
+ CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
498
+ CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
499
+ CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
500
+ CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
501
+ CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
502
+ CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
503
+ CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
504
+ CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
505
+ CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
506
+ CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
507
+ CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
508
+ CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
509
+ CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
510
+ CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
511
+ CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
512
+ CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
513
+ CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
514
+ CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
515
+ CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
516
+ CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
517
+ CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
518
+ CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
519
+ CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
520
+ CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
521
+ CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
522
+ CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
523
+ CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
524
+ CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
525
+ CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
526
+ CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
527
+ CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
528
+ CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
529
+ CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
530
+ CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
531
+ CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
532
+ CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
533
+ CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
534
+ CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
535
+ CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
536
+ CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
537
+ CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
538
+ CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
539
+ CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
540
+ CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
541
+ CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
542
+ CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
543
+ CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
544
+ CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
545
+ CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
546
+ CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
547
+ CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
548
+ CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
549
+ CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
550
+ })(CharacterCodes || (CharacterCodes = {}));
551
+
552
+ // node_modules/jsonc-parser/lib/esm/impl/string-intern.js
553
+ var cachedSpaces = new Array(20).fill(0).map((_, index) => {
554
+ return " ".repeat(index);
555
+ });
556
+ var maxCachedValues = 200;
557
+ var cachedBreakLinesWithSpaces = {
558
+ " ": {
559
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
560
+ return "\n" + " ".repeat(index);
561
+ }),
562
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
563
+ return "\r" + " ".repeat(index);
564
+ }),
565
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
566
+ return "\r\n" + " ".repeat(index);
567
+ })
568
+ },
569
+ " ": {
570
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
571
+ return "\n" + " ".repeat(index);
572
+ }),
573
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
574
+ return "\r" + " ".repeat(index);
575
+ }),
576
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
577
+ return "\r\n" + " ".repeat(index);
578
+ })
579
+ }
580
+ };
581
+ var supportedEols = ["\n", "\r", "\r\n"];
582
+
583
+ // node_modules/jsonc-parser/lib/esm/impl/format.js
584
+ function format(documentText, range, options) {
585
+ let initialIndentLevel;
586
+ let formatText;
587
+ let formatTextStart;
588
+ let rangeStart;
589
+ let rangeEnd;
590
+ if (range) {
591
+ rangeStart = range.offset;
592
+ rangeEnd = rangeStart + range.length;
593
+ formatTextStart = rangeStart;
594
+ while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
595
+ formatTextStart--;
596
+ }
597
+ let endOffset = rangeEnd;
598
+ while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
599
+ endOffset++;
600
+ }
601
+ formatText = documentText.substring(formatTextStart, endOffset);
602
+ initialIndentLevel = computeIndentLevel(formatText, options);
603
+ } else {
604
+ formatText = documentText;
605
+ initialIndentLevel = 0;
606
+ formatTextStart = 0;
607
+ rangeStart = 0;
608
+ rangeEnd = documentText.length;
609
+ }
610
+ const eol = getEOL(options, documentText);
611
+ const eolFastPathSupported = supportedEols.includes(eol);
612
+ let numberLineBreaks = 0;
613
+ let indentLevel = 0;
614
+ let indentValue;
615
+ if (options.insertSpaces) {
616
+ indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);
617
+ } else {
618
+ indentValue = " ";
619
+ }
620
+ const indentType = indentValue === " " ? " " : " ";
621
+ let scanner = createScanner(formatText, false);
622
+ let hasError = false;
623
+ function newLinesAndIndent() {
624
+ if (numberLineBreaks > 1) {
625
+ return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
626
+ }
627
+ const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);
628
+ if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {
629
+ return eol + repeat(indentValue, initialIndentLevel + indentLevel);
630
+ }
631
+ if (amountOfSpaces <= 0) {
632
+ return eol;
633
+ }
634
+ return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];
635
+ }
636
+ function scanNext() {
637
+ let token = scanner.scan();
638
+ numberLineBreaks = 0;
639
+ while (token === 15 || token === 14) {
640
+ if (token === 14 && options.keepLines) {
641
+ numberLineBreaks += 1;
642
+ } else if (token === 14) {
643
+ numberLineBreaks = 1;
644
+ }
645
+ token = scanner.scan();
646
+ }
647
+ hasError = token === 16 || scanner.getTokenError() !== 0;
648
+ return token;
649
+ }
650
+ const editOperations = [];
651
+ function addEdit(text, startOffset, endOffset) {
652
+ if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) {
653
+ editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
654
+ }
655
+ }
656
+ let firstToken = scanNext();
657
+ if (options.keepLines && numberLineBreaks > 0) {
658
+ addEdit(repeat(eol, numberLineBreaks), 0, 0);
659
+ }
660
+ if (firstToken !== 17) {
661
+ let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
662
+ let initialIndent = indentValue.length * initialIndentLevel < 20 && options.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel);
663
+ addEdit(initialIndent, formatTextStart, firstTokenStart);
664
+ }
665
+ while (firstToken !== 17) {
666
+ let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
667
+ let secondToken = scanNext();
668
+ let replaceContent = "";
669
+ let needsLineBreak = false;
670
+ while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
671
+ let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
672
+ addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);
673
+ firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
674
+ needsLineBreak = secondToken === 12;
675
+ replaceContent = needsLineBreak ? newLinesAndIndent() : "";
676
+ secondToken = scanNext();
677
+ }
678
+ if (secondToken === 2) {
679
+ if (firstToken !== 1) {
680
+ indentLevel--;
681
+ }
682
+ ;
683
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) {
684
+ replaceContent = newLinesAndIndent();
685
+ } else if (options.keepLines) {
686
+ replaceContent = cachedSpaces[1];
687
+ }
688
+ } else if (secondToken === 4) {
689
+ if (firstToken !== 3) {
690
+ indentLevel--;
691
+ }
692
+ ;
693
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) {
694
+ replaceContent = newLinesAndIndent();
695
+ } else if (options.keepLines) {
696
+ replaceContent = cachedSpaces[1];
697
+ }
698
+ } else {
699
+ switch (firstToken) {
700
+ case 3:
701
+ case 1:
702
+ indentLevel++;
703
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
704
+ replaceContent = newLinesAndIndent();
705
+ } else {
706
+ replaceContent = cachedSpaces[1];
707
+ }
708
+ break;
709
+ case 5:
710
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
711
+ replaceContent = newLinesAndIndent();
712
+ } else {
713
+ replaceContent = cachedSpaces[1];
714
+ }
715
+ break;
716
+ case 12:
717
+ replaceContent = newLinesAndIndent();
718
+ break;
719
+ case 13:
720
+ if (numberLineBreaks > 0) {
721
+ replaceContent = newLinesAndIndent();
722
+ } else if (!needsLineBreak) {
723
+ replaceContent = cachedSpaces[1];
724
+ }
725
+ break;
726
+ case 6:
727
+ if (options.keepLines && numberLineBreaks > 0) {
728
+ replaceContent = newLinesAndIndent();
729
+ } else if (!needsLineBreak) {
730
+ replaceContent = cachedSpaces[1];
731
+ }
732
+ break;
733
+ case 10:
734
+ if (options.keepLines && numberLineBreaks > 0) {
735
+ replaceContent = newLinesAndIndent();
736
+ } else if (secondToken === 6 && !needsLineBreak) {
737
+ replaceContent = "";
738
+ }
739
+ break;
740
+ case 7:
741
+ case 8:
742
+ case 9:
743
+ case 11:
744
+ case 2:
745
+ case 4:
746
+ if (options.keepLines && numberLineBreaks > 0) {
747
+ replaceContent = newLinesAndIndent();
748
+ } else {
749
+ if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) {
750
+ replaceContent = cachedSpaces[1];
751
+ } else if (secondToken !== 5 && secondToken !== 17) {
752
+ hasError = true;
753
+ }
754
+ }
755
+ break;
756
+ case 16:
757
+ hasError = true;
758
+ break;
759
+ }
760
+ if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) {
761
+ replaceContent = newLinesAndIndent();
762
+ }
763
+ }
764
+ if (secondToken === 17) {
765
+ if (options.keepLines && numberLineBreaks > 0) {
766
+ replaceContent = newLinesAndIndent();
767
+ } else {
768
+ replaceContent = options.insertFinalNewline ? eol : "";
769
+ }
770
+ }
771
+ const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
772
+ addEdit(replaceContent, firstTokenEnd, secondTokenStart);
773
+ firstToken = secondToken;
774
+ }
775
+ return editOperations;
776
+ }
777
+ function repeat(s, count) {
778
+ let result = "";
779
+ for (let i = 0; i < count; i++) {
780
+ result += s;
781
+ }
782
+ return result;
783
+ }
784
+ function computeIndentLevel(content, options) {
785
+ let i = 0;
786
+ let nChars = 0;
787
+ const tabSize = options.tabSize || 4;
788
+ while (i < content.length) {
789
+ let ch = content.charAt(i);
790
+ if (ch === cachedSpaces[1]) {
791
+ nChars++;
792
+ } else if (ch === " ") {
793
+ nChars += tabSize;
794
+ } else {
795
+ break;
796
+ }
797
+ i++;
798
+ }
799
+ return Math.floor(nChars / tabSize);
800
+ }
801
+ function getEOL(options, text) {
802
+ for (let i = 0; i < text.length; i++) {
803
+ const ch = text.charAt(i);
804
+ if (ch === "\r") {
805
+ if (i + 1 < text.length && text.charAt(i + 1) === "\n") {
806
+ return "\r\n";
807
+ }
808
+ return "\r";
809
+ } else if (ch === "\n") {
810
+ return "\n";
811
+ }
812
+ }
813
+ return options && options.eol || "\n";
814
+ }
815
+ function isEOL(text, offset) {
816
+ return "\r\n".indexOf(text.charAt(offset)) !== -1;
817
+ }
818
+
819
+ // node_modules/jsonc-parser/lib/esm/impl/parser.js
820
+ var ParseOptions;
821
+ (function(ParseOptions2) {
822
+ ParseOptions2.DEFAULT = {
823
+ allowTrailingComma: false
824
+ };
825
+ })(ParseOptions || (ParseOptions = {}));
826
+ function parse(text, errors = [], options = ParseOptions.DEFAULT) {
827
+ let currentProperty = null;
828
+ let currentParent = [];
829
+ const previousParents = [];
830
+ function onValue(value) {
831
+ if (Array.isArray(currentParent)) {
832
+ currentParent.push(value);
833
+ } else if (currentProperty !== null) {
834
+ currentParent[currentProperty] = value;
835
+ }
836
+ }
837
+ const visitor = {
838
+ onObjectBegin: () => {
839
+ const object = {};
840
+ onValue(object);
841
+ previousParents.push(currentParent);
842
+ currentParent = object;
843
+ currentProperty = null;
844
+ },
845
+ onObjectProperty: (name) => {
846
+ currentProperty = name;
847
+ },
848
+ onObjectEnd: () => {
849
+ currentParent = previousParents.pop();
850
+ },
851
+ onArrayBegin: () => {
852
+ const array = [];
853
+ onValue(array);
854
+ previousParents.push(currentParent);
855
+ currentParent = array;
856
+ currentProperty = null;
857
+ },
858
+ onArrayEnd: () => {
859
+ currentParent = previousParents.pop();
860
+ },
861
+ onLiteralValue: onValue,
862
+ onError: (error, offset, length) => {
863
+ errors.push({ error, offset, length });
864
+ }
865
+ };
866
+ visit(text, visitor, options);
867
+ return currentParent[0];
868
+ }
869
+ function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
870
+ let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: void 0 };
871
+ function ensurePropertyComplete(endOffset) {
872
+ if (currentParent.type === "property") {
873
+ currentParent.length = endOffset - currentParent.offset;
874
+ currentParent = currentParent.parent;
875
+ }
876
+ }
877
+ function onValue(valueNode) {
878
+ currentParent.children.push(valueNode);
879
+ return valueNode;
880
+ }
881
+ const visitor = {
882
+ onObjectBegin: (offset) => {
883
+ currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] });
884
+ },
885
+ onObjectProperty: (name, offset, length) => {
886
+ currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] });
887
+ currentParent.children.push({ type: "string", value: name, offset, length, parent: currentParent });
888
+ },
889
+ onObjectEnd: (offset, length) => {
890
+ ensurePropertyComplete(offset + length);
891
+ currentParent.length = offset + length - currentParent.offset;
892
+ currentParent = currentParent.parent;
893
+ ensurePropertyComplete(offset + length);
894
+ },
895
+ onArrayBegin: (offset, length) => {
896
+ currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] });
897
+ },
898
+ onArrayEnd: (offset, length) => {
899
+ currentParent.length = offset + length - currentParent.offset;
900
+ currentParent = currentParent.parent;
901
+ ensurePropertyComplete(offset + length);
902
+ },
903
+ onLiteralValue: (value, offset, length) => {
904
+ onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });
905
+ ensurePropertyComplete(offset + length);
906
+ },
907
+ onSeparator: (sep, offset, length) => {
908
+ if (currentParent.type === "property") {
909
+ if (sep === ":") {
910
+ currentParent.colonOffset = offset;
911
+ } else if (sep === ",") {
912
+ ensurePropertyComplete(offset);
913
+ }
914
+ }
915
+ },
916
+ onError: (error, offset, length) => {
917
+ errors.push({ error, offset, length });
918
+ }
919
+ };
920
+ visit(text, visitor, options);
921
+ const result = currentParent.children[0];
922
+ if (result) {
923
+ delete result.parent;
924
+ }
925
+ return result;
926
+ }
927
+ function findNodeAtLocation(root, path3) {
928
+ if (!root) {
929
+ return void 0;
930
+ }
931
+ let node = root;
932
+ for (let segment of path3) {
933
+ if (typeof segment === "string") {
934
+ if (node.type !== "object" || !Array.isArray(node.children)) {
935
+ return void 0;
936
+ }
937
+ let found = false;
938
+ for (const propertyNode of node.children) {
939
+ if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
940
+ node = propertyNode.children[1];
941
+ found = true;
942
+ break;
943
+ }
944
+ }
945
+ if (!found) {
946
+ return void 0;
947
+ }
948
+ } else {
949
+ const index = segment;
950
+ if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
951
+ return void 0;
952
+ }
953
+ node = node.children[index];
954
+ }
955
+ }
956
+ return node;
957
+ }
958
+ function visit(text, visitor, options = ParseOptions.DEFAULT) {
959
+ const _scanner = createScanner(text, false);
960
+ const _jsonPath = [];
961
+ let suppressedCallbacks = 0;
962
+ function toNoArgVisit(visitFunction) {
963
+ return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
964
+ }
965
+ function toOneArgVisit(visitFunction) {
966
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
967
+ }
968
+ function toOneArgVisitWithPath(visitFunction) {
969
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
970
+ }
971
+ function toBeginVisit(visitFunction) {
972
+ return visitFunction ? () => {
973
+ if (suppressedCallbacks > 0) {
974
+ suppressedCallbacks++;
975
+ } else {
976
+ let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());
977
+ if (cbReturn === false) {
978
+ suppressedCallbacks = 1;
979
+ }
980
+ }
981
+ } : () => true;
982
+ }
983
+ function toEndVisit(visitFunction) {
984
+ return visitFunction ? () => {
985
+ if (suppressedCallbacks > 0) {
986
+ suppressedCallbacks--;
987
+ }
988
+ if (suppressedCallbacks === 0) {
989
+ visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
990
+ }
991
+ } : () => true;
992
+ }
993
+ 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);
994
+ const disallowComments = options && options.disallowComments;
995
+ const allowTrailingComma = options && options.allowTrailingComma;
996
+ function scanNext() {
997
+ while (true) {
998
+ const token = _scanner.scan();
999
+ switch (_scanner.getTokenError()) {
1000
+ case 4:
1001
+ handleError(
1002
+ 14
1003
+ /* ParseErrorCode.InvalidUnicode */
1004
+ );
1005
+ break;
1006
+ case 5:
1007
+ handleError(
1008
+ 15
1009
+ /* ParseErrorCode.InvalidEscapeCharacter */
1010
+ );
1011
+ break;
1012
+ case 3:
1013
+ handleError(
1014
+ 13
1015
+ /* ParseErrorCode.UnexpectedEndOfNumber */
1016
+ );
1017
+ break;
1018
+ case 1:
1019
+ if (!disallowComments) {
1020
+ handleError(
1021
+ 11
1022
+ /* ParseErrorCode.UnexpectedEndOfComment */
1023
+ );
1024
+ }
1025
+ break;
1026
+ case 2:
1027
+ handleError(
1028
+ 12
1029
+ /* ParseErrorCode.UnexpectedEndOfString */
1030
+ );
1031
+ break;
1032
+ case 6:
1033
+ handleError(
1034
+ 16
1035
+ /* ParseErrorCode.InvalidCharacter */
1036
+ );
1037
+ break;
1038
+ }
1039
+ switch (token) {
1040
+ case 12:
1041
+ case 13:
1042
+ if (disallowComments) {
1043
+ handleError(
1044
+ 10
1045
+ /* ParseErrorCode.InvalidCommentToken */
1046
+ );
1047
+ } else {
1048
+ onComment();
1049
+ }
1050
+ break;
1051
+ case 16:
1052
+ handleError(
1053
+ 1
1054
+ /* ParseErrorCode.InvalidSymbol */
1055
+ );
1056
+ break;
1057
+ case 15:
1058
+ case 14:
1059
+ break;
1060
+ default:
1061
+ return token;
1062
+ }
1063
+ }
1064
+ }
1065
+ function handleError(error, skipUntilAfter = [], skipUntil = []) {
1066
+ onError(error);
1067
+ if (skipUntilAfter.length + skipUntil.length > 0) {
1068
+ let token = _scanner.getToken();
1069
+ while (token !== 17) {
1070
+ if (skipUntilAfter.indexOf(token) !== -1) {
1071
+ scanNext();
1072
+ break;
1073
+ } else if (skipUntil.indexOf(token) !== -1) {
1074
+ break;
1075
+ }
1076
+ token = scanNext();
1077
+ }
1078
+ }
1079
+ }
1080
+ function parseString(isValue) {
1081
+ const value = _scanner.getTokenValue();
1082
+ if (isValue) {
1083
+ onLiteralValue(value);
1084
+ } else {
1085
+ onObjectProperty(value);
1086
+ _jsonPath.push(value);
1087
+ }
1088
+ scanNext();
1089
+ return true;
1090
+ }
1091
+ function parseLiteral() {
1092
+ switch (_scanner.getToken()) {
1093
+ case 11:
1094
+ const tokenValue = _scanner.getTokenValue();
1095
+ let value = Number(tokenValue);
1096
+ if (isNaN(value)) {
1097
+ handleError(
1098
+ 2
1099
+ /* ParseErrorCode.InvalidNumberFormat */
1100
+ );
1101
+ value = 0;
1102
+ }
1103
+ onLiteralValue(value);
1104
+ break;
1105
+ case 7:
1106
+ onLiteralValue(null);
1107
+ break;
1108
+ case 8:
1109
+ onLiteralValue(true);
1110
+ break;
1111
+ case 9:
1112
+ onLiteralValue(false);
1113
+ break;
1114
+ default:
1115
+ return false;
1116
+ }
1117
+ scanNext();
1118
+ return true;
1119
+ }
1120
+ function parseProperty() {
1121
+ if (_scanner.getToken() !== 10) {
1122
+ handleError(3, [], [
1123
+ 2,
1124
+ 5
1125
+ /* SyntaxKind.CommaToken */
1126
+ ]);
1127
+ return false;
1128
+ }
1129
+ parseString(false);
1130
+ if (_scanner.getToken() === 6) {
1131
+ onSeparator(":");
1132
+ scanNext();
1133
+ if (!parseValue()) {
1134
+ handleError(4, [], [
1135
+ 2,
1136
+ 5
1137
+ /* SyntaxKind.CommaToken */
1138
+ ]);
1139
+ }
1140
+ } else {
1141
+ handleError(5, [], [
1142
+ 2,
1143
+ 5
1144
+ /* SyntaxKind.CommaToken */
1145
+ ]);
1146
+ }
1147
+ _jsonPath.pop();
1148
+ return true;
1149
+ }
1150
+ function parseObject() {
1151
+ onObjectBegin();
1152
+ scanNext();
1153
+ let needsComma = false;
1154
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
1155
+ if (_scanner.getToken() === 5) {
1156
+ if (!needsComma) {
1157
+ handleError(4, [], []);
1158
+ }
1159
+ onSeparator(",");
1160
+ scanNext();
1161
+ if (_scanner.getToken() === 2 && allowTrailingComma) {
1162
+ break;
1163
+ }
1164
+ } else if (needsComma) {
1165
+ handleError(6, [], []);
1166
+ }
1167
+ if (!parseProperty()) {
1168
+ handleError(4, [], [
1169
+ 2,
1170
+ 5
1171
+ /* SyntaxKind.CommaToken */
1172
+ ]);
1173
+ }
1174
+ needsComma = true;
1175
+ }
1176
+ onObjectEnd();
1177
+ if (_scanner.getToken() !== 2) {
1178
+ handleError(7, [
1179
+ 2
1180
+ /* SyntaxKind.CloseBraceToken */
1181
+ ], []);
1182
+ } else {
1183
+ scanNext();
1184
+ }
1185
+ return true;
1186
+ }
1187
+ function parseArray() {
1188
+ onArrayBegin();
1189
+ scanNext();
1190
+ let isFirstElement = true;
1191
+ let needsComma = false;
1192
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
1193
+ if (_scanner.getToken() === 5) {
1194
+ if (!needsComma) {
1195
+ handleError(4, [], []);
1196
+ }
1197
+ onSeparator(",");
1198
+ scanNext();
1199
+ if (_scanner.getToken() === 4 && allowTrailingComma) {
1200
+ break;
1201
+ }
1202
+ } else if (needsComma) {
1203
+ handleError(6, [], []);
1204
+ }
1205
+ if (isFirstElement) {
1206
+ _jsonPath.push(0);
1207
+ isFirstElement = false;
1208
+ } else {
1209
+ _jsonPath[_jsonPath.length - 1]++;
1210
+ }
1211
+ if (!parseValue()) {
1212
+ handleError(4, [], [
1213
+ 4,
1214
+ 5
1215
+ /* SyntaxKind.CommaToken */
1216
+ ]);
1217
+ }
1218
+ needsComma = true;
1219
+ }
1220
+ onArrayEnd();
1221
+ if (!isFirstElement) {
1222
+ _jsonPath.pop();
1223
+ }
1224
+ if (_scanner.getToken() !== 4) {
1225
+ handleError(8, [
1226
+ 4
1227
+ /* SyntaxKind.CloseBracketToken */
1228
+ ], []);
1229
+ } else {
1230
+ scanNext();
1231
+ }
1232
+ return true;
1233
+ }
1234
+ function parseValue() {
1235
+ switch (_scanner.getToken()) {
1236
+ case 3:
1237
+ return parseArray();
1238
+ case 1:
1239
+ return parseObject();
1240
+ case 10:
1241
+ return parseString(true);
1242
+ default:
1243
+ return parseLiteral();
1244
+ }
1245
+ }
1246
+ scanNext();
1247
+ if (_scanner.getToken() === 17) {
1248
+ if (options.allowEmptyContent) {
1249
+ return true;
1250
+ }
1251
+ handleError(4, [], []);
1252
+ return false;
1253
+ }
1254
+ if (!parseValue()) {
1255
+ handleError(4, [], []);
1256
+ return false;
1257
+ }
1258
+ if (_scanner.getToken() !== 17) {
1259
+ handleError(9, [], []);
1260
+ }
1261
+ return true;
1262
+ }
1263
+ function getNodeType(value) {
1264
+ switch (typeof value) {
1265
+ case "boolean":
1266
+ return "boolean";
1267
+ case "number":
1268
+ return "number";
1269
+ case "string":
1270
+ return "string";
1271
+ case "object": {
1272
+ if (!value) {
1273
+ return "null";
1274
+ } else if (Array.isArray(value)) {
1275
+ return "array";
1276
+ }
1277
+ return "object";
1278
+ }
1279
+ default:
1280
+ return "null";
1281
+ }
1282
+ }
1283
+
1284
+ // node_modules/jsonc-parser/lib/esm/impl/edit.js
1285
+ function setProperty(text, originalPath, value, options) {
1286
+ const path3 = originalPath.slice();
1287
+ const errors = [];
1288
+ const root = parseTree(text, errors);
1289
+ let parent = void 0;
1290
+ let lastSegment = void 0;
1291
+ while (path3.length > 0) {
1292
+ lastSegment = path3.pop();
1293
+ parent = findNodeAtLocation(root, path3);
1294
+ if (parent === void 0 && value !== void 0) {
1295
+ if (typeof lastSegment === "string") {
1296
+ value = { [lastSegment]: value };
1297
+ } else {
1298
+ value = [value];
1299
+ }
1300
+ } else {
1301
+ break;
1302
+ }
1303
+ }
1304
+ if (!parent) {
1305
+ if (value === void 0) {
1306
+ throw new Error("Can not delete in empty document");
1307
+ }
1308
+ return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
1309
+ } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
1310
+ const existing = findNodeAtLocation(parent, [lastSegment]);
1311
+ if (existing !== void 0) {
1312
+ if (value === void 0) {
1313
+ if (!existing.parent) {
1314
+ throw new Error("Malformed AST");
1315
+ }
1316
+ const propertyIndex = parent.children.indexOf(existing.parent);
1317
+ let removeBegin;
1318
+ let removeEnd = existing.parent.offset + existing.parent.length;
1319
+ if (propertyIndex > 0) {
1320
+ let previous = parent.children[propertyIndex - 1];
1321
+ removeBegin = previous.offset + previous.length;
1322
+ } else {
1323
+ removeBegin = parent.offset + 1;
1324
+ if (parent.children.length > 1) {
1325
+ let next = parent.children[1];
1326
+ removeEnd = next.offset;
1327
+ }
1328
+ }
1329
+ return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, options);
1330
+ } else {
1331
+ return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
1332
+ }
1333
+ } else {
1334
+ if (value === void 0) {
1335
+ return [];
1336
+ }
1337
+ const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
1338
+ const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
1339
+ let edit;
1340
+ if (index > 0) {
1341
+ let previous = parent.children[index - 1];
1342
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
1343
+ } else if (parent.children.length === 0) {
1344
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty };
1345
+ } else {
1346
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
1347
+ }
1348
+ return withFormatting(text, edit, options);
1349
+ }
1350
+ } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
1351
+ const insertIndex = lastSegment;
1352
+ if (insertIndex === -1) {
1353
+ const newProperty = `${JSON.stringify(value)}`;
1354
+ let edit;
1355
+ if (parent.children.length === 0) {
1356
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty };
1357
+ } else {
1358
+ const previous = parent.children[parent.children.length - 1];
1359
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
1360
+ }
1361
+ return withFormatting(text, edit, options);
1362
+ } else if (value === void 0 && parent.children.length >= 0) {
1363
+ const removalIndex = lastSegment;
1364
+ const toRemove = parent.children[removalIndex];
1365
+ let edit;
1366
+ if (parent.children.length === 1) {
1367
+ edit = { offset: parent.offset + 1, length: parent.length - 2, content: "" };
1368
+ } else if (parent.children.length - 1 === removalIndex) {
1369
+ let previous = parent.children[removalIndex - 1];
1370
+ let offset = previous.offset + previous.length;
1371
+ let parentEndOffset = parent.offset + parent.length;
1372
+ edit = { offset, length: parentEndOffset - 2 - offset, content: "" };
1373
+ } else {
1374
+ edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
1375
+ }
1376
+ return withFormatting(text, edit, options);
1377
+ } else if (value !== void 0) {
1378
+ let edit;
1379
+ const newProperty = `${JSON.stringify(value)}`;
1380
+ if (!options.isArrayInsertion && parent.children.length > lastSegment) {
1381
+ const toModify = parent.children[lastSegment];
1382
+ edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
1383
+ } else if (parent.children.length === 0 || lastSegment === 0) {
1384
+ edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + "," };
1385
+ } else {
1386
+ const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
1387
+ const previous = parent.children[index - 1];
1388
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
1389
+ }
1390
+ return withFormatting(text, edit, options);
1391
+ } else {
1392
+ throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
1393
+ }
1394
+ } else {
1395
+ throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
1396
+ }
1397
+ }
1398
+ function withFormatting(text, edit, options) {
1399
+ if (!options.formattingOptions) {
1400
+ return [edit];
1401
+ }
1402
+ let newText = applyEdit(text, edit);
1403
+ let begin = edit.offset;
1404
+ let end = edit.offset + edit.content.length;
1405
+ if (edit.length === 0 || edit.content.length === 0) {
1406
+ while (begin > 0 && !isEOL(newText, begin - 1)) {
1407
+ begin--;
1408
+ }
1409
+ while (end < newText.length && !isEOL(newText, end)) {
1410
+ end++;
1411
+ }
1412
+ }
1413
+ const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });
1414
+ for (let i = edits.length - 1; i >= 0; i--) {
1415
+ const edit2 = edits[i];
1416
+ newText = applyEdit(newText, edit2);
1417
+ begin = Math.min(begin, edit2.offset);
1418
+ end = Math.max(end, edit2.offset + edit2.length);
1419
+ end += edit2.content.length - edit2.length;
1420
+ }
1421
+ const editLength = text.length - (newText.length - end) - begin;
1422
+ return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
1423
+ }
1424
+ function applyEdit(text, edit) {
1425
+ return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
1426
+ }
1427
+
1428
+ // node_modules/jsonc-parser/lib/esm/main.js
1429
+ var ScanError;
1430
+ (function(ScanError2) {
1431
+ ScanError2[ScanError2["None"] = 0] = "None";
1432
+ ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
1433
+ ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
1434
+ ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
1435
+ ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
1436
+ ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
1437
+ ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
1438
+ })(ScanError || (ScanError = {}));
1439
+ var SyntaxKind;
1440
+ (function(SyntaxKind2) {
1441
+ SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
1442
+ SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
1443
+ SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
1444
+ SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
1445
+ SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
1446
+ SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
1447
+ SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
1448
+ SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
1449
+ SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
1450
+ SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
1451
+ SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
1452
+ SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
1453
+ SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
1454
+ SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
1455
+ SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
1456
+ SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
1457
+ SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
1458
+ })(SyntaxKind || (SyntaxKind = {}));
1459
+ var parse2 = parse;
1460
+ var ParseErrorCode;
1461
+ (function(ParseErrorCode2) {
1462
+ ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
1463
+ ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
1464
+ ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
1465
+ ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
1466
+ ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
1467
+ ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
1468
+ ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
1469
+ ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
1470
+ ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
1471
+ ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
1472
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
1473
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
1474
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
1475
+ ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
1476
+ ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
1477
+ ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
1478
+ })(ParseErrorCode || (ParseErrorCode = {}));
1479
+ function modify(text, path3, value, options) {
1480
+ return setProperty(text, path3, value, options);
1481
+ }
1482
+ function applyEdits(text, edits) {
1483
+ let sortedEdits = edits.slice(0).sort((a, b) => {
1484
+ const diff = a.offset - b.offset;
1485
+ if (diff === 0) {
1486
+ return a.length - b.length;
1487
+ }
1488
+ return diff;
1489
+ });
1490
+ let lastModifiedOffset = text.length;
1491
+ for (let i = sortedEdits.length - 1; i >= 0; i--) {
1492
+ let e = sortedEdits[i];
1493
+ if (e.offset + e.length <= lastModifiedOffset) {
1494
+ text = applyEdit(text, e);
1495
+ } else {
1496
+ throw new Error("Overlapping edit");
1497
+ }
1498
+ lastModifiedOffset = e.offset;
1499
+ }
1500
+ return text;
1501
+ }
1502
+
1503
+ // src/lib/file-utils.ts
1504
+ var API_TIMEOUT_MS = 3e4;
1505
+ var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
1506
+ var LOCK_STALE_THRESHOLD_MS = 5 * 60 * 1e3;
1507
+ var LOCK_RETRY_INTERVAL_MS = 100;
1508
+ var MIN_MANUAL_REFRESH_INTERVAL_MS = 6e4;
1509
+ var MAX_BACKUPS = 5;
1510
+ async function readJSONC(filePath, validate) {
1511
+ try {
1512
+ const content = await fs.readFile(filePath, "utf-8");
1513
+ const errors = [];
1514
+ const result = parse2(content, errors);
1515
+ if (errors.length > 0) {
1516
+ const errorDetails = errors.map((e) => `Parse error code ${e.error} at offset ${e.offset}`).join("; ");
1517
+ throw new Error(`JSONC parse errors in ${filePath}: ${errorDetails}`);
1518
+ }
1519
+ if (validate && !validate(result)) {
1520
+ throw new Error(`Invalid data structure in ${filePath}`);
1521
+ }
1522
+ return result;
1523
+ } catch (error) {
1524
+ if (error.code === "ENOENT") {
1525
+ return {};
1526
+ }
1527
+ throw error;
1528
+ }
1529
+ }
1530
+ async function writeJSONC(filePath, data, options) {
1531
+ const content = JSON.stringify(data, null, 2);
1532
+ await atomicWrite(filePath, content, options);
1533
+ }
1534
+ async function updateJSONCPath(filePath, jsonPath, data, options) {
1535
+ let existingContent = "";
1536
+ try {
1537
+ existingContent = await fs.readFile(filePath, "utf-8");
1538
+ } catch (error) {
1539
+ if (error.code !== "ENOENT") {
1540
+ throw error;
1541
+ }
1542
+ }
1543
+ const eol = existingContent.includes("\r\n") ? "\r\n" : "\n";
1544
+ const edits = modify(existingContent, jsonPath, data, {
1545
+ formattingOptions: {
1546
+ insertSpaces: true,
1547
+ tabSize: 2,
1548
+ eol
1549
+ }
1550
+ });
1551
+ const updatedContent = applyEdits(existingContent, edits);
1552
+ await atomicWrite(filePath, updatedContent, options);
1553
+ }
1554
+ async function atomicWrite(filePath, content, options = {}) {
1555
+ const dir = path.dirname(filePath);
1556
+ const tempPath = `${filePath}.${Date.now()}.tmp`;
1557
+ try {
1558
+ await fs.mkdir(dir, { recursive: true });
1559
+ if (options.backup) {
1560
+ try {
1561
+ await fs.access(filePath);
1562
+ const backupDir = path.join(dir, "backups");
1563
+ if (options.createBackupDir) {
1564
+ await fs.mkdir(backupDir, { recursive: true });
1565
+ }
1566
+ const backupPath = path.join(backupDir, `${path.basename(filePath)}.${Date.now()}.bak`);
1567
+ await fs.copyFile(filePath, backupPath);
1568
+ await cleanupOldBackups(backupDir, path.basename(filePath));
1569
+ } catch (error) {
1570
+ if (error.code !== "ENOENT") {
1571
+ throw new Error(`Failed to create backup: ${error instanceof Error ? error.message : "Unknown error"}`);
1572
+ }
1573
+ }
1574
+ }
1575
+ await fs.writeFile(tempPath, content, "utf-8");
1576
+ await fs.rename(tempPath, filePath);
1577
+ } catch (error) {
1578
+ try {
1579
+ await fs.unlink(tempPath);
1580
+ } catch {
1581
+ }
1582
+ throw error;
1583
+ }
1584
+ }
1585
+ async function ensureDir(dirPath) {
1586
+ try {
1587
+ await fs.mkdir(dirPath, { recursive: true });
1588
+ } catch (error) {
1589
+ if (error.code !== "EEXIST") {
1590
+ throw error;
1591
+ }
1592
+ }
1593
+ }
1594
+ function getPlatformPaths() {
1595
+ const home = process.env.HOME || process.env.USERPROFILE || "";
1596
+ const isWindows = process.platform === "win32";
1597
+ return {
1598
+ config: isWindows ? path.join(home, "AppData", "Roaming", "opencode") : path.join(home, ".config", "opencode"),
1599
+ data: isWindows ? path.join(home, "AppData", "Roaming", "opencode") : path.join(home, ".local", "share", "opencode"),
1600
+ cache: isWindows ? path.join(home, "AppData", "Local", "opencode", "cache") : path.join(home, ".cache", "opencode")
1601
+ };
1602
+ }
1603
+ function getConfigDir() {
1604
+ return getPlatformPaths().config;
1605
+ }
1606
+ function getCacheDir() {
1607
+ return getPlatformPaths().cache;
1608
+ }
1609
+ function getDataDir() {
1610
+ return getPlatformPaths().data;
1611
+ }
1612
+ function isProcessRunning(pid) {
1613
+ try {
1614
+ process.kill(pid, 0);
1615
+ return true;
1616
+ } catch {
1617
+ return false;
1618
+ }
1619
+ }
1620
+ async function cleanupOldBackups(backupDir, baseName) {
1621
+ try {
1622
+ const files = await fs.readdir(backupDir);
1623
+ const backups = files.filter((f) => f.startsWith(baseName) && f.endsWith(".bak")).map((f) => ({
1624
+ name: f,
1625
+ // Extract timestamp from filename like "file.json.1234567890.bak"
1626
+ timestamp: parseInt(f.split(".").slice(-2, -1)[0]) || 0
1627
+ })).sort((a, b) => b.timestamp - a.timestamp);
1628
+ for (const oldBackup of backups.slice(MAX_BACKUPS)) {
1629
+ await fs.unlink(path.join(backupDir, oldBackup.name));
1630
+ }
1631
+ } catch {
1632
+ }
1633
+ }
1634
+ async function acquireLock(lockName, timeoutMs = 5e3) {
1635
+ const lockDir = getCacheDir();
1636
+ const lockPath = path.join(lockDir, `${lockName}.lock`);
1637
+ await ensureDir(lockDir);
1638
+ try {
1639
+ const lockContent = await fs.readFile(lockPath, "utf-8");
1640
+ const metadata = JSON.parse(lockContent);
1641
+ const staleThreshold = Date.now() - LOCK_STALE_THRESHOLD_MS;
1642
+ const isStale = metadata.timestamp < staleThreshold;
1643
+ const processExists = metadata.pid ? isProcessRunning(metadata.pid) : true;
1644
+ if (isStale || !processExists) {
1645
+ await fs.unlink(lockPath);
1646
+ }
1647
+ } catch (error) {
1648
+ if (error.code !== "ENOENT") {
1649
+ console.error("Failed to clean up stale lock");
1650
+ }
1651
+ }
1652
+ const startTime = Date.now();
1653
+ while (Date.now() - startTime < timeoutMs) {
1654
+ try {
1655
+ const fd = await fs.open(lockPath, "wx");
1656
+ const metadata = {
1657
+ pid: process.pid,
1658
+ timestamp: Date.now()
1659
+ };
1660
+ await fd.writeFile(JSON.stringify(metadata));
1661
+ await fd.close();
1662
+ return async () => {
1663
+ try {
1664
+ await fs.unlink(lockPath);
1665
+ } catch {
1666
+ }
1667
+ };
1668
+ } catch (error) {
1669
+ if (error.code !== "EEXIST") {
1670
+ throw error;
1671
+ }
1672
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_INTERVAL_MS));
1673
+ }
1674
+ }
1675
+ throw new Error(`Failed to acquire lock "${lockName}" after ${timeoutMs}ms`);
1676
+ }
1677
+
1678
+ // src/plugin/nim-sync.ts
1679
+ var NIM_BASE_URL = "https://integrate.api.nvidia.com/v1";
1680
+ var CACHE_FILE_NAME = "nim-sync-cache.json";
1681
+ var CONFIG_FILE_NAME = "opencode.jsonc";
1682
+ var ALLOWED_MODEL_PROPERTIES = /* @__PURE__ */ new Set([
1683
+ "id",
1684
+ "name",
1685
+ "description",
1686
+ "model_type",
1687
+ "quantization",
1688
+ "created",
1689
+ "owned_by",
1690
+ "object",
1691
+ "root",
1692
+ "parent",
1693
+ "permission"
1694
+ ]);
1695
+ async function syncNIMModels(api) {
1696
+ let refreshInProgress = false;
1697
+ let lastManualRefresh = 0;
1698
+ const safeShowToast = (options) => {
1699
+ try {
1700
+ api.tui.toast.show(options);
1701
+ } catch (e) {
1702
+ console.debug("[NIM-Sync] Toast display failed:", e instanceof Error ? e.message : "Unknown");
1703
+ }
1704
+ };
1705
+ const sanitizeErrorMessage = (msg, apiKey) => {
1706
+ if (!apiKey) return msg;
1707
+ return msg.replace(apiKey, "[REDACTED]");
1708
+ };
1709
+ const getCachePath = () => path2.join(getCacheDir(), CACHE_FILE_NAME);
1710
+ const getConfigPath = () => path2.join(getConfigDir(), CONFIG_FILE_NAME);
1711
+ const getAuthPath = () => path2.join(getDataDir(), "auth.json");
1712
+ const readCache = async () => {
1713
+ try {
1714
+ const cache = await readJSONC(getCachePath());
1715
+ return cache?.lastRefresh ? cache : null;
1716
+ } catch {
1717
+ return null;
1718
+ }
1719
+ };
1720
+ const writeCache = async (cache) => {
1721
+ let releaseLockFn = null;
1722
+ try {
1723
+ releaseLockFn = await acquireLock("nim-cache-write");
1724
+ } catch (lockError) {
1725
+ const msg = lockError instanceof Error ? lockError.message : "Unknown error";
1726
+ console.error("[NIM-Sync] Cache lock failed:", msg);
1727
+ safeShowToast({ title: "NVIDIA Sync Warning", description: "Cache lock failed: " + msg, variant: "error" });
1728
+ throw lockError;
1729
+ }
1730
+ try {
1731
+ await writeJSONC(getCachePath(), cache, { backup: true });
1732
+ } catch (writeError) {
1733
+ const msg = writeError instanceof Error ? writeError.message : "Unknown error";
1734
+ console.error("[NIM-Sync] Cache write failed:", msg);
1735
+ safeShowToast({ title: "NVIDIA Sync Failed", description: "Failed to write cache: " + msg, variant: "error" });
1736
+ throw writeError;
1737
+ } finally {
1738
+ if (releaseLockFn) {
1739
+ try {
1740
+ await releaseLockFn();
1741
+ } catch (e) {
1742
+ console.error("[NIM-Sync] Failed to release cache lock:", e);
1743
+ }
1744
+ }
1745
+ }
1746
+ };
1747
+ const getAPIKey = async () => {
1748
+ try {
1749
+ const auth = await readJSONC(getAuthPath());
1750
+ if (!auth || Object.keys(auth).length === 0) {
1751
+ console.debug("[NIM-Sync] No auth.json found, checking env var");
1752
+ return process.env.NVIDIA_API_KEY || null;
1753
+ }
1754
+ if (auth.credentials?.nim?.apiKey && typeof auth.credentials.nim.apiKey === "string") {
1755
+ return auth.credentials.nim.apiKey;
1756
+ }
1757
+ console.debug("[NIM-Sync] No credentials in auth.json, checking env var");
1758
+ return process.env.NVIDIA_API_KEY || null;
1759
+ } catch (error) {
1760
+ console.error("[NIM-Sync] Failed to read auth:", error instanceof Error ? error.message : "Unknown error");
1761
+ return process.env.NVIDIA_API_KEY || null;
1762
+ }
1763
+ };
1764
+ const exposedGetAPIKey = getAPIKey;
1765
+ function validateAPIResponse(response) {
1766
+ if (!response || typeof response !== "object") throw new Error("Invalid API response: Expected object, got " + (response === null ? "null" : typeof response));
1767
+ const obj = response;
1768
+ if (!("data" in obj)) throw new Error("Invalid API response: Missing data field. Keys: [" + Object.keys(obj).join(", ") + "]");
1769
+ const data = obj.data;
1770
+ if (!Array.isArray(data)) throw new Error("Invalid API response: data must be array, got " + typeof data);
1771
+ const seenIds = /* @__PURE__ */ new Set();
1772
+ const models = [];
1773
+ for (let i = 0; i < data.length; i++) {
1774
+ const m = data[i];
1775
+ if (!m || typeof m !== "object") throw new Error("Invalid model at index " + i + ": not an object");
1776
+ if (typeof m.id !== "string" || m.id.length === 0) throw new Error("Invalid model at index " + i + ": invalid id");
1777
+ if (typeof m.name !== "string" || m.name.length === 0) throw new Error("Model " + m.id + ": invalid name");
1778
+ if (seenIds.has(m.id)) throw new Error("Duplicate model ID: " + m.id);
1779
+ const unexpected = Object.keys(m).filter((k) => !ALLOWED_MODEL_PROPERTIES.has(k));
1780
+ if (unexpected.length > 0) console.warn("[NIM-Sync] Model " + m.id + " has unexpected props: [" + unexpected.join(", ") + "]");
1781
+ seenIds.add(m.id);
1782
+ models.push({
1783
+ id: m.id,
1784
+ name: m.name,
1785
+ description: typeof m.description === "string" ? m.description : void 0,
1786
+ model_type: typeof m.model_type === "string" ? m.model_type : void 0,
1787
+ quantization: typeof m.quantization === "string" ? m.quantization : void 0
1788
+ });
1789
+ }
1790
+ return models;
1791
+ }
1792
+ const fetchModels = async (apiKey) => {
1793
+ return withRetry(async () => {
1794
+ const controller = new AbortController();
1795
+ const timeoutId = setTimeout(() => controller.abort(), API_TIMEOUT_MS);
1796
+ try {
1797
+ const response = await fetch(NIM_BASE_URL + "/models", {
1798
+ headers: { "Authorization": "Bearer " + apiKey, "Content-Type": "application/json" },
1799
+ signal: controller.signal
1800
+ });
1801
+ clearTimeout(timeoutId);
1802
+ if (!response.ok) throw new NVIDIAApiError(response.status, response.statusText);
1803
+ let data;
1804
+ try {
1805
+ data = await response.json();
1806
+ } catch (e) {
1807
+ throw new Error("Failed to parse JSON: " + (e instanceof Error ? e.message : "Unknown"));
1808
+ }
1809
+ return validateAPIResponse(data);
1810
+ } catch (error) {
1811
+ clearTimeout(timeoutId);
1812
+ if (error instanceof Error && error.name === "AbortError") throw new Error("NVIDIA API request timed out after " + API_TIMEOUT_MS / 1e3 + " seconds");
1813
+ throw error;
1814
+ }
1815
+ }, { maxRetries: 3, initialDelay: 1e3, maxDelay: 1e4, retryStatusCodes: [429, 500, 502, 503, 504] });
1816
+ };
1817
+ const hashModels = (models) => {
1818
+ const hash = crypto.createHash("sha256");
1819
+ hash.update(JSON.stringify([...models].sort((a, b) => a.id.localeCompare(b.id))));
1820
+ return hash.digest("hex");
1821
+ };
1822
+ const sortKeysDeep = (value) => {
1823
+ if (Array.isArray(value)) {
1824
+ return value.map(sortKeysDeep);
1825
+ }
1826
+ if (value && typeof value === "object") {
1827
+ return Object.keys(value).sort().reduce((acc, key) => {
1828
+ acc[key] = sortKeysDeep(value[key]);
1829
+ return acc;
1830
+ }, {});
1831
+ }
1832
+ return value;
1833
+ };
1834
+ const managedNIMConfigMatches = (currentConfig, nextConfig) => {
1835
+ return JSON.stringify(sortKeysDeep(currentConfig ?? null)) === JSON.stringify(sortKeysDeep(nextConfig));
1836
+ };
1837
+ const shouldRefresh = async () => {
1838
+ try {
1839
+ const config = api.config.get();
1840
+ if (!config?.provider?.nim) return true;
1841
+ const cache = await readCache();
1842
+ if (!cache?.lastRefresh) return true;
1843
+ return Date.now() - cache.lastRefresh > CACHE_TTL_MS;
1844
+ } catch {
1845
+ return true;
1846
+ }
1847
+ };
1848
+ const exposedShouldRefresh = shouldRefresh;
1849
+ const updateConfig = async (models) => {
1850
+ const config = await readJSONC(getConfigPath());
1851
+ const newModels = models.reduce((acc, m) => {
1852
+ acc[m.id] = { name: m.name, options: config?.provider?.nim?.models?.[m.id]?.options || {} };
1853
+ return acc;
1854
+ }, {});
1855
+ const modelsHash = hashModels(models);
1856
+ const cache = await readCache();
1857
+ const updatedNIMConfig = {
1858
+ ...config?.provider?.nim,
1859
+ npm: "@ai-sdk/openai-compatible",
1860
+ name: "NVIDIA NIM",
1861
+ options: {
1862
+ ...config?.provider?.nim?.options,
1863
+ baseURL: NIM_BASE_URL
1864
+ },
1865
+ models: newModels
1866
+ };
1867
+ const managedConfigChanged = !managedNIMConfigMatches(config?.provider?.nim, updatedNIMConfig);
1868
+ if (cache?.modelsHash === modelsHash && !managedConfigChanged) {
1869
+ try {
1870
+ await writeCache({ ...cache, lastRefresh: Date.now(), modelsHash, baseURL: NIM_BASE_URL });
1871
+ } catch {
1872
+ }
1873
+ return false;
1874
+ }
1875
+ let releaseLockFn = null;
1876
+ try {
1877
+ releaseLockFn = await acquireLock("nim-config-update");
1878
+ } catch (e) {
1879
+ const msg = e instanceof Error ? e.message : "Unknown";
1880
+ console.error("[NIM-Sync] Config lock failed:", msg);
1881
+ safeShowToast({ title: "NVIDIA Config Lock Failed", description: msg, variant: "error" });
1882
+ throw e;
1883
+ }
1884
+ try {
1885
+ const updatedConfig = {
1886
+ ...config || {},
1887
+ provider: { ...config?.provider, nim: updatedNIMConfig }
1888
+ };
1889
+ const validation = validateOpenCodeConfig(updatedConfig);
1890
+ if (!validation.valid) {
1891
+ console.warn("[NIM-Sync] Config validation warnings:", validation.errors);
1892
+ }
1893
+ await updateJSONCPath(getConfigPath(), ["provider", "nim"], updatedNIMConfig, { backup: true, createBackupDir: true });
1894
+ try {
1895
+ await writeCache({ lastRefresh: Date.now(), modelsHash, baseURL: NIM_BASE_URL });
1896
+ } catch {
1897
+ }
1898
+ return true;
1899
+ } catch (e) {
1900
+ const msg = e instanceof Error ? e.message : "Unknown";
1901
+ console.error("[NIM-Sync] Config update failed:", msg);
1902
+ safeShowToast({ title: "NVIDIA Config Update Failed", description: msg, variant: "error" });
1903
+ throw e;
1904
+ } finally {
1905
+ if (releaseLockFn) {
1906
+ try {
1907
+ await releaseLockFn();
1908
+ } catch (e) {
1909
+ console.error("[NIM-Sync] Failed to release config lock:", e);
1910
+ }
1911
+ }
1912
+ }
1913
+ };
1914
+ const exposedUpdateConfig = updateConfig;
1915
+ const refreshModels = async (force = false) => {
1916
+ if (refreshInProgress) return;
1917
+ refreshInProgress = true;
1918
+ let apiKey = null;
1919
+ try {
1920
+ if (!force && !await shouldRefresh()) return;
1921
+ apiKey = await getAPIKey();
1922
+ if (!apiKey) {
1923
+ safeShowToast({ title: "NVIDIA API Key Required", description: "Run /connect to add your NVIDIA API key", variant: "error" });
1924
+ return;
1925
+ }
1926
+ const models = await fetchModels(apiKey);
1927
+ if (models.length === 0) {
1928
+ safeShowToast({ title: "No Models Available", description: "NVIDIA API returned no models.", variant: "error" });
1929
+ return;
1930
+ }
1931
+ const changed = await updateConfig(models);
1932
+ if (changed) safeShowToast({ title: "NVIDIA NIM Models Updated", description: models.length + " models synchronized", variant: "success" });
1933
+ } catch (error) {
1934
+ const msg = sanitizeErrorMessage(error instanceof Error ? error.message : "Unknown error", apiKey);
1935
+ console.error("[NIM-Sync] Model refresh failed:", msg);
1936
+ safeShowToast({ title: "NVIDIA Sync Failed", description: msg, variant: "error" });
1937
+ try {
1938
+ await writeCache({ modelsHash: "", lastError: msg, baseURL: NIM_BASE_URL });
1939
+ } catch {
1940
+ }
1941
+ } finally {
1942
+ refreshInProgress = false;
1943
+ }
1944
+ };
1945
+ const init = async () => {
1946
+ try {
1947
+ api.command.register("nim-refresh", async () => {
1948
+ const now = Date.now();
1949
+ if (now - lastManualRefresh < MIN_MANUAL_REFRESH_INTERVAL_MS) {
1950
+ const remainingSeconds = Math.ceil((MIN_MANUAL_REFRESH_INTERVAL_MS - (now - lastManualRefresh)) / 1e3);
1951
+ safeShowToast({ title: "Rate Limited", description: "Please wait " + remainingSeconds + "s before refreshing again", variant: "default" });
1952
+ return;
1953
+ }
1954
+ lastManualRefresh = now;
1955
+ await refreshModels(true);
1956
+ }, { description: "Force refresh NVIDIA NIM models" });
1957
+ } catch (e) {
1958
+ console.error("[NIM-Sync] Failed to register command:", e);
1959
+ }
1960
+ void refreshModels().catch((e) => {
1961
+ console.error("[NIM-Sync] Init failed:", e);
1962
+ });
1963
+ };
1964
+ const hooks = {
1965
+ "server.connected": async () => {
1966
+ try {
1967
+ await refreshModels();
1968
+ } catch (e) {
1969
+ console.error("[NIM-Sync] Hook failed:", e);
1970
+ }
1971
+ },
1972
+ "session.created": async () => {
1973
+ try {
1974
+ await refreshModels();
1975
+ } catch (e) {
1976
+ console.error("[NIM-Sync] Hook failed:", e);
1977
+ }
1978
+ }
1979
+ };
1980
+ const exposedRefreshModels = refreshModels;
1981
+ return { init, hooks, getAPIKey: exposedGetAPIKey, updateConfig: exposedUpdateConfig, refreshModels: exposedRefreshModels, shouldRefresh: exposedShouldRefresh };
1982
+ }
1983
+
1984
+ // src/index.ts
1985
+ var index_default = syncNIMModels;
1986
+ export {
1987
+ index_default as default
1988
+ };
1989
+ //# sourceMappingURL=nim-sync.mjs.map