@cloudflare/config 0.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,3699 @@
1
+ import { a as bindings, i as triggers, n as resolveWorkerDefinition, r as exports$1, t as defineWorker } from "./public-CFHebTo4.mjs";
2
+ import * as nodeModule from "node:module";
3
+ import * as fsp from "node:fs/promises";
4
+ import * as path from "node:path";
5
+ import path2, { dirname, isAbsolute, join, resolve } from "node:path";
6
+ import fs2, { existsSync, readFileSync, statSync } from "node:fs";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import { AsyncLocalStorage } from "node:async_hooks";
9
+ import * as z from "zod";
10
+
11
+ //#region rolldown:runtime
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __commonJS = (cb, mod) => function() {
14
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ };
16
+
17
+ //#endregion
18
+ //#region ../workers-utils/dist/chunk-6IEM75FG.mjs
19
+ var __defProp = Object.defineProperty;
20
+ var __name = (target, value) => __defProp(target, "name", {
21
+ value,
22
+ configurable: true
23
+ });
24
+
25
+ //#endregion
26
+ //#region ../workers-utils/dist/chunk-DPLELERC.mjs
27
+ function isDirectory(path$1) {
28
+ return fs2.statSync(path$1, { throwIfNoEntry: false })?.isDirectory() ?? false;
29
+ }
30
+ __name(isDirectory, "isDirectory");
31
+ function removeDir(dirPath, { fireAndForget = false } = {}) {
32
+ const result = fs2.promises.rm(dirPath, {
33
+ recursive: true,
34
+ force: true,
35
+ maxRetries: 5,
36
+ retryDelay: 100
37
+ });
38
+ if (fireAndForget) result.catch(() => {});
39
+ else return result;
40
+ }
41
+ __name(removeDir, "removeDir");
42
+ function removeDirSync(dirPath) {
43
+ fs2.rmSync(dirPath, {
44
+ recursive: true,
45
+ force: true,
46
+ maxRetries: 5,
47
+ retryDelay: 100
48
+ });
49
+ }
50
+ __name(removeDirSync, "removeDirSync");
51
+
52
+ //#endregion
53
+ //#region ../workers-utils/dist/chunk-WYII773A.mjs
54
+ function partitionExports(exports$2) {
55
+ const partitioned = {
56
+ "durable-object": {},
57
+ worker: {}
58
+ };
59
+ if (exports$2 === void 0) return partitioned;
60
+ for (const [name, entry] of Object.entries(exports$2)) partitioned[entry.type][name] = entry;
61
+ return partitioned;
62
+ }
63
+ __name(partitionExports, "partitionExports");
64
+ var UserError = class extends Error {
65
+ static {
66
+ __name(this, "UserError");
67
+ }
68
+ telemetryMessage;
69
+ constructor(message, options) {
70
+ super(message, options);
71
+ Object.setPrototypeOf(this, new.target.prototype);
72
+ this.telemetryMessage = typeof options?.telemetryMessage === "string" ? options.telemetryMessage : options?.telemetryMessage ? message : void 0;
73
+ }
74
+ };
75
+ var DeprecationError = class extends UserError {
76
+ static {
77
+ __name(this, "DeprecationError");
78
+ }
79
+ constructor(message, options) {
80
+ super(`Deprecation:
81
+ ${message}`, options);
82
+ }
83
+ };
84
+ var FatalError = class extends UserError {
85
+ static {
86
+ __name(this, "FatalError");
87
+ }
88
+ code;
89
+ constructor(message, options) {
90
+ super(message, options);
91
+ this.code = options.code;
92
+ }
93
+ };
94
+ var CommandLineArgsError = class extends UserError {
95
+ static {
96
+ __name(this, "CommandLineArgsError");
97
+ }
98
+ };
99
+ var JsonFriendlyFatalError = class extends FatalError {
100
+ static {
101
+ __name(this, "JsonFriendlyFatalError");
102
+ }
103
+ };
104
+ var MissingConfigError = class extends Error {
105
+ static {
106
+ __name(this, "MissingConfigError");
107
+ }
108
+ telemetryMessage;
109
+ constructor(key) {
110
+ super(`Missing config value for ${key}`);
111
+ this.telemetryMessage = `Missing config value for ${key}`;
112
+ }
113
+ };
114
+ function createFatalError(message, isJson, options) {
115
+ if (isJson) return new JsonFriendlyFatalError(JSON.stringify(message), options);
116
+ return new FatalError(`${message}`, options);
117
+ }
118
+ __name(createFatalError, "createFatalError");
119
+ function createScanner(text, ignoreTrivia = false) {
120
+ const len = text.length;
121
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
122
+ function scanHexDigits(count, exact) {
123
+ let digits = 0;
124
+ let value2 = 0;
125
+ while (digits < count || !exact) {
126
+ let ch = text.charCodeAt(pos);
127
+ if (ch >= 48 && ch <= 57) value2 = value2 * 16 + ch - 48;
128
+ else if (ch >= 65 && ch <= 70) value2 = value2 * 16 + ch - 65 + 10;
129
+ else if (ch >= 97 && ch <= 102) value2 = value2 * 16 + ch - 97 + 10;
130
+ else break;
131
+ pos++;
132
+ digits++;
133
+ }
134
+ if (digits < count) value2 = -1;
135
+ return value2;
136
+ }
137
+ __name(scanHexDigits, "scanHexDigits");
138
+ function setPosition(newPosition) {
139
+ pos = newPosition;
140
+ value = "";
141
+ tokenOffset = 0;
142
+ token = 16;
143
+ scanError = 0;
144
+ }
145
+ __name(setPosition, "setPosition");
146
+ function scanNumber() {
147
+ let start = pos;
148
+ if (text.charCodeAt(pos) === 48) pos++;
149
+ else {
150
+ pos++;
151
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
152
+ }
153
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
154
+ pos++;
155
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
156
+ pos++;
157
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
158
+ } else {
159
+ scanError = 3;
160
+ return text.substring(start, pos);
161
+ }
162
+ }
163
+ let end = pos;
164
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
165
+ pos++;
166
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++;
167
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
168
+ pos++;
169
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
170
+ end = pos;
171
+ } else scanError = 3;
172
+ }
173
+ return text.substring(start, end);
174
+ }
175
+ __name(scanNumber, "scanNumber");
176
+ function scanString() {
177
+ let result = "", start = pos;
178
+ while (true) {
179
+ if (pos >= len) {
180
+ result += text.substring(start, pos);
181
+ scanError = 2;
182
+ break;
183
+ }
184
+ const ch = text.charCodeAt(pos);
185
+ if (ch === 34) {
186
+ result += text.substring(start, pos);
187
+ pos++;
188
+ break;
189
+ }
190
+ if (ch === 92) {
191
+ result += text.substring(start, pos);
192
+ pos++;
193
+ if (pos >= len) {
194
+ scanError = 2;
195
+ break;
196
+ }
197
+ switch (text.charCodeAt(pos++)) {
198
+ case 34:
199
+ result += "\"";
200
+ break;
201
+ case 92:
202
+ result += "\\";
203
+ break;
204
+ case 47:
205
+ result += "/";
206
+ break;
207
+ case 98:
208
+ result += "\b";
209
+ break;
210
+ case 102:
211
+ result += "\f";
212
+ break;
213
+ case 110:
214
+ result += "\n";
215
+ break;
216
+ case 114:
217
+ result += "\r";
218
+ break;
219
+ case 116:
220
+ result += " ";
221
+ break;
222
+ case 117:
223
+ const ch3 = scanHexDigits(4, true);
224
+ if (ch3 >= 0) result += String.fromCharCode(ch3);
225
+ else scanError = 4;
226
+ break;
227
+ default: scanError = 5;
228
+ }
229
+ start = pos;
230
+ continue;
231
+ }
232
+ if (ch >= 0 && ch <= 31) if (isLineBreak(ch)) {
233
+ result += text.substring(start, pos);
234
+ scanError = 2;
235
+ break;
236
+ } else scanError = 6;
237
+ pos++;
238
+ }
239
+ return result;
240
+ }
241
+ __name(scanString, "scanString");
242
+ function scanNext() {
243
+ value = "";
244
+ scanError = 0;
245
+ tokenOffset = pos;
246
+ lineStartOffset = lineNumber;
247
+ prevTokenLineStartOffset = tokenLineStartOffset;
248
+ if (pos >= len) {
249
+ tokenOffset = len;
250
+ return token = 17;
251
+ }
252
+ let code = text.charCodeAt(pos);
253
+ if (isWhiteSpace(code)) {
254
+ do {
255
+ pos++;
256
+ value += String.fromCharCode(code);
257
+ code = text.charCodeAt(pos);
258
+ } while (isWhiteSpace(code));
259
+ return token = 15;
260
+ }
261
+ if (isLineBreak(code)) {
262
+ pos++;
263
+ value += String.fromCharCode(code);
264
+ if (code === 13 && text.charCodeAt(pos) === 10) {
265
+ pos++;
266
+ value += "\n";
267
+ }
268
+ lineNumber++;
269
+ tokenLineStartOffset = pos;
270
+ return token = 14;
271
+ }
272
+ switch (code) {
273
+ case 123:
274
+ pos++;
275
+ return token = 1;
276
+ case 125:
277
+ pos++;
278
+ return token = 2;
279
+ case 91:
280
+ pos++;
281
+ return token = 3;
282
+ case 93:
283
+ pos++;
284
+ return token = 4;
285
+ case 58:
286
+ pos++;
287
+ return token = 6;
288
+ case 44:
289
+ pos++;
290
+ return token = 5;
291
+ case 34:
292
+ pos++;
293
+ value = scanString();
294
+ return token = 10;
295
+ case 47:
296
+ const start = pos - 1;
297
+ if (text.charCodeAt(pos + 1) === 47) {
298
+ pos += 2;
299
+ while (pos < len) {
300
+ if (isLineBreak(text.charCodeAt(pos))) break;
301
+ pos++;
302
+ }
303
+ value = text.substring(start, pos);
304
+ return token = 12;
305
+ }
306
+ if (text.charCodeAt(pos + 1) === 42) {
307
+ pos += 2;
308
+ const safeLength = len - 1;
309
+ let commentClosed = false;
310
+ while (pos < safeLength) {
311
+ const ch = text.charCodeAt(pos);
312
+ if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
313
+ pos += 2;
314
+ commentClosed = true;
315
+ break;
316
+ }
317
+ pos++;
318
+ if (isLineBreak(ch)) {
319
+ if (ch === 13 && text.charCodeAt(pos) === 10) pos++;
320
+ lineNumber++;
321
+ tokenLineStartOffset = pos;
322
+ }
323
+ }
324
+ if (!commentClosed) {
325
+ pos++;
326
+ scanError = 1;
327
+ }
328
+ value = text.substring(start, pos);
329
+ return token = 13;
330
+ }
331
+ value += String.fromCharCode(code);
332
+ pos++;
333
+ return token = 16;
334
+ case 45:
335
+ value += String.fromCharCode(code);
336
+ pos++;
337
+ if (pos === len || !isDigit(text.charCodeAt(pos))) return token = 16;
338
+ case 48:
339
+ case 49:
340
+ case 50:
341
+ case 51:
342
+ case 52:
343
+ case 53:
344
+ case 54:
345
+ case 55:
346
+ case 56:
347
+ case 57:
348
+ value += scanNumber();
349
+ return token = 11;
350
+ default:
351
+ while (pos < len && isUnknownContentCharacter(code)) {
352
+ pos++;
353
+ code = text.charCodeAt(pos);
354
+ }
355
+ if (tokenOffset !== pos) {
356
+ value = text.substring(tokenOffset, pos);
357
+ switch (value) {
358
+ case "true": return token = 8;
359
+ case "false": return token = 9;
360
+ case "null": return token = 7;
361
+ }
362
+ return token = 16;
363
+ }
364
+ value += String.fromCharCode(code);
365
+ pos++;
366
+ return token = 16;
367
+ }
368
+ }
369
+ __name(scanNext, "scanNext");
370
+ function isUnknownContentCharacter(code) {
371
+ if (isWhiteSpace(code) || isLineBreak(code)) return false;
372
+ switch (code) {
373
+ case 125:
374
+ case 93:
375
+ case 123:
376
+ case 91:
377
+ case 34:
378
+ case 58:
379
+ case 44:
380
+ case 47: return false;
381
+ }
382
+ return true;
383
+ }
384
+ __name(isUnknownContentCharacter, "isUnknownContentCharacter");
385
+ function scanNextNonTrivia() {
386
+ let result;
387
+ do
388
+ result = scanNext();
389
+ while (result >= 12 && result <= 15);
390
+ return result;
391
+ }
392
+ __name(scanNextNonTrivia, "scanNextNonTrivia");
393
+ return {
394
+ setPosition,
395
+ getPosition: /* @__PURE__ */ __name(() => pos, "getPosition"),
396
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
397
+ getToken: /* @__PURE__ */ __name(() => token, "getToken"),
398
+ getTokenValue: /* @__PURE__ */ __name(() => value, "getTokenValue"),
399
+ getTokenOffset: /* @__PURE__ */ __name(() => tokenOffset, "getTokenOffset"),
400
+ getTokenLength: /* @__PURE__ */ __name(() => pos - tokenOffset, "getTokenLength"),
401
+ getTokenStartLine: /* @__PURE__ */ __name(() => lineStartOffset, "getTokenStartLine"),
402
+ getTokenStartCharacter: /* @__PURE__ */ __name(() => tokenOffset - prevTokenLineStartOffset, "getTokenStartCharacter"),
403
+ getTokenError: /* @__PURE__ */ __name(() => scanError, "getTokenError")
404
+ };
405
+ }
406
+ __name(createScanner, "createScanner");
407
+ function isWhiteSpace(ch) {
408
+ return ch === 32 || ch === 9;
409
+ }
410
+ __name(isWhiteSpace, "isWhiteSpace");
411
+ function isLineBreak(ch) {
412
+ return ch === 10 || ch === 13;
413
+ }
414
+ __name(isLineBreak, "isLineBreak");
415
+ function isDigit(ch) {
416
+ return ch >= 48 && ch <= 57;
417
+ }
418
+ __name(isDigit, "isDigit");
419
+ var CharacterCodes;
420
+ (function(CharacterCodes2) {
421
+ CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
422
+ CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
423
+ CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
424
+ CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
425
+ CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
426
+ CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
427
+ CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
428
+ CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
429
+ CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
430
+ CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
431
+ CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
432
+ CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
433
+ CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
434
+ CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
435
+ CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
436
+ CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
437
+ CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
438
+ CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
439
+ CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
440
+ CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
441
+ CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
442
+ CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
443
+ CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
444
+ CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
445
+ CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
446
+ CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
447
+ CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
448
+ CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
449
+ CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
450
+ CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
451
+ CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
452
+ CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
453
+ CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
454
+ CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
455
+ CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
456
+ CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
457
+ CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
458
+ CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
459
+ CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
460
+ CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
461
+ CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
462
+ CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
463
+ CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
464
+ CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
465
+ CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
466
+ CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
467
+ CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
468
+ CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
469
+ CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
470
+ CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
471
+ CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
472
+ CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
473
+ CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
474
+ CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
475
+ CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
476
+ CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
477
+ CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
478
+ CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
479
+ CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
480
+ CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
481
+ CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
482
+ CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
483
+ CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
484
+ CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
485
+ CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
486
+ CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
487
+ CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
488
+ CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
489
+ CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
490
+ CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
491
+ CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
492
+ CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
493
+ CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
494
+ CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
495
+ CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
496
+ CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
497
+ CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
498
+ CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
499
+ CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
500
+ CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
501
+ })(CharacterCodes || (CharacterCodes = {}));
502
+ function format(documentText, range, options) {
503
+ let initialIndentLevel;
504
+ let formatText;
505
+ let formatTextStart;
506
+ let rangeStart;
507
+ let rangeEnd;
508
+ if (range) {
509
+ rangeStart = range.offset;
510
+ rangeEnd = rangeStart + range.length;
511
+ formatTextStart = rangeStart;
512
+ while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) formatTextStart--;
513
+ let endOffset = rangeEnd;
514
+ while (endOffset < documentText.length && !isEOL(documentText, endOffset)) endOffset++;
515
+ formatText = documentText.substring(formatTextStart, endOffset);
516
+ initialIndentLevel = computeIndentLevel(formatText, options);
517
+ } else {
518
+ formatText = documentText;
519
+ initialIndentLevel = 0;
520
+ formatTextStart = 0;
521
+ rangeStart = 0;
522
+ rangeEnd = documentText.length;
523
+ }
524
+ const eol = getEOL(options, documentText);
525
+ let numberLineBreaks = 0;
526
+ let indentLevel = 0;
527
+ let indentValue;
528
+ if (options.insertSpaces) indentValue = repeat(" ", options.tabSize || 4);
529
+ else indentValue = " ";
530
+ let scanner = createScanner(formatText, false);
531
+ let hasError = false;
532
+ function newLinesAndIndent() {
533
+ if (numberLineBreaks > 1) return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
534
+ else return eol + repeat(indentValue, initialIndentLevel + indentLevel);
535
+ }
536
+ __name(newLinesAndIndent, "newLinesAndIndent");
537
+ function scanNext() {
538
+ let token = scanner.scan();
539
+ numberLineBreaks = 0;
540
+ while (token === 15 || token === 14) {
541
+ if (token === 14 && options.keepLines) numberLineBreaks += 1;
542
+ else if (token === 14) numberLineBreaks = 1;
543
+ token = scanner.scan();
544
+ }
545
+ hasError = token === 16 || scanner.getTokenError() !== 0;
546
+ return token;
547
+ }
548
+ __name(scanNext, "scanNext");
549
+ const editOperations = [];
550
+ function addEdit(text, startOffset, endOffset) {
551
+ if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) editOperations.push({
552
+ offset: startOffset,
553
+ length: endOffset - startOffset,
554
+ content: text
555
+ });
556
+ }
557
+ __name(addEdit, "addEdit");
558
+ let firstToken = scanNext();
559
+ if (options.keepLines && numberLineBreaks > 0) addEdit(repeat(eol, numberLineBreaks), 0, 0);
560
+ if (firstToken !== 17) {
561
+ let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
562
+ addEdit(repeat(indentValue, initialIndentLevel), formatTextStart, firstTokenStart);
563
+ }
564
+ while (firstToken !== 17) {
565
+ let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
566
+ let secondToken = scanNext();
567
+ let replaceContent = "";
568
+ let needsLineBreak = false;
569
+ while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
570
+ let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
571
+ addEdit(" ", firstTokenEnd, commentTokenStart);
572
+ firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
573
+ needsLineBreak = secondToken === 12;
574
+ replaceContent = needsLineBreak ? newLinesAndIndent() : "";
575
+ secondToken = scanNext();
576
+ }
577
+ if (secondToken === 2) {
578
+ if (firstToken !== 1) indentLevel--;
579
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) replaceContent = newLinesAndIndent();
580
+ else if (options.keepLines) replaceContent = " ";
581
+ } else if (secondToken === 4) {
582
+ if (firstToken !== 3) indentLevel--;
583
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) replaceContent = newLinesAndIndent();
584
+ else if (options.keepLines) replaceContent = " ";
585
+ } else {
586
+ switch (firstToken) {
587
+ case 3:
588
+ case 1:
589
+ indentLevel++;
590
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent();
591
+ else replaceContent = " ";
592
+ break;
593
+ case 5:
594
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent();
595
+ else replaceContent = " ";
596
+ break;
597
+ case 12:
598
+ replaceContent = newLinesAndIndent();
599
+ break;
600
+ case 13:
601
+ if (numberLineBreaks > 0) replaceContent = newLinesAndIndent();
602
+ else if (!needsLineBreak) replaceContent = " ";
603
+ break;
604
+ case 6:
605
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
606
+ else if (!needsLineBreak) replaceContent = " ";
607
+ break;
608
+ case 10:
609
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
610
+ else if (secondToken === 6 && !needsLineBreak) replaceContent = "";
611
+ break;
612
+ case 7:
613
+ case 8:
614
+ case 9:
615
+ case 11:
616
+ case 2:
617
+ case 4:
618
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
619
+ else if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) replaceContent = " ";
620
+ else if (secondToken !== 5 && secondToken !== 17) hasError = true;
621
+ break;
622
+ case 16:
623
+ hasError = true;
624
+ break;
625
+ }
626
+ if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) replaceContent = newLinesAndIndent();
627
+ }
628
+ if (secondToken === 17) if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
629
+ else replaceContent = options.insertFinalNewline ? eol : "";
630
+ const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
631
+ addEdit(replaceContent, firstTokenEnd, secondTokenStart);
632
+ firstToken = secondToken;
633
+ }
634
+ return editOperations;
635
+ }
636
+ __name(format, "format");
637
+ function repeat(s, count) {
638
+ let result = "";
639
+ for (let i = 0; i < count; i++) result += s;
640
+ return result;
641
+ }
642
+ __name(repeat, "repeat");
643
+ function computeIndentLevel(content, options) {
644
+ let i = 0;
645
+ let nChars = 0;
646
+ const tabSize = options.tabSize || 4;
647
+ while (i < content.length) {
648
+ let ch = content.charAt(i);
649
+ if (ch === " ") nChars++;
650
+ else if (ch === " ") nChars += tabSize;
651
+ else break;
652
+ i++;
653
+ }
654
+ return Math.floor(nChars / tabSize);
655
+ }
656
+ __name(computeIndentLevel, "computeIndentLevel");
657
+ function getEOL(options, text) {
658
+ for (let i = 0; i < text.length; i++) {
659
+ const ch = text.charAt(i);
660
+ if (ch === "\r") {
661
+ if (i + 1 < text.length && text.charAt(i + 1) === "\n") return "\r\n";
662
+ return "\r";
663
+ } else if (ch === "\n") return "\n";
664
+ }
665
+ return options && options.eol || "\n";
666
+ }
667
+ __name(getEOL, "getEOL");
668
+ function isEOL(text, offset) {
669
+ return "\r\n".indexOf(text.charAt(offset)) !== -1;
670
+ }
671
+ __name(isEOL, "isEOL");
672
+ var ParseOptions;
673
+ (function(ParseOptions2) {
674
+ ParseOptions2.DEFAULT = { allowTrailingComma: false };
675
+ })(ParseOptions || (ParseOptions = {}));
676
+ function parse(text, errors = [], options = ParseOptions.DEFAULT) {
677
+ let currentProperty = null;
678
+ let currentParent = [];
679
+ const previousParents = [];
680
+ function onValue(value) {
681
+ if (Array.isArray(currentParent)) currentParent.push(value);
682
+ else if (currentProperty !== null) currentParent[currentProperty] = value;
683
+ }
684
+ __name(onValue, "onValue");
685
+ visit(text, {
686
+ onObjectBegin: /* @__PURE__ */ __name(() => {
687
+ const object = {};
688
+ onValue(object);
689
+ previousParents.push(currentParent);
690
+ currentParent = object;
691
+ currentProperty = null;
692
+ }, "onObjectBegin"),
693
+ onObjectProperty: /* @__PURE__ */ __name((name) => {
694
+ currentProperty = name;
695
+ }, "onObjectProperty"),
696
+ onObjectEnd: /* @__PURE__ */ __name(() => {
697
+ currentParent = previousParents.pop();
698
+ }, "onObjectEnd"),
699
+ onArrayBegin: /* @__PURE__ */ __name(() => {
700
+ const array = [];
701
+ onValue(array);
702
+ previousParents.push(currentParent);
703
+ currentParent = array;
704
+ currentProperty = null;
705
+ }, "onArrayBegin"),
706
+ onArrayEnd: /* @__PURE__ */ __name(() => {
707
+ currentParent = previousParents.pop();
708
+ }, "onArrayEnd"),
709
+ onLiteralValue: onValue,
710
+ onError: /* @__PURE__ */ __name((error, offset, length) => {
711
+ errors.push({
712
+ error,
713
+ offset,
714
+ length
715
+ });
716
+ }, "onError")
717
+ }, options);
718
+ return currentParent[0];
719
+ }
720
+ __name(parse, "parse");
721
+ function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
722
+ let currentParent = {
723
+ type: "array",
724
+ offset: -1,
725
+ length: -1,
726
+ children: [],
727
+ parent: void 0
728
+ };
729
+ function ensurePropertyComplete(endOffset) {
730
+ if (currentParent.type === "property") {
731
+ currentParent.length = endOffset - currentParent.offset;
732
+ currentParent = currentParent.parent;
733
+ }
734
+ }
735
+ __name(ensurePropertyComplete, "ensurePropertyComplete");
736
+ function onValue(valueNode) {
737
+ currentParent.children.push(valueNode);
738
+ return valueNode;
739
+ }
740
+ __name(onValue, "onValue");
741
+ visit(text, {
742
+ onObjectBegin: /* @__PURE__ */ __name((offset) => {
743
+ currentParent = onValue({
744
+ type: "object",
745
+ offset,
746
+ length: -1,
747
+ parent: currentParent,
748
+ children: []
749
+ });
750
+ }, "onObjectBegin"),
751
+ onObjectProperty: /* @__PURE__ */ __name((name, offset, length) => {
752
+ currentParent = onValue({
753
+ type: "property",
754
+ offset,
755
+ length: -1,
756
+ parent: currentParent,
757
+ children: []
758
+ });
759
+ currentParent.children.push({
760
+ type: "string",
761
+ value: name,
762
+ offset,
763
+ length,
764
+ parent: currentParent
765
+ });
766
+ }, "onObjectProperty"),
767
+ onObjectEnd: /* @__PURE__ */ __name((offset, length) => {
768
+ ensurePropertyComplete(offset + length);
769
+ currentParent.length = offset + length - currentParent.offset;
770
+ currentParent = currentParent.parent;
771
+ ensurePropertyComplete(offset + length);
772
+ }, "onObjectEnd"),
773
+ onArrayBegin: /* @__PURE__ */ __name((offset, length) => {
774
+ currentParent = onValue({
775
+ type: "array",
776
+ offset,
777
+ length: -1,
778
+ parent: currentParent,
779
+ children: []
780
+ });
781
+ }, "onArrayBegin"),
782
+ onArrayEnd: /* @__PURE__ */ __name((offset, length) => {
783
+ currentParent.length = offset + length - currentParent.offset;
784
+ currentParent = currentParent.parent;
785
+ ensurePropertyComplete(offset + length);
786
+ }, "onArrayEnd"),
787
+ onLiteralValue: /* @__PURE__ */ __name((value, offset, length) => {
788
+ onValue({
789
+ type: getNodeType(value),
790
+ offset,
791
+ length,
792
+ parent: currentParent,
793
+ value
794
+ });
795
+ ensurePropertyComplete(offset + length);
796
+ }, "onLiteralValue"),
797
+ onSeparator: /* @__PURE__ */ __name((sep, offset, length) => {
798
+ if (currentParent.type === "property") {
799
+ if (sep === ":") currentParent.colonOffset = offset;
800
+ else if (sep === ",") ensurePropertyComplete(offset);
801
+ }
802
+ }, "onSeparator"),
803
+ onError: /* @__PURE__ */ __name((error, offset, length) => {
804
+ errors.push({
805
+ error,
806
+ offset,
807
+ length
808
+ });
809
+ }, "onError")
810
+ }, options);
811
+ const result = currentParent.children[0];
812
+ if (result) delete result.parent;
813
+ return result;
814
+ }
815
+ __name(parseTree, "parseTree");
816
+ function findNodeAtLocation(root, path2$1) {
817
+ if (!root) return;
818
+ let node = root;
819
+ for (let segment of path2$1) if (typeof segment === "string") {
820
+ if (node.type !== "object" || !Array.isArray(node.children)) return;
821
+ let found = false;
822
+ for (const propertyNode of node.children) if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
823
+ node = propertyNode.children[1];
824
+ found = true;
825
+ break;
826
+ }
827
+ if (!found) return;
828
+ } else {
829
+ const index = segment;
830
+ if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) return;
831
+ node = node.children[index];
832
+ }
833
+ return node;
834
+ }
835
+ __name(findNodeAtLocation, "findNodeAtLocation");
836
+ function visit(text, visitor, options = ParseOptions.DEFAULT) {
837
+ const _scanner = createScanner(text, false);
838
+ const _jsonPath = [];
839
+ function toNoArgVisit(visitFunction) {
840
+ return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
841
+ }
842
+ __name(toNoArgVisit, "toNoArgVisit");
843
+ function toNoArgVisitWithPath(visitFunction) {
844
+ return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
845
+ }
846
+ __name(toNoArgVisitWithPath, "toNoArgVisitWithPath");
847
+ function toOneArgVisit(visitFunction) {
848
+ return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
849
+ }
850
+ __name(toOneArgVisit, "toOneArgVisit");
851
+ function toOneArgVisitWithPath(visitFunction) {
852
+ return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
853
+ }
854
+ __name(toOneArgVisitWithPath, "toOneArgVisitWithPath");
855
+ const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
856
+ const disallowComments = options && options.disallowComments;
857
+ const allowTrailingComma = options && options.allowTrailingComma;
858
+ function scanNext() {
859
+ while (true) {
860
+ const token = _scanner.scan();
861
+ switch (_scanner.getTokenError()) {
862
+ case 4:
863
+ handleError(14);
864
+ break;
865
+ case 5:
866
+ handleError(15);
867
+ break;
868
+ case 3:
869
+ handleError(13);
870
+ break;
871
+ case 1:
872
+ if (!disallowComments) handleError(11);
873
+ break;
874
+ case 2:
875
+ handleError(12);
876
+ break;
877
+ case 6:
878
+ handleError(16);
879
+ break;
880
+ }
881
+ switch (token) {
882
+ case 12:
883
+ case 13:
884
+ if (disallowComments) handleError(10);
885
+ else onComment();
886
+ break;
887
+ case 16:
888
+ handleError(1);
889
+ break;
890
+ case 15:
891
+ case 14: break;
892
+ default: return token;
893
+ }
894
+ }
895
+ }
896
+ __name(scanNext, "scanNext");
897
+ function handleError(error, skipUntilAfter = [], skipUntil2 = []) {
898
+ onError(error);
899
+ if (skipUntilAfter.length + skipUntil2.length > 0) {
900
+ let token = _scanner.getToken();
901
+ while (token !== 17) {
902
+ if (skipUntilAfter.indexOf(token) !== -1) {
903
+ scanNext();
904
+ break;
905
+ } else if (skipUntil2.indexOf(token) !== -1) break;
906
+ token = scanNext();
907
+ }
908
+ }
909
+ }
910
+ __name(handleError, "handleError");
911
+ function parseString2(isValue) {
912
+ const value = _scanner.getTokenValue();
913
+ if (isValue) onLiteralValue(value);
914
+ else {
915
+ onObjectProperty(value);
916
+ _jsonPath.push(value);
917
+ }
918
+ scanNext();
919
+ return true;
920
+ }
921
+ __name(parseString2, "parseString");
922
+ function parseLiteral() {
923
+ switch (_scanner.getToken()) {
924
+ case 11:
925
+ const tokenValue = _scanner.getTokenValue();
926
+ let value = Number(tokenValue);
927
+ if (isNaN(value)) {
928
+ handleError(2);
929
+ value = 0;
930
+ }
931
+ onLiteralValue(value);
932
+ break;
933
+ case 7:
934
+ onLiteralValue(null);
935
+ break;
936
+ case 8:
937
+ onLiteralValue(true);
938
+ break;
939
+ case 9:
940
+ onLiteralValue(false);
941
+ break;
942
+ default: return false;
943
+ }
944
+ scanNext();
945
+ return true;
946
+ }
947
+ __name(parseLiteral, "parseLiteral");
948
+ function parseProperty() {
949
+ if (_scanner.getToken() !== 10) {
950
+ handleError(3, [], [2, 5]);
951
+ return false;
952
+ }
953
+ parseString2(false);
954
+ if (_scanner.getToken() === 6) {
955
+ onSeparator(":");
956
+ scanNext();
957
+ if (!parseValue2()) handleError(4, [], [2, 5]);
958
+ } else handleError(5, [], [2, 5]);
959
+ _jsonPath.pop();
960
+ return true;
961
+ }
962
+ __name(parseProperty, "parseProperty");
963
+ function parseObject() {
964
+ onObjectBegin();
965
+ scanNext();
966
+ let needsComma = false;
967
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
968
+ if (_scanner.getToken() === 5) {
969
+ if (!needsComma) handleError(4, [], []);
970
+ onSeparator(",");
971
+ scanNext();
972
+ if (_scanner.getToken() === 2 && allowTrailingComma) break;
973
+ } else if (needsComma) handleError(6, [], []);
974
+ if (!parseProperty()) handleError(4, [], [2, 5]);
975
+ needsComma = true;
976
+ }
977
+ onObjectEnd();
978
+ if (_scanner.getToken() !== 2) handleError(7, [2], []);
979
+ else scanNext();
980
+ return true;
981
+ }
982
+ __name(parseObject, "parseObject");
983
+ function parseArray2() {
984
+ onArrayBegin();
985
+ scanNext();
986
+ let isFirstElement = true;
987
+ let needsComma = false;
988
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
989
+ if (_scanner.getToken() === 5) {
990
+ if (!needsComma) handleError(4, [], []);
991
+ onSeparator(",");
992
+ scanNext();
993
+ if (_scanner.getToken() === 4 && allowTrailingComma) break;
994
+ } else if (needsComma) handleError(6, [], []);
995
+ if (isFirstElement) {
996
+ _jsonPath.push(0);
997
+ isFirstElement = false;
998
+ } else _jsonPath[_jsonPath.length - 1]++;
999
+ if (!parseValue2()) handleError(4, [], [4, 5]);
1000
+ needsComma = true;
1001
+ }
1002
+ onArrayEnd();
1003
+ if (!isFirstElement) _jsonPath.pop();
1004
+ if (_scanner.getToken() !== 4) handleError(8, [4], []);
1005
+ else scanNext();
1006
+ return true;
1007
+ }
1008
+ __name(parseArray2, "parseArray");
1009
+ function parseValue2() {
1010
+ switch (_scanner.getToken()) {
1011
+ case 3: return parseArray2();
1012
+ case 1: return parseObject();
1013
+ case 10: return parseString2(true);
1014
+ default: return parseLiteral();
1015
+ }
1016
+ }
1017
+ __name(parseValue2, "parseValue");
1018
+ scanNext();
1019
+ if (_scanner.getToken() === 17) {
1020
+ if (options.allowEmptyContent) return true;
1021
+ handleError(4, [], []);
1022
+ return false;
1023
+ }
1024
+ if (!parseValue2()) {
1025
+ handleError(4, [], []);
1026
+ return false;
1027
+ }
1028
+ if (_scanner.getToken() !== 17) handleError(9, [], []);
1029
+ return true;
1030
+ }
1031
+ __name(visit, "visit");
1032
+ function getNodeType(value) {
1033
+ switch (typeof value) {
1034
+ case "boolean": return "boolean";
1035
+ case "number": return "number";
1036
+ case "string": return "string";
1037
+ case "object":
1038
+ if (!value) return "null";
1039
+ else if (Array.isArray(value)) return "array";
1040
+ return "object";
1041
+ default: return "null";
1042
+ }
1043
+ }
1044
+ __name(getNodeType, "getNodeType");
1045
+ function setProperty(text, originalPath, value, options) {
1046
+ const path2$1 = originalPath.slice();
1047
+ const root = parseTree(text, []);
1048
+ let parent = void 0;
1049
+ let lastSegment = void 0;
1050
+ while (path2$1.length > 0) {
1051
+ lastSegment = path2$1.pop();
1052
+ parent = findNodeAtLocation(root, path2$1);
1053
+ if (parent === void 0 && value !== void 0) if (typeof lastSegment === "string") value = { [lastSegment]: value };
1054
+ else value = [value];
1055
+ else break;
1056
+ }
1057
+ if (!parent) {
1058
+ if (value === void 0) throw new Error("Can not delete in empty document");
1059
+ return withFormatting(text, {
1060
+ offset: root ? root.offset : 0,
1061
+ length: root ? root.length : 0,
1062
+ content: JSON.stringify(value)
1063
+ }, options);
1064
+ } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
1065
+ const existing = findNodeAtLocation(parent, [lastSegment]);
1066
+ if (existing !== void 0) if (value === void 0) {
1067
+ if (!existing.parent) throw new Error("Malformed AST");
1068
+ const propertyIndex = parent.children.indexOf(existing.parent);
1069
+ let removeBegin;
1070
+ let removeEnd = existing.parent.offset + existing.parent.length;
1071
+ if (propertyIndex > 0) {
1072
+ let previous = parent.children[propertyIndex - 1];
1073
+ removeBegin = previous.offset + previous.length;
1074
+ } else {
1075
+ removeBegin = parent.offset + 1;
1076
+ if (parent.children.length > 1) removeEnd = parent.children[1].offset;
1077
+ }
1078
+ return withFormatting(text, {
1079
+ offset: removeBegin,
1080
+ length: removeEnd - removeBegin,
1081
+ content: ""
1082
+ }, options);
1083
+ } else return withFormatting(text, {
1084
+ offset: existing.offset,
1085
+ length: existing.length,
1086
+ content: JSON.stringify(value)
1087
+ }, options);
1088
+ else {
1089
+ if (value === void 0) return [];
1090
+ const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
1091
+ const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
1092
+ let edit;
1093
+ if (index > 0) {
1094
+ let previous = parent.children[index - 1];
1095
+ edit = {
1096
+ offset: previous.offset + previous.length,
1097
+ length: 0,
1098
+ content: "," + newProperty
1099
+ };
1100
+ } else if (parent.children.length === 0) edit = {
1101
+ offset: parent.offset + 1,
1102
+ length: 0,
1103
+ content: newProperty
1104
+ };
1105
+ else edit = {
1106
+ offset: parent.offset + 1,
1107
+ length: 0,
1108
+ content: newProperty + ","
1109
+ };
1110
+ return withFormatting(text, edit, options);
1111
+ }
1112
+ } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
1113
+ const insertIndex = lastSegment;
1114
+ if (insertIndex === -1) {
1115
+ const newProperty = `${JSON.stringify(value)}`;
1116
+ let edit;
1117
+ if (parent.children.length === 0) edit = {
1118
+ offset: parent.offset + 1,
1119
+ length: 0,
1120
+ content: newProperty
1121
+ };
1122
+ else {
1123
+ const previous = parent.children[parent.children.length - 1];
1124
+ edit = {
1125
+ offset: previous.offset + previous.length,
1126
+ length: 0,
1127
+ content: "," + newProperty
1128
+ };
1129
+ }
1130
+ return withFormatting(text, edit, options);
1131
+ } else if (value === void 0 && parent.children.length >= 0) {
1132
+ const removalIndex = lastSegment;
1133
+ const toRemove = parent.children[removalIndex];
1134
+ let edit;
1135
+ if (parent.children.length === 1) edit = {
1136
+ offset: parent.offset + 1,
1137
+ length: parent.length - 2,
1138
+ content: ""
1139
+ };
1140
+ else if (parent.children.length - 1 === removalIndex) {
1141
+ let previous = parent.children[removalIndex - 1];
1142
+ let offset = previous.offset + previous.length;
1143
+ edit = {
1144
+ offset,
1145
+ length: parent.offset + parent.length - 2 - offset,
1146
+ content: ""
1147
+ };
1148
+ } else edit = {
1149
+ offset: toRemove.offset,
1150
+ length: parent.children[removalIndex + 1].offset - toRemove.offset,
1151
+ content: ""
1152
+ };
1153
+ return withFormatting(text, edit, options);
1154
+ } else if (value !== void 0) {
1155
+ let edit;
1156
+ const newProperty = `${JSON.stringify(value)}`;
1157
+ if (!options.isArrayInsertion && parent.children.length > lastSegment) {
1158
+ const toModify = parent.children[lastSegment];
1159
+ edit = {
1160
+ offset: toModify.offset,
1161
+ length: toModify.length,
1162
+ content: newProperty
1163
+ };
1164
+ } else if (parent.children.length === 0 || lastSegment === 0) edit = {
1165
+ offset: parent.offset + 1,
1166
+ length: 0,
1167
+ content: parent.children.length === 0 ? newProperty : newProperty + ","
1168
+ };
1169
+ else {
1170
+ const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
1171
+ const previous = parent.children[index - 1];
1172
+ edit = {
1173
+ offset: previous.offset + previous.length,
1174
+ length: 0,
1175
+ content: "," + newProperty
1176
+ };
1177
+ }
1178
+ return withFormatting(text, edit, options);
1179
+ } else throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
1180
+ } else throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
1181
+ }
1182
+ __name(setProperty, "setProperty");
1183
+ function withFormatting(text, edit, options) {
1184
+ if (!options.formattingOptions) return [edit];
1185
+ let newText = applyEdit(text, edit);
1186
+ let begin = edit.offset;
1187
+ let end = edit.offset + edit.content.length;
1188
+ if (edit.length === 0 || edit.content.length === 0) {
1189
+ while (begin > 0 && !isEOL(newText, begin - 1)) begin--;
1190
+ while (end < newText.length && !isEOL(newText, end)) end++;
1191
+ }
1192
+ const edits = format(newText, {
1193
+ offset: begin,
1194
+ length: end - begin
1195
+ }, {
1196
+ ...options.formattingOptions,
1197
+ keepLines: false
1198
+ });
1199
+ for (let i = edits.length - 1; i >= 0; i--) {
1200
+ const edit2 = edits[i];
1201
+ newText = applyEdit(newText, edit2);
1202
+ begin = Math.min(begin, edit2.offset);
1203
+ end = Math.max(end, edit2.offset + edit2.length);
1204
+ end += edit2.content.length - edit2.length;
1205
+ }
1206
+ const editLength = text.length - (newText.length - end) - begin;
1207
+ return [{
1208
+ offset: begin,
1209
+ length: editLength,
1210
+ content: newText.substring(begin, end)
1211
+ }];
1212
+ }
1213
+ __name(withFormatting, "withFormatting");
1214
+ function applyEdit(text, edit) {
1215
+ return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
1216
+ }
1217
+ __name(applyEdit, "applyEdit");
1218
+ var ScanError;
1219
+ (function(ScanError2) {
1220
+ ScanError2[ScanError2["None"] = 0] = "None";
1221
+ ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
1222
+ ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
1223
+ ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
1224
+ ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
1225
+ ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
1226
+ ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
1227
+ })(ScanError || (ScanError = {}));
1228
+ var SyntaxKind;
1229
+ (function(SyntaxKind2) {
1230
+ SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
1231
+ SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
1232
+ SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
1233
+ SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
1234
+ SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
1235
+ SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
1236
+ SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
1237
+ SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
1238
+ SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
1239
+ SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
1240
+ SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
1241
+ SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
1242
+ SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
1243
+ SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
1244
+ SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
1245
+ SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
1246
+ SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
1247
+ })(SyntaxKind || (SyntaxKind = {}));
1248
+ var parse2 = parse;
1249
+ var ParseErrorCode;
1250
+ (function(ParseErrorCode2) {
1251
+ ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
1252
+ ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
1253
+ ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
1254
+ ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
1255
+ ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
1256
+ ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
1257
+ ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
1258
+ ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
1259
+ ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
1260
+ ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
1261
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
1262
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
1263
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
1264
+ ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
1265
+ ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
1266
+ ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
1267
+ })(ParseErrorCode || (ParseErrorCode = {}));
1268
+ function printParseErrorCode(code) {
1269
+ switch (code) {
1270
+ case 1: return "InvalidSymbol";
1271
+ case 2: return "InvalidNumberFormat";
1272
+ case 3: return "PropertyNameExpected";
1273
+ case 4: return "ValueExpected";
1274
+ case 5: return "ColonExpected";
1275
+ case 6: return "CommaExpected";
1276
+ case 7: return "CloseBraceExpected";
1277
+ case 8: return "CloseBracketExpected";
1278
+ case 9: return "EndOfFileExpected";
1279
+ case 10: return "InvalidCommentToken";
1280
+ case 11: return "UnexpectedEndOfComment";
1281
+ case 12: return "UnexpectedEndOfString";
1282
+ case 13: return "UnexpectedEndOfNumber";
1283
+ case 14: return "InvalidUnicode";
1284
+ case 15: return "InvalidEscapeCharacter";
1285
+ case 16: return "InvalidCharacter";
1286
+ }
1287
+ return "<unknown ParseErrorCode>";
1288
+ }
1289
+ __name(printParseErrorCode, "printParseErrorCode");
1290
+ function format2(documentText, range, options) {
1291
+ return format(documentText, range, options);
1292
+ }
1293
+ __name(format2, "format");
1294
+ function modify(text, path2$1, value, options) {
1295
+ return setProperty(text, path2$1, value, options);
1296
+ }
1297
+ __name(modify, "modify");
1298
+ function applyEdits(text, edits) {
1299
+ let sortedEdits = edits.slice(0).sort((a, b) => {
1300
+ const diff = a.offset - b.offset;
1301
+ if (diff === 0) return a.length - b.length;
1302
+ return diff;
1303
+ });
1304
+ let lastModifiedOffset = text.length;
1305
+ for (let i = sortedEdits.length - 1; i >= 0; i--) {
1306
+ let e = sortedEdits[i];
1307
+ if (e.offset + e.length <= lastModifiedOffset) text = applyEdit(text, e);
1308
+ else throw new Error("Overlapping edit");
1309
+ lastModifiedOffset = e.offset;
1310
+ }
1311
+ return text;
1312
+ }
1313
+ __name(applyEdits, "applyEdits");
1314
+ function getLineColFromPtr(string, ptr) {
1315
+ let lines = string.slice(0, ptr).split(/\r\n|\n|\r/g);
1316
+ return [lines.length, lines.pop().length + 1];
1317
+ }
1318
+ __name(getLineColFromPtr, "getLineColFromPtr");
1319
+ function makeCodeBlock(string, line, column) {
1320
+ let lines = string.split(/\r\n|\n|\r/g);
1321
+ let codeblock = "";
1322
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
1323
+ for (let i = line - 1; i <= line + 1; i++) {
1324
+ let l = lines[i - 1];
1325
+ if (!l) continue;
1326
+ codeblock += i.toString().padEnd(numberLen, " ");
1327
+ codeblock += ": ";
1328
+ codeblock += l;
1329
+ codeblock += "\n";
1330
+ if (i === line) {
1331
+ codeblock += " ".repeat(numberLen + column + 2);
1332
+ codeblock += "^\n";
1333
+ }
1334
+ }
1335
+ return codeblock;
1336
+ }
1337
+ __name(makeCodeBlock, "makeCodeBlock");
1338
+ var TomlError = class extends Error {
1339
+ static {
1340
+ __name(this, "TomlError");
1341
+ }
1342
+ line;
1343
+ column;
1344
+ codeblock;
1345
+ constructor(message, options) {
1346
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
1347
+ const codeblock = makeCodeBlock(options.toml, line, column);
1348
+ super(`Invalid TOML document: ${message}
1349
+
1350
+ ${codeblock}`, options);
1351
+ this.line = line;
1352
+ this.column = column;
1353
+ this.codeblock = codeblock;
1354
+ }
1355
+ };
1356
+ function isEscaped(str, ptr) {
1357
+ let i = 0;
1358
+ while (str[ptr - ++i] === "\\");
1359
+ return --i && i % 2;
1360
+ }
1361
+ __name(isEscaped, "isEscaped");
1362
+ function indexOfNewline(str, start = 0, end = str.length) {
1363
+ let idx = str.indexOf("\n", start);
1364
+ if (str[idx - 1] === "\r") idx--;
1365
+ return idx <= end ? idx : -1;
1366
+ }
1367
+ __name(indexOfNewline, "indexOfNewline");
1368
+ function skipComment(str, ptr) {
1369
+ for (let i = ptr; i < str.length; i++) {
1370
+ let c = str[i];
1371
+ if (c === "\n") return i;
1372
+ if (c === "\r" && str[i + 1] === "\n") return i + 1;
1373
+ if (c < " " && c !== " " || c === "") throw new TomlError("control characters are not allowed in comments", {
1374
+ toml: str,
1375
+ ptr
1376
+ });
1377
+ }
1378
+ return str.length;
1379
+ }
1380
+ __name(skipComment, "skipComment");
1381
+ function skipVoid(str, ptr, banNewLines, banComments) {
1382
+ let c;
1383
+ while ((c = str[ptr]) === " " || c === " " || !banNewLines && (c === "\n" || c === "\r" && str[ptr + 1] === "\n")) ptr++;
1384
+ return banComments || c !== "#" ? ptr : skipVoid(str, skipComment(str, ptr), banNewLines);
1385
+ }
1386
+ __name(skipVoid, "skipVoid");
1387
+ function skipUntil(str, ptr, sep, end, banNewLines = false) {
1388
+ if (!end) {
1389
+ ptr = indexOfNewline(str, ptr);
1390
+ return ptr < 0 ? str.length : ptr;
1391
+ }
1392
+ for (let i = ptr; i < str.length; i++) {
1393
+ let c = str[i];
1394
+ if (c === "#") i = indexOfNewline(str, i);
1395
+ else if (c === sep) return i + 1;
1396
+ else if (c === end || banNewLines && (c === "\n" || c === "\r" && str[i + 1] === "\n")) return i;
1397
+ }
1398
+ throw new TomlError("cannot find end of structure", {
1399
+ toml: str,
1400
+ ptr
1401
+ });
1402
+ }
1403
+ __name(skipUntil, "skipUntil");
1404
+ function getStringEnd(str, seek) {
1405
+ let first = str[seek];
1406
+ let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2] ? str.slice(seek, seek + 3) : first;
1407
+ seek += target.length - 1;
1408
+ do
1409
+ seek = str.indexOf(target, ++seek);
1410
+ while (seek > -1 && first !== "'" && isEscaped(str, seek));
1411
+ if (seek > -1) {
1412
+ seek += target.length;
1413
+ if (target.length > 1) {
1414
+ if (str[seek] === first) seek++;
1415
+ if (str[seek] === first) seek++;
1416
+ }
1417
+ }
1418
+ return seek;
1419
+ }
1420
+ __name(getStringEnd, "getStringEnd");
1421
+ var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}:\d{2}(?:\.\d+)?)?(Z|[-+]\d{2}:\d{2})?$/i;
1422
+ var TomlDate = class _TomlDate extends Date {
1423
+ static {
1424
+ __name(this, "TomlDate");
1425
+ }
1426
+ #hasDate = false;
1427
+ #hasTime = false;
1428
+ #offset = null;
1429
+ constructor(date) {
1430
+ let hasDate = true;
1431
+ let hasTime = true;
1432
+ let offset = "Z";
1433
+ if (typeof date === "string") {
1434
+ let match = date.match(DATE_TIME_RE);
1435
+ if (match) {
1436
+ if (!match[1]) {
1437
+ hasDate = false;
1438
+ date = `0000-01-01T${date}`;
1439
+ }
1440
+ hasTime = !!match[2];
1441
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
1442
+ if (match[2] && +match[2] > 23) date = "";
1443
+ else {
1444
+ offset = match[3] || null;
1445
+ date = date.toUpperCase();
1446
+ if (!offset && hasTime) date += "Z";
1447
+ }
1448
+ } else date = "";
1449
+ }
1450
+ super(date);
1451
+ if (!isNaN(this.getTime())) {
1452
+ this.#hasDate = hasDate;
1453
+ this.#hasTime = hasTime;
1454
+ this.#offset = offset;
1455
+ }
1456
+ }
1457
+ isDateTime() {
1458
+ return this.#hasDate && this.#hasTime;
1459
+ }
1460
+ isLocal() {
1461
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
1462
+ }
1463
+ isDate() {
1464
+ return this.#hasDate && !this.#hasTime;
1465
+ }
1466
+ isTime() {
1467
+ return this.#hasTime && !this.#hasDate;
1468
+ }
1469
+ isValid() {
1470
+ return this.#hasDate || this.#hasTime;
1471
+ }
1472
+ toISOString() {
1473
+ let iso = super.toISOString();
1474
+ if (this.isDate()) return iso.slice(0, 10);
1475
+ if (this.isTime()) return iso.slice(11, 23);
1476
+ if (this.#offset === null) return iso.slice(0, -1);
1477
+ if (this.#offset === "Z") return iso;
1478
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
1479
+ offset = this.#offset[0] === "-" ? offset : -offset;
1480
+ return (/* @__PURE__ */ new Date(this.getTime() - offset * 6e4)).toISOString().slice(0, -1) + this.#offset;
1481
+ }
1482
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
1483
+ let date = new _TomlDate(jsDate);
1484
+ date.#offset = offset;
1485
+ return date;
1486
+ }
1487
+ static wrapAsLocalDateTime(jsDate) {
1488
+ let date = new _TomlDate(jsDate);
1489
+ date.#offset = null;
1490
+ return date;
1491
+ }
1492
+ static wrapAsLocalDate(jsDate) {
1493
+ let date = new _TomlDate(jsDate);
1494
+ date.#hasTime = false;
1495
+ date.#offset = null;
1496
+ return date;
1497
+ }
1498
+ static wrapAsLocalTime(jsDate) {
1499
+ let date = new _TomlDate(jsDate);
1500
+ date.#hasDate = false;
1501
+ date.#offset = null;
1502
+ return date;
1503
+ }
1504
+ };
1505
+ var INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/;
1506
+ var FLOAT_REGEX = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/;
1507
+ var LEADING_ZERO = /^[+-]?0[0-9_]/;
1508
+ var ESCAPE_REGEX = /^[0-9a-f]{4,8}$/i;
1509
+ var ESC_MAP = {
1510
+ b: "\b",
1511
+ t: " ",
1512
+ n: "\n",
1513
+ f: "\f",
1514
+ r: "\r",
1515
+ "\"": "\"",
1516
+ "\\": "\\"
1517
+ };
1518
+ function parseString(str, ptr = 0, endPtr = str.length) {
1519
+ let isLiteral = str[ptr] === "'";
1520
+ let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];
1521
+ if (isMultiline) {
1522
+ endPtr -= 2;
1523
+ if (str[ptr += 2] === "\r") ptr++;
1524
+ if (str[ptr] === "\n") ptr++;
1525
+ }
1526
+ let tmp = 0;
1527
+ let isEscape;
1528
+ let parsed = "";
1529
+ let sliceStart = ptr;
1530
+ while (ptr < endPtr - 1) {
1531
+ let c = str[ptr++];
1532
+ if (c === "\n" || c === "\r" && str[ptr] === "\n") {
1533
+ if (!isMultiline) throw new TomlError("newlines are not allowed in strings", {
1534
+ toml: str,
1535
+ ptr: ptr - 1
1536
+ });
1537
+ } else if (c < " " && c !== " " || c === "") throw new TomlError("control characters are not allowed in strings", {
1538
+ toml: str,
1539
+ ptr: ptr - 1
1540
+ });
1541
+ if (isEscape) {
1542
+ isEscape = false;
1543
+ if (c === "u" || c === "U") {
1544
+ let code = str.slice(ptr, ptr += c === "u" ? 4 : 8);
1545
+ if (!ESCAPE_REGEX.test(code)) throw new TomlError("invalid unicode escape", {
1546
+ toml: str,
1547
+ ptr: tmp
1548
+ });
1549
+ try {
1550
+ parsed += String.fromCodePoint(parseInt(code, 16));
1551
+ } catch {
1552
+ throw new TomlError("invalid unicode escape", {
1553
+ toml: str,
1554
+ ptr: tmp
1555
+ });
1556
+ }
1557
+ } else if (isMultiline && (c === "\n" || c === " " || c === " " || c === "\r")) {
1558
+ ptr = skipVoid(str, ptr - 1, true);
1559
+ if (str[ptr] !== "\n" && str[ptr] !== "\r") throw new TomlError("invalid escape: only line-ending whitespace may be escaped", {
1560
+ toml: str,
1561
+ ptr: tmp
1562
+ });
1563
+ ptr = skipVoid(str, ptr);
1564
+ } else if (c in ESC_MAP) parsed += ESC_MAP[c];
1565
+ else throw new TomlError("unrecognized escape sequence", {
1566
+ toml: str,
1567
+ ptr: tmp
1568
+ });
1569
+ sliceStart = ptr;
1570
+ } else if (!isLiteral && c === "\\") {
1571
+ tmp = ptr - 1;
1572
+ isEscape = true;
1573
+ parsed += str.slice(sliceStart, tmp);
1574
+ }
1575
+ }
1576
+ return parsed + str.slice(sliceStart, endPtr - 1);
1577
+ }
1578
+ __name(parseString, "parseString");
1579
+ function parseValue(value, toml, ptr, integersAsBigInt) {
1580
+ if (value === "true") return true;
1581
+ if (value === "false") return false;
1582
+ if (value === "-inf") return -Infinity;
1583
+ if (value === "inf" || value === "+inf") return Infinity;
1584
+ if (value === "nan" || value === "+nan" || value === "-nan") return NaN;
1585
+ if (value === "-0") return integersAsBigInt ? 0n : 0;
1586
+ let isInt = INT_REGEX.test(value);
1587
+ if (isInt || FLOAT_REGEX.test(value)) {
1588
+ if (LEADING_ZERO.test(value)) throw new TomlError("leading zeroes are not allowed", {
1589
+ toml,
1590
+ ptr
1591
+ });
1592
+ value = value.replace(/_/g, "");
1593
+ let numeric = +value;
1594
+ if (isNaN(numeric)) throw new TomlError("invalid number", {
1595
+ toml,
1596
+ ptr
1597
+ });
1598
+ if (isInt) {
1599
+ if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) throw new TomlError("integer value cannot be represented losslessly", {
1600
+ toml,
1601
+ ptr
1602
+ });
1603
+ if (isInt || integersAsBigInt === true) numeric = BigInt(value);
1604
+ }
1605
+ return numeric;
1606
+ }
1607
+ const date = new TomlDate(value);
1608
+ if (!date.isValid()) throw new TomlError("invalid value", {
1609
+ toml,
1610
+ ptr
1611
+ });
1612
+ return date;
1613
+ }
1614
+ __name(parseValue, "parseValue");
1615
+ function sliceAndTrimEndOf(str, startPtr, endPtr, allowNewLines) {
1616
+ let value = str.slice(startPtr, endPtr);
1617
+ let commentIdx = value.indexOf("#");
1618
+ if (commentIdx > -1) {
1619
+ skipComment(str, commentIdx);
1620
+ value = value.slice(0, commentIdx);
1621
+ }
1622
+ let trimmed = value.trimEnd();
1623
+ if (!allowNewLines) {
1624
+ let newlineIdx = value.indexOf("\n", trimmed.length);
1625
+ if (newlineIdx > -1) throw new TomlError("newlines are not allowed in inline tables", {
1626
+ toml: str,
1627
+ ptr: startPtr + newlineIdx
1628
+ });
1629
+ }
1630
+ return [trimmed, commentIdx];
1631
+ }
1632
+ __name(sliceAndTrimEndOf, "sliceAndTrimEndOf");
1633
+ function extractValue(str, ptr, end, depth, integersAsBigInt) {
1634
+ if (depth === 0) throw new TomlError("document contains excessively nested structures. aborting.", {
1635
+ toml: str,
1636
+ ptr
1637
+ });
1638
+ let c = str[ptr];
1639
+ if (c === "[" || c === "{") {
1640
+ let [value, endPtr2] = c === "[" ? parseArray(str, ptr, depth, integersAsBigInt) : parseInlineTable(str, ptr, depth, integersAsBigInt);
1641
+ let newPtr = end ? skipUntil(str, endPtr2, ",", end) : endPtr2;
1642
+ if (endPtr2 - newPtr && end === "}") {
1643
+ let nextNewLine = indexOfNewline(str, endPtr2, newPtr);
1644
+ if (nextNewLine > -1) throw new TomlError("newlines are not allowed in inline tables", {
1645
+ toml: str,
1646
+ ptr: nextNewLine
1647
+ });
1648
+ }
1649
+ return [value, newPtr];
1650
+ }
1651
+ let endPtr;
1652
+ if (c === "\"" || c === "'") {
1653
+ endPtr = getStringEnd(str, ptr);
1654
+ let parsed = parseString(str, ptr, endPtr);
1655
+ if (end) {
1656
+ endPtr = skipVoid(str, endPtr, end !== "]");
1657
+ if (str[endPtr] && str[endPtr] !== "," && str[endPtr] !== end && str[endPtr] !== "\n" && str[endPtr] !== "\r") throw new TomlError("unexpected character encountered", {
1658
+ toml: str,
1659
+ ptr: endPtr
1660
+ });
1661
+ endPtr += +(str[endPtr] === ",");
1662
+ }
1663
+ return [parsed, endPtr];
1664
+ }
1665
+ endPtr = skipUntil(str, ptr, ",", end);
1666
+ let slice = sliceAndTrimEndOf(str, ptr, endPtr - +(str[endPtr - 1] === ","), end === "]");
1667
+ if (!slice[0]) throw new TomlError("incomplete key-value declaration: no value specified", {
1668
+ toml: str,
1669
+ ptr
1670
+ });
1671
+ if (end && slice[1] > -1) {
1672
+ endPtr = skipVoid(str, ptr + slice[1]);
1673
+ endPtr += +(str[endPtr] === ",");
1674
+ }
1675
+ return [parseValue(slice[0], str, ptr, integersAsBigInt), endPtr];
1676
+ }
1677
+ __name(extractValue, "extractValue");
1678
+ var KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \t]*$/;
1679
+ function parseKey(str, ptr, end = "=") {
1680
+ let dot = ptr - 1;
1681
+ let parsed = [];
1682
+ let endPtr = str.indexOf(end, ptr);
1683
+ if (endPtr < 0) throw new TomlError("incomplete key-value: cannot find end of key", {
1684
+ toml: str,
1685
+ ptr
1686
+ });
1687
+ do {
1688
+ let c = str[ptr = ++dot];
1689
+ if (c !== " " && c !== " ") if (c === "\"" || c === "'") {
1690
+ if (c === str[ptr + 1] && c === str[ptr + 2]) throw new TomlError("multiline strings are not allowed in keys", {
1691
+ toml: str,
1692
+ ptr
1693
+ });
1694
+ let eos = getStringEnd(str, ptr);
1695
+ if (eos < 0) throw new TomlError("unfinished string encountered", {
1696
+ toml: str,
1697
+ ptr
1698
+ });
1699
+ dot = str.indexOf(".", eos);
1700
+ let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);
1701
+ let newLine = indexOfNewline(strEnd);
1702
+ if (newLine > -1) throw new TomlError("newlines are not allowed in keys", {
1703
+ toml: str,
1704
+ ptr: ptr + dot + newLine
1705
+ });
1706
+ if (strEnd.trimStart()) throw new TomlError("found extra tokens after the string part", {
1707
+ toml: str,
1708
+ ptr: eos
1709
+ });
1710
+ if (endPtr < eos) {
1711
+ endPtr = str.indexOf(end, eos);
1712
+ if (endPtr < 0) throw new TomlError("incomplete key-value: cannot find end of key", {
1713
+ toml: str,
1714
+ ptr
1715
+ });
1716
+ }
1717
+ parsed.push(parseString(str, ptr, eos));
1718
+ } else {
1719
+ dot = str.indexOf(".", ptr);
1720
+ let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);
1721
+ if (!KEY_PART_RE.test(part)) throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys", {
1722
+ toml: str,
1723
+ ptr
1724
+ });
1725
+ parsed.push(part.trimEnd());
1726
+ }
1727
+ } while (dot + 1 && dot < endPtr);
1728
+ return [parsed, skipVoid(str, endPtr + 1, true, true)];
1729
+ }
1730
+ __name(parseKey, "parseKey");
1731
+ function parseInlineTable(str, ptr, depth, integersAsBigInt) {
1732
+ let res = {};
1733
+ let seen = /* @__PURE__ */ new Set();
1734
+ let c;
1735
+ let comma = 0;
1736
+ ptr++;
1737
+ while ((c = str[ptr++]) !== "}" && c) {
1738
+ let err = {
1739
+ toml: str,
1740
+ ptr: ptr - 1
1741
+ };
1742
+ if (c === "\n") throw new TomlError("newlines are not allowed in inline tables", err);
1743
+ else if (c === "#") throw new TomlError("inline tables cannot contain comments", err);
1744
+ else if (c === ",") throw new TomlError("expected key-value, found comma", err);
1745
+ else if (c !== " " && c !== " ") {
1746
+ let k;
1747
+ let t = res;
1748
+ let hasOwn = false;
1749
+ let [key, keyEndPtr] = parseKey(str, ptr - 1);
1750
+ for (let i = 0; i < key.length; i++) {
1751
+ if (i) t = hasOwn ? t[k] : t[k] = {};
1752
+ k = key[i];
1753
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) throw new TomlError("trying to redefine an already defined value", {
1754
+ toml: str,
1755
+ ptr
1756
+ });
1757
+ if (!hasOwn && k === "__proto__") Object.defineProperty(t, k, {
1758
+ enumerable: true,
1759
+ configurable: true,
1760
+ writable: true
1761
+ });
1762
+ }
1763
+ if (hasOwn) throw new TomlError("trying to redefine an already defined value", {
1764
+ toml: str,
1765
+ ptr
1766
+ });
1767
+ let [value, valueEndPtr] = extractValue(str, keyEndPtr, "}", depth - 1, integersAsBigInt);
1768
+ seen.add(value);
1769
+ t[k] = value;
1770
+ ptr = valueEndPtr;
1771
+ comma = str[ptr - 1] === "," ? ptr - 1 : 0;
1772
+ }
1773
+ }
1774
+ if (comma) throw new TomlError("trailing commas are not allowed in inline tables", {
1775
+ toml: str,
1776
+ ptr: comma
1777
+ });
1778
+ if (!c) throw new TomlError("unfinished table encountered", {
1779
+ toml: str,
1780
+ ptr
1781
+ });
1782
+ return [res, ptr];
1783
+ }
1784
+ __name(parseInlineTable, "parseInlineTable");
1785
+ function parseArray(str, ptr, depth, integersAsBigInt) {
1786
+ let res = [];
1787
+ let c;
1788
+ ptr++;
1789
+ while ((c = str[ptr++]) !== "]" && c) if (c === ",") throw new TomlError("expected value, found comma", {
1790
+ toml: str,
1791
+ ptr: ptr - 1
1792
+ });
1793
+ else if (c === "#") ptr = skipComment(str, ptr);
1794
+ else if (c !== " " && c !== " " && c !== "\n" && c !== "\r") {
1795
+ let e = extractValue(str, ptr - 1, "]", depth - 1, integersAsBigInt);
1796
+ res.push(e[0]);
1797
+ ptr = e[1];
1798
+ }
1799
+ if (!c) throw new TomlError("unfinished array encountered", {
1800
+ toml: str,
1801
+ ptr
1802
+ });
1803
+ return [res, ptr];
1804
+ }
1805
+ __name(parseArray, "parseArray");
1806
+ function peekTable(key, table, meta, type) {
1807
+ let t = table;
1808
+ let m = meta;
1809
+ let k;
1810
+ let hasOwn = false;
1811
+ let state;
1812
+ for (let i = 0; i < key.length; i++) {
1813
+ if (i) {
1814
+ t = hasOwn ? t[k] : t[k] = {};
1815
+ m = (state = m[k]).c;
1816
+ if (type === 0 && (state.t === 1 || state.t === 2)) return null;
1817
+ if (state.t === 2) {
1818
+ let l = t.length - 1;
1819
+ t = t[l];
1820
+ m = m[l].c;
1821
+ }
1822
+ }
1823
+ k = key[i];
1824
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) return null;
1825
+ if (!hasOwn) {
1826
+ if (k === "__proto__") {
1827
+ Object.defineProperty(t, k, {
1828
+ enumerable: true,
1829
+ configurable: true,
1830
+ writable: true
1831
+ });
1832
+ Object.defineProperty(m, k, {
1833
+ enumerable: true,
1834
+ configurable: true,
1835
+ writable: true
1836
+ });
1837
+ }
1838
+ m[k] = {
1839
+ t: i < key.length - 1 && type === 2 ? 3 : type,
1840
+ d: false,
1841
+ i: 0,
1842
+ c: {}
1843
+ };
1844
+ }
1845
+ }
1846
+ state = m[k];
1847
+ if (state.t !== type && !(type === 1 && state.t === 3)) return null;
1848
+ if (type === 2) {
1849
+ if (!state.d) {
1850
+ state.d = true;
1851
+ t[k] = [];
1852
+ }
1853
+ t[k].push(t = {});
1854
+ state.c[state.i++] = state = {
1855
+ t: 1,
1856
+ d: false,
1857
+ i: 0,
1858
+ c: {}
1859
+ };
1860
+ }
1861
+ if (state.d) return null;
1862
+ state.d = true;
1863
+ if (type === 1) t = hasOwn ? t[k] : t[k] = {};
1864
+ else if (type === 0 && hasOwn) return null;
1865
+ return [
1866
+ k,
1867
+ t,
1868
+ state.c
1869
+ ];
1870
+ }
1871
+ __name(peekTable, "peekTable");
1872
+ function parse3(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
1873
+ let res = {};
1874
+ let meta = {};
1875
+ let tbl = res;
1876
+ let m = meta;
1877
+ for (let ptr = skipVoid(toml, 0); ptr < toml.length;) {
1878
+ if (toml[ptr] === "[") {
1879
+ let isTableArray = toml[++ptr] === "[";
1880
+ let k = parseKey(toml, ptr += +isTableArray, "]");
1881
+ if (isTableArray) {
1882
+ if (toml[k[1] - 1] !== "]") throw new TomlError("expected end of table declaration", {
1883
+ toml,
1884
+ ptr: k[1] - 1
1885
+ });
1886
+ k[1]++;
1887
+ }
1888
+ let p = peekTable(k[0], res, meta, isTableArray ? 2 : 1);
1889
+ if (!p) throw new TomlError("trying to redefine an already defined table or value", {
1890
+ toml,
1891
+ ptr
1892
+ });
1893
+ m = p[2];
1894
+ tbl = p[1];
1895
+ ptr = k[1];
1896
+ } else {
1897
+ let k = parseKey(toml, ptr);
1898
+ let p = peekTable(k[0], tbl, m, 0);
1899
+ if (!p) throw new TomlError("trying to redefine an already defined table or value", {
1900
+ toml,
1901
+ ptr
1902
+ });
1903
+ let v = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);
1904
+ p[1][p[0]] = v[0];
1905
+ ptr = v[1];
1906
+ }
1907
+ ptr = skipVoid(toml, ptr, true);
1908
+ if (toml[ptr] && toml[ptr] !== "\n" && toml[ptr] !== "\r") throw new TomlError("each key-value declaration must be followed by an end-of-line", {
1909
+ toml,
1910
+ ptr
1911
+ });
1912
+ ptr = skipVoid(toml, ptr);
1913
+ }
1914
+ return res;
1915
+ }
1916
+ __name(parse3, "parse");
1917
+ var BARE_KEY = /^[a-z0-9-_]+$/i;
1918
+ function extendedTypeOf(obj) {
1919
+ let type = typeof obj;
1920
+ if (type === "object") {
1921
+ if (Array.isArray(obj)) return "array";
1922
+ if (obj instanceof Date) return "date";
1923
+ }
1924
+ return type;
1925
+ }
1926
+ __name(extendedTypeOf, "extendedTypeOf");
1927
+ function isArrayOfTables(obj) {
1928
+ for (let i = 0; i < obj.length; i++) if (extendedTypeOf(obj[i]) !== "object") return false;
1929
+ return obj.length != 0;
1930
+ }
1931
+ __name(isArrayOfTables, "isArrayOfTables");
1932
+ function formatString(s) {
1933
+ return JSON.stringify(s).replace(/\x7f/g, "\\u007f");
1934
+ }
1935
+ __name(formatString, "formatString");
1936
+ function stringifyValue(val, type, depth, numberAsFloat) {
1937
+ if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
1938
+ if (type === "number") {
1939
+ if (isNaN(val)) return "nan";
1940
+ if (val === Infinity) return "inf";
1941
+ if (val === -Infinity) return "-inf";
1942
+ if (numberAsFloat && Number.isInteger(val)) return val.toFixed(1);
1943
+ return val.toString();
1944
+ }
1945
+ if (type === "bigint" || type === "boolean") return val.toString();
1946
+ if (type === "string") return formatString(val);
1947
+ if (type === "date") {
1948
+ if (isNaN(val.getTime())) throw new TypeError("cannot serialize invalid date");
1949
+ return val.toISOString();
1950
+ }
1951
+ if (type === "object") return stringifyInlineTable(val, depth, numberAsFloat);
1952
+ if (type === "array") return stringifyArray(val, depth, numberAsFloat);
1953
+ }
1954
+ __name(stringifyValue, "stringifyValue");
1955
+ function stringifyInlineTable(obj, depth, numberAsFloat) {
1956
+ let keys = Object.keys(obj);
1957
+ if (keys.length === 0) return "{}";
1958
+ let res = "{ ";
1959
+ for (let i = 0; i < keys.length; i++) {
1960
+ let k = keys[i];
1961
+ if (i) res += ", ";
1962
+ res += BARE_KEY.test(k) ? k : formatString(k);
1963
+ res += " = ";
1964
+ res += stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat);
1965
+ }
1966
+ return res + " }";
1967
+ }
1968
+ __name(stringifyInlineTable, "stringifyInlineTable");
1969
+ function stringifyArray(array, depth, numberAsFloat) {
1970
+ if (array.length === 0) return "[]";
1971
+ let res = "[ ";
1972
+ for (let i = 0; i < array.length; i++) {
1973
+ if (i) res += ", ";
1974
+ if (array[i] === null || array[i] === void 0) throw new TypeError("arrays cannot contain null or undefined values");
1975
+ res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat);
1976
+ }
1977
+ return res + " ]";
1978
+ }
1979
+ __name(stringifyArray, "stringifyArray");
1980
+ function stringifyArrayTable(array, key, depth, numberAsFloat) {
1981
+ if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
1982
+ let res = "";
1983
+ for (let i = 0; i < array.length; i++) {
1984
+ res += `${res && "\n"}[[${key}]]
1985
+ `;
1986
+ res += stringifyTable(0, array[i], key, depth, numberAsFloat);
1987
+ }
1988
+ return res;
1989
+ }
1990
+ __name(stringifyArrayTable, "stringifyArrayTable");
1991
+ function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat) {
1992
+ if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
1993
+ let preamble = "";
1994
+ let tables = "";
1995
+ let keys = Object.keys(obj);
1996
+ for (let i = 0; i < keys.length; i++) {
1997
+ let k = keys[i];
1998
+ if (obj[k] !== null && obj[k] !== void 0) {
1999
+ let type = extendedTypeOf(obj[k]);
2000
+ if (type === "symbol" || type === "function") throw new TypeError(`cannot serialize values of type '${type}'`);
2001
+ let key = BARE_KEY.test(k) ? k : formatString(k);
2002
+ if (type === "array" && isArrayOfTables(obj[k])) tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat);
2003
+ else if (type === "object") {
2004
+ let tblKey = prefix ? `${prefix}.${key}` : key;
2005
+ tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat);
2006
+ } else {
2007
+ preamble += key;
2008
+ preamble += " = ";
2009
+ preamble += stringifyValue(obj[k], type, depth, numberAsFloat);
2010
+ preamble += "\n";
2011
+ }
2012
+ }
2013
+ }
2014
+ if (tableKey && (preamble || !tables)) preamble = preamble ? `[${tableKey}]
2015
+ ${preamble}` : `[${tableKey}]`;
2016
+ return preamble && tables ? `${preamble}
2017
+ ${tables}` : preamble || tables;
2018
+ }
2019
+ __name(stringifyTable, "stringifyTable");
2020
+ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false } = {}) {
2021
+ if (extendedTypeOf(obj) !== "object") throw new TypeError("stringify can only be called with an object");
2022
+ let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat);
2023
+ if (str[str.length - 1] !== "\n") return str + "\n";
2024
+ return str;
2025
+ }
2026
+ __name(stringify, "stringify");
2027
+ var dist_default = {
2028
+ parse: parse3,
2029
+ stringify,
2030
+ TomlDate,
2031
+ TomlError
2032
+ };
2033
+ var ParseError = class extends UserError {
2034
+ static {
2035
+ __name(this, "ParseError");
2036
+ }
2037
+ text;
2038
+ notes;
2039
+ location;
2040
+ kind;
2041
+ constructor({ text, notes, location, kind, telemetryMessage }) {
2042
+ super(text, { telemetryMessage });
2043
+ this.name = this.constructor.name;
2044
+ this.text = text;
2045
+ this.notes = notes ?? [];
2046
+ this.location = location;
2047
+ this.kind = kind ?? "error";
2048
+ }
2049
+ };
2050
+ var APIError = class extends ParseError {
2051
+ static {
2052
+ __name(this, "APIError");
2053
+ }
2054
+ #status;
2055
+ code;
2056
+ accountTag;
2057
+ /**
2058
+ * Optional structured metadata hoisted from the first `FetchError.meta`
2059
+ * on the v4 response envelope. Consumers can inspect this to render
2060
+ * endpoint-specific structured error payloads.
2061
+ */
2062
+ meta;
2063
+ constructor({ status,...rest }) {
2064
+ super(rest);
2065
+ this.name = this.constructor.name;
2066
+ this.#status = status;
2067
+ }
2068
+ get status() {
2069
+ return this.#status;
2070
+ }
2071
+ isGatewayError() {
2072
+ if (this.#status !== void 0) return [524].includes(this.#status);
2073
+ return false;
2074
+ }
2075
+ isRetryable() {
2076
+ return String(this.#status).startsWith("5");
2077
+ }
2078
+ #reportable = true;
2079
+ get reportable() {
2080
+ return this.#reportable;
2081
+ }
2082
+ preventReport() {
2083
+ this.#reportable = false;
2084
+ }
2085
+ };
2086
+ function parseTOML(tomlContent, filePath) {
2087
+ try {
2088
+ return dist_default.parse(tomlContent);
2089
+ } catch (err) {
2090
+ if (!(err instanceof TomlError)) throw err;
2091
+ const location = {
2092
+ lineText: tomlContent.split("\n")[err.line - 1],
2093
+ line: err.line,
2094
+ column: err.column - 1,
2095
+ file: filePath,
2096
+ fileText: tomlContent
2097
+ };
2098
+ throw new ParseError({
2099
+ text: err.message.substring(0, err.message.indexOf("\n")),
2100
+ location,
2101
+ telemetryMessage: "TOML parse error"
2102
+ });
2103
+ }
2104
+ }
2105
+ __name(parseTOML, "parseTOML");
2106
+ function parsePackageJSON(input, file2) {
2107
+ return parseJSON(input, file2);
2108
+ }
2109
+ __name(parsePackageJSON, "parsePackageJSON");
2110
+ function parseJSON(input, file2) {
2111
+ return parseJSONC(input, file2, {
2112
+ allowEmptyContent: false,
2113
+ allowTrailingComma: false,
2114
+ disallowComments: true
2115
+ });
2116
+ }
2117
+ __name(parseJSON, "parseJSON");
2118
+ function parseJSONC(input, file2, options = { allowTrailingComma: true }) {
2119
+ const errors = [];
2120
+ const data = parse2(input, errors, options);
2121
+ if (errors.length) throw new ParseError({
2122
+ text: printParseErrorCode(errors[0].error),
2123
+ location: {
2124
+ ...indexLocation({
2125
+ file: file2,
2126
+ fileText: input
2127
+ }, errors[0].offset + 1),
2128
+ length: errors[0].length
2129
+ },
2130
+ telemetryMessage: "JSON(C) parse error"
2131
+ });
2132
+ return data;
2133
+ }
2134
+ __name(parseJSONC, "parseJSONC");
2135
+ function readFileSyncToBuffer(file2) {
2136
+ try {
2137
+ return readFileSync(file2);
2138
+ } catch (err) {
2139
+ const { message } = err;
2140
+ throw new ParseError({
2141
+ text: `Could not read file: ${file2}`,
2142
+ notes: [{ text: message.replace(file2, resolve(file2)) }],
2143
+ telemetryMessage: false
2144
+ });
2145
+ }
2146
+ }
2147
+ __name(readFileSyncToBuffer, "readFileSyncToBuffer");
2148
+ function readFileSync$1(file2) {
2149
+ try {
2150
+ return removeBOMAndValidate(readFileSync(file2), file2);
2151
+ } catch (err) {
2152
+ if (err instanceof ParseError) throw err;
2153
+ const { message } = err;
2154
+ throw new ParseError({
2155
+ text: `Could not read file: ${file2}`,
2156
+ notes: [{ text: message.replace(file2, resolve(file2)) }],
2157
+ telemetryMessage: "Could not read file"
2158
+ });
2159
+ }
2160
+ }
2161
+ __name(readFileSync$1, "readFileSync");
2162
+ function indexLocation(file2, index) {
2163
+ let lineText, line = 0, column = 0, cursor = 0;
2164
+ const { fileText = "" } = file2;
2165
+ for (const row of fileText.split("\n")) {
2166
+ line++;
2167
+ cursor += row.length + 1;
2168
+ if (cursor >= index) {
2169
+ lineText = row;
2170
+ column = row.length - (cursor - index);
2171
+ break;
2172
+ }
2173
+ }
2174
+ return {
2175
+ lineText,
2176
+ line,
2177
+ column,
2178
+ ...file2
2179
+ };
2180
+ }
2181
+ __name(indexLocation, "indexLocation");
2182
+ function searchLocation(file2, query) {
2183
+ let lineText, length, line = 0, column = 0;
2184
+ const queryText = String(query);
2185
+ const { fileText = "" } = file2;
2186
+ for (const content of fileText.split("\n")) {
2187
+ line++;
2188
+ const index = content.indexOf(queryText);
2189
+ if (index >= 0) {
2190
+ lineText = content;
2191
+ column = index;
2192
+ length = queryText.length;
2193
+ break;
2194
+ }
2195
+ }
2196
+ return {
2197
+ lineText,
2198
+ line,
2199
+ column,
2200
+ length,
2201
+ ...file2
2202
+ };
2203
+ }
2204
+ __name(searchLocation, "searchLocation");
2205
+ var units = {
2206
+ nanoseconds: 1e-9,
2207
+ nanosecond: 1e-9,
2208
+ microseconds: 1e-6,
2209
+ microsecond: 1e-6,
2210
+ milliseconds: .001,
2211
+ millisecond: .001,
2212
+ seconds: 1,
2213
+ second: 1,
2214
+ minutes: 60,
2215
+ minute: 60,
2216
+ hours: 3600,
2217
+ hour: 3600,
2218
+ days: 86400,
2219
+ day: 86400,
2220
+ weeks: 604800,
2221
+ week: 604800,
2222
+ month: 18144e3,
2223
+ year: 220752e3,
2224
+ nsecs: 1e-9,
2225
+ nsec: 1e-9,
2226
+ usecs: 1e-6,
2227
+ usec: 1e-6,
2228
+ msecs: .001,
2229
+ msec: .001,
2230
+ secs: 1,
2231
+ sec: 1,
2232
+ mins: 60,
2233
+ min: 60,
2234
+ ns: 1e-9,
2235
+ us: 1e-6,
2236
+ ms: .001,
2237
+ mo: 18144e3,
2238
+ yr: 220752e3,
2239
+ s: 1,
2240
+ m: 60,
2241
+ h: 3600,
2242
+ d: 86400,
2243
+ w: 604800,
2244
+ y: 220752e3
2245
+ };
2246
+ function parseHumanDuration(s) {
2247
+ const unitsMap = new Map(Object.entries(units));
2248
+ s = s.trim().toLowerCase();
2249
+ let base = 1;
2250
+ for (const [name, _] of unitsMap) if (s.endsWith(name)) {
2251
+ s = s.substring(0, s.length - name.length);
2252
+ base = unitsMap.get(name) || 1;
2253
+ break;
2254
+ }
2255
+ return Number(s) * base;
2256
+ }
2257
+ __name(parseHumanDuration, "parseHumanDuration");
2258
+ function parseNonHyphenedUuid(uuid) {
2259
+ if (uuid == null || uuid.includes("-")) return uuid;
2260
+ if (uuid.length != 32) return null;
2261
+ const uuid_parts = [];
2262
+ uuid_parts.push(uuid.slice(0, 8));
2263
+ uuid_parts.push(uuid.slice(8, 12));
2264
+ uuid_parts.push(uuid.slice(12, 16));
2265
+ uuid_parts.push(uuid.slice(16, 20));
2266
+ uuid_parts.push(uuid.slice(20));
2267
+ let hyphenated = "";
2268
+ uuid_parts.forEach((part) => hyphenated += part + "-");
2269
+ return hyphenated.slice(0, 36);
2270
+ }
2271
+ __name(parseNonHyphenedUuid, "parseNonHyphenedUuid");
2272
+ function parseByteSize(s, base = void 0) {
2273
+ const match = s.match(/^(\d*\.*\d*)\s*([kKmMgGtTpP]{0,1})([i]{0,1}[bB]{0,1})$/);
2274
+ if (!match) return NaN;
2275
+ const size = match[1];
2276
+ if (size.length === 0 || isNaN(Number(size))) return NaN;
2277
+ const unit = match[2].toLowerCase();
2278
+ const sizeUnits = {
2279
+ k: 1,
2280
+ m: 2,
2281
+ g: 3,
2282
+ t: 4,
2283
+ p: 5
2284
+ };
2285
+ if (unit.length !== 0 && !(unit in sizeUnits)) return NaN;
2286
+ const binary = match[3].toLowerCase() == "ib";
2287
+ if (binary && unit.length === 0) return NaN;
2288
+ const pow = sizeUnits[unit] || 0;
2289
+ return Math.floor(Number(size) * Math.pow(base ?? (binary ? 1024 : 1e3), pow));
2290
+ }
2291
+ __name(parseByteSize, "parseByteSize");
2292
+ var UNSUPPORTED_BOMS = [
2293
+ {
2294
+ buffer: Buffer.from([
2295
+ 0,
2296
+ 0,
2297
+ 254,
2298
+ 255
2299
+ ]),
2300
+ encoding: "UTF-32 BE"
2301
+ },
2302
+ {
2303
+ buffer: Buffer.from([
2304
+ 255,
2305
+ 254,
2306
+ 0,
2307
+ 0
2308
+ ]),
2309
+ encoding: "UTF-32 LE"
2310
+ },
2311
+ {
2312
+ buffer: Buffer.from([254, 255]),
2313
+ encoding: "UTF-16 BE"
2314
+ },
2315
+ {
2316
+ buffer: Buffer.from([255, 254]),
2317
+ encoding: "UTF-16 LE"
2318
+ }
2319
+ ];
2320
+ function removeBOMAndValidate(buffer, file2) {
2321
+ for (const bom of UNSUPPORTED_BOMS) if (buffer.length >= bom.buffer.length && buffer.subarray(0, bom.buffer.length).equals(bom.buffer)) throw new ParseError({
2322
+ text: `Configuration file contains ${bom.encoding} byte order marker`,
2323
+ notes: [{ text: `The file "${file2}" appears to be encoded as ${bom.encoding}. Please save the file as UTF-8 without BOM.` }],
2324
+ location: {
2325
+ file: file2,
2326
+ line: 1,
2327
+ column: 0
2328
+ },
2329
+ telemetryMessage: `${bom.encoding} BOM detected`
2330
+ });
2331
+ const content = buffer.toString("utf-8");
2332
+ if (content.charCodeAt(0) === 65279) return content.slice(1);
2333
+ return content;
2334
+ }
2335
+ __name(removeBOMAndValidate, "removeBOMAndValidate");
2336
+ var INHERIT_SYMBOL = Symbol.for("inherit_binding");
2337
+ var PATH_TO_DEPLOY_CONFIG = ".wrangler/deploy/config.json";
2338
+ function absolute(input, root) {
2339
+ return isAbsolute(input) ? input : resolve(root || ".", input);
2340
+ }
2341
+ __name(absolute, "absolute");
2342
+ function up(base, options) {
2343
+ let { last, cwd } = options || {};
2344
+ let tmp = absolute(base, cwd);
2345
+ let root = absolute(last || "/", cwd);
2346
+ let prev, arr = [];
2347
+ while (prev !== root) {
2348
+ arr.push(tmp);
2349
+ tmp = dirname(prev = tmp);
2350
+ if (tmp === prev) break;
2351
+ }
2352
+ return arr;
2353
+ }
2354
+ __name(up, "up");
2355
+ function file(name, options) {
2356
+ let dir, tmp;
2357
+ for (dir of up(options && options.cwd || "", options)) try {
2358
+ tmp = join(dir, name);
2359
+ if (statSync(tmp).isFile()) return tmp;
2360
+ } catch {}
2361
+ }
2362
+ __name(file, "file");
2363
+ function dedent$2(templ) {
2364
+ var values = [];
2365
+ for (var _i = 1; _i < arguments.length; _i++) values[_i - 1] = arguments[_i];
2366
+ var strings = Array.from(typeof templ === "string" ? [templ] : templ);
2367
+ strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
2368
+ var indentLengths = strings.reduce(function(arr, str) {
2369
+ var matches = str.match(/\n([\t ]+|(?!\s).)/g);
2370
+ if (matches) return arr.concat(matches.map(function(match) {
2371
+ var _a, _b;
2372
+ return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
2373
+ }));
2374
+ return arr;
2375
+ }, []);
2376
+ if (indentLengths.length) {
2377
+ var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
2378
+ strings = strings.map(function(str) {
2379
+ return str.replace(pattern_1, "\n");
2380
+ });
2381
+ }
2382
+ strings[0] = strings[0].replace(/^\r?\n/, "");
2383
+ var string = strings[0];
2384
+ values.forEach(function(value, i) {
2385
+ var endentations = string.match(/(?:^|\n)( *)$/);
2386
+ var endentation = endentations ? endentations[1] : "";
2387
+ var indentedValue = value;
2388
+ if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map(function(str, i2) {
2389
+ return i2 === 0 ? str : "" + endentation + str;
2390
+ }).join("\n");
2391
+ string += indentedValue + strings[i + 1];
2392
+ });
2393
+ return string;
2394
+ }
2395
+ __name(dedent$2, "dedent");
2396
+ var esm_default = dedent$2;
2397
+ function resolveWranglerConfigPath({ config, script }, options) {
2398
+ if (config !== void 0) return {
2399
+ userConfigPath: config,
2400
+ configPath: config,
2401
+ deployConfigPath: void 0,
2402
+ redirected: false
2403
+ };
2404
+ return findWranglerConfig(script !== void 0 ? path2.dirname(script) : process.cwd(), options);
2405
+ }
2406
+ __name(resolveWranglerConfigPath, "resolveWranglerConfigPath");
2407
+ function findWranglerConfig(referencePath = process.cwd(), { useRedirectIfAvailable = false } = {}) {
2408
+ const userConfigPath = file(`wrangler.json`, { cwd: referencePath }) ?? file(`wrangler.jsonc`, { cwd: referencePath }) ?? file(`wrangler.toml`, { cwd: referencePath });
2409
+ if (!useRedirectIfAvailable) return {
2410
+ userConfigPath,
2411
+ configPath: userConfigPath,
2412
+ deployConfigPath: void 0,
2413
+ redirected: false
2414
+ };
2415
+ const { configPath, deployConfigPath, redirected } = findRedirectedWranglerConfig(referencePath, userConfigPath);
2416
+ return {
2417
+ userConfigPath,
2418
+ configPath,
2419
+ deployConfigPath,
2420
+ redirected
2421
+ };
2422
+ }
2423
+ __name(findWranglerConfig, "findWranglerConfig");
2424
+ function findRedirectedWranglerConfig(cwd, userConfigPath) {
2425
+ const deployConfigPath = file(PATH_TO_DEPLOY_CONFIG, { cwd });
2426
+ if (deployConfigPath === void 0) return {
2427
+ configPath: userConfigPath,
2428
+ deployConfigPath,
2429
+ redirected: false
2430
+ };
2431
+ let redirectedConfigPath;
2432
+ const deployConfigFile = readFileSync$1(deployConfigPath);
2433
+ try {
2434
+ const deployConfig = parseJSONC(deployConfigFile, deployConfigPath);
2435
+ redirectedConfigPath = deployConfig.configPath && path2.resolve(path2.dirname(deployConfigPath), deployConfig.configPath);
2436
+ } catch (e) {
2437
+ throw new UserError(`Failed to parse the deploy configuration file at ${path2.relative(".", deployConfigPath)}`, {
2438
+ cause: e,
2439
+ telemetryMessage: false
2440
+ });
2441
+ }
2442
+ if (!redirectedConfigPath) throw new UserError(esm_default`
2443
+ A deploy configuration file was found at "${path2.relative(".", deployConfigPath)}".
2444
+ But this is not valid - the required "configPath" property was not found.
2445
+ Instead this file contains:
2446
+ \`\`\`
2447
+ ${deployConfigFile}
2448
+ \`\`\`
2449
+ `, { telemetryMessage: false });
2450
+ if (!existsSync(redirectedConfigPath)) throw new UserError(esm_default`
2451
+ There is a deploy configuration at "${path2.relative(".", deployConfigPath)}".
2452
+ But the redirected configuration path it points to, "${path2.relative(".", redirectedConfigPath)}", does not exist.
2453
+ `, { telemetryMessage: false });
2454
+ if (userConfigPath) {
2455
+ if (path2.join(path2.dirname(userConfigPath), PATH_TO_DEPLOY_CONFIG) !== deployConfigPath) throw new UserError(esm_default`
2456
+ Found both a user configuration file at "${path2.relative(".", userConfigPath)}"
2457
+ and a deploy configuration file at "${path2.relative(".", deployConfigPath)}".
2458
+ But these do not share the same base path so it is not clear which should be used.
2459
+ `, { telemetryMessage: false });
2460
+ }
2461
+ return {
2462
+ configPath: redirectedConfigPath,
2463
+ deployConfigPath,
2464
+ redirected: true
2465
+ };
2466
+ }
2467
+ __name(findRedirectedWranglerConfig, "findRedirectedWranglerConfig");
2468
+ function isRedirectedConfig(config) {
2469
+ return config.configPath !== void 0 && config.configPath !== config.userConfigPath;
2470
+ }
2471
+ __name(isRedirectedConfig, "isRedirectedConfig");
2472
+ function isRedirectedRawConfig(rawConfig, configPath, userConfigPath) {
2473
+ return isRedirectedConfig({
2474
+ configPath,
2475
+ userConfigPath
2476
+ });
2477
+ }
2478
+ __name(isRedirectedRawConfig, "isRedirectedRawConfig");
2479
+ function configFormat(configPath) {
2480
+ if (configPath?.endsWith("toml")) return "toml";
2481
+ if (configPath?.endsWith("jsonc")) return "jsonc";
2482
+ if (configPath?.endsWith("json")) return "json";
2483
+ return "none";
2484
+ }
2485
+ __name(configFormat, "configFormat");
2486
+ function configFileName(configPath) {
2487
+ switch (configFormat(configPath)) {
2488
+ case "toml": return "wrangler.toml";
2489
+ case "json": return "wrangler.json";
2490
+ case "jsonc": return "wrangler.jsonc";
2491
+ default: return "Wrangler configuration";
2492
+ }
2493
+ }
2494
+ __name(configFileName, "configFileName");
2495
+ function formatConfigSnippet(snippet, configPath, formatted = true) {
2496
+ if (configFormat(configPath) === "toml") return dist_default.stringify(snippet);
2497
+ else return formatted ? JSON.stringify(snippet, null, 2) : JSON.stringify(snippet);
2498
+ }
2499
+ __name(formatConfigSnippet, "formatConfigSnippet");
2500
+
2501
+ //#endregion
2502
+ //#region src/build-output.ts
2503
+ /**
2504
+ * Initial draft version of the Build Output API.
2505
+ *
2506
+ * Will move to `v1` when the spec stabilises.
2507
+ */
2508
+ const BUILD_OUTPUT_VERSION = "v0";
2509
+ /**
2510
+ * Project-relative root.
2511
+ */
2512
+ const BUILD_OUTPUT_ROOT = ".cloudflare/output";
2513
+ /**
2514
+ * Filename of the per-Worker config.
2515
+ */
2516
+ const WORKER_CONFIG_FILENAME = "worker.config.json";
2517
+ /**
2518
+ * Absolute path to the Build Output API root for the current project.
2519
+ */
2520
+ function getBuildOutputDir(root) {
2521
+ return path.resolve(root, BUILD_OUTPUT_ROOT);
2522
+ }
2523
+ /**
2524
+ * Clean the build output directory.
2525
+ */
2526
+ async function cleanBuildOutputDir(root) {
2527
+ await removeDir(getBuildOutputDir(root));
2528
+ }
2529
+ /**
2530
+ * Absolute path to the Workers output directory.
2531
+ */
2532
+ function getWorkersDir(root) {
2533
+ return path.join(getBuildOutputDir(root), BUILD_OUTPUT_VERSION, "workers");
2534
+ }
2535
+ /**
2536
+ * Absolute path to the config file for a given Worker.
2537
+ */
2538
+ function getWorkerConfigPath(root, workerName) {
2539
+ return path.join(getWorkersDir(root), workerName, WORKER_CONFIG_FILENAME);
2540
+ }
2541
+ /**
2542
+ * Absolute path to the bundle directory for a given Worker.
2543
+ */
2544
+ function getWorkerBundleDir(root, workerName) {
2545
+ return path.join(getWorkersDir(root), workerName, "bundle");
2546
+ }
2547
+ /**
2548
+ * Absolute path to the assets directory for a given Worker.
2549
+ */
2550
+ function getWorkerAssetsDir(root, workerName) {
2551
+ return path.join(getWorkersDir(root), workerName, "assets");
2552
+ }
2553
+ /**
2554
+ * Write the output `worker.config.json` for a given Worker to the Build
2555
+ * Output API tree.
2556
+ *
2557
+ * - Workers mode: `manifest` is provided (bundle/ present on disk).
2558
+ * - Assets-only mode: `manifest` is omitted (no bundle/ directory).
2559
+ */
2560
+ async function writeOutputWorkerConfig(root, parsedConfig, manifest) {
2561
+ const { entrypoint: _entrypoint,...rest } = parsedConfig;
2562
+ const outputConfig = {
2563
+ ...rest,
2564
+ manifest
2565
+ };
2566
+ const workerOutputDir = path.join(getWorkersDir(root), outputConfig.name);
2567
+ await fsp.mkdir(workerOutputDir, { recursive: true });
2568
+ const configPath = getWorkerConfigPath(root, outputConfig.name);
2569
+ await fsp.writeFile(configPath, JSON.stringify(outputConfig));
2570
+ }
2571
+
2572
+ //#endregion
2573
+ //#region src/schema.ts
2574
+ const AssetsSchema = z.strictObject({
2575
+ htmlHandling: z.enum([
2576
+ "auto-trailing-slash",
2577
+ "drop-trailing-slash",
2578
+ "force-trailing-slash",
2579
+ "none"
2580
+ ]).optional(),
2581
+ notFoundHandling: z.enum([
2582
+ "single-page-application",
2583
+ "404-page",
2584
+ "none"
2585
+ ]).optional(),
2586
+ runWorkerFirst: z.union([z.array(z.string()), z.boolean()]).optional()
2587
+ });
2588
+ const KnownBindingSchema = z.discriminatedUnion("type", [
2589
+ z.strictObject({
2590
+ type: z.literal("agent-memory"),
2591
+ namespace: z.string(),
2592
+ remote: z.boolean().optional()
2593
+ }),
2594
+ z.strictObject({
2595
+ type: z.literal("ai"),
2596
+ remote: z.boolean().optional()
2597
+ }),
2598
+ z.strictObject({
2599
+ type: z.literal("ai-search"),
2600
+ name: z.string(),
2601
+ remote: z.boolean().optional()
2602
+ }),
2603
+ z.strictObject({
2604
+ type: z.literal("ai-search-namespace"),
2605
+ namespace: z.string(),
2606
+ remote: z.boolean().optional()
2607
+ }),
2608
+ z.strictObject({
2609
+ type: z.literal("analytics-engine-dataset"),
2610
+ name: z.string().optional()
2611
+ }),
2612
+ z.strictObject({
2613
+ type: z.literal("artifacts"),
2614
+ namespace: z.string(),
2615
+ remote: z.boolean().optional()
2616
+ }),
2617
+ z.strictObject({ type: z.literal("assets") }),
2618
+ z.strictObject({
2619
+ type: z.literal("browser"),
2620
+ remote: z.boolean().optional()
2621
+ }),
2622
+ z.strictObject({
2623
+ type: z.literal("d1"),
2624
+ name: z.string().optional(),
2625
+ id: z.string().optional(),
2626
+ remote: z.boolean().optional()
2627
+ }),
2628
+ z.strictObject({
2629
+ type: z.literal("dispatch-namespace"),
2630
+ namespace: z.string(),
2631
+ outbound: z.strictObject({
2632
+ workerName: z.string(),
2633
+ parameters: z.array(z.string()).optional()
2634
+ }).optional(),
2635
+ remote: z.boolean().optional()
2636
+ }),
2637
+ z.strictObject({
2638
+ type: z.literal("durable-object"),
2639
+ workerName: z.string(),
2640
+ exportName: z.string()
2641
+ }),
2642
+ z.strictObject({
2643
+ type: z.literal("flagship"),
2644
+ id: z.string(),
2645
+ remote: z.boolean().optional()
2646
+ }),
2647
+ z.strictObject({
2648
+ type: z.literal("hyperdrive"),
2649
+ id: z.string(),
2650
+ localConnectionString: z.string().optional()
2651
+ }),
2652
+ z.strictObject({
2653
+ type: z.literal("images"),
2654
+ remote: z.boolean().optional()
2655
+ }),
2656
+ z.strictObject({
2657
+ type: z.literal("json"),
2658
+ value: z.json()
2659
+ }),
2660
+ z.strictObject({
2661
+ type: z.literal("kv"),
2662
+ id: z.string().optional(),
2663
+ remote: z.boolean().optional()
2664
+ }),
2665
+ z.strictObject({
2666
+ type: z.literal("logfwdr"),
2667
+ destination: z.string()
2668
+ }),
2669
+ z.strictObject({
2670
+ type: z.literal("media"),
2671
+ remote: z.boolean().optional()
2672
+ }),
2673
+ z.strictObject({
2674
+ type: z.literal("mtls-certificate"),
2675
+ id: z.string(),
2676
+ remote: z.boolean().optional()
2677
+ }),
2678
+ z.strictObject({
2679
+ type: z.literal("pipeline"),
2680
+ name: z.string(),
2681
+ remote: z.boolean().optional()
2682
+ }),
2683
+ z.strictObject({
2684
+ type: z.literal("queue"),
2685
+ name: z.string(),
2686
+ deliveryDelay: z.number().optional(),
2687
+ remote: z.boolean().optional()
2688
+ }),
2689
+ z.strictObject({
2690
+ type: z.literal("rate-limit"),
2691
+ namespace: z.string(),
2692
+ simple: z.strictObject({
2693
+ limit: z.number(),
2694
+ period: z.union([z.literal(10), z.literal(60)])
2695
+ })
2696
+ }),
2697
+ z.strictObject({
2698
+ type: z.literal("r2"),
2699
+ name: z.string().optional(),
2700
+ jurisdiction: z.string().optional(),
2701
+ remote: z.boolean().optional()
2702
+ }),
2703
+ z.strictObject({ type: z.literal("secret") }),
2704
+ z.strictObject({
2705
+ type: z.literal("secrets-store-secret"),
2706
+ storeId: z.string(),
2707
+ secretName: z.string()
2708
+ }),
2709
+ z.strictObject({
2710
+ type: z.literal("send-email"),
2711
+ destinationAddress: z.string().optional(),
2712
+ allowedDestinationAddresses: z.array(z.string()).optional(),
2713
+ allowedSenderAddresses: z.array(z.string()).optional(),
2714
+ remote: z.boolean().optional()
2715
+ }),
2716
+ z.strictObject({
2717
+ type: z.literal("stream"),
2718
+ remote: z.boolean().optional()
2719
+ }),
2720
+ z.strictObject({
2721
+ type: z.literal("text"),
2722
+ value: z.string()
2723
+ }),
2724
+ z.strictObject({
2725
+ type: z.literal("vectorize"),
2726
+ name: z.string(),
2727
+ remote: z.boolean().optional()
2728
+ }),
2729
+ z.strictObject({ type: z.literal("version-metadata") }),
2730
+ z.strictObject({
2731
+ type: z.literal("vpc-service"),
2732
+ id: z.string(),
2733
+ remote: z.boolean().optional()
2734
+ }),
2735
+ z.strictObject({
2736
+ type: z.literal("vpc-network"),
2737
+ tunnelId: z.string().optional(),
2738
+ networkId: z.string().optional(),
2739
+ remote: z.boolean().optional()
2740
+ }).superRefine((value, ctx) => {
2741
+ const hasTunnel = value.tunnelId !== void 0;
2742
+ if (hasTunnel === (value.networkId !== void 0)) ctx.addIssue({
2743
+ code: "custom",
2744
+ message: hasTunnel ? `"vpc-network" bindings must specify exactly one of "tunnelId" or "networkId", not both` : `"vpc-network" bindings must specify either "tunnelId" or "networkId"`
2745
+ });
2746
+ }),
2747
+ z.strictObject({
2748
+ type: z.literal("web-search"),
2749
+ remote: z.boolean().optional()
2750
+ }),
2751
+ z.strictObject({
2752
+ type: z.literal("worker"),
2753
+ workerName: z.string(),
2754
+ exportName: z.string().optional(),
2755
+ props: z.record(z.string(), z.unknown()).optional(),
2756
+ remote: z.boolean().optional()
2757
+ }),
2758
+ z.strictObject({ type: z.literal("worker-loader") })
2759
+ ]);
2760
+ const UnsafeBindingSchema = z.looseObject({
2761
+ type: z.templateLiteral(["unsafe:", z.string().min(1)]),
2762
+ dev: z.strictObject({
2763
+ plugin: z.strictObject({
2764
+ package: z.string(),
2765
+ name: z.string()
2766
+ }),
2767
+ options: z.record(z.string(), z.unknown()).optional()
2768
+ }).optional()
2769
+ });
2770
+ const BindingSchema = z.unknown().transform((value, ctx) => {
2771
+ const result = (typeof value === "object" && value !== null && "type" in value && typeof value.type === "string" && value.type.startsWith("unsafe:") ? UnsafeBindingSchema : KnownBindingSchema).safeParse(value);
2772
+ if (!result.success) {
2773
+ ctx.issues.push(...result.error.issues);
2774
+ return z.NEVER;
2775
+ }
2776
+ return result.data;
2777
+ });
2778
+ function isParsedUnsafeBinding(binding) {
2779
+ return binding.type.startsWith("unsafe:");
2780
+ }
2781
+ const CacheSchema = z.strictObject({
2782
+ enabled: z.boolean(),
2783
+ crossVersionCache: z.boolean().optional()
2784
+ });
2785
+ /**
2786
+ * Binding types that can only be defined once per worker.
2787
+ */
2788
+ const SINGLETON_BINDING_TYPES = new Set([
2789
+ "ai",
2790
+ "assets",
2791
+ "browser",
2792
+ "images",
2793
+ "media",
2794
+ "stream",
2795
+ "version-metadata",
2796
+ "web-search"
2797
+ ]);
2798
+ const listFormatter = new Intl.ListFormat("en-US");
2799
+ const EnvSchema = z.record(z.string(), BindingSchema).superRefine((env, ctx) => {
2800
+ const seen = /* @__PURE__ */ new Set();
2801
+ const duplicates = /* @__PURE__ */ new Set();
2802
+ for (const binding of Object.values(env)) {
2803
+ const type = binding.type;
2804
+ if (SINGLETON_BINDING_TYPES.has(type)) {
2805
+ if (seen.has(type)) duplicates.add(type);
2806
+ seen.add(type);
2807
+ }
2808
+ }
2809
+ if (duplicates.size > 0) ctx.addIssue({
2810
+ code: "custom",
2811
+ message: `${listFormatter.format([...duplicates].sort())} bindings can only be defined once`
2812
+ });
2813
+ }).optional();
2814
+ const ExportSchema = z.union([
2815
+ z.strictObject({
2816
+ type: z.literal("durable-object"),
2817
+ state: z.literal("created").optional(),
2818
+ storage: z.enum(["sqlite", "legacy-kv"])
2819
+ }),
2820
+ z.strictObject({
2821
+ type: z.literal("durable-object"),
2822
+ state: z.literal("deleted")
2823
+ }),
2824
+ z.strictObject({
2825
+ type: z.literal("durable-object"),
2826
+ state: z.literal("renamed"),
2827
+ renamedTo: z.string()
2828
+ }),
2829
+ z.strictObject({
2830
+ type: z.literal("durable-object"),
2831
+ state: z.literal("transferred"),
2832
+ transferredTo: z.string()
2833
+ }),
2834
+ z.strictObject({
2835
+ type: z.literal("durable-object"),
2836
+ state: z.literal("expecting-transfer"),
2837
+ storage: z.enum(["sqlite", "legacy-kv"]),
2838
+ transferFrom: z.string()
2839
+ }),
2840
+ z.strictObject({
2841
+ type: z.literal("worker"),
2842
+ cache: z.strictObject({ enabled: z.boolean() }).optional()
2843
+ })
2844
+ ]);
2845
+ const LimitsSchema = z.strictObject({
2846
+ cpuMs: z.number().optional(),
2847
+ subrequests: z.number().optional()
2848
+ });
2849
+ const ObservabilitySchema = z.strictObject({
2850
+ enabled: z.boolean().optional(),
2851
+ headSamplingRate: z.number().optional(),
2852
+ logs: z.strictObject({
2853
+ enabled: z.boolean().optional(),
2854
+ headSamplingRate: z.number().optional(),
2855
+ invocationLogs: z.boolean().optional(),
2856
+ persist: z.boolean().optional(),
2857
+ destinations: z.array(z.string()).optional()
2858
+ }).optional(),
2859
+ traces: z.strictObject({
2860
+ enabled: z.boolean().optional(),
2861
+ headSamplingRate: z.number().optional(),
2862
+ persist: z.boolean().optional(),
2863
+ destinations: z.array(z.string()).optional()
2864
+ }).optional()
2865
+ });
2866
+ const PlacementSchema = z.union([
2867
+ z.strictObject({
2868
+ mode: z.enum(["off", "smart"]),
2869
+ hint: z.string().optional()
2870
+ }),
2871
+ z.strictObject({
2872
+ mode: z.literal("targeted").optional(),
2873
+ region: z.string()
2874
+ }),
2875
+ z.strictObject({
2876
+ mode: z.literal("targeted").optional(),
2877
+ host: z.string()
2878
+ }),
2879
+ z.strictObject({
2880
+ mode: z.literal("targeted").optional(),
2881
+ hostname: z.string()
2882
+ })
2883
+ ]);
2884
+ const TailConsumerSchema = z.strictObject({
2885
+ workerName: z.string(),
2886
+ streaming: z.boolean().optional()
2887
+ });
2888
+ const TriggerSchema = z.discriminatedUnion("type", [
2889
+ z.strictObject({
2890
+ type: z.literal("fetch"),
2891
+ pattern: z.string(),
2892
+ zone: z.string().optional()
2893
+ }),
2894
+ z.strictObject({
2895
+ type: z.literal("queue"),
2896
+ name: z.string(),
2897
+ deadLetterQueue: z.string().optional(),
2898
+ maxBatchSize: z.number().optional(),
2899
+ maxBatchTimeout: z.number().optional(),
2900
+ maxConcurrency: z.number().nullable().optional(),
2901
+ maxRetries: z.number().optional(),
2902
+ retryDelay: z.number().optional(),
2903
+ visibilityTimeoutMs: z.number().optional()
2904
+ }),
2905
+ z.strictObject({
2906
+ type: z.literal("scheduled"),
2907
+ schedule: z.string()
2908
+ })
2909
+ ]);
2910
+ const UnsafeSchema = z.strictObject({
2911
+ metadata: z.record(z.string(), z.unknown()).optional(),
2912
+ capnp: z.union([z.strictObject({
2913
+ basePath: z.string(),
2914
+ sourceSchemas: z.array(z.string()),
2915
+ compiledSchema: z.never().optional()
2916
+ }), z.strictObject({
2917
+ basePath: z.never().optional(),
2918
+ sourceSchemas: z.never().optional(),
2919
+ compiledSchema: z.string()
2920
+ })]).optional()
2921
+ });
2922
+ /**
2923
+ * Base Worker schema — the set of fields shared between the input
2924
+ * (user-authored) and output (on-disk) Worker configs.
2925
+ */
2926
+ const BaseWorkerSchema = z.strictObject({
2927
+ name: z.string(),
2928
+ accountId: z.string().optional(),
2929
+ compatibilityDate: z.string(),
2930
+ compatibilityFlags: z.array(z.string()).optional(),
2931
+ assets: AssetsSchema.optional(),
2932
+ domains: z.array(z.string()).optional(),
2933
+ triggers: z.array(TriggerSchema).optional(),
2934
+ tailConsumers: z.array(TailConsumerSchema).optional(),
2935
+ cache: CacheSchema.optional(),
2936
+ placement: PlacementSchema.optional(),
2937
+ limits: LimitsSchema.optional(),
2938
+ logpush: z.boolean().optional(),
2939
+ observability: ObservabilitySchema.optional(),
2940
+ workersDev: z.boolean().optional(),
2941
+ previewUrls: z.boolean().optional(),
2942
+ complianceRegion: z.enum(["public", "fedramp-high"]).optional(),
2943
+ firstPartyWorker: z.boolean().optional(),
2944
+ unsafe: UnsafeSchema.optional(),
2945
+ env: EnvSchema,
2946
+ exports: z.record(z.string(), ExportSchema).optional()
2947
+ });
2948
+ /**
2949
+ * Input Worker schema — the shape that user-authored `cloudflare.config.ts`
2950
+ * files are validated against. Adds an optional `entrypoint` field to the
2951
+ * base schema.
2952
+ */
2953
+ const InputWorkerSchema = BaseWorkerSchema.extend({ entrypoint: z.union([z.string(), z.strictObject({ default: z.string() })]).transform((value) => typeof value === "string" ? value : value.default).optional() });
2954
+ const ModuleTypeSchema = z.enum([
2955
+ "esm",
2956
+ "cjs",
2957
+ "python",
2958
+ "python-requirement",
2959
+ "wasm",
2960
+ "text",
2961
+ "data",
2962
+ "json",
2963
+ "sourcemap"
2964
+ ]);
2965
+ const ManifestSchema = z.strictObject({
2966
+ mainModule: z.string(),
2967
+ modules: z.record(z.string(), z.strictObject({ type: ModuleTypeSchema }))
2968
+ });
2969
+ /**
2970
+ * Output Worker schema — the shape of `worker.config.json` in the
2971
+ * Build Output API. Adds an optional `manifest` field to the
2972
+ * base schema.
2973
+ */
2974
+ const OutputWorkerSchema = BaseWorkerSchema.extend({ manifest: ManifestSchema.optional() });
2975
+
2976
+ //#endregion
2977
+ //#region ../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/dist/index.js
2978
+ var require_dist = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/dist/index.js": ((exports) => {
2979
+ Object.defineProperty(exports, "__esModule", { value: true });
2980
+ exports.dedent = void 0;
2981
+ function dedent$1(templ) {
2982
+ var values = [];
2983
+ for (var _i = 1; _i < arguments.length; _i++) values[_i - 1] = arguments[_i];
2984
+ var strings = Array.from(typeof templ === "string" ? [templ] : templ);
2985
+ strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
2986
+ var indentLengths = strings.reduce(function(arr, str) {
2987
+ var matches = str.match(/\n([\t ]+|(?!\s).)/g);
2988
+ if (matches) return arr.concat(matches.map(function(match) {
2989
+ var _a, _b;
2990
+ return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
2991
+ }));
2992
+ return arr;
2993
+ }, []);
2994
+ if (indentLengths.length) {
2995
+ var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
2996
+ strings = strings.map(function(str) {
2997
+ return str.replace(pattern_1, "\n");
2998
+ });
2999
+ }
3000
+ strings[0] = strings[0].replace(/^\r?\n/, "");
3001
+ var string = strings[0];
3002
+ values.forEach(function(value, i) {
3003
+ var endentations = string.match(/(?:^|\n)( *)$/);
3004
+ var endentation = endentations ? endentations[1] : "";
3005
+ var indentedValue = value;
3006
+ if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map(function(str, i$1) {
3007
+ return i$1 === 0 ? str : "" + endentation + str;
3008
+ }).join("\n");
3009
+ string += indentedValue + strings[i + 1];
3010
+ });
3011
+ return string;
3012
+ }
3013
+ exports.dedent = dedent$1;
3014
+ }) });
3015
+
3016
+ //#endregion
3017
+ //#region src/generate.ts
3018
+ var import_dist = require_dist();
3019
+ /**
3020
+ * Generate the content for worker-configuration.d.ts
3021
+ *
3022
+ * @example
3023
+ * ```typescript
3024
+ * import { generateTypes } from "@cloudflare/config";
3025
+ * import { writeFileSync } from "node:fs";
3026
+ *
3027
+ * const content = generateTypes({
3028
+ * configPath: "./cloudflare.config.ts",
3029
+ * });
3030
+ *
3031
+ * writeFileSync("worker-configuration.d.ts", content);
3032
+ * ```
3033
+ */
3034
+ function generateTypes({ configPath, packageName = "@cloudflare/config" }) {
3035
+ return import_dist.dedent`
3036
+ /* eslint-disable */
3037
+ // Generated by @cloudflare/config
3038
+ type __WorkerConfig = import("${packageName}").UnwrapConfig<typeof import("${configPath.replace(/\.(ts|js|mts|mjs)$/, "")}").default>;
3039
+ type __Env = import("${packageName}").InferEnv<__WorkerConfig>;
3040
+
3041
+ declare namespace Cloudflare {
3042
+ interface GlobalProps {
3043
+ mainModule: import("${packageName}").InferMainModule<__WorkerConfig>;
3044
+ durableNamespaces: import("${packageName}").InferDurableNamespaces<__WorkerConfig>;
3045
+ }
3046
+ interface Env extends __Env {}
3047
+ }
3048
+ interface Env extends Cloudflare.Env {}
3049
+
3050
+ `;
3051
+ }
3052
+
3053
+ //#endregion
3054
+ //#region src/convert.ts
3055
+ /**
3056
+ * Convert a parsed `@cloudflare/config` config into a Wrangler `RawConfig`.
3057
+ *
3058
+ * The caller is responsible for unwrapping any function/promise wrapper around
3059
+ * the config and validating it against `InputWorkerSchema` before passing it in.
3060
+ *
3061
+ * @param config The parsed (post-validation) config.
3062
+ * @returns The corresponding Wrangler `RawConfig`.
3063
+ */
3064
+ function convertToWranglerConfig(config) {
3065
+ const result = {};
3066
+ convertTopLevel(config, result);
3067
+ convertBindingsAndAssets(config, result);
3068
+ convertExports(config, result);
3069
+ convertDomains(config, result);
3070
+ convertTriggers(config, result);
3071
+ convertTailConsumers(config, result);
3072
+ return result;
3073
+ }
3074
+ function convertTopLevel(config, result) {
3075
+ if (config.name !== void 0) result.name = config.name;
3076
+ if (typeof config.entrypoint === "string") result.main = config.entrypoint;
3077
+ if (config.accountId !== void 0) result.account_id = config.accountId;
3078
+ if (config.compatibilityDate !== void 0) result.compatibility_date = config.compatibilityDate;
3079
+ if (config.compatibilityFlags !== void 0) result.compatibility_flags = config.compatibilityFlags;
3080
+ if (config.workersDev !== void 0) result.workers_dev = config.workersDev;
3081
+ if (config.previewUrls !== void 0) result.preview_urls = config.previewUrls;
3082
+ if (config.logpush !== void 0) result.logpush = config.logpush;
3083
+ if (config.complianceRegion !== void 0) result.compliance_region = config.complianceRegion === "fedramp-high" ? "fedramp_high" : "public";
3084
+ if (config.firstPartyWorker !== void 0) result.first_party_worker = config.firstPartyWorker;
3085
+ if (config.placement !== void 0) result.placement = config.placement;
3086
+ if (config.limits !== void 0) {
3087
+ const limits = {};
3088
+ if (config.limits.cpuMs !== void 0) limits.cpu_ms = config.limits.cpuMs;
3089
+ if (config.limits.subrequests !== void 0) limits.subrequests = config.limits.subrequests;
3090
+ result.limits = limits;
3091
+ }
3092
+ if (config.observability !== void 0) result.observability = convertObservability(config.observability);
3093
+ if (config.cache !== void 0) {
3094
+ const cache = { enabled: config.cache.enabled };
3095
+ if (config.cache.crossVersionCache !== void 0) cache.cross_version_cache = config.cache.crossVersionCache;
3096
+ result.cache = cache;
3097
+ }
3098
+ if (config.unsafe !== void 0) result.unsafe = convertUnsafeTopLevel(config.unsafe);
3099
+ }
3100
+ function convertObservability(observability) {
3101
+ const out = {};
3102
+ if (observability.enabled !== void 0) out.enabled = observability.enabled;
3103
+ if (observability.headSamplingRate !== void 0) out.head_sampling_rate = observability.headSamplingRate;
3104
+ if (observability.logs !== void 0) {
3105
+ const logs = {};
3106
+ const { logs: src } = observability;
3107
+ if (src.enabled !== void 0) logs.enabled = src.enabled;
3108
+ if (src.headSamplingRate !== void 0) logs.head_sampling_rate = src.headSamplingRate;
3109
+ if (src.invocationLogs !== void 0) logs.invocation_logs = src.invocationLogs;
3110
+ if (src.persist !== void 0) logs.persist = src.persist;
3111
+ if (src.destinations !== void 0) logs.destinations = src.destinations;
3112
+ out.logs = logs;
3113
+ }
3114
+ if (observability.traces !== void 0) {
3115
+ const traces = {};
3116
+ const { traces: src } = observability;
3117
+ if (src.enabled !== void 0) traces.enabled = src.enabled;
3118
+ if (src.headSamplingRate !== void 0) traces.head_sampling_rate = src.headSamplingRate;
3119
+ if (src.persist !== void 0) traces.persist = src.persist;
3120
+ if (src.destinations !== void 0) traces.destinations = src.destinations;
3121
+ out.traces = traces;
3122
+ }
3123
+ return out;
3124
+ }
3125
+ function convertUnsafeTopLevel(unsafe) {
3126
+ const out = {};
3127
+ if (unsafe.metadata !== void 0) out.metadata = unsafe.metadata;
3128
+ if (unsafe.capnp !== void 0) {
3129
+ if ("compiledSchema" in unsafe.capnp && unsafe.capnp.compiledSchema) out.capnp = { compiled_schema: unsafe.capnp.compiledSchema };
3130
+ else if ("basePath" in unsafe.capnp && unsafe.capnp.basePath) out.capnp = {
3131
+ base_path: unsafe.capnp.basePath,
3132
+ source_schemas: unsafe.capnp.sourceSchemas ?? []
3133
+ };
3134
+ }
3135
+ return out;
3136
+ }
3137
+ function convertBindingsAndAssets(config, result) {
3138
+ let assetsBindingName;
3139
+ const env = config.env ?? {};
3140
+ const kvNamespaces = [];
3141
+ const d1Databases = [];
3142
+ const r2Buckets = [];
3143
+ const vectorize = [];
3144
+ const mtlsCertificates = [];
3145
+ const hyperdrive = [];
3146
+ const pipelines = [];
3147
+ const flagship = [];
3148
+ const aiSearch = [];
3149
+ const aiSearchNamespaces = [];
3150
+ const agentMemory = [];
3151
+ const analyticsEngineDatasets = [];
3152
+ const artifacts = [];
3153
+ const dispatchNamespaces = [];
3154
+ const secretsStoreSecrets = [];
3155
+ const sendEmail = [];
3156
+ const vpcServices = [];
3157
+ const vpcNetworks = [];
3158
+ const workerLoaders = [];
3159
+ const ratelimits = [];
3160
+ const services = [];
3161
+ const durableObjectBindings = [];
3162
+ const workflows = [];
3163
+ const queueProducers = [];
3164
+ const logfwdrBindings = [];
3165
+ const unsafeBindings = [];
3166
+ const vars = {};
3167
+ const secretsRequired = [];
3168
+ for (const [name, binding] of Object.entries(env)) {
3169
+ if (isParsedUnsafeBinding(binding)) {
3170
+ unsafeBindings.push({
3171
+ ...binding,
3172
+ name,
3173
+ type: binding.type.slice(7)
3174
+ });
3175
+ continue;
3176
+ }
3177
+ switch (binding.type) {
3178
+ case "agent-memory":
3179
+ agentMemory.push(omitUndefined({
3180
+ binding: name,
3181
+ namespace: binding.namespace,
3182
+ remote: binding.remote
3183
+ }));
3184
+ break;
3185
+ case "ai":
3186
+ result.ai = omitUndefined({
3187
+ binding: name,
3188
+ remote: binding.remote
3189
+ });
3190
+ break;
3191
+ case "ai-search":
3192
+ aiSearch.push(omitUndefined({
3193
+ binding: name,
3194
+ instance_name: binding.name,
3195
+ remote: binding.remote
3196
+ }));
3197
+ break;
3198
+ case "ai-search-namespace":
3199
+ aiSearchNamespaces.push(omitUndefined({
3200
+ binding: name,
3201
+ namespace: binding.namespace,
3202
+ remote: binding.remote
3203
+ }));
3204
+ break;
3205
+ case "analytics-engine-dataset":
3206
+ analyticsEngineDatasets.push(omitUndefined({
3207
+ binding: name,
3208
+ dataset: binding.name
3209
+ }));
3210
+ break;
3211
+ case "artifacts":
3212
+ artifacts.push(omitUndefined({
3213
+ binding: name,
3214
+ namespace: binding.namespace,
3215
+ remote: binding.remote
3216
+ }));
3217
+ break;
3218
+ case "assets":
3219
+ assetsBindingName = name;
3220
+ break;
3221
+ case "browser":
3222
+ result.browser = omitUndefined({
3223
+ binding: name,
3224
+ remote: binding.remote
3225
+ });
3226
+ break;
3227
+ case "d1":
3228
+ d1Databases.push(omitUndefined({
3229
+ binding: name,
3230
+ database_id: binding.id,
3231
+ database_name: binding.name,
3232
+ remote: binding.remote
3233
+ }));
3234
+ break;
3235
+ case "dispatch-namespace": {
3236
+ const entry = {
3237
+ binding: name,
3238
+ namespace: binding.namespace
3239
+ };
3240
+ if (binding.outbound) entry.outbound = omitUndefined({
3241
+ service: binding.outbound.workerName,
3242
+ parameters: binding.outbound.parameters
3243
+ });
3244
+ if (binding.remote !== void 0) entry.remote = binding.remote;
3245
+ dispatchNamespaces.push(entry);
3246
+ break;
3247
+ }
3248
+ case "durable-object":
3249
+ durableObjectBindings.push({
3250
+ name,
3251
+ class_name: binding.exportName,
3252
+ script_name: binding.workerName
3253
+ });
3254
+ break;
3255
+ case "flagship":
3256
+ flagship.push(omitUndefined({
3257
+ binding: name,
3258
+ app_id: binding.id,
3259
+ remote: binding.remote
3260
+ }));
3261
+ break;
3262
+ case "hyperdrive":
3263
+ hyperdrive.push(omitUndefined({
3264
+ binding: name,
3265
+ id: binding.id,
3266
+ localConnectionString: binding.localConnectionString
3267
+ }));
3268
+ break;
3269
+ case "images":
3270
+ result.images = omitUndefined({
3271
+ binding: name,
3272
+ remote: binding.remote
3273
+ });
3274
+ break;
3275
+ case "json":
3276
+ vars[name] = binding.value;
3277
+ break;
3278
+ case "kv":
3279
+ kvNamespaces.push(omitUndefined({
3280
+ binding: name,
3281
+ id: binding.id,
3282
+ remote: binding.remote
3283
+ }));
3284
+ break;
3285
+ case "logfwdr":
3286
+ logfwdrBindings.push({
3287
+ name,
3288
+ destination: binding.destination
3289
+ });
3290
+ break;
3291
+ case "media":
3292
+ result.media = omitUndefined({
3293
+ binding: name,
3294
+ remote: binding.remote
3295
+ });
3296
+ break;
3297
+ case "mtls-certificate":
3298
+ mtlsCertificates.push(omitUndefined({
3299
+ binding: name,
3300
+ certificate_id: binding.id,
3301
+ remote: binding.remote
3302
+ }));
3303
+ break;
3304
+ case "pipeline":
3305
+ pipelines.push(omitUndefined({
3306
+ binding: name,
3307
+ stream: binding.name,
3308
+ remote: binding.remote
3309
+ }));
3310
+ break;
3311
+ case "queue":
3312
+ queueProducers.push(omitUndefined({
3313
+ binding: name,
3314
+ queue: binding.name,
3315
+ delivery_delay: binding.deliveryDelay,
3316
+ remote: binding.remote
3317
+ }));
3318
+ break;
3319
+ case "rate-limit":
3320
+ ratelimits.push({
3321
+ name,
3322
+ namespace_id: binding.namespace,
3323
+ simple: binding.simple
3324
+ });
3325
+ break;
3326
+ case "r2":
3327
+ r2Buckets.push(omitUndefined({
3328
+ binding: name,
3329
+ bucket_name: binding.name,
3330
+ jurisdiction: binding.jurisdiction,
3331
+ remote: binding.remote
3332
+ }));
3333
+ break;
3334
+ case "secret":
3335
+ secretsRequired.push(name);
3336
+ break;
3337
+ case "secrets-store-secret":
3338
+ secretsStoreSecrets.push({
3339
+ binding: name,
3340
+ store_id: binding.storeId,
3341
+ secret_name: binding.secretName
3342
+ });
3343
+ break;
3344
+ case "send-email":
3345
+ sendEmail.push(omitUndefined({
3346
+ name,
3347
+ destination_address: binding.destinationAddress,
3348
+ allowed_destination_addresses: binding.allowedDestinationAddresses,
3349
+ allowed_sender_addresses: binding.allowedSenderAddresses,
3350
+ remote: binding.remote
3351
+ }));
3352
+ break;
3353
+ case "stream":
3354
+ result.stream = omitUndefined({
3355
+ binding: name,
3356
+ remote: binding.remote
3357
+ });
3358
+ break;
3359
+ case "text":
3360
+ vars[name] = binding.value;
3361
+ break;
3362
+ case "vectorize":
3363
+ vectorize.push(omitUndefined({
3364
+ binding: name,
3365
+ index_name: binding.name,
3366
+ remote: binding.remote
3367
+ }));
3368
+ break;
3369
+ case "version-metadata":
3370
+ result.version_metadata = { binding: name };
3371
+ break;
3372
+ case "vpc-service":
3373
+ vpcServices.push(omitUndefined({
3374
+ binding: name,
3375
+ service_id: binding.id,
3376
+ remote: binding.remote
3377
+ }));
3378
+ break;
3379
+ case "vpc-network":
3380
+ if (binding.tunnelId !== void 0) vpcNetworks.push(omitUndefined({
3381
+ binding: name,
3382
+ tunnel_id: binding.tunnelId,
3383
+ remote: binding.remote
3384
+ }));
3385
+ else if (binding.networkId !== void 0) vpcNetworks.push(omitUndefined({
3386
+ binding: name,
3387
+ network_id: binding.networkId,
3388
+ remote: binding.remote
3389
+ }));
3390
+ break;
3391
+ case "web-search":
3392
+ result.websearch = omitUndefined({
3393
+ binding: name,
3394
+ remote: binding.remote
3395
+ });
3396
+ break;
3397
+ case "worker":
3398
+ services.push(omitUndefined({
3399
+ binding: name,
3400
+ service: binding.workerName,
3401
+ entrypoint: binding.exportName,
3402
+ props: binding.props,
3403
+ remote: binding.remote
3404
+ }));
3405
+ break;
3406
+ case "worker-loader":
3407
+ workerLoaders.push({ binding: name });
3408
+ break;
3409
+ }
3410
+ }
3411
+ if (kvNamespaces.length) result.kv_namespaces = kvNamespaces;
3412
+ if (d1Databases.length) result.d1_databases = d1Databases;
3413
+ if (r2Buckets.length) result.r2_buckets = r2Buckets;
3414
+ if (vectorize.length) result.vectorize = vectorize;
3415
+ if (mtlsCertificates.length) result.mtls_certificates = mtlsCertificates;
3416
+ if (hyperdrive.length) result.hyperdrive = hyperdrive;
3417
+ if (pipelines.length) result.pipelines = pipelines;
3418
+ if (flagship.length) result.flagship = flagship;
3419
+ if (aiSearch.length) result.ai_search = aiSearch;
3420
+ if (aiSearchNamespaces.length) result.ai_search_namespaces = aiSearchNamespaces;
3421
+ if (agentMemory.length) result.agent_memory = agentMemory;
3422
+ if (analyticsEngineDatasets.length) result.analytics_engine_datasets = analyticsEngineDatasets;
3423
+ if (artifacts.length) result.artifacts = artifacts;
3424
+ if (dispatchNamespaces.length) result.dispatch_namespaces = dispatchNamespaces;
3425
+ if (secretsStoreSecrets.length) result.secrets_store_secrets = secretsStoreSecrets;
3426
+ if (sendEmail.length) result.send_email = sendEmail;
3427
+ if (vpcServices.length) result.vpc_services = vpcServices;
3428
+ if (vpcNetworks.length) result.vpc_networks = vpcNetworks;
3429
+ if (workerLoaders.length) result.worker_loaders = workerLoaders;
3430
+ if (ratelimits.length) result.ratelimits = ratelimits;
3431
+ if (services.length) result.services = services;
3432
+ if (durableObjectBindings.length) result.durable_objects = { bindings: durableObjectBindings };
3433
+ if (workflows.length) result.workflows = workflows;
3434
+ if (queueProducers.length) result.queues = {
3435
+ ...result.queues ?? {},
3436
+ producers: queueProducers
3437
+ };
3438
+ if (logfwdrBindings.length) result.logfwdr = { bindings: logfwdrBindings };
3439
+ if (unsafeBindings.length) result.unsafe = {
3440
+ ...result.unsafe ?? {},
3441
+ bindings: unsafeBindings
3442
+ };
3443
+ if (Object.keys(vars).length) result.vars = vars;
3444
+ if (secretsRequired.length) result.secrets = { required: secretsRequired };
3445
+ if (config.assets !== void 0 || assetsBindingName !== void 0) {
3446
+ const assets = {};
3447
+ if (assetsBindingName !== void 0) assets.binding = assetsBindingName;
3448
+ if (config.assets?.htmlHandling !== void 0) assets.html_handling = config.assets.htmlHandling;
3449
+ if (config.assets?.notFoundHandling !== void 0) assets.not_found_handling = config.assets.notFoundHandling;
3450
+ if (config.assets?.runWorkerFirst !== void 0) assets.run_worker_first = config.assets.runWorkerFirst;
3451
+ result.assets = assets;
3452
+ }
3453
+ }
3454
+ function convertExports(config, result) {
3455
+ const exports$2 = config.exports;
3456
+ if (!exports$2) return;
3457
+ const converted = {};
3458
+ const unknownExports = {};
3459
+ for (const [exportName, value] of Object.entries(exports$2)) {
3460
+ if (value.type === "worker") {
3461
+ converted[exportName] = value;
3462
+ continue;
3463
+ }
3464
+ if (value.type !== "durable-object") {
3465
+ unknownExports[exportName] = value;
3466
+ continue;
3467
+ }
3468
+ switch (value.state) {
3469
+ case void 0:
3470
+ case "created":
3471
+ converted[exportName] = {
3472
+ type: "durable-object",
3473
+ storage: value.storage
3474
+ };
3475
+ break;
3476
+ case "deleted":
3477
+ converted[exportName] = {
3478
+ type: "durable-object",
3479
+ state: "deleted"
3480
+ };
3481
+ break;
3482
+ case "renamed":
3483
+ converted[exportName] = {
3484
+ type: "durable-object",
3485
+ state: "renamed",
3486
+ renamed_to: value.renamedTo
3487
+ };
3488
+ break;
3489
+ case "transferred":
3490
+ converted[exportName] = {
3491
+ type: "durable-object",
3492
+ state: "transferred",
3493
+ transferred_to: value.transferredTo
3494
+ };
3495
+ break;
3496
+ case "expecting-transfer":
3497
+ converted[exportName] = {
3498
+ type: "durable-object",
3499
+ state: "expecting-transfer",
3500
+ storage: value.storage,
3501
+ transfer_from: value.transferFrom
3502
+ };
3503
+ break;
3504
+ }
3505
+ }
3506
+ if (Object.keys(unknownExports).length > 0) throw new UserError("Unknown export types found: " + Object.entries(unknownExports).map(([exportName, { type }]) => `- ${exportName} : ${type}`).join("\n"), { telemetryMessage: "Unknown export types found" });
3507
+ if (Object.keys(converted).length > 0) result.exports = converted;
3508
+ }
3509
+ function convertTriggers(config, result) {
3510
+ const triggers$1 = config.triggers;
3511
+ if (!triggers$1 || triggers$1.length === 0) return;
3512
+ const crons = [];
3513
+ const routes = result.routes ? [...result.routes] : [];
3514
+ const queueConsumers = result.queues?.consumers ? [...result.queues.consumers] : [];
3515
+ for (const trigger of triggers$1) switch (trigger.type) {
3516
+ case "scheduled":
3517
+ crons.push(trigger.schedule);
3518
+ break;
3519
+ case "fetch":
3520
+ if (trigger.zone === void 0) routes.push(trigger.pattern);
3521
+ else if (trigger.zone.includes(".")) routes.push({
3522
+ pattern: trigger.pattern,
3523
+ zone_name: trigger.zone
3524
+ });
3525
+ else routes.push({
3526
+ pattern: trigger.pattern,
3527
+ zone_id: trigger.zone
3528
+ });
3529
+ break;
3530
+ case "queue":
3531
+ queueConsumers.push(omitUndefined({
3532
+ queue: trigger.name,
3533
+ dead_letter_queue: trigger.deadLetterQueue,
3534
+ max_batch_size: trigger.maxBatchSize,
3535
+ max_batch_timeout: trigger.maxBatchTimeout,
3536
+ max_concurrency: trigger.maxConcurrency,
3537
+ max_retries: trigger.maxRetries,
3538
+ retry_delay: trigger.retryDelay,
3539
+ visibility_timeout_ms: trigger.visibilityTimeoutMs
3540
+ }));
3541
+ break;
3542
+ }
3543
+ if (crons.length) result.triggers = { crons };
3544
+ if (routes.length) result.routes = routes;
3545
+ if (queueConsumers.length) result.queues = {
3546
+ ...result.queues ?? {},
3547
+ consumers: queueConsumers
3548
+ };
3549
+ }
3550
+ function convertDomains(config, result) {
3551
+ if (!config.domains || config.domains.length === 0) return;
3552
+ const routes = result.routes ? [...result.routes] : [];
3553
+ for (const domain of config.domains) routes.push({
3554
+ pattern: domain,
3555
+ custom_domain: true
3556
+ });
3557
+ result.routes = routes;
3558
+ }
3559
+ function convertTailConsumers(config, result) {
3560
+ const consumers = config.tailConsumers;
3561
+ if (!consumers || consumers.length === 0) return;
3562
+ const tail = [];
3563
+ const streaming = [];
3564
+ for (const consumer of consumers) if (consumer.streaming) streaming.push({ service: consumer.workerName });
3565
+ else tail.push({ service: consumer.workerName });
3566
+ if (tail.length) result.tail_consumers = tail;
3567
+ if (streaming.length) result.streaming_tail_consumers = streaming;
3568
+ }
3569
+ /**
3570
+ * Strip keys whose value is `undefined`. Returns a new object preserving the
3571
+ * input's value type.
3572
+ */
3573
+ function omitUndefined(obj) {
3574
+ const out = {};
3575
+ for (const [key, value] of Object.entries(obj)) if (value !== void 0) out[key] = value;
3576
+ return out;
3577
+ }
3578
+
3579
+ //#endregion
3580
+ //#region src/load.ts
3581
+ /**
3582
+ * @module
3583
+ *
3584
+ * The no-cache import logic in this file is adapted from `import-without-cache`
3585
+ * by Kevin Deng (https://github.com/sxzz/import-without-cache), published under
3586
+ * the MIT License and Copyright © 2025-PRESENT Kevin Deng.
3587
+ *
3588
+ * See https://github.com/sxzz/import-without-cache for the original code.
3589
+ */
3590
+ const CF_WORKER_SCHEME = "cf-worker:";
3591
+ const CF_WORKER_TYPE = "cf-worker";
3592
+ const CF_ATTR = "cf";
3593
+ const CF_NO_CACHE_VALUE = "no-cache";
3594
+ const CF_NO_CACHE_QUERY_KEY = "cf-no-cache";
3595
+ const RE_NODE_MODULES = /[/\\]node_modules[/\\]/;
3596
+ const depsStore = new AsyncLocalStorage();
3597
+ /**
3598
+ * Dynamically import a worker config file from disk.
3599
+ *
3600
+ * Returns the module's default export, plus the set of file paths
3601
+ * imported during resolution. Callers are responsible for unwrapping
3602
+ * function/promise wrappers around the returned value and validating it
3603
+ * against `InputWorkerSchema`.
3604
+ *
3605
+ * @param configPath Filesystem path to the config file. Relative paths are
3606
+ * resolved against `process.cwd()`.
3607
+ */
3608
+ async function loadConfig(configPath) {
3609
+ registerConfigHooks();
3610
+ const url = pathToFileURL(configPath).href;
3611
+ const dependencies = /* @__PURE__ */ new Set();
3612
+ return {
3613
+ config: (await depsStore.run(dependencies, () => import(url, { with: { [CF_ATTR]: CF_NO_CACHE_VALUE } }))).default,
3614
+ dependencies
3615
+ };
3616
+ }
3617
+ let deregister;
3618
+ /**
3619
+ * Register Node module hooks for loading Worker configs. Idempotent —
3620
+ * repeated calls return the same deregister function.
3621
+ *
3622
+ * - Handles `with { type: "cf-worker" }` import attributes by synthesising an
3623
+ * ES module whose default export is the entrypoint specifier. Relative
3624
+ * specifiers (`./`, `../`) are anchored to the importing module and emitted
3625
+ * as absolute paths; bare specifiers and virtual-module specifiers pass
3626
+ * through unchanged so consumers can apply their own resolution semantics.
3627
+ * The referenced module is NOT loaded, is NOT executed, and is NOT added to
3628
+ * the dependencies set.
3629
+ * - Handles `with { cf: "no-cache" }` import attributes (set internally by
3630
+ * `loadConfig`) by tagging the resolved URL with a unique UUID query
3631
+ * string so Node treats each import as a fresh module. The UUID is
3632
+ * propagated to all transitive imports via the parent URL, ensuring the
3633
+ * entire subgraph is re-evaluated. Imports inside `node_modules` are
3634
+ * skipped (treated as immutable for config purposes).
3635
+ */
3636
+ function registerConfigHooks() {
3637
+ if (deregister) return deregister;
3638
+ if (typeof process !== "undefined" && process.versions.bun) throw new Error("cloudflare.config.ts loading is not supported on Bun. Please use Node.js v22.18.0 or higher.");
3639
+ const registerHooks = nodeModule.registerHooks;
3640
+ if (typeof registerHooks !== "function") throw new Error("cloudflare.config.ts loading requires Node.js v22.18.0 or higher.");
3641
+ const hooks = registerHooks({
3642
+ resolve(specifier, context, nextResolve) {
3643
+ const importAttributes = context.importAttributes ?? {};
3644
+ if (importAttributes.type === CF_WORKER_TYPE) {
3645
+ const entrypoint = (specifier.startsWith("./") || specifier.startsWith("../")) && context.parentURL ? fileURLToPath(new URL(specifier, context.parentURL)) : specifier;
3646
+ return {
3647
+ url: `${CF_WORKER_SCHEME}${encodeURIComponent(entrypoint)}`,
3648
+ format: "module",
3649
+ shortCircuit: true
3650
+ };
3651
+ }
3652
+ const isNoCache = importAttributes[CF_ATTR] === CF_NO_CACHE_VALUE;
3653
+ const resolved = nextResolve(specifier, context);
3654
+ if (RE_NODE_MODULES.test(resolved.url)) return resolved;
3655
+ if (!resolved.url.startsWith("file://")) return resolved;
3656
+ const parentUuid = getParentUUID(context.parentURL);
3657
+ if (!parentUuid && !isNoCache) return resolved;
3658
+ depsStore.getStore()?.add(fileURLToPath(resolved.url));
3659
+ resolved.url = appendUUID(resolved.url, parentUuid || crypto.randomUUID());
3660
+ return resolved;
3661
+ },
3662
+ load(url, context, nextLoad) {
3663
+ if (url.startsWith(CF_WORKER_SCHEME)) {
3664
+ const specifier = decodeURIComponent(url.slice(10));
3665
+ return {
3666
+ format: "module",
3667
+ source: `export default ${JSON.stringify(specifier)};`,
3668
+ shortCircuit: true
3669
+ };
3670
+ }
3671
+ cleanupImportAttributes(context);
3672
+ return nextLoad(url, context);
3673
+ }
3674
+ });
3675
+ deregister = () => {
3676
+ hooks.deregister();
3677
+ deregister = void 0;
3678
+ };
3679
+ return deregister;
3680
+ }
3681
+ function getParentUUID(parentURL) {
3682
+ if (!parentURL) return;
3683
+ return new URL(parentURL).searchParams.get(CF_NO_CACHE_QUERY_KEY) ?? void 0;
3684
+ }
3685
+ function appendUUID(url, uuid) {
3686
+ const parsed = new URL(url);
3687
+ parsed.searchParams.set(CF_NO_CACHE_QUERY_KEY, uuid);
3688
+ return parsed.toString();
3689
+ }
3690
+ function cleanupImportAttributes(context) {
3691
+ if (!context.importAttributes?.[CF_ATTR]) return;
3692
+ const attrs = Object.assign(Object.create(null), context.importAttributes);
3693
+ delete attrs[CF_ATTR];
3694
+ context.importAttributes = attrs;
3695
+ Object.freeze(context.importAttributes);
3696
+ }
3697
+
3698
+ //#endregion
3699
+ export { BUILD_OUTPUT_ROOT, BUILD_OUTPUT_VERSION, InputWorkerSchema, ModuleTypeSchema, OutputWorkerSchema, WORKER_CONFIG_FILENAME, bindings, cleanBuildOutputDir, convertToWranglerConfig, defineWorker, exports$1 as exports, generateTypes, getWorkerAssetsDir, getWorkerBundleDir, getWorkerConfigPath, getWorkersDir, loadConfig, registerConfigHooks, resolveWorkerDefinition, triggers, writeOutputWorkerConfig };