llmz 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/DOCS.md +1 -3
  2. package/dist/_baseForOwn-9MK5s55q.cjs +103 -0
  3. package/dist/_baseForOwn-D8-Dvy2A.js +48 -0
  4. package/dist/_baseIteratee-7Un0_Up5.cjs +2377 -0
  5. package/dist/_baseIteratee-D5Jf7fip.js +2138 -0
  6. package/dist/_getPrototype-ClNRmwmh.cjs +10 -0
  7. package/dist/_getPrototype-DslcqzTw.js +6 -0
  8. package/dist/_overArg-BLtNSzsS.js +153 -0
  9. package/dist/_overArg-ypvt7e2w.cjs +194 -0
  10. package/dist/citations.d.ts +11 -11
  11. package/dist/component-505RuR8N.cjs +73 -0
  12. package/dist/component-BEupuE6R.js +44 -0
  13. package/dist/context.d.ts +8 -8
  14. package/dist/custom-client-CCwAr3HL.cjs +2618 -0
  15. package/dist/custom-client-CGLO1gl2.js +2547 -0
  16. package/dist/dual-modes-RFJ2wqKn.js +2747 -0
  17. package/dist/dual-modes-VSvmn7CC.cjs +2837 -0
  18. package/dist/errors-C962uJdS.cjs +220 -0
  19. package/dist/errors-Cg1G0Awu.js +161 -0
  20. package/dist/execute-CsMxT51Z.cjs +1003 -0
  21. package/dist/execute-Cy0aokFn.js +1001 -0
  22. package/dist/exit-D8q65E62.js +415 -0
  23. package/dist/exit-s7Vuu_cZ.cjs +426 -0
  24. package/dist/index.cjs +1786 -1489
  25. package/dist/index.d.ts +10 -9
  26. package/dist/index.js +1721 -1479
  27. package/dist/index.workerd.js +17509 -16875
  28. package/dist/isEmpty-BRazOx0g.cjs +57 -0
  29. package/dist/isEmpty-C-uBEvAD.js +52 -0
  30. package/dist/isPlainObject-BB1ER-H9.js +51 -0
  31. package/dist/isPlainObject-ChaHUF2F.cjs +56 -0
  32. package/dist/jsx-BQPpLyio.cjs +75 -0
  33. package/dist/jsx-DDGNq80p.js +52 -0
  34. package/dist/jsx.d.ts +2 -2
  35. package/dist/prompts/chat-mode/system.md.d.ts +1 -1
  36. package/dist/prompts/chat-mode/user.md.d.ts +1 -1
  37. package/dist/prompts/worker-mode/system.md.d.ts +1 -1
  38. package/dist/prompts/worker-mode/user.md.d.ts +1 -1
  39. package/dist/quickjs-variant-BYhMBpwU.js +45 -0
  40. package/dist/quickjs-variant-CsIwTVFC.cjs +56 -0
  41. package/dist/quickjs-variant.workerd.d.ts +1 -1
  42. package/dist/result.d.ts +12 -12
  43. package/dist/rolldown-runtime-EAsCxrDo.js +14 -0
  44. package/dist/runtime/interpret-result.d.ts +1 -1
  45. package/dist/snapshots.d.ts +5 -5
  46. package/dist/stack-traces-BIE_5Xwf.js +21 -0
  47. package/dist/stack-traces-ntw_qhoy.cjs +26 -0
  48. package/dist/tool-DOS3cQkd.js +637 -0
  49. package/dist/tool-GH5dsFIz.cjs +648 -0
  50. package/dist/tool.d.ts +3 -3
  51. package/dist/truncator-BRlpGJpc.js +249 -0
  52. package/dist/truncator-r91qJjmi.cjs +272 -0
  53. package/dist/typings-Cg4iFis8.cjs +782 -0
  54. package/dist/typings-o1oM8StG.js +741 -0
  55. package/dist/uniq-BNJ4Jqjc.js +183 -0
  56. package/dist/uniq-C0m757AJ.cjs +200 -0
  57. package/dist/utils-BHvQ0Rup.cjs +1075 -0
  58. package/dist/utils-CXVukcZs.js +950 -0
  59. package/dist/vm/errors.d.ts +2 -2
  60. package/dist/vm-BHo3ENPb.js +3430 -0
  61. package/dist/vm-CXx3RAQt.cjs +3432 -0
  62. package/package.json +7 -7
  63. package/dist/chunk-34GJUS6U.js +0 -3266
  64. package/dist/chunk-3UZKLXAD.cjs +0 -3249
  65. package/dist/chunk-4POZJQXN.js +0 -1530
  66. package/dist/chunk-5WBNTV42.cjs +0 -1530
  67. package/dist/chunk-5ZF6NTYI.cjs +0 -33
  68. package/dist/chunk-72ZWBNZV.js +0 -173
  69. package/dist/chunk-DDSJTR6Q.cjs +0 -257
  70. package/dist/chunk-GDJTKI7J.js +0 -792
  71. package/dist/chunk-GLXADNTR.js +0 -199
  72. package/dist/chunk-GOWPACSK.cjs +0 -199
  73. package/dist/chunk-HB2G32AK.js +0 -257
  74. package/dist/chunk-HC2QZTVT.cjs +0 -3266
  75. package/dist/chunk-HEAQAEFZ.cjs +0 -173
  76. package/dist/chunk-HMMM32RG.cjs +0 -792
  77. package/dist/chunk-I56MPOVG.cjs +0 -62
  78. package/dist/chunk-KIN7Y247.cjs +0 -32
  79. package/dist/chunk-KTDBAJBB.cjs +0 -1685
  80. package/dist/chunk-KWQTYXAT.js +0 -62
  81. package/dist/chunk-LOX7GOR6.js +0 -1685
  82. package/dist/chunk-PK72FAKD.cjs +0 -175
  83. package/dist/chunk-PZE6PIPG.cjs +0 -621
  84. package/dist/chunk-RGUG3UMF.cjs +0 -26
  85. package/dist/chunk-TDALRNGL.js +0 -621
  86. package/dist/chunk-UGHFNCPD.js +0 -26
  87. package/dist/chunk-WSVDMGMR.js +0 -175
  88. package/dist/chunk-XTEHT2TK.js +0 -33
  89. package/dist/chunk-YEAWWJSJ.js +0 -32
  90. package/dist/chunk-YRS7KRKP.js +0 -3249
  91. package/dist/component-2NYFY6CW.cjs +0 -14
  92. package/dist/component-ASNZHQUR.js +0 -14
  93. package/dist/dual-modes-S5TJ5JVJ.js +0 -10
  94. package/dist/dual-modes-TCMWBZIH.cjs +0 -10
  95. package/dist/execute-FF7D46TY.js +0 -1109
  96. package/dist/execute-IK6O4SU2.cjs +0 -1109
  97. package/dist/exit-MX56VN2C.cjs +0 -8
  98. package/dist/exit-UQ3EUX5D.js +0 -8
  99. package/dist/jsx-DDZ63UUF.js +0 -13
  100. package/dist/jsx-ULPWX5TW.cjs +0 -13
  101. package/dist/tool-KD7FL45V.js +0 -11
  102. package/dist/tool-VE2YHIY2.cjs +0 -11
  103. package/dist/truncator-73RCL52Y.js +0 -12
  104. package/dist/truncator-FZNLYSDL.cjs +0 -12
  105. package/dist/typings-E2RROCLT.js +0 -10
  106. package/dist/typings-LQOBZXSO.cjs +0 -10
  107. package/dist/utils-IATCUNKF.js +0 -43
  108. package/dist/utils-ITB4NEL7.cjs +0 -43
  109. package/dist/vm-6D3IIIU7.cjs +0 -12
  110. package/dist/vm-QO5FSGPN.js +0 -12
@@ -0,0 +1,3430 @@
1
+ import { t as __commonJSMin } from "./rolldown-runtime-EAsCxrDo.js";
2
+ import { B as isSymbol, I as isFunction, M as baseAssignValue, t as baseIteratee } from "./_baseIteratee-D5Jf7fip.js";
3
+ import { t as baseForOwn } from "./_baseForOwn-D8-Dvy2A.js";
4
+ import { t as cleanStackTrace } from "./stack-traces-BIE_5Xwf.js";
5
+ import { a as InvalidCodeError, c as SnapshotSignal, n as CodeExecutionError, s as Signals, u as VMSignal } from "./errors-Cg1G0Awu.js";
6
+ import { n as getQuickJSVariant } from "./quickjs-variant-BYhMBpwU.js";
7
+ import MagicString from "magic-string";
8
+ import { parse } from "acorn";
9
+ import { newQuickJSWASMModuleFromVariant, shouldInterruptAfterDeadline } from "quickjs-emscripten-core";
10
+ //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGt.js
11
+ /**
12
+ * The base implementation of `_.gt` which doesn't coerce arguments.
13
+ *
14
+ * @private
15
+ * @param {*} value The value to compare.
16
+ * @param {*} other The other value to compare.
17
+ * @returns {boolean} Returns `true` if `value` is greater than `other`,
18
+ * else `false`.
19
+ */
20
+ function baseGt(value, other) {
21
+ return value > other;
22
+ }
23
+ //#endregion
24
+ //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/mapValues.js
25
+ /**
26
+ * Creates an object with the same keys as `object` and values generated
27
+ * by running each own enumerable string keyed property of `object` thru
28
+ * `iteratee`. The iteratee is invoked with three arguments:
29
+ * (value, key, object).
30
+ *
31
+ * @static
32
+ * @memberOf _
33
+ * @since 2.4.0
34
+ * @category Object
35
+ * @param {Object} object The object to iterate over.
36
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
37
+ * @returns {Object} Returns the new mapped object.
38
+ * @see _.mapKeys
39
+ * @example
40
+ *
41
+ * var users = {
42
+ * 'fred': { 'user': 'fred', 'age': 40 },
43
+ * 'pebbles': { 'user': 'pebbles', 'age': 1 }
44
+ * };
45
+ *
46
+ * _.mapValues(users, function(o) { return o.age; });
47
+ * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
48
+ *
49
+ * // The `_.property` iteratee shorthand.
50
+ * _.mapValues(users, 'age');
51
+ * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
52
+ */
53
+ function mapValues(object, iteratee) {
54
+ var result = {};
55
+ iteratee = baseIteratee(iteratee, 3);
56
+ baseForOwn(object, function(value, key, object) {
57
+ baseAssignValue(result, key, iteratee(value, key, object));
58
+ });
59
+ return result;
60
+ }
61
+ //#endregion
62
+ //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseExtremum.js
63
+ /**
64
+ * The base implementation of methods like `_.max` and `_.min` which accepts a
65
+ * `comparator` to determine the extremum value.
66
+ *
67
+ * @private
68
+ * @param {Array} array The array to iterate over.
69
+ * @param {Function} iteratee The iteratee invoked per iteration.
70
+ * @param {Function} comparator The comparator used to compare values.
71
+ * @returns {*} Returns the extremum value.
72
+ */
73
+ function baseExtremum(array, iteratee, comparator) {
74
+ var index = -1, length = array.length;
75
+ while (++index < length) {
76
+ var value = array[index], current = iteratee(value);
77
+ if (current != null && (computed === void 0 ? current === current && !isSymbol(current) : comparator(current, computed))) var computed = current, result = value;
78
+ }
79
+ return result;
80
+ }
81
+ //#endregion
82
+ //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/maxBy.js
83
+ /**
84
+ * This method is like `_.max` except that it accepts `iteratee` which is
85
+ * invoked for each element in `array` to generate the criterion by which
86
+ * the value is ranked. The iteratee is invoked with one argument: (value).
87
+ *
88
+ * @static
89
+ * @memberOf _
90
+ * @since 4.0.0
91
+ * @category Math
92
+ * @param {Array} array The array to iterate over.
93
+ * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
94
+ * @returns {*} Returns the maximum value.
95
+ * @example
96
+ *
97
+ * var objects = [{ 'n': 1 }, { 'n': 2 }];
98
+ *
99
+ * _.maxBy(objects, function(o) { return o.n; });
100
+ * // => { 'n': 2 }
101
+ *
102
+ * // The `_.property` iteratee shorthand.
103
+ * _.maxBy(objects, 'n');
104
+ * // => { 'n': 2 }
105
+ */
106
+ function maxBy(array, iteratee) {
107
+ return array && array.length ? baseExtremum(array, baseIteratee(iteratee, 2), baseGt) : void 0;
108
+ }
109
+ //#endregion
110
+ //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/base64.js
111
+ var require_base64 = /* @__PURE__ */ __commonJSMin(((exports) => {
112
+ var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
113
+ /**
114
+ * Encode an integer in the range of 0 to 63 to a single base 64 digit.
115
+ */
116
+ exports.encode = function(number) {
117
+ if (0 <= number && number < intToCharMap.length) return intToCharMap[number];
118
+ throw new TypeError("Must be between 0 and 63: " + number);
119
+ };
120
+ /**
121
+ * Decode a single base 64 character code digit to an integer. Returns -1 on
122
+ * failure.
123
+ */
124
+ exports.decode = function(charCode) {
125
+ var bigA = 65;
126
+ var bigZ = 90;
127
+ var littleA = 97;
128
+ var littleZ = 122;
129
+ var zero = 48;
130
+ var nine = 57;
131
+ var plus = 43;
132
+ var slash = 47;
133
+ var littleOffset = 26;
134
+ var numberOffset = 52;
135
+ if (bigA <= charCode && charCode <= bigZ) return charCode - bigA;
136
+ if (littleA <= charCode && charCode <= littleZ) return charCode - littleA + littleOffset;
137
+ if (zero <= charCode && charCode <= nine) return charCode - zero + numberOffset;
138
+ if (charCode == plus) return 62;
139
+ if (charCode == slash) return 63;
140
+ return -1;
141
+ };
142
+ }));
143
+ //#endregion
144
+ //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/base64-vlq.js
145
+ var require_base64_vlq = /* @__PURE__ */ __commonJSMin(((exports) => {
146
+ var base64 = require_base64();
147
+ var VLQ_BASE_SHIFT = 5;
148
+ var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
149
+ var VLQ_BASE_MASK = VLQ_BASE - 1;
150
+ var VLQ_CONTINUATION_BIT = VLQ_BASE;
151
+ /**
152
+ * Converts from a two-complement value to a value where the sign bit is
153
+ * placed in the least significant bit. For example, as decimals:
154
+ * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
155
+ * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
156
+ */
157
+ function toVLQSigned(aValue) {
158
+ return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
159
+ }
160
+ /**
161
+ * Converts to a two-complement value from a value where the sign bit is
162
+ * placed in the least significant bit. For example, as decimals:
163
+ * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
164
+ * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
165
+ */
166
+ function fromVLQSigned(aValue) {
167
+ var isNegative = (aValue & 1) === 1;
168
+ var shifted = aValue >> 1;
169
+ return isNegative ? -shifted : shifted;
170
+ }
171
+ /**
172
+ * Returns the base 64 VLQ encoded value.
173
+ */
174
+ exports.encode = function base64VLQ_encode(aValue) {
175
+ var encoded = "";
176
+ var digit;
177
+ var vlq = toVLQSigned(aValue);
178
+ do {
179
+ digit = vlq & VLQ_BASE_MASK;
180
+ vlq >>>= VLQ_BASE_SHIFT;
181
+ if (vlq > 0) digit |= VLQ_CONTINUATION_BIT;
182
+ encoded += base64.encode(digit);
183
+ } while (vlq > 0);
184
+ return encoded;
185
+ };
186
+ /**
187
+ * Decodes the next base 64 VLQ value from the given string and returns the
188
+ * value and the rest of the string via the out parameter.
189
+ */
190
+ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
191
+ var strLen = aStr.length;
192
+ var result = 0;
193
+ var shift = 0;
194
+ var continuation, digit;
195
+ do {
196
+ if (aIndex >= strLen) throw new Error("Expected more digits in base 64 VLQ value.");
197
+ digit = base64.decode(aStr.charCodeAt(aIndex++));
198
+ if (digit === -1) throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
199
+ continuation = !!(digit & VLQ_CONTINUATION_BIT);
200
+ digit &= VLQ_BASE_MASK;
201
+ result = result + (digit << shift);
202
+ shift += VLQ_BASE_SHIFT;
203
+ } while (continuation);
204
+ aOutParam.value = fromVLQSigned(result);
205
+ aOutParam.rest = aIndex;
206
+ };
207
+ }));
208
+ //#endregion
209
+ //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/util.js
210
+ var require_util = /* @__PURE__ */ __commonJSMin(((exports) => {
211
+ /**
212
+ * This is a helper function for getting values from parameter/options
213
+ * objects.
214
+ *
215
+ * @param args The object we are extracting values from
216
+ * @param name The name of the property we are getting.
217
+ * @param defaultValue An optional value to return if the property is missing
218
+ * from the object. If this is not specified and the property is missing, an
219
+ * error will be thrown.
220
+ */
221
+ function getArg(aArgs, aName, aDefaultValue) {
222
+ if (aName in aArgs) return aArgs[aName];
223
+ else if (arguments.length === 3) return aDefaultValue;
224
+ else throw new Error("\"" + aName + "\" is a required argument.");
225
+ }
226
+ exports.getArg = getArg;
227
+ var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
228
+ var dataUrlRegexp = /^data:.+\,.+$/;
229
+ function urlParse(aUrl) {
230
+ var match = aUrl.match(urlRegexp);
231
+ if (!match) return null;
232
+ return {
233
+ scheme: match[1],
234
+ auth: match[2],
235
+ host: match[3],
236
+ port: match[4],
237
+ path: match[5]
238
+ };
239
+ }
240
+ exports.urlParse = urlParse;
241
+ function urlGenerate(aParsedUrl) {
242
+ var url = "";
243
+ if (aParsedUrl.scheme) url += aParsedUrl.scheme + ":";
244
+ url += "//";
245
+ if (aParsedUrl.auth) url += aParsedUrl.auth + "@";
246
+ if (aParsedUrl.host) url += aParsedUrl.host;
247
+ if (aParsedUrl.port) url += ":" + aParsedUrl.port;
248
+ if (aParsedUrl.path) url += aParsedUrl.path;
249
+ return url;
250
+ }
251
+ exports.urlGenerate = urlGenerate;
252
+ var MAX_CACHED_INPUTS = 32;
253
+ /**
254
+ * Takes some function `f(input) -> result` and returns a memoized version of
255
+ * `f`.
256
+ *
257
+ * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
258
+ * memoization is a dumb-simple, linear least-recently-used cache.
259
+ */
260
+ function lruMemoize(f) {
261
+ var cache = [];
262
+ return function(input) {
263
+ for (var i = 0; i < cache.length; i++) if (cache[i].input === input) {
264
+ var temp = cache[0];
265
+ cache[0] = cache[i];
266
+ cache[i] = temp;
267
+ return cache[0].result;
268
+ }
269
+ var result = f(input);
270
+ cache.unshift({
271
+ input,
272
+ result
273
+ });
274
+ if (cache.length > MAX_CACHED_INPUTS) cache.pop();
275
+ return result;
276
+ };
277
+ }
278
+ /**
279
+ * Normalizes a path, or the path portion of a URL:
280
+ *
281
+ * - Replaces consecutive slashes with one slash.
282
+ * - Removes unnecessary '.' parts.
283
+ * - Removes unnecessary '<dir>/..' parts.
284
+ *
285
+ * Based on code in the Node.js 'path' core module.
286
+ *
287
+ * @param aPath The path or url to normalize.
288
+ */
289
+ var normalize = lruMemoize(function normalize(aPath) {
290
+ var path = aPath;
291
+ var url = urlParse(aPath);
292
+ if (url) {
293
+ if (!url.path) return aPath;
294
+ path = url.path;
295
+ }
296
+ var isAbsolute = exports.isAbsolute(path);
297
+ var parts = [];
298
+ var start = 0;
299
+ var i = 0;
300
+ while (true) {
301
+ start = i;
302
+ i = path.indexOf("/", start);
303
+ if (i === -1) {
304
+ parts.push(path.slice(start));
305
+ break;
306
+ } else {
307
+ parts.push(path.slice(start, i));
308
+ while (i < path.length && path[i] === "/") i++;
309
+ }
310
+ }
311
+ for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
312
+ part = parts[i];
313
+ if (part === ".") parts.splice(i, 1);
314
+ else if (part === "..") up++;
315
+ else if (up > 0) if (part === "") {
316
+ parts.splice(i + 1, up);
317
+ up = 0;
318
+ } else {
319
+ parts.splice(i, 2);
320
+ up--;
321
+ }
322
+ }
323
+ path = parts.join("/");
324
+ if (path === "") path = isAbsolute ? "/" : ".";
325
+ if (url) {
326
+ url.path = path;
327
+ return urlGenerate(url);
328
+ }
329
+ return path;
330
+ });
331
+ exports.normalize = normalize;
332
+ /**
333
+ * Joins two paths/URLs.
334
+ *
335
+ * @param aRoot The root path or URL.
336
+ * @param aPath The path or URL to be joined with the root.
337
+ *
338
+ * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
339
+ * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
340
+ * first.
341
+ * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
342
+ * is updated with the result and aRoot is returned. Otherwise the result
343
+ * is returned.
344
+ * - If aPath is absolute, the result is aPath.
345
+ * - Otherwise the two paths are joined with a slash.
346
+ * - Joining for example 'http://' and 'www.example.com' is also supported.
347
+ */
348
+ function join(aRoot, aPath) {
349
+ if (aRoot === "") aRoot = ".";
350
+ if (aPath === "") aPath = ".";
351
+ var aPathUrl = urlParse(aPath);
352
+ var aRootUrl = urlParse(aRoot);
353
+ if (aRootUrl) aRoot = aRootUrl.path || "/";
354
+ if (aPathUrl && !aPathUrl.scheme) {
355
+ if (aRootUrl) aPathUrl.scheme = aRootUrl.scheme;
356
+ return urlGenerate(aPathUrl);
357
+ }
358
+ if (aPathUrl || aPath.match(dataUrlRegexp)) return aPath;
359
+ if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
360
+ aRootUrl.host = aPath;
361
+ return urlGenerate(aRootUrl);
362
+ }
363
+ var joined = aPath.charAt(0) === "/" ? aPath : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath);
364
+ if (aRootUrl) {
365
+ aRootUrl.path = joined;
366
+ return urlGenerate(aRootUrl);
367
+ }
368
+ return joined;
369
+ }
370
+ exports.join = join;
371
+ exports.isAbsolute = function(aPath) {
372
+ return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
373
+ };
374
+ /**
375
+ * Make a path relative to a URL or another path.
376
+ *
377
+ * @param aRoot The root path or URL.
378
+ * @param aPath The path or URL to be made relative to aRoot.
379
+ */
380
+ function relative(aRoot, aPath) {
381
+ if (aRoot === "") aRoot = ".";
382
+ aRoot = aRoot.replace(/\/$/, "");
383
+ var level = 0;
384
+ while (aPath.indexOf(aRoot + "/") !== 0) {
385
+ var index = aRoot.lastIndexOf("/");
386
+ if (index < 0) return aPath;
387
+ aRoot = aRoot.slice(0, index);
388
+ if (aRoot.match(/^([^\/]+:\/)?\/*$/)) return aPath;
389
+ ++level;
390
+ }
391
+ return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
392
+ }
393
+ exports.relative = relative;
394
+ var supportsNullProto = function() {
395
+ return !("__proto__" in Object.create(null));
396
+ }();
397
+ function identity(s) {
398
+ return s;
399
+ }
400
+ /**
401
+ * Because behavior goes wacky when you set `__proto__` on objects, we
402
+ * have to prefix all the strings in our set with an arbitrary character.
403
+ *
404
+ * See https://github.com/mozilla/source-map/pull/31 and
405
+ * https://github.com/mozilla/source-map/issues/30
406
+ *
407
+ * @param String aStr
408
+ */
409
+ function toSetString(aStr) {
410
+ if (isProtoString(aStr)) return "$" + aStr;
411
+ return aStr;
412
+ }
413
+ exports.toSetString = supportsNullProto ? identity : toSetString;
414
+ function fromSetString(aStr) {
415
+ if (isProtoString(aStr)) return aStr.slice(1);
416
+ return aStr;
417
+ }
418
+ exports.fromSetString = supportsNullProto ? identity : fromSetString;
419
+ function isProtoString(s) {
420
+ if (!s) return false;
421
+ var length = s.length;
422
+ if (length < 9) return false;
423
+ if (s.charCodeAt(length - 1) !== 95 || s.charCodeAt(length - 2) !== 95 || s.charCodeAt(length - 3) !== 111 || s.charCodeAt(length - 4) !== 116 || s.charCodeAt(length - 5) !== 111 || s.charCodeAt(length - 6) !== 114 || s.charCodeAt(length - 7) !== 112 || s.charCodeAt(length - 8) !== 95 || s.charCodeAt(length - 9) !== 95) return false;
424
+ for (var i = length - 10; i >= 0; i--) if (s.charCodeAt(i) !== 36) return false;
425
+ return true;
426
+ }
427
+ /**
428
+ * Comparator between two mappings where the original positions are compared.
429
+ *
430
+ * Optionally pass in `true` as `onlyCompareGenerated` to consider two
431
+ * mappings with the same original source/line/column, but different generated
432
+ * line and column the same. Useful when searching for a mapping with a
433
+ * stubbed out mapping.
434
+ */
435
+ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
436
+ var cmp = strcmp(mappingA.source, mappingB.source);
437
+ if (cmp !== 0) return cmp;
438
+ cmp = mappingA.originalLine - mappingB.originalLine;
439
+ if (cmp !== 0) return cmp;
440
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
441
+ if (cmp !== 0 || onlyCompareOriginal) return cmp;
442
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
443
+ if (cmp !== 0) return cmp;
444
+ cmp = mappingA.generatedLine - mappingB.generatedLine;
445
+ if (cmp !== 0) return cmp;
446
+ return strcmp(mappingA.name, mappingB.name);
447
+ }
448
+ exports.compareByOriginalPositions = compareByOriginalPositions;
449
+ function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
450
+ var cmp = mappingA.originalLine - mappingB.originalLine;
451
+ if (cmp !== 0) return cmp;
452
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
453
+ if (cmp !== 0 || onlyCompareOriginal) return cmp;
454
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
455
+ if (cmp !== 0) return cmp;
456
+ cmp = mappingA.generatedLine - mappingB.generatedLine;
457
+ if (cmp !== 0) return cmp;
458
+ return strcmp(mappingA.name, mappingB.name);
459
+ }
460
+ exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
461
+ /**
462
+ * Comparator between two mappings with deflated source and name indices where
463
+ * the generated positions are compared.
464
+ *
465
+ * Optionally pass in `true` as `onlyCompareGenerated` to consider two
466
+ * mappings with the same generated line and column, but different
467
+ * source/name/original line and column the same. Useful when searching for a
468
+ * mapping with a stubbed out mapping.
469
+ */
470
+ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
471
+ var cmp = mappingA.generatedLine - mappingB.generatedLine;
472
+ if (cmp !== 0) return cmp;
473
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
474
+ if (cmp !== 0 || onlyCompareGenerated) return cmp;
475
+ cmp = strcmp(mappingA.source, mappingB.source);
476
+ if (cmp !== 0) return cmp;
477
+ cmp = mappingA.originalLine - mappingB.originalLine;
478
+ if (cmp !== 0) return cmp;
479
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
480
+ if (cmp !== 0) return cmp;
481
+ return strcmp(mappingA.name, mappingB.name);
482
+ }
483
+ exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
484
+ function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
485
+ var cmp = mappingA.generatedColumn - mappingB.generatedColumn;
486
+ if (cmp !== 0 || onlyCompareGenerated) return cmp;
487
+ cmp = strcmp(mappingA.source, mappingB.source);
488
+ if (cmp !== 0) return cmp;
489
+ cmp = mappingA.originalLine - mappingB.originalLine;
490
+ if (cmp !== 0) return cmp;
491
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
492
+ if (cmp !== 0) return cmp;
493
+ return strcmp(mappingA.name, mappingB.name);
494
+ }
495
+ exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
496
+ function strcmp(aStr1, aStr2) {
497
+ if (aStr1 === aStr2) return 0;
498
+ if (aStr1 === null) return 1;
499
+ if (aStr2 === null) return -1;
500
+ if (aStr1 > aStr2) return 1;
501
+ return -1;
502
+ }
503
+ /**
504
+ * Comparator between two mappings with inflated source and name strings where
505
+ * the generated positions are compared.
506
+ */
507
+ function compareByGeneratedPositionsInflated(mappingA, mappingB) {
508
+ var cmp = mappingA.generatedLine - mappingB.generatedLine;
509
+ if (cmp !== 0) return cmp;
510
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
511
+ if (cmp !== 0) return cmp;
512
+ cmp = strcmp(mappingA.source, mappingB.source);
513
+ if (cmp !== 0) return cmp;
514
+ cmp = mappingA.originalLine - mappingB.originalLine;
515
+ if (cmp !== 0) return cmp;
516
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
517
+ if (cmp !== 0) return cmp;
518
+ return strcmp(mappingA.name, mappingB.name);
519
+ }
520
+ exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
521
+ /**
522
+ * Strip any JSON XSSI avoidance prefix from the string (as documented
523
+ * in the source maps specification), and then parse the string as
524
+ * JSON.
525
+ */
526
+ function parseSourceMapInput(str) {
527
+ return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
528
+ }
529
+ exports.parseSourceMapInput = parseSourceMapInput;
530
+ /**
531
+ * Compute the URL of a source given the the source root, the source's
532
+ * URL, and the source map's URL.
533
+ */
534
+ function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
535
+ sourceURL = sourceURL || "";
536
+ if (sourceRoot) {
537
+ if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") sourceRoot += "/";
538
+ sourceURL = sourceRoot + sourceURL;
539
+ }
540
+ if (sourceMapURL) {
541
+ var parsed = urlParse(sourceMapURL);
542
+ if (!parsed) throw new Error("sourceMapURL could not be parsed");
543
+ if (parsed.path) {
544
+ var index = parsed.path.lastIndexOf("/");
545
+ if (index >= 0) parsed.path = parsed.path.substring(0, index + 1);
546
+ }
547
+ sourceURL = join(urlGenerate(parsed), sourceURL);
548
+ }
549
+ return normalize(sourceURL);
550
+ }
551
+ exports.computeSourceURL = computeSourceURL;
552
+ }));
553
+ //#endregion
554
+ //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/array-set.js
555
+ var require_array_set = /* @__PURE__ */ __commonJSMin(((exports) => {
556
+ var util = require_util();
557
+ var has = Object.prototype.hasOwnProperty;
558
+ var hasNativeMap = typeof Map !== "undefined";
559
+ /**
560
+ * A data structure which is a combination of an array and a set. Adding a new
561
+ * member is O(1), testing for membership is O(1), and finding the index of an
562
+ * element is O(1). Removing elements from the set is not supported. Only
563
+ * strings are supported for membership.
564
+ */
565
+ function ArraySet() {
566
+ this._array = [];
567
+ this._set = hasNativeMap ? /* @__PURE__ */ new Map() : Object.create(null);
568
+ }
569
+ /**
570
+ * Static method for creating ArraySet instances from an existing array.
571
+ */
572
+ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
573
+ var set = new ArraySet();
574
+ for (var i = 0, len = aArray.length; i < len; i++) set.add(aArray[i], aAllowDuplicates);
575
+ return set;
576
+ };
577
+ /**
578
+ * Return how many unique items are in this ArraySet. If duplicates have been
579
+ * added, than those do not count towards the size.
580
+ *
581
+ * @returns Number
582
+ */
583
+ ArraySet.prototype.size = function ArraySet_size() {
584
+ return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
585
+ };
586
+ /**
587
+ * Add the given string to this set.
588
+ *
589
+ * @param String aStr
590
+ */
591
+ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
592
+ var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
593
+ var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
594
+ var idx = this._array.length;
595
+ if (!isDuplicate || aAllowDuplicates) this._array.push(aStr);
596
+ if (!isDuplicate) if (hasNativeMap) this._set.set(aStr, idx);
597
+ else this._set[sStr] = idx;
598
+ };
599
+ /**
600
+ * Is the given string a member of this set?
601
+ *
602
+ * @param String aStr
603
+ */
604
+ ArraySet.prototype.has = function ArraySet_has(aStr) {
605
+ if (hasNativeMap) return this._set.has(aStr);
606
+ else {
607
+ var sStr = util.toSetString(aStr);
608
+ return has.call(this._set, sStr);
609
+ }
610
+ };
611
+ /**
612
+ * What is the index of the given string in the array?
613
+ *
614
+ * @param String aStr
615
+ */
616
+ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
617
+ if (hasNativeMap) {
618
+ var idx = this._set.get(aStr);
619
+ if (idx >= 0) return idx;
620
+ } else {
621
+ var sStr = util.toSetString(aStr);
622
+ if (has.call(this._set, sStr)) return this._set[sStr];
623
+ }
624
+ throw new Error("\"" + aStr + "\" is not in the set.");
625
+ };
626
+ /**
627
+ * What is the element at the given index?
628
+ *
629
+ * @param Number aIdx
630
+ */
631
+ ArraySet.prototype.at = function ArraySet_at(aIdx) {
632
+ if (aIdx >= 0 && aIdx < this._array.length) return this._array[aIdx];
633
+ throw new Error("No element indexed by " + aIdx);
634
+ };
635
+ /**
636
+ * Returns the array representation of this set (which has the proper indices
637
+ * indicated by indexOf). Note that this is a copy of the internal array used
638
+ * for storing the members so that no one can mess with internal state.
639
+ */
640
+ ArraySet.prototype.toArray = function ArraySet_toArray() {
641
+ return this._array.slice();
642
+ };
643
+ exports.ArraySet = ArraySet;
644
+ }));
645
+ //#endregion
646
+ //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/mapping-list.js
647
+ var require_mapping_list = /* @__PURE__ */ __commonJSMin(((exports) => {
648
+ var util = require_util();
649
+ /**
650
+ * Determine whether mappingB is after mappingA with respect to generated
651
+ * position.
652
+ */
653
+ function generatedPositionAfter(mappingA, mappingB) {
654
+ var lineA = mappingA.generatedLine;
655
+ var lineB = mappingB.generatedLine;
656
+ var columnA = mappingA.generatedColumn;
657
+ var columnB = mappingB.generatedColumn;
658
+ return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
659
+ }
660
+ /**
661
+ * A data structure to provide a sorted view of accumulated mappings in a
662
+ * performance conscious manner. It trades a neglibable overhead in general
663
+ * case for a large speedup in case of mappings being added in order.
664
+ */
665
+ function MappingList() {
666
+ this._array = [];
667
+ this._sorted = true;
668
+ this._last = {
669
+ generatedLine: -1,
670
+ generatedColumn: 0
671
+ };
672
+ }
673
+ /**
674
+ * Iterate through internal items. This method takes the same arguments that
675
+ * `Array.prototype.forEach` takes.
676
+ *
677
+ * NOTE: The order of the mappings is NOT guaranteed.
678
+ */
679
+ MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) {
680
+ this._array.forEach(aCallback, aThisArg);
681
+ };
682
+ /**
683
+ * Add the given source mapping.
684
+ *
685
+ * @param Object aMapping
686
+ */
687
+ MappingList.prototype.add = function MappingList_add(aMapping) {
688
+ if (generatedPositionAfter(this._last, aMapping)) {
689
+ this._last = aMapping;
690
+ this._array.push(aMapping);
691
+ } else {
692
+ this._sorted = false;
693
+ this._array.push(aMapping);
694
+ }
695
+ };
696
+ /**
697
+ * Returns the flat, sorted array of mappings. The mappings are sorted by
698
+ * generated position.
699
+ *
700
+ * WARNING: This method returns internal data without copying, for
701
+ * performance. The return value must NOT be mutated, and should be treated as
702
+ * an immutable borrow. If you want to take ownership, you must make your own
703
+ * copy.
704
+ */
705
+ MappingList.prototype.toArray = function MappingList_toArray() {
706
+ if (!this._sorted) {
707
+ this._array.sort(util.compareByGeneratedPositionsInflated);
708
+ this._sorted = true;
709
+ }
710
+ return this._array;
711
+ };
712
+ exports.MappingList = MappingList;
713
+ }));
714
+ //#endregion
715
+ //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/source-map-generator.js
716
+ var require_source_map_generator = /* @__PURE__ */ __commonJSMin(((exports) => {
717
+ var base64VLQ = require_base64_vlq();
718
+ var util = require_util();
719
+ var ArraySet = require_array_set().ArraySet;
720
+ var MappingList = require_mapping_list().MappingList;
721
+ /**
722
+ * An instance of the SourceMapGenerator represents a source map which is
723
+ * being built incrementally. You may pass an object with the following
724
+ * properties:
725
+ *
726
+ * - file: The filename of the generated source.
727
+ * - sourceRoot: A root for all relative URLs in this source map.
728
+ */
729
+ function SourceMapGenerator(aArgs) {
730
+ if (!aArgs) aArgs = {};
731
+ this._file = util.getArg(aArgs, "file", null);
732
+ this._sourceRoot = util.getArg(aArgs, "sourceRoot", null);
733
+ this._skipValidation = util.getArg(aArgs, "skipValidation", false);
734
+ this._ignoreInvalidMapping = util.getArg(aArgs, "ignoreInvalidMapping", false);
735
+ this._sources = new ArraySet();
736
+ this._names = new ArraySet();
737
+ this._mappings = new MappingList();
738
+ this._sourcesContents = null;
739
+ }
740
+ SourceMapGenerator.prototype._version = 3;
741
+ /**
742
+ * Creates a new SourceMapGenerator based on a SourceMapConsumer
743
+ *
744
+ * @param aSourceMapConsumer The SourceMap.
745
+ */
746
+ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) {
747
+ var sourceRoot = aSourceMapConsumer.sourceRoot;
748
+ var generator = new SourceMapGenerator(Object.assign(generatorOps || {}, {
749
+ file: aSourceMapConsumer.file,
750
+ sourceRoot
751
+ }));
752
+ aSourceMapConsumer.eachMapping(function(mapping) {
753
+ var newMapping = { generated: {
754
+ line: mapping.generatedLine,
755
+ column: mapping.generatedColumn
756
+ } };
757
+ if (mapping.source != null) {
758
+ newMapping.source = mapping.source;
759
+ if (sourceRoot != null) newMapping.source = util.relative(sourceRoot, newMapping.source);
760
+ newMapping.original = {
761
+ line: mapping.originalLine,
762
+ column: mapping.originalColumn
763
+ };
764
+ if (mapping.name != null) newMapping.name = mapping.name;
765
+ }
766
+ generator.addMapping(newMapping);
767
+ });
768
+ aSourceMapConsumer.sources.forEach(function(sourceFile) {
769
+ var sourceRelative = sourceFile;
770
+ if (sourceRoot !== null) sourceRelative = util.relative(sourceRoot, sourceFile);
771
+ if (!generator._sources.has(sourceRelative)) generator._sources.add(sourceRelative);
772
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
773
+ if (content != null) generator.setSourceContent(sourceFile, content);
774
+ });
775
+ return generator;
776
+ };
777
+ /**
778
+ * Add a single mapping from original source line and column to the generated
779
+ * source's line and column for this source map being created. The mapping
780
+ * object should have the following properties:
781
+ *
782
+ * - generated: An object with the generated line and column positions.
783
+ * - original: An object with the original line and column positions.
784
+ * - source: The original source file (relative to the sourceRoot).
785
+ * - name: An optional original token name for this mapping.
786
+ */
787
+ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) {
788
+ var generated = util.getArg(aArgs, "generated");
789
+ var original = util.getArg(aArgs, "original", null);
790
+ var source = util.getArg(aArgs, "source", null);
791
+ var name = util.getArg(aArgs, "name", null);
792
+ if (!this._skipValidation) {
793
+ if (this._validateMapping(generated, original, source, name) === false) return;
794
+ }
795
+ if (source != null) {
796
+ source = String(source);
797
+ if (!this._sources.has(source)) this._sources.add(source);
798
+ }
799
+ if (name != null) {
800
+ name = String(name);
801
+ if (!this._names.has(name)) this._names.add(name);
802
+ }
803
+ this._mappings.add({
804
+ generatedLine: generated.line,
805
+ generatedColumn: generated.column,
806
+ originalLine: original != null && original.line,
807
+ originalColumn: original != null && original.column,
808
+ source,
809
+ name
810
+ });
811
+ };
812
+ /**
813
+ * Set the source content for a source file.
814
+ */
815
+ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
816
+ var source = aSourceFile;
817
+ if (this._sourceRoot != null) source = util.relative(this._sourceRoot, source);
818
+ if (aSourceContent != null) {
819
+ if (!this._sourcesContents) this._sourcesContents = Object.create(null);
820
+ this._sourcesContents[util.toSetString(source)] = aSourceContent;
821
+ } else if (this._sourcesContents) {
822
+ delete this._sourcesContents[util.toSetString(source)];
823
+ if (Object.keys(this._sourcesContents).length === 0) this._sourcesContents = null;
824
+ }
825
+ };
826
+ /**
827
+ * Applies the mappings of a sub-source-map for a specific source file to the
828
+ * source map being generated. Each mapping to the supplied source file is
829
+ * rewritten using the supplied source map. Note: The resolution for the
830
+ * resulting mappings is the minimium of this map and the supplied map.
831
+ *
832
+ * @param aSourceMapConsumer The source map to be applied.
833
+ * @param aSourceFile Optional. The filename of the source file.
834
+ * If omitted, SourceMapConsumer's file property will be used.
835
+ * @param aSourceMapPath Optional. The dirname of the path to the source map
836
+ * to be applied. If relative, it is relative to the SourceMapConsumer.
837
+ * This parameter is needed when the two source maps aren't in the same
838
+ * directory, and the source map to be applied contains relative source
839
+ * paths. If so, those relative source paths need to be rewritten
840
+ * relative to the SourceMapGenerator.
841
+ */
842
+ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
843
+ var sourceFile = aSourceFile;
844
+ if (aSourceFile == null) {
845
+ if (aSourceMapConsumer.file == null) throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's \"file\" property. Both were omitted.");
846
+ sourceFile = aSourceMapConsumer.file;
847
+ }
848
+ var sourceRoot = this._sourceRoot;
849
+ if (sourceRoot != null) sourceFile = util.relative(sourceRoot, sourceFile);
850
+ var newSources = new ArraySet();
851
+ var newNames = new ArraySet();
852
+ this._mappings.unsortedForEach(function(mapping) {
853
+ if (mapping.source === sourceFile && mapping.originalLine != null) {
854
+ var original = aSourceMapConsumer.originalPositionFor({
855
+ line: mapping.originalLine,
856
+ column: mapping.originalColumn
857
+ });
858
+ if (original.source != null) {
859
+ mapping.source = original.source;
860
+ if (aSourceMapPath != null) mapping.source = util.join(aSourceMapPath, mapping.source);
861
+ if (sourceRoot != null) mapping.source = util.relative(sourceRoot, mapping.source);
862
+ mapping.originalLine = original.line;
863
+ mapping.originalColumn = original.column;
864
+ if (original.name != null) mapping.name = original.name;
865
+ }
866
+ }
867
+ var source = mapping.source;
868
+ if (source != null && !newSources.has(source)) newSources.add(source);
869
+ var name = mapping.name;
870
+ if (name != null && !newNames.has(name)) newNames.add(name);
871
+ }, this);
872
+ this._sources = newSources;
873
+ this._names = newNames;
874
+ aSourceMapConsumer.sources.forEach(function(sourceFile) {
875
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
876
+ if (content != null) {
877
+ if (aSourceMapPath != null) sourceFile = util.join(aSourceMapPath, sourceFile);
878
+ if (sourceRoot != null) sourceFile = util.relative(sourceRoot, sourceFile);
879
+ this.setSourceContent(sourceFile, content);
880
+ }
881
+ }, this);
882
+ };
883
+ /**
884
+ * A mapping can have one of the three levels of data:
885
+ *
886
+ * 1. Just the generated position.
887
+ * 2. The Generated position, original position, and original source.
888
+ * 3. Generated and original position, original source, as well as a name
889
+ * token.
890
+ *
891
+ * To maintain consistency, we validate that any new mapping being added falls
892
+ * in to one of these categories.
893
+ */
894
+ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
895
+ if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") {
896
+ var message = "original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.";
897
+ if (this._ignoreInvalidMapping) {
898
+ if (typeof console !== "undefined" && console.warn) console.warn(message);
899
+ return false;
900
+ } else throw new Error(message);
901
+ }
902
+ if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) return;
903
+ else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) return;
904
+ else {
905
+ var message = "Invalid mapping: " + JSON.stringify({
906
+ generated: aGenerated,
907
+ source: aSource,
908
+ original: aOriginal,
909
+ name: aName
910
+ });
911
+ if (this._ignoreInvalidMapping) {
912
+ if (typeof console !== "undefined" && console.warn) console.warn(message);
913
+ return false;
914
+ } else throw new Error(message);
915
+ }
916
+ };
917
+ /**
918
+ * Serialize the accumulated mappings in to the stream of base 64 VLQs
919
+ * specified by the source map format.
920
+ */
921
+ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() {
922
+ var previousGeneratedColumn = 0;
923
+ var previousGeneratedLine = 1;
924
+ var previousOriginalColumn = 0;
925
+ var previousOriginalLine = 0;
926
+ var previousName = 0;
927
+ var previousSource = 0;
928
+ var result = "";
929
+ var next;
930
+ var mapping;
931
+ var nameIdx;
932
+ var sourceIdx;
933
+ var mappings = this._mappings.toArray();
934
+ for (var i = 0, len = mappings.length; i < len; i++) {
935
+ mapping = mappings[i];
936
+ next = "";
937
+ if (mapping.generatedLine !== previousGeneratedLine) {
938
+ previousGeneratedColumn = 0;
939
+ while (mapping.generatedLine !== previousGeneratedLine) {
940
+ next += ";";
941
+ previousGeneratedLine++;
942
+ }
943
+ } else if (i > 0) {
944
+ if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) continue;
945
+ next += ",";
946
+ }
947
+ next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn);
948
+ previousGeneratedColumn = mapping.generatedColumn;
949
+ if (mapping.source != null) {
950
+ sourceIdx = this._sources.indexOf(mapping.source);
951
+ next += base64VLQ.encode(sourceIdx - previousSource);
952
+ previousSource = sourceIdx;
953
+ next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine);
954
+ previousOriginalLine = mapping.originalLine - 1;
955
+ next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn);
956
+ previousOriginalColumn = mapping.originalColumn;
957
+ if (mapping.name != null) {
958
+ nameIdx = this._names.indexOf(mapping.name);
959
+ next += base64VLQ.encode(nameIdx - previousName);
960
+ previousName = nameIdx;
961
+ }
962
+ }
963
+ result += next;
964
+ }
965
+ return result;
966
+ };
967
+ SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
968
+ return aSources.map(function(source) {
969
+ if (!this._sourcesContents) return null;
970
+ if (aSourceRoot != null) source = util.relative(aSourceRoot, source);
971
+ var key = util.toSetString(source);
972
+ return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
973
+ }, this);
974
+ };
975
+ /**
976
+ * Externalize the source map.
977
+ */
978
+ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
979
+ var map = {
980
+ version: this._version,
981
+ sources: this._sources.toArray(),
982
+ names: this._names.toArray(),
983
+ mappings: this._serializeMappings()
984
+ };
985
+ if (this._file != null) map.file = this._file;
986
+ if (this._sourceRoot != null) map.sourceRoot = this._sourceRoot;
987
+ if (this._sourcesContents) map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
988
+ return map;
989
+ };
990
+ /**
991
+ * Render the source map being generated to a string.
992
+ */
993
+ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() {
994
+ return JSON.stringify(this.toJSON());
995
+ };
996
+ exports.SourceMapGenerator = SourceMapGenerator;
997
+ }));
998
+ //#endregion
999
+ //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/binary-search.js
1000
+ var require_binary_search = /* @__PURE__ */ __commonJSMin(((exports) => {
1001
+ exports.GREATEST_LOWER_BOUND = 1;
1002
+ exports.LEAST_UPPER_BOUND = 2;
1003
+ /**
1004
+ * Recursive implementation of binary search.
1005
+ *
1006
+ * @param aLow Indices here and lower do not contain the needle.
1007
+ * @param aHigh Indices here and higher do not contain the needle.
1008
+ * @param aNeedle The element being searched for.
1009
+ * @param aHaystack The non-empty array being searched.
1010
+ * @param aCompare Function which takes two elements and returns -1, 0, or 1.
1011
+ * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
1012
+ * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
1013
+ * closest element that is smaller than or greater than the one we are
1014
+ * searching for, respectively, if the exact element cannot be found.
1015
+ */
1016
+ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
1017
+ var mid = Math.floor((aHigh - aLow) / 2) + aLow;
1018
+ var cmp = aCompare(aNeedle, aHaystack[mid], true);
1019
+ if (cmp === 0) return mid;
1020
+ else if (cmp > 0) {
1021
+ if (aHigh - mid > 1) return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
1022
+ if (aBias == exports.LEAST_UPPER_BOUND) return aHigh < aHaystack.length ? aHigh : -1;
1023
+ else return mid;
1024
+ } else {
1025
+ if (mid - aLow > 1) return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
1026
+ if (aBias == exports.LEAST_UPPER_BOUND) return mid;
1027
+ else return aLow < 0 ? -1 : aLow;
1028
+ }
1029
+ }
1030
+ /**
1031
+ * This is an implementation of binary search which will always try and return
1032
+ * the index of the closest element if there is no exact hit. This is because
1033
+ * mappings between original and generated line/col pairs are single points,
1034
+ * and there is an implicit region between each of them, so a miss just means
1035
+ * that you aren't on the very start of a region.
1036
+ *
1037
+ * @param aNeedle The element you are looking for.
1038
+ * @param aHaystack The array that is being searched.
1039
+ * @param aCompare A function which takes the needle and an element in the
1040
+ * array and returns -1, 0, or 1 depending on whether the needle is less
1041
+ * than, equal to, or greater than the element, respectively.
1042
+ * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
1043
+ * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
1044
+ * closest element that is smaller than or greater than the one we are
1045
+ * searching for, respectively, if the exact element cannot be found.
1046
+ * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
1047
+ */
1048
+ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
1049
+ if (aHaystack.length === 0) return -1;
1050
+ var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND);
1051
+ if (index < 0) return -1;
1052
+ while (index - 1 >= 0) {
1053
+ if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) break;
1054
+ --index;
1055
+ }
1056
+ return index;
1057
+ };
1058
+ }));
1059
+ //#endregion
1060
+ //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/quick-sort.js
1061
+ var require_quick_sort = /* @__PURE__ */ __commonJSMin(((exports) => {
1062
+ function SortTemplate(comparator) {
1063
+ /**
1064
+ * Swap the elements indexed by `x` and `y` in the array `ary`.
1065
+ *
1066
+ * @param {Array} ary
1067
+ * The array.
1068
+ * @param {Number} x
1069
+ * The index of the first item.
1070
+ * @param {Number} y
1071
+ * The index of the second item.
1072
+ */
1073
+ function swap(ary, x, y) {
1074
+ var temp = ary[x];
1075
+ ary[x] = ary[y];
1076
+ ary[y] = temp;
1077
+ }
1078
+ /**
1079
+ * Returns a random integer within the range `low .. high` inclusive.
1080
+ *
1081
+ * @param {Number} low
1082
+ * The lower bound on the range.
1083
+ * @param {Number} high
1084
+ * The upper bound on the range.
1085
+ */
1086
+ function randomIntInRange(low, high) {
1087
+ return Math.round(low + Math.random() * (high - low));
1088
+ }
1089
+ /**
1090
+ * The Quick Sort algorithm.
1091
+ *
1092
+ * @param {Array} ary
1093
+ * An array to sort.
1094
+ * @param {function} comparator
1095
+ * Function to use to compare two items.
1096
+ * @param {Number} p
1097
+ * Start index of the array
1098
+ * @param {Number} r
1099
+ * End index of the array
1100
+ */
1101
+ function doQuickSort(ary, comparator, p, r) {
1102
+ if (p < r) {
1103
+ var pivotIndex = randomIntInRange(p, r);
1104
+ var i = p - 1;
1105
+ swap(ary, pivotIndex, r);
1106
+ var pivot = ary[r];
1107
+ for (var j = p; j < r; j++) if (comparator(ary[j], pivot, false) <= 0) {
1108
+ i += 1;
1109
+ swap(ary, i, j);
1110
+ }
1111
+ swap(ary, i + 1, j);
1112
+ var q = i + 1;
1113
+ doQuickSort(ary, comparator, p, q - 1);
1114
+ doQuickSort(ary, comparator, q + 1, r);
1115
+ }
1116
+ }
1117
+ return doQuickSort;
1118
+ }
1119
+ function cloneSort(comparator) {
1120
+ let templateFn = (...args) => SortTemplate(...args);
1121
+ return templateFn(comparator);
1122
+ }
1123
+ /**
1124
+ * Sort the given array in-place with the given comparator function.
1125
+ *
1126
+ * @param {Array} ary
1127
+ * An array to sort.
1128
+ * @param {function} comparator
1129
+ * Function to use to compare two items.
1130
+ */
1131
+ let sortCache = /* @__PURE__ */ new WeakMap();
1132
+ exports.quickSort = function(ary, comparator, start = 0) {
1133
+ let doQuickSort = sortCache.get(comparator);
1134
+ if (doQuickSort === void 0) {
1135
+ doQuickSort = cloneSort(comparator);
1136
+ sortCache.set(comparator, doQuickSort);
1137
+ }
1138
+ doQuickSort(ary, comparator, start, ary.length - 1);
1139
+ };
1140
+ }));
1141
+ //#endregion
1142
+ //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/source-map-consumer.js
1143
+ var require_source_map_consumer = /* @__PURE__ */ __commonJSMin(((exports) => {
1144
+ var util = require_util();
1145
+ var binarySearch = require_binary_search();
1146
+ var ArraySet = require_array_set().ArraySet;
1147
+ var base64VLQ = require_base64_vlq();
1148
+ var quickSort = require_quick_sort().quickSort;
1149
+ function SourceMapConsumer(aSourceMap, aSourceMapURL) {
1150
+ var sourceMap = aSourceMap;
1151
+ if (typeof aSourceMap === "string") sourceMap = util.parseSourceMapInput(aSourceMap);
1152
+ return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
1153
+ }
1154
+ SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
1155
+ return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
1156
+ };
1157
+ /**
1158
+ * The version of the source mapping spec that we are consuming.
1159
+ */
1160
+ SourceMapConsumer.prototype._version = 3;
1161
+ SourceMapConsumer.prototype.__generatedMappings = null;
1162
+ Object.defineProperty(SourceMapConsumer.prototype, "_generatedMappings", {
1163
+ configurable: true,
1164
+ enumerable: true,
1165
+ get: function() {
1166
+ if (!this.__generatedMappings) this._parseMappings(this._mappings, this.sourceRoot);
1167
+ return this.__generatedMappings;
1168
+ }
1169
+ });
1170
+ SourceMapConsumer.prototype.__originalMappings = null;
1171
+ Object.defineProperty(SourceMapConsumer.prototype, "_originalMappings", {
1172
+ configurable: true,
1173
+ enumerable: true,
1174
+ get: function() {
1175
+ if (!this.__originalMappings) this._parseMappings(this._mappings, this.sourceRoot);
1176
+ return this.__originalMappings;
1177
+ }
1178
+ });
1179
+ SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
1180
+ var c = aStr.charAt(index);
1181
+ return c === ";" || c === ",";
1182
+ };
1183
+ /**
1184
+ * Parse the mappings in a string in to a data structure which we can easily
1185
+ * query (the ordered arrays in the `this.__generatedMappings` and
1186
+ * `this.__originalMappings` properties).
1187
+ */
1188
+ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
1189
+ throw new Error("Subclasses must implement _parseMappings");
1190
+ };
1191
+ SourceMapConsumer.GENERATED_ORDER = 1;
1192
+ SourceMapConsumer.ORIGINAL_ORDER = 2;
1193
+ SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
1194
+ SourceMapConsumer.LEAST_UPPER_BOUND = 2;
1195
+ /**
1196
+ * Iterate over each mapping between an original source/line/column and a
1197
+ * generated line/column in this source map.
1198
+ *
1199
+ * @param Function aCallback
1200
+ * The function that is called with each mapping.
1201
+ * @param Object aContext
1202
+ * Optional. If specified, this object will be the value of `this` every
1203
+ * time that `aCallback` is called.
1204
+ * @param aOrder
1205
+ * Either `SourceMapConsumer.GENERATED_ORDER` or
1206
+ * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
1207
+ * iterate over the mappings sorted by the generated file's line/column
1208
+ * order or the original's source/line/column order, respectively. Defaults to
1209
+ * `SourceMapConsumer.GENERATED_ORDER`.
1210
+ */
1211
+ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
1212
+ var context = aContext || null;
1213
+ var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
1214
+ var mappings;
1215
+ switch (order) {
1216
+ case SourceMapConsumer.GENERATED_ORDER:
1217
+ mappings = this._generatedMappings;
1218
+ break;
1219
+ case SourceMapConsumer.ORIGINAL_ORDER:
1220
+ mappings = this._originalMappings;
1221
+ break;
1222
+ default: throw new Error("Unknown order of iteration.");
1223
+ }
1224
+ var sourceRoot = this.sourceRoot;
1225
+ var boundCallback = aCallback.bind(context);
1226
+ var names = this._names;
1227
+ var sources = this._sources;
1228
+ var sourceMapURL = this._sourceMapURL;
1229
+ for (var i = 0, n = mappings.length; i < n; i++) {
1230
+ var mapping = mappings[i];
1231
+ var source = mapping.source === null ? null : sources.at(mapping.source);
1232
+ if (source !== null) source = util.computeSourceURL(sourceRoot, source, sourceMapURL);
1233
+ boundCallback({
1234
+ source,
1235
+ generatedLine: mapping.generatedLine,
1236
+ generatedColumn: mapping.generatedColumn,
1237
+ originalLine: mapping.originalLine,
1238
+ originalColumn: mapping.originalColumn,
1239
+ name: mapping.name === null ? null : names.at(mapping.name)
1240
+ });
1241
+ }
1242
+ };
1243
+ /**
1244
+ * Returns all generated line and column information for the original source,
1245
+ * line, and column provided. If no column is provided, returns all mappings
1246
+ * corresponding to a either the line we are searching for or the next
1247
+ * closest line that has any mappings. Otherwise, returns all mappings
1248
+ * corresponding to the given line and either the column we are searching for
1249
+ * or the next closest column that has any offsets.
1250
+ *
1251
+ * The only argument is an object with the following properties:
1252
+ *
1253
+ * - source: The filename of the original source.
1254
+ * - line: The line number in the original source. The line number is 1-based.
1255
+ * - column: Optional. the column number in the original source.
1256
+ * The column number is 0-based.
1257
+ *
1258
+ * and an array of objects is returned, each with the following properties:
1259
+ *
1260
+ * - line: The line number in the generated source, or null. The
1261
+ * line number is 1-based.
1262
+ * - column: The column number in the generated source, or null.
1263
+ * The column number is 0-based.
1264
+ */
1265
+ SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
1266
+ var line = util.getArg(aArgs, "line");
1267
+ var needle = {
1268
+ source: util.getArg(aArgs, "source"),
1269
+ originalLine: line,
1270
+ originalColumn: util.getArg(aArgs, "column", 0)
1271
+ };
1272
+ needle.source = this._findSourceIndex(needle.source);
1273
+ if (needle.source < 0) return [];
1274
+ var mappings = [];
1275
+ var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND);
1276
+ if (index >= 0) {
1277
+ var mapping = this._originalMappings[index];
1278
+ if (aArgs.column === void 0) {
1279
+ var originalLine = mapping.originalLine;
1280
+ while (mapping && mapping.originalLine === originalLine) {
1281
+ mappings.push({
1282
+ line: util.getArg(mapping, "generatedLine", null),
1283
+ column: util.getArg(mapping, "generatedColumn", null),
1284
+ lastColumn: util.getArg(mapping, "lastGeneratedColumn", null)
1285
+ });
1286
+ mapping = this._originalMappings[++index];
1287
+ }
1288
+ } else {
1289
+ var originalColumn = mapping.originalColumn;
1290
+ while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
1291
+ mappings.push({
1292
+ line: util.getArg(mapping, "generatedLine", null),
1293
+ column: util.getArg(mapping, "generatedColumn", null),
1294
+ lastColumn: util.getArg(mapping, "lastGeneratedColumn", null)
1295
+ });
1296
+ mapping = this._originalMappings[++index];
1297
+ }
1298
+ }
1299
+ }
1300
+ return mappings;
1301
+ };
1302
+ exports.SourceMapConsumer = SourceMapConsumer;
1303
+ /**
1304
+ * A BasicSourceMapConsumer instance represents a parsed source map which we can
1305
+ * query for information about the original file positions by giving it a file
1306
+ * position in the generated source.
1307
+ *
1308
+ * The first parameter is the raw source map (either as a JSON string, or
1309
+ * already parsed to an object). According to the spec, source maps have the
1310
+ * following attributes:
1311
+ *
1312
+ * - version: Which version of the source map spec this map is following.
1313
+ * - sources: An array of URLs to the original source files.
1314
+ * - names: An array of identifiers which can be referrenced by individual mappings.
1315
+ * - sourceRoot: Optional. The URL root from which all sources are relative.
1316
+ * - sourcesContent: Optional. An array of contents of the original source files.
1317
+ * - mappings: A string of base64 VLQs which contain the actual mappings.
1318
+ * - file: Optional. The generated file this source map is associated with.
1319
+ *
1320
+ * Here is an example source map, taken from the source map spec[0]:
1321
+ *
1322
+ * {
1323
+ * version : 3,
1324
+ * file: "out.js",
1325
+ * sourceRoot : "",
1326
+ * sources: ["foo.js", "bar.js"],
1327
+ * names: ["src", "maps", "are", "fun"],
1328
+ * mappings: "AA,AB;;ABCDE;"
1329
+ * }
1330
+ *
1331
+ * The second parameter, if given, is a string whose value is the URL
1332
+ * at which the source map was found. This URL is used to compute the
1333
+ * sources array.
1334
+ *
1335
+ * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
1336
+ */
1337
+ function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
1338
+ var sourceMap = aSourceMap;
1339
+ if (typeof aSourceMap === "string") sourceMap = util.parseSourceMapInput(aSourceMap);
1340
+ var version = util.getArg(sourceMap, "version");
1341
+ var sources = util.getArg(sourceMap, "sources");
1342
+ var names = util.getArg(sourceMap, "names", []);
1343
+ var sourceRoot = util.getArg(sourceMap, "sourceRoot", null);
1344
+ var sourcesContent = util.getArg(sourceMap, "sourcesContent", null);
1345
+ var mappings = util.getArg(sourceMap, "mappings");
1346
+ var file = util.getArg(sourceMap, "file", null);
1347
+ if (version != this._version) throw new Error("Unsupported version: " + version);
1348
+ if (sourceRoot) sourceRoot = util.normalize(sourceRoot);
1349
+ sources = sources.map(String).map(util.normalize).map(function(source) {
1350
+ return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source;
1351
+ });
1352
+ this._names = ArraySet.fromArray(names.map(String), true);
1353
+ this._sources = ArraySet.fromArray(sources, true);
1354
+ this._absoluteSources = this._sources.toArray().map(function(s) {
1355
+ return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
1356
+ });
1357
+ this.sourceRoot = sourceRoot;
1358
+ this.sourcesContent = sourcesContent;
1359
+ this._mappings = mappings;
1360
+ this._sourceMapURL = aSourceMapURL;
1361
+ this.file = file;
1362
+ }
1363
+ BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
1364
+ BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
1365
+ /**
1366
+ * Utility function to find the index of a source. Returns -1 if not
1367
+ * found.
1368
+ */
1369
+ BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
1370
+ var relativeSource = aSource;
1371
+ if (this.sourceRoot != null) relativeSource = util.relative(this.sourceRoot, relativeSource);
1372
+ if (this._sources.has(relativeSource)) return this._sources.indexOf(relativeSource);
1373
+ var i;
1374
+ for (i = 0; i < this._absoluteSources.length; ++i) if (this._absoluteSources[i] == aSource) return i;
1375
+ return -1;
1376
+ };
1377
+ /**
1378
+ * Create a BasicSourceMapConsumer from a SourceMapGenerator.
1379
+ *
1380
+ * @param SourceMapGenerator aSourceMap
1381
+ * The source map that will be consumed.
1382
+ * @param String aSourceMapURL
1383
+ * The URL at which the source map can be found (optional)
1384
+ * @returns BasicSourceMapConsumer
1385
+ */
1386
+ BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
1387
+ var smc = Object.create(BasicSourceMapConsumer.prototype);
1388
+ var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
1389
+ var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
1390
+ smc.sourceRoot = aSourceMap._sourceRoot;
1391
+ smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot);
1392
+ smc.file = aSourceMap._file;
1393
+ smc._sourceMapURL = aSourceMapURL;
1394
+ smc._absoluteSources = smc._sources.toArray().map(function(s) {
1395
+ return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
1396
+ });
1397
+ var generatedMappings = aSourceMap._mappings.toArray().slice();
1398
+ var destGeneratedMappings = smc.__generatedMappings = [];
1399
+ var destOriginalMappings = smc.__originalMappings = [];
1400
+ for (var i = 0, length = generatedMappings.length; i < length; i++) {
1401
+ var srcMapping = generatedMappings[i];
1402
+ var destMapping = new Mapping();
1403
+ destMapping.generatedLine = srcMapping.generatedLine;
1404
+ destMapping.generatedColumn = srcMapping.generatedColumn;
1405
+ if (srcMapping.source) {
1406
+ destMapping.source = sources.indexOf(srcMapping.source);
1407
+ destMapping.originalLine = srcMapping.originalLine;
1408
+ destMapping.originalColumn = srcMapping.originalColumn;
1409
+ if (srcMapping.name) destMapping.name = names.indexOf(srcMapping.name);
1410
+ destOriginalMappings.push(destMapping);
1411
+ }
1412
+ destGeneratedMappings.push(destMapping);
1413
+ }
1414
+ quickSort(smc.__originalMappings, util.compareByOriginalPositions);
1415
+ return smc;
1416
+ };
1417
+ /**
1418
+ * The version of the source mapping spec that we are consuming.
1419
+ */
1420
+ BasicSourceMapConsumer.prototype._version = 3;
1421
+ /**
1422
+ * The list of original sources.
1423
+ */
1424
+ Object.defineProperty(BasicSourceMapConsumer.prototype, "sources", { get: function() {
1425
+ return this._absoluteSources.slice();
1426
+ } });
1427
+ /**
1428
+ * Provide the JIT with a nice shape / hidden class.
1429
+ */
1430
+ function Mapping() {
1431
+ this.generatedLine = 0;
1432
+ this.generatedColumn = 0;
1433
+ this.source = null;
1434
+ this.originalLine = null;
1435
+ this.originalColumn = null;
1436
+ this.name = null;
1437
+ }
1438
+ /**
1439
+ * Parse the mappings in a string in to a data structure which we can easily
1440
+ * query (the ordered arrays in the `this.__generatedMappings` and
1441
+ * `this.__originalMappings` properties).
1442
+ */
1443
+ const compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine;
1444
+ function sortGenerated(array, start) {
1445
+ let l = array.length;
1446
+ let n = array.length - start;
1447
+ if (n <= 1) return;
1448
+ else if (n == 2) {
1449
+ let a = array[start];
1450
+ let b = array[start + 1];
1451
+ if (compareGenerated(a, b) > 0) {
1452
+ array[start] = b;
1453
+ array[start + 1] = a;
1454
+ }
1455
+ } else if (n < 20) for (let i = start; i < l; i++) for (let j = i; j > start; j--) {
1456
+ let a = array[j - 1];
1457
+ let b = array[j];
1458
+ if (compareGenerated(a, b) <= 0) break;
1459
+ array[j - 1] = b;
1460
+ array[j] = a;
1461
+ }
1462
+ else quickSort(array, compareGenerated, start);
1463
+ }
1464
+ BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
1465
+ var generatedLine = 1;
1466
+ var previousGeneratedColumn = 0;
1467
+ var previousOriginalLine = 0;
1468
+ var previousOriginalColumn = 0;
1469
+ var previousSource = 0;
1470
+ var previousName = 0;
1471
+ var length = aStr.length;
1472
+ var index = 0;
1473
+ var temp = {};
1474
+ var originalMappings = [];
1475
+ var generatedMappings = [], mapping, segment, end, value;
1476
+ let subarrayStart = 0;
1477
+ while (index < length) if (aStr.charAt(index) === ";") {
1478
+ generatedLine++;
1479
+ index++;
1480
+ previousGeneratedColumn = 0;
1481
+ sortGenerated(generatedMappings, subarrayStart);
1482
+ subarrayStart = generatedMappings.length;
1483
+ } else if (aStr.charAt(index) === ",") index++;
1484
+ else {
1485
+ mapping = new Mapping();
1486
+ mapping.generatedLine = generatedLine;
1487
+ for (end = index; end < length; end++) if (this._charIsMappingSeparator(aStr, end)) break;
1488
+ aStr.slice(index, end);
1489
+ segment = [];
1490
+ while (index < end) {
1491
+ base64VLQ.decode(aStr, index, temp);
1492
+ value = temp.value;
1493
+ index = temp.rest;
1494
+ segment.push(value);
1495
+ }
1496
+ if (segment.length === 2) throw new Error("Found a source, but no line and column");
1497
+ if (segment.length === 3) throw new Error("Found a source and line, but no column");
1498
+ mapping.generatedColumn = previousGeneratedColumn + segment[0];
1499
+ previousGeneratedColumn = mapping.generatedColumn;
1500
+ if (segment.length > 1) {
1501
+ mapping.source = previousSource + segment[1];
1502
+ previousSource += segment[1];
1503
+ mapping.originalLine = previousOriginalLine + segment[2];
1504
+ previousOriginalLine = mapping.originalLine;
1505
+ mapping.originalLine += 1;
1506
+ mapping.originalColumn = previousOriginalColumn + segment[3];
1507
+ previousOriginalColumn = mapping.originalColumn;
1508
+ if (segment.length > 4) {
1509
+ mapping.name = previousName + segment[4];
1510
+ previousName += segment[4];
1511
+ }
1512
+ }
1513
+ generatedMappings.push(mapping);
1514
+ if (typeof mapping.originalLine === "number") {
1515
+ let currentSource = mapping.source;
1516
+ while (originalMappings.length <= currentSource) originalMappings.push(null);
1517
+ if (originalMappings[currentSource] === null) originalMappings[currentSource] = [];
1518
+ originalMappings[currentSource].push(mapping);
1519
+ }
1520
+ }
1521
+ sortGenerated(generatedMappings, subarrayStart);
1522
+ this.__generatedMappings = generatedMappings;
1523
+ for (var i = 0; i < originalMappings.length; i++) if (originalMappings[i] != null) quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource);
1524
+ this.__originalMappings = [].concat(...originalMappings);
1525
+ };
1526
+ /**
1527
+ * Find the mapping that best matches the hypothetical "needle" mapping that
1528
+ * we are searching for in the given "haystack" of mappings.
1529
+ */
1530
+ BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
1531
+ if (aNeedle[aLineName] <= 0) throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]);
1532
+ if (aNeedle[aColumnName] < 0) throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]);
1533
+ return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
1534
+ };
1535
+ /**
1536
+ * Compute the last column for each generated mapping. The last column is
1537
+ * inclusive.
1538
+ */
1539
+ BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() {
1540
+ for (var index = 0; index < this._generatedMappings.length; ++index) {
1541
+ var mapping = this._generatedMappings[index];
1542
+ if (index + 1 < this._generatedMappings.length) {
1543
+ var nextMapping = this._generatedMappings[index + 1];
1544
+ if (mapping.generatedLine === nextMapping.generatedLine) {
1545
+ mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
1546
+ continue;
1547
+ }
1548
+ }
1549
+ mapping.lastGeneratedColumn = Infinity;
1550
+ }
1551
+ };
1552
+ /**
1553
+ * Returns the original source, line, and column information for the generated
1554
+ * source's line and column positions provided. The only argument is an object
1555
+ * with the following properties:
1556
+ *
1557
+ * - line: The line number in the generated source. The line number
1558
+ * is 1-based.
1559
+ * - column: The column number in the generated source. The column
1560
+ * number is 0-based.
1561
+ * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
1562
+ * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
1563
+ * closest element that is smaller than or greater than the one we are
1564
+ * searching for, respectively, if the exact element cannot be found.
1565
+ * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
1566
+ *
1567
+ * and an object is returned with the following properties:
1568
+ *
1569
+ * - source: The original source file, or null.
1570
+ * - line: The line number in the original source, or null. The
1571
+ * line number is 1-based.
1572
+ * - column: The column number in the original source, or null. The
1573
+ * column number is 0-based.
1574
+ * - name: The original identifier, or null.
1575
+ */
1576
+ BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
1577
+ var needle = {
1578
+ generatedLine: util.getArg(aArgs, "line"),
1579
+ generatedColumn: util.getArg(aArgs, "column")
1580
+ };
1581
+ var index = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND));
1582
+ if (index >= 0) {
1583
+ var mapping = this._generatedMappings[index];
1584
+ if (mapping.generatedLine === needle.generatedLine) {
1585
+ var source = util.getArg(mapping, "source", null);
1586
+ if (source !== null) {
1587
+ source = this._sources.at(source);
1588
+ source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
1589
+ }
1590
+ var name = util.getArg(mapping, "name", null);
1591
+ if (name !== null) name = this._names.at(name);
1592
+ return {
1593
+ source,
1594
+ line: util.getArg(mapping, "originalLine", null),
1595
+ column: util.getArg(mapping, "originalColumn", null),
1596
+ name
1597
+ };
1598
+ }
1599
+ }
1600
+ return {
1601
+ source: null,
1602
+ line: null,
1603
+ column: null,
1604
+ name: null
1605
+ };
1606
+ };
1607
+ /**
1608
+ * Return true if we have the source content for every source in the source
1609
+ * map, false otherwise.
1610
+ */
1611
+ BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() {
1612
+ if (!this.sourcesContent) return false;
1613
+ return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) {
1614
+ return sc == null;
1615
+ });
1616
+ };
1617
+ /**
1618
+ * Returns the original source content. The only argument is the url of the
1619
+ * original source file. Returns null if no original source content is
1620
+ * available.
1621
+ */
1622
+ BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
1623
+ if (!this.sourcesContent) return null;
1624
+ var index = this._findSourceIndex(aSource);
1625
+ if (index >= 0) return this.sourcesContent[index];
1626
+ var relativeSource = aSource;
1627
+ if (this.sourceRoot != null) relativeSource = util.relative(this.sourceRoot, relativeSource);
1628
+ var url;
1629
+ if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) {
1630
+ var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
1631
+ if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
1632
+ if ((!url.path || url.path == "/") && this._sources.has("/" + relativeSource)) return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
1633
+ }
1634
+ if (nullOnMissing) return null;
1635
+ else throw new Error("\"" + relativeSource + "\" is not in the SourceMap.");
1636
+ };
1637
+ /**
1638
+ * Returns the generated line and column information for the original source,
1639
+ * line, and column positions provided. The only argument is an object with
1640
+ * the following properties:
1641
+ *
1642
+ * - source: The filename of the original source.
1643
+ * - line: The line number in the original source. The line number
1644
+ * is 1-based.
1645
+ * - column: The column number in the original source. The column
1646
+ * number is 0-based.
1647
+ * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
1648
+ * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
1649
+ * closest element that is smaller than or greater than the one we are
1650
+ * searching for, respectively, if the exact element cannot be found.
1651
+ * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
1652
+ *
1653
+ * and an object is returned with the following properties:
1654
+ *
1655
+ * - line: The line number in the generated source, or null. The
1656
+ * line number is 1-based.
1657
+ * - column: The column number in the generated source, or null.
1658
+ * The column number is 0-based.
1659
+ */
1660
+ BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
1661
+ var source = util.getArg(aArgs, "source");
1662
+ source = this._findSourceIndex(source);
1663
+ if (source < 0) return {
1664
+ line: null,
1665
+ column: null,
1666
+ lastColumn: null
1667
+ };
1668
+ var needle = {
1669
+ source,
1670
+ originalLine: util.getArg(aArgs, "line"),
1671
+ originalColumn: util.getArg(aArgs, "column")
1672
+ };
1673
+ var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND));
1674
+ if (index >= 0) {
1675
+ var mapping = this._originalMappings[index];
1676
+ if (mapping.source === needle.source) return {
1677
+ line: util.getArg(mapping, "generatedLine", null),
1678
+ column: util.getArg(mapping, "generatedColumn", null),
1679
+ lastColumn: util.getArg(mapping, "lastGeneratedColumn", null)
1680
+ };
1681
+ }
1682
+ return {
1683
+ line: null,
1684
+ column: null,
1685
+ lastColumn: null
1686
+ };
1687
+ };
1688
+ exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
1689
+ /**
1690
+ * An IndexedSourceMapConsumer instance represents a parsed source map which
1691
+ * we can query for information. It differs from BasicSourceMapConsumer in
1692
+ * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
1693
+ * input.
1694
+ *
1695
+ * The first parameter is a raw source map (either as a JSON string, or already
1696
+ * parsed to an object). According to the spec for indexed source maps, they
1697
+ * have the following attributes:
1698
+ *
1699
+ * - version: Which version of the source map spec this map is following.
1700
+ * - file: Optional. The generated file this source map is associated with.
1701
+ * - sections: A list of section definitions.
1702
+ *
1703
+ * Each value under the "sections" field has two fields:
1704
+ * - offset: The offset into the original specified at which this section
1705
+ * begins to apply, defined as an object with a "line" and "column"
1706
+ * field.
1707
+ * - map: A source map definition. This source map could also be indexed,
1708
+ * but doesn't have to be.
1709
+ *
1710
+ * Instead of the "map" field, it's also possible to have a "url" field
1711
+ * specifying a URL to retrieve a source map from, but that's currently
1712
+ * unsupported.
1713
+ *
1714
+ * Here's an example source map, taken from the source map spec[0], but
1715
+ * modified to omit a section which uses the "url" field.
1716
+ *
1717
+ * {
1718
+ * version : 3,
1719
+ * file: "app.js",
1720
+ * sections: [{
1721
+ * offset: {line:100, column:10},
1722
+ * map: {
1723
+ * version : 3,
1724
+ * file: "section.js",
1725
+ * sources: ["foo.js", "bar.js"],
1726
+ * names: ["src", "maps", "are", "fun"],
1727
+ * mappings: "AAAA,E;;ABCDE;"
1728
+ * }
1729
+ * }],
1730
+ * }
1731
+ *
1732
+ * The second parameter, if given, is a string whose value is the URL
1733
+ * at which the source map was found. This URL is used to compute the
1734
+ * sources array.
1735
+ *
1736
+ * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
1737
+ */
1738
+ function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
1739
+ var sourceMap = aSourceMap;
1740
+ if (typeof aSourceMap === "string") sourceMap = util.parseSourceMapInput(aSourceMap);
1741
+ var version = util.getArg(sourceMap, "version");
1742
+ var sections = util.getArg(sourceMap, "sections");
1743
+ if (version != this._version) throw new Error("Unsupported version: " + version);
1744
+ this._sources = new ArraySet();
1745
+ this._names = new ArraySet();
1746
+ var lastOffset = {
1747
+ line: -1,
1748
+ column: 0
1749
+ };
1750
+ this._sections = sections.map(function(s) {
1751
+ if (s.url) throw new Error("Support for url field in sections not implemented.");
1752
+ var offset = util.getArg(s, "offset");
1753
+ var offsetLine = util.getArg(offset, "line");
1754
+ var offsetColumn = util.getArg(offset, "column");
1755
+ if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) throw new Error("Section offsets must be ordered and non-overlapping.");
1756
+ lastOffset = offset;
1757
+ return {
1758
+ generatedOffset: {
1759
+ generatedLine: offsetLine + 1,
1760
+ generatedColumn: offsetColumn + 1
1761
+ },
1762
+ consumer: new SourceMapConsumer(util.getArg(s, "map"), aSourceMapURL)
1763
+ };
1764
+ });
1765
+ }
1766
+ IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
1767
+ IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
1768
+ /**
1769
+ * The version of the source mapping spec that we are consuming.
1770
+ */
1771
+ IndexedSourceMapConsumer.prototype._version = 3;
1772
+ /**
1773
+ * The list of original sources.
1774
+ */
1775
+ Object.defineProperty(IndexedSourceMapConsumer.prototype, "sources", { get: function() {
1776
+ var sources = [];
1777
+ for (var i = 0; i < this._sections.length; i++) for (var j = 0; j < this._sections[i].consumer.sources.length; j++) sources.push(this._sections[i].consumer.sources[j]);
1778
+ return sources;
1779
+ } });
1780
+ /**
1781
+ * Returns the original source, line, and column information for the generated
1782
+ * source's line and column positions provided. The only argument is an object
1783
+ * with the following properties:
1784
+ *
1785
+ * - line: The line number in the generated source. The line number
1786
+ * is 1-based.
1787
+ * - column: The column number in the generated source. The column
1788
+ * number is 0-based.
1789
+ *
1790
+ * and an object is returned with the following properties:
1791
+ *
1792
+ * - source: The original source file, or null.
1793
+ * - line: The line number in the original source, or null. The
1794
+ * line number is 1-based.
1795
+ * - column: The column number in the original source, or null. The
1796
+ * column number is 0-based.
1797
+ * - name: The original identifier, or null.
1798
+ */
1799
+ IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
1800
+ var needle = {
1801
+ generatedLine: util.getArg(aArgs, "line"),
1802
+ generatedColumn: util.getArg(aArgs, "column")
1803
+ };
1804
+ var sectionIndex = binarySearch.search(needle, this._sections, function(needle, section) {
1805
+ var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
1806
+ if (cmp) return cmp;
1807
+ return needle.generatedColumn - section.generatedOffset.generatedColumn;
1808
+ });
1809
+ var section = this._sections[sectionIndex];
1810
+ if (!section) return {
1811
+ source: null,
1812
+ line: null,
1813
+ column: null,
1814
+ name: null
1815
+ };
1816
+ return section.consumer.originalPositionFor({
1817
+ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
1818
+ column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
1819
+ bias: aArgs.bias
1820
+ });
1821
+ };
1822
+ /**
1823
+ * Return true if we have the source content for every source in the source
1824
+ * map, false otherwise.
1825
+ */
1826
+ IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() {
1827
+ return this._sections.every(function(s) {
1828
+ return s.consumer.hasContentsOfAllSources();
1829
+ });
1830
+ };
1831
+ /**
1832
+ * Returns the original source content. The only argument is the url of the
1833
+ * original source file. Returns null if no original source content is
1834
+ * available.
1835
+ */
1836
+ IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
1837
+ for (var i = 0; i < this._sections.length; i++) {
1838
+ var content = this._sections[i].consumer.sourceContentFor(aSource, true);
1839
+ if (content || content === "") return content;
1840
+ }
1841
+ if (nullOnMissing) return null;
1842
+ else throw new Error("\"" + aSource + "\" is not in the SourceMap.");
1843
+ };
1844
+ /**
1845
+ * Returns the generated line and column information for the original source,
1846
+ * line, and column positions provided. The only argument is an object with
1847
+ * the following properties:
1848
+ *
1849
+ * - source: The filename of the original source.
1850
+ * - line: The line number in the original source. The line number
1851
+ * is 1-based.
1852
+ * - column: The column number in the original source. The column
1853
+ * number is 0-based.
1854
+ *
1855
+ * and an object is returned with the following properties:
1856
+ *
1857
+ * - line: The line number in the generated source, or null. The
1858
+ * line number is 1-based.
1859
+ * - column: The column number in the generated source, or null.
1860
+ * The column number is 0-based.
1861
+ */
1862
+ IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
1863
+ for (var i = 0; i < this._sections.length; i++) {
1864
+ var section = this._sections[i];
1865
+ if (section.consumer._findSourceIndex(util.getArg(aArgs, "source")) === -1) continue;
1866
+ var generatedPosition = section.consumer.generatedPositionFor(aArgs);
1867
+ if (generatedPosition) return {
1868
+ line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
1869
+ column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
1870
+ };
1871
+ }
1872
+ return {
1873
+ line: null,
1874
+ column: null
1875
+ };
1876
+ };
1877
+ /**
1878
+ * Parse the mappings in a string in to a data structure which we can easily
1879
+ * query (the ordered arrays in the `this.__generatedMappings` and
1880
+ * `this.__originalMappings` properties).
1881
+ */
1882
+ IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
1883
+ this.__generatedMappings = [];
1884
+ this.__originalMappings = [];
1885
+ for (var i = 0; i < this._sections.length; i++) {
1886
+ var section = this._sections[i];
1887
+ var sectionMappings = section.consumer._generatedMappings;
1888
+ for (var j = 0; j < sectionMappings.length; j++) {
1889
+ var mapping = sectionMappings[j];
1890
+ var source = section.consumer._sources.at(mapping.source);
1891
+ if (source !== null) source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
1892
+ this._sources.add(source);
1893
+ source = this._sources.indexOf(source);
1894
+ var name = null;
1895
+ if (mapping.name) {
1896
+ name = section.consumer._names.at(mapping.name);
1897
+ this._names.add(name);
1898
+ name = this._names.indexOf(name);
1899
+ }
1900
+ var adjustedMapping = {
1901
+ source,
1902
+ generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
1903
+ generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
1904
+ originalLine: mapping.originalLine,
1905
+ originalColumn: mapping.originalColumn,
1906
+ name
1907
+ };
1908
+ this.__generatedMappings.push(adjustedMapping);
1909
+ if (typeof adjustedMapping.originalLine === "number") this.__originalMappings.push(adjustedMapping);
1910
+ }
1911
+ }
1912
+ quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
1913
+ quickSort(this.__originalMappings, util.compareByOriginalPositions);
1914
+ };
1915
+ exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
1916
+ }));
1917
+ //#endregion
1918
+ //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/source-node.js
1919
+ var require_source_node = /* @__PURE__ */ __commonJSMin(((exports) => {
1920
+ var SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
1921
+ var util = require_util();
1922
+ var REGEX_NEWLINE = /(\r?\n)/;
1923
+ var NEWLINE_CODE = 10;
1924
+ var isSourceNode = "$$$isSourceNode$$$";
1925
+ /**
1926
+ * SourceNodes provide a way to abstract over interpolating/concatenating
1927
+ * snippets of generated JavaScript source code while maintaining the line and
1928
+ * column information associated with the original source code.
1929
+ *
1930
+ * @param aLine The original line number.
1931
+ * @param aColumn The original column number.
1932
+ * @param aSource The original source's filename.
1933
+ * @param aChunks Optional. An array of strings which are snippets of
1934
+ * generated JS, or other SourceNodes.
1935
+ * @param aName The original identifier.
1936
+ */
1937
+ function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
1938
+ this.children = [];
1939
+ this.sourceContents = {};
1940
+ this.line = aLine == null ? null : aLine;
1941
+ this.column = aColumn == null ? null : aColumn;
1942
+ this.source = aSource == null ? null : aSource;
1943
+ this.name = aName == null ? null : aName;
1944
+ this[isSourceNode] = true;
1945
+ if (aChunks != null) this.add(aChunks);
1946
+ }
1947
+ /**
1948
+ * Creates a SourceNode from generated code and a SourceMapConsumer.
1949
+ *
1950
+ * @param aGeneratedCode The generated code
1951
+ * @param aSourceMapConsumer The SourceMap for the generated code
1952
+ * @param aRelativePath Optional. The path that relative sources in the
1953
+ * SourceMapConsumer should be relative to.
1954
+ */
1955
+ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
1956
+ var node = new SourceNode();
1957
+ var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
1958
+ var remainingLinesIndex = 0;
1959
+ var shiftNextLine = function() {
1960
+ return getNextLine() + (getNextLine() || "");
1961
+ function getNextLine() {
1962
+ return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0;
1963
+ }
1964
+ };
1965
+ var lastGeneratedLine = 1, lastGeneratedColumn = 0;
1966
+ var lastMapping = null;
1967
+ aSourceMapConsumer.eachMapping(function(mapping) {
1968
+ if (lastMapping !== null) if (lastGeneratedLine < mapping.generatedLine) {
1969
+ addMappingWithCode(lastMapping, shiftNextLine());
1970
+ lastGeneratedLine++;
1971
+ lastGeneratedColumn = 0;
1972
+ } else {
1973
+ var nextLine = remainingLines[remainingLinesIndex] || "";
1974
+ var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
1975
+ remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
1976
+ lastGeneratedColumn = mapping.generatedColumn;
1977
+ addMappingWithCode(lastMapping, code);
1978
+ lastMapping = mapping;
1979
+ return;
1980
+ }
1981
+ while (lastGeneratedLine < mapping.generatedLine) {
1982
+ node.add(shiftNextLine());
1983
+ lastGeneratedLine++;
1984
+ }
1985
+ if (lastGeneratedColumn < mapping.generatedColumn) {
1986
+ var nextLine = remainingLines[remainingLinesIndex] || "";
1987
+ node.add(nextLine.substr(0, mapping.generatedColumn));
1988
+ remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
1989
+ lastGeneratedColumn = mapping.generatedColumn;
1990
+ }
1991
+ lastMapping = mapping;
1992
+ }, this);
1993
+ if (remainingLinesIndex < remainingLines.length) {
1994
+ if (lastMapping) addMappingWithCode(lastMapping, shiftNextLine());
1995
+ node.add(remainingLines.splice(remainingLinesIndex).join(""));
1996
+ }
1997
+ aSourceMapConsumer.sources.forEach(function(sourceFile) {
1998
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
1999
+ if (content != null) {
2000
+ if (aRelativePath != null) sourceFile = util.join(aRelativePath, sourceFile);
2001
+ node.setSourceContent(sourceFile, content);
2002
+ }
2003
+ });
2004
+ return node;
2005
+ function addMappingWithCode(mapping, code) {
2006
+ if (mapping === null || mapping.source === void 0) node.add(code);
2007
+ else {
2008
+ var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source;
2009
+ node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name));
2010
+ }
2011
+ }
2012
+ };
2013
+ /**
2014
+ * Add a chunk of generated JS to this source node.
2015
+ *
2016
+ * @param aChunk A string snippet of generated JS code, another instance of
2017
+ * SourceNode, or an array where each member is one of those things.
2018
+ */
2019
+ SourceNode.prototype.add = function SourceNode_add(aChunk) {
2020
+ if (Array.isArray(aChunk)) aChunk.forEach(function(chunk) {
2021
+ this.add(chunk);
2022
+ }, this);
2023
+ else if (aChunk[isSourceNode] || typeof aChunk === "string") {
2024
+ if (aChunk) this.children.push(aChunk);
2025
+ } else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
2026
+ return this;
2027
+ };
2028
+ /**
2029
+ * Add a chunk of generated JS to the beginning of this source node.
2030
+ *
2031
+ * @param aChunk A string snippet of generated JS code, another instance of
2032
+ * SourceNode, or an array where each member is one of those things.
2033
+ */
2034
+ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
2035
+ if (Array.isArray(aChunk)) for (var i = aChunk.length - 1; i >= 0; i--) this.prepend(aChunk[i]);
2036
+ else if (aChunk[isSourceNode] || typeof aChunk === "string") this.children.unshift(aChunk);
2037
+ else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
2038
+ return this;
2039
+ };
2040
+ /**
2041
+ * Walk over the tree of JS snippets in this node and its children. The
2042
+ * walking function is called once for each snippet of JS and is passed that
2043
+ * snippet and the its original associated source's line/column location.
2044
+ *
2045
+ * @param aFn The traversal function.
2046
+ */
2047
+ SourceNode.prototype.walk = function SourceNode_walk(aFn) {
2048
+ var chunk;
2049
+ for (var i = 0, len = this.children.length; i < len; i++) {
2050
+ chunk = this.children[i];
2051
+ if (chunk[isSourceNode]) chunk.walk(aFn);
2052
+ else if (chunk !== "") aFn(chunk, {
2053
+ source: this.source,
2054
+ line: this.line,
2055
+ column: this.column,
2056
+ name: this.name
2057
+ });
2058
+ }
2059
+ };
2060
+ /**
2061
+ * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
2062
+ * each of `this.children`.
2063
+ *
2064
+ * @param aSep The separator.
2065
+ */
2066
+ SourceNode.prototype.join = function SourceNode_join(aSep) {
2067
+ var newChildren;
2068
+ var i;
2069
+ var len = this.children.length;
2070
+ if (len > 0) {
2071
+ newChildren = [];
2072
+ for (i = 0; i < len - 1; i++) {
2073
+ newChildren.push(this.children[i]);
2074
+ newChildren.push(aSep);
2075
+ }
2076
+ newChildren.push(this.children[i]);
2077
+ this.children = newChildren;
2078
+ }
2079
+ return this;
2080
+ };
2081
+ /**
2082
+ * Call String.prototype.replace on the very right-most source snippet. Useful
2083
+ * for trimming whitespace from the end of a source node, etc.
2084
+ *
2085
+ * @param aPattern The pattern to replace.
2086
+ * @param aReplacement The thing to replace the pattern with.
2087
+ */
2088
+ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
2089
+ var lastChild = this.children[this.children.length - 1];
2090
+ if (lastChild[isSourceNode]) lastChild.replaceRight(aPattern, aReplacement);
2091
+ else if (typeof lastChild === "string") this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
2092
+ else this.children.push("".replace(aPattern, aReplacement));
2093
+ return this;
2094
+ };
2095
+ /**
2096
+ * Set the source content for a source file. This will be added to the SourceMapGenerator
2097
+ * in the sourcesContent field.
2098
+ *
2099
+ * @param aSourceFile The filename of the source file
2100
+ * @param aSourceContent The content of the source file
2101
+ */
2102
+ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
2103
+ this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
2104
+ };
2105
+ /**
2106
+ * Walk over the tree of SourceNodes. The walking function is called for each
2107
+ * source file content and is passed the filename and source content.
2108
+ *
2109
+ * @param aFn The traversal function.
2110
+ */
2111
+ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) {
2112
+ for (var i = 0, len = this.children.length; i < len; i++) if (this.children[i][isSourceNode]) this.children[i].walkSourceContents(aFn);
2113
+ var sources = Object.keys(this.sourceContents);
2114
+ for (var i = 0, len = sources.length; i < len; i++) aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
2115
+ };
2116
+ /**
2117
+ * Return the string representation of this source node. Walks over the tree
2118
+ * and concatenates all the various snippets together to one string.
2119
+ */
2120
+ SourceNode.prototype.toString = function SourceNode_toString() {
2121
+ var str = "";
2122
+ this.walk(function(chunk) {
2123
+ str += chunk;
2124
+ });
2125
+ return str;
2126
+ };
2127
+ /**
2128
+ * Returns the string representation of this source node along with a source
2129
+ * map.
2130
+ */
2131
+ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
2132
+ var generated = {
2133
+ code: "",
2134
+ line: 1,
2135
+ column: 0
2136
+ };
2137
+ var map = new SourceMapGenerator(aArgs);
2138
+ var sourceMappingActive = false;
2139
+ var lastOriginalSource = null;
2140
+ var lastOriginalLine = null;
2141
+ var lastOriginalColumn = null;
2142
+ var lastOriginalName = null;
2143
+ this.walk(function(chunk, original) {
2144
+ generated.code += chunk;
2145
+ if (original.source !== null && original.line !== null && original.column !== null) {
2146
+ if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) map.addMapping({
2147
+ source: original.source,
2148
+ original: {
2149
+ line: original.line,
2150
+ column: original.column
2151
+ },
2152
+ generated: {
2153
+ line: generated.line,
2154
+ column: generated.column
2155
+ },
2156
+ name: original.name
2157
+ });
2158
+ lastOriginalSource = original.source;
2159
+ lastOriginalLine = original.line;
2160
+ lastOriginalColumn = original.column;
2161
+ lastOriginalName = original.name;
2162
+ sourceMappingActive = true;
2163
+ } else if (sourceMappingActive) {
2164
+ map.addMapping({ generated: {
2165
+ line: generated.line,
2166
+ column: generated.column
2167
+ } });
2168
+ lastOriginalSource = null;
2169
+ sourceMappingActive = false;
2170
+ }
2171
+ for (var idx = 0, length = chunk.length; idx < length; idx++) if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
2172
+ generated.line++;
2173
+ generated.column = 0;
2174
+ if (idx + 1 === length) {
2175
+ lastOriginalSource = null;
2176
+ sourceMappingActive = false;
2177
+ } else if (sourceMappingActive) map.addMapping({
2178
+ source: original.source,
2179
+ original: {
2180
+ line: original.line,
2181
+ column: original.column
2182
+ },
2183
+ generated: {
2184
+ line: generated.line,
2185
+ column: generated.column
2186
+ },
2187
+ name: original.name
2188
+ });
2189
+ } else generated.column++;
2190
+ });
2191
+ this.walkSourceContents(function(sourceFile, sourceContent) {
2192
+ map.setSourceContent(sourceFile, sourceContent);
2193
+ });
2194
+ return {
2195
+ code: generated.code,
2196
+ map
2197
+ };
2198
+ };
2199
+ exports.SourceNode = SourceNode;
2200
+ }));
2201
+ //#endregion
2202
+ //#region src/compiler/ast.ts
2203
+ var import_source_map = (/* @__PURE__ */ __commonJSMin(((exports) => {
2204
+ exports.SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
2205
+ exports.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer;
2206
+ exports.SourceNode = require_source_node().SourceNode;
2207
+ })))();
2208
+ const TS_SMELL = /(^|[^:]):\s*(string|number|boolean|any|unknown|void)\b|\bas\s+(const\b|[A-Z])|\binterface\s+[A-Z]|^\s*type\s+[A-Z]|[a-zA-Z)\]]!\.|<(string|number|boolean)[,>]/m;
2209
+ function parseScript(code, opts) {
2210
+ try {
2211
+ return parse(code, {
2212
+ ecmaVersion: "latest",
2213
+ sourceType: "script",
2214
+ locations: true,
2215
+ allowReturnOutsideFunction: true,
2216
+ allowAwaitOutsideFunction: true,
2217
+ ...opts,
2218
+ onComment: opts === null || opts === void 0 ? void 0 : opts.comments
2219
+ });
2220
+ } catch (err) {
2221
+ if (err instanceof SyntaxError && TS_SMELL.test(code)) err.message += ". The code must be plain JavaScript: do not use TypeScript syntax (type annotations, \"as\" casts, generics, interfaces or type aliases).";
2222
+ throw err;
2223
+ }
2224
+ }
2225
+ /**
2226
+ * Depth-first pre-order walk. `ancestors` is ordered outermost → innermost and
2227
+ * excludes `node` itself; `parent` is `ancestors[ancestors.length - 1]`.
2228
+ */
2229
+ function walk(root, enter) {
2230
+ const ancestors = [];
2231
+ const visit = (node) => {
2232
+ enter(node, ancestors[ancestors.length - 1] ?? null, ancestors);
2233
+ ancestors.push(node);
2234
+ for (const key of Object.keys(node)) {
2235
+ if (key === "loc") continue;
2236
+ const value = node[key];
2237
+ if (Array.isArray(value)) {
2238
+ for (const child of value) if (isNode(child)) visit(child);
2239
+ } else if (isNode(value)) visit(value);
2240
+ }
2241
+ ancestors.pop();
2242
+ };
2243
+ visit(root);
2244
+ }
2245
+ const isNode = (value) => !!value && typeof value === "object" && typeof value.type === "string";
2246
+ const isStatementContainer = (node) => !!node && (node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock");
2247
+ /**
2248
+ * The statement that contains `node`: the outermost ancestor (or the node
2249
+ * itself) whose parent is a statement container.
2250
+ */
2251
+ function enclosingStatement(node, ancestors) {
2252
+ const chain = [...ancestors, node];
2253
+ for (let i = chain.length - 1; i > 0; i--) if (isStatementContainer(chain[i - 1])) return chain[i];
2254
+ return null;
2255
+ }
2256
+ /** The innermost node whose range contains [start, end] */
2257
+ function innermostContaining(ast, start, end) {
2258
+ let best = null;
2259
+ walk(ast, (node) => {
2260
+ if (node.start <= start && node.end >= end) {
2261
+ if (!best || node.start >= best.start && node.end <= best.end) best = node;
2262
+ }
2263
+ });
2264
+ return best;
2265
+ }
2266
+ //#endregion
2267
+ //#region src/compiler/plugins/async-wrapper.ts
2268
+ const Open = "async function __fn__() {";
2269
+ const Close = "}";
2270
+ const USER_CODE_START_MARKER = "/* __LLMZ_USER_CODE_START__ */";
2271
+ const USER_CODE_END_MARKER = "/* __LLMZ_USER_CODE_END__ */";
2272
+ /**
2273
+ * Wraps user code in an async function so top-level `await` and `return` parse,
2274
+ * and so plugins can target the `__fn__` declaration. The wrapper is removed
2275
+ * after transformation — drivers re-wrap the bare statements themselves.
2276
+ */
2277
+ const AsyncWrapper = {
2278
+ preProcessing: (code) => {
2279
+ return `"use strict";
2280
+ ${Open}
2281
+ ${USER_CODE_START_MARKER}
2282
+ ${code}
2283
+ ${USER_CODE_END_MARKER}
2284
+ ${Close}
2285
+ `.trim();
2286
+ },
2287
+ postProcessing: (code) => {
2288
+ code = code.slice(code.indexOf(Open) + 25);
2289
+ code = code.slice(0, code.lastIndexOf(Close));
2290
+ code = code.replace(USER_CODE_START_MARKER, "").replace(USER_CODE_END_MARKER, "");
2291
+ return code.trimEnd();
2292
+ }
2293
+ };
2294
+ //#endregion
2295
+ //#region src/compiler/plugins/line-tracking.ts
2296
+ const LineTrackingFnIdentifier = "__track__";
2297
+ const TRACKED_TYPES = /* @__PURE__ */ new Set([
2298
+ "FunctionDeclaration",
2299
+ "MethodDefinition",
2300
+ "ReturnStatement",
2301
+ "AwaitExpression",
2302
+ "ForOfStatement",
2303
+ "CallExpression",
2304
+ "UnaryExpression",
2305
+ "VariableDeclaration",
2306
+ "AssignmentExpression"
2307
+ ]);
2308
+ const SKIPPED_PARENT_TYPES = /* @__PURE__ */ new Set([
2309
+ "ArrowFunctionExpression",
2310
+ "Property",
2311
+ "AwaitExpression",
2312
+ "UnaryExpression",
2313
+ "ReturnStatement",
2314
+ "ForOfStatement",
2315
+ "ForStatement",
2316
+ "ForInStatement",
2317
+ "VariableDeclaration",
2318
+ "BinaryExpression",
2319
+ "LogicalExpression"
2320
+ ]);
2321
+ /**
2322
+ * Inserts a `__track__(<line>)` call before the statement containing each
2323
+ * tracked node — at most one per source line.
2324
+ */
2325
+ function applyLineTracking(ctx) {
2326
+ const trackedLines = /* @__PURE__ */ new Set();
2327
+ walk(ctx.ast, (node, parent, ancestors) => {
2328
+ if (!parent || !node.loc) return;
2329
+ if (!TRACKED_TYPES.has(node.type) && parent.type !== "BlockStatement") return;
2330
+ const line = node.loc.start.line;
2331
+ if (trackedLines.has(line) || SKIPPED_PARENT_TYPES.has(parent.type)) return;
2332
+ const statement = enclosingStatement(node, ancestors);
2333
+ if (!statement) return;
2334
+ trackedLines.add(line);
2335
+ ctx.ms.appendLeft(statement.start, `${LineTrackingFnIdentifier}(${line});`);
2336
+ });
2337
+ }
2338
+ //#endregion
2339
+ //#region src/compiler/plugins/replace-comment.ts
2340
+ const CommentFnIdentifier = "__comment__";
2341
+ const MARKER_TAGS = [USER_CODE_START_MARKER, USER_CODE_END_MARKER].map((m) => m.replace(/\/\*|\*\/|\s/g, ""));
2342
+ /** Blanks a range, keeping newlines so line numbers are preserved */
2343
+ const blank = (ctx, start, end) => {
2344
+ ctx.ms.update(start, end, ctx.code.slice(start, end).replace(/[^\n]/g, " "));
2345
+ };
2346
+ /**
2347
+ * Replaces comments at statement position with `__comment__("<text>", <line>)`
2348
+ * calls so the agent's inline "thinking" comments show up as traces at runtime.
2349
+ * Comments inside expressions and the user-code markers are blanked; comments
2350
+ * inside instrumented tool-call ranges are left verbatim.
2351
+ */
2352
+ function applyCommentReplacement(ctx, skipRanges) {
2353
+ for (const comment of ctx.comments) {
2354
+ const text = comment.value.trim();
2355
+ if (MARKER_TAGS.some((tag) => text.includes(tag))) {
2356
+ blank(ctx, comment.start, comment.end);
2357
+ continue;
2358
+ }
2359
+ if (skipRanges.some(([start, end]) => comment.start >= start && comment.end <= end)) continue;
2360
+ const container = innermostContaining(ctx.ast, comment.start, comment.end);
2361
+ if (isStatementContainer(container)) {
2362
+ const newlines = ctx.code.slice(comment.start, comment.end).replace(/[^\n]/g, "");
2363
+ ctx.ms.update(comment.start, comment.end, `;${CommentFnIdentifier}(${JSON.stringify(text)}, ${comment.loc.start.line});${newlines}`);
2364
+ } else blank(ctx, comment.start, comment.end);
2365
+ }
2366
+ }
2367
+ //#endregion
2368
+ //#region src/compiler/plugins/return-async.ts
2369
+ /**
2370
+ * Plans the instrumentation of the last statement of the `__fn__` wrapper so
2371
+ * the generated code always returns an awaited value (the isolated VM cannot
2372
+ * return a pending Promise):
2373
+ * - `return expr` → `return await (expr)`
2374
+ * - a trailing `call()` / `await call()` statement → `return await (…)`
2375
+ *
2376
+ * The prefix must be applied before, and the suffix after, all other edits so
2377
+ * they wrap around the tool-call instrumentation.
2378
+ */
2379
+ function planLastLineInstrumentation(ast) {
2380
+ const fn = ast.body.find((node) => {
2381
+ var _id;
2382
+ return node.type === "FunctionDeclaration" && ((_id = node.id) === null || _id === void 0 ? void 0 : _id.name) === "__fn__";
2383
+ });
2384
+ if (!fn) return null;
2385
+ const statements = fn.body.body;
2386
+ const last = statements[statements.length - 1];
2387
+ if (!last) return null;
2388
+ if (last.type === "ReturnStatement") {
2389
+ if (!last.argument) return null;
2390
+ return {
2391
+ prefixPos: last.argument.start,
2392
+ prefix: "await (",
2393
+ suffixPos: last.argument.end,
2394
+ suffix: ")"
2395
+ };
2396
+ }
2397
+ if (last.type === "ExpressionStatement" && (last.expression.type === "CallExpression" || last.expression.type === "AwaitExpression")) return {
2398
+ prefixPos: last.expression.start,
2399
+ prefix: "return await (",
2400
+ suffixPos: last.expression.end,
2401
+ suffix: ")"
2402
+ };
2403
+ return null;
2404
+ }
2405
+ //#endregion
2406
+ //#region src/compiler/plugins/track-tool-calls.ts
2407
+ const ToolCallTrackerFnIdentifier = "__toolc__";
2408
+ const ToolTrackerRetIdentifier = "__ret__";
2409
+ /**
2410
+ * Wraps every outermost call expression in an IIFE that reports
2411
+ * `__toolc__(<id>, "start" | "end", …)` events around the call:
2412
+ *
2413
+ * const x = (() => {
2414
+ * try {
2415
+ * __toolc__(0, "start");
2416
+ * const __ret__ = tool();
2417
+ * __toolc__(0, "end", __ret__);
2418
+ * return __ret__;
2419
+ * } catch (err) { __toolc__(1, "end", err); throw new Error(err.message); }
2420
+ * })()
2421
+ *
2422
+ * Calls assigned to a variable are registered in `calls` (keyed by the id used
2423
+ * in the catch clause — the id the runtime sees when a tool throws a
2424
+ * SnapshotSignal). Awaited calls get an async IIFE that awaits the call.
2425
+ *
2426
+ * Returns the wrapped source ranges so later passes can avoid editing inside.
2427
+ */
2428
+ function applyToolCallTracking(ctx, calls) {
2429
+ let callId = 0;
2430
+ const wrappedRanges = [];
2431
+ const src = ctx.code;
2432
+ const sliceOf = (node) => src.slice(node.start, node.end);
2433
+ const extractAssignment = (lval) => {
2434
+ const source = sliceOf(lval);
2435
+ if (lval.type === "Identifier") return {
2436
+ type: "single",
2437
+ left: source,
2438
+ evalFn: `let ${source} = arguments[0]; return { ${source} };`
2439
+ };
2440
+ if (lval.type === "ArrayPattern") {
2441
+ const elements = lval.elements.map((el) => el ? sliceOf(el) : "").join(", ");
2442
+ return {
2443
+ type: "array",
2444
+ left: elements,
2445
+ evalFn: `let [${elements}] = arguments[0] ?? []; return { ${elements} };`
2446
+ };
2447
+ }
2448
+ if (lval.type === "ObjectPattern") return {
2449
+ type: "object",
2450
+ left: source,
2451
+ evalFn: `let ${source} = arguments[0] ?? {}; return ${source};`
2452
+ };
2453
+ return {
2454
+ type: "unsupported",
2455
+ left: "",
2456
+ evalFn: ""
2457
+ };
2458
+ };
2459
+ walk(ctx.ast, (node, parent, ancestors) => {
2460
+ if (node.type !== "CallExpression") return;
2461
+ if (wrappedRanges.some(([start, end]) => node.start >= start && node.end <= end)) return;
2462
+ if ((parent === null || parent === void 0 ? void 0 : parent.type) === "YieldExpression") return;
2463
+ const declaration = [...ancestors].reverse().find((n) => n.type === "VariableDeclaration");
2464
+ const assignment = [...ancestors].reverse().find((n) => n.type === "AssignmentExpression");
2465
+ let lval = null;
2466
+ if (declaration) {
2467
+ var _;
2468
+ lval = ((_ = declaration.declarations[0]) === null || _ === void 0 ? void 0 : _.id) ?? null;
2469
+ }
2470
+ if (assignment) lval = assignment.left;
2471
+ const isAsync = (parent === null || parent === void 0 ? void 0 : parent.type) === "AwaitExpression";
2472
+ const start = (id) => `${ToolCallTrackerFnIdentifier}(${id}, "start");`;
2473
+ const end = (id, value) => `${ToolCallTrackerFnIdentifier}(${id}, "end", ${value});`;
2474
+ const prefix = (id) => `(${isAsync ? "async " : ""}() => {try {${start(id)}const ${ToolTrackerRetIdentifier} = ${isAsync ? "await " : ""}`;
2475
+ const successSuffix = (id) => `;${end(id, ToolTrackerRetIdentifier)}return ${ToolTrackerRetIdentifier};}`;
2476
+ if (!lval) {
2477
+ if (!sliceOf(node).trim().length) return;
2478
+ const catchClause = ` catch (err) {${end(callId, "err")}const __newError = new Error(err.message);__newError.stack = err.stack + ("\\n" + __newError.stack);throw __newError;}})()`;
2479
+ ctx.ms.appendLeft(node.start, prefix(callId));
2480
+ ctx.ms.appendRight(node.end, successSuffix(callId) + catchClause);
2481
+ wrappedRanges.push([node.start, node.end]);
2482
+ callId++;
2483
+ return;
2484
+ }
2485
+ const assign = extractAssignment(lval);
2486
+ if (assign.type === "unsupported") return;
2487
+ const tryId = callId;
2488
+ callId++;
2489
+ const callee = node.callee;
2490
+ let object = "global";
2491
+ let tool = callee.type === "Identifier" ? callee.name : sliceOf(callee);
2492
+ if (callee.type === "MemberExpression") {
2493
+ object = sliceOf(callee.object);
2494
+ const property = callee.property;
2495
+ tool = property.type === "Identifier" ? property.name : property.type === "Literal" ? String(property.value) : sliceOf(property);
2496
+ }
2497
+ const catchClause = ` catch (err) {${end(callId, "err")}throw new Error(err.message);}})()`;
2498
+ ctx.ms.appendLeft(node.start, prefix(tryId));
2499
+ ctx.ms.appendRight(node.end, successSuffix(tryId) + catchClause);
2500
+ wrappedRanges.push([node.start, node.end]);
2501
+ calls.set(callId, {
2502
+ object,
2503
+ tool,
2504
+ assignment: assign
2505
+ });
2506
+ });
2507
+ return wrappedRanges;
2508
+ }
2509
+ //#endregion
2510
+ //#region src/compiler/plugins/variable-extraction.ts
2511
+ const VariableTrackingFnIdentifier = "__var__";
2512
+ /**
2513
+ * Tracks user variables so the VM can read their values between iterations:
2514
+ * - after each variable declaration: `__var__("a", () => eval("a"));`
2515
+ * - at the top of function bodies, for their parameters
2516
+ *
2517
+ * The `eval` indirection captures the variable lazily in its own scope.
2518
+ */
2519
+ function applyVariableTracking(ctx, variables) {
2520
+ const trackerFor = (name) => {
2521
+ if (name.startsWith("__")) return null;
2522
+ variables.add(name);
2523
+ return `${VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}));`;
2524
+ };
2525
+ const track = (names) => names.map(trackerFor).filter((t) => !!t).join("");
2526
+ const declaredNames = (id) => {
2527
+ if (id.type === "Identifier") return [id.name];
2528
+ if (id.type === "ObjectPattern") {
2529
+ const names = [];
2530
+ for (const prop of id.properties) {
2531
+ if (prop.type !== "Property") continue;
2532
+ if (prop.value.type === "Identifier") names.push(prop.value.name);
2533
+ else if (prop.value.type === "ObjectPattern") names.push(...declaredNames(prop.value));
2534
+ else if (prop.value.type === "AssignmentPattern" && prop.value.left.type === "Identifier") names.push(prop.value.left.name);
2535
+ }
2536
+ return names;
2537
+ }
2538
+ if (id.type === "ArrayPattern") {
2539
+ const names = [];
2540
+ for (const element of id.elements) {
2541
+ if (!element) continue;
2542
+ if (element.type === "Identifier") names.push(element.name);
2543
+ else if (element.type === "RestElement" && element.argument.type === "Identifier") names.push(element.argument.name);
2544
+ else if (element.type === "AssignmentPattern" && element.left.type === "Identifier") names.push(element.left.name);
2545
+ }
2546
+ return names;
2547
+ }
2548
+ return [];
2549
+ };
2550
+ const paramNames = (params) => {
2551
+ const names = [];
2552
+ for (const param of params) if (param.type === "Identifier") names.push(param.name);
2553
+ else if (param.type === "AssignmentPattern" && param.left.type === "Identifier") names.push(param.left.name);
2554
+ else if (param.type === "ObjectPattern") {
2555
+ for (const prop of param.properties) if (prop.type === "Property" && prop.value.type === "Identifier") names.push(prop.value.name);
2556
+ } else if (param.type === "ArrayPattern") {
2557
+ for (const element of param.elements) if ((element === null || element === void 0 ? void 0 : element.type) === "Identifier") names.push(element.name);
2558
+ }
2559
+ return names;
2560
+ };
2561
+ walk(ctx.ast, (node, parent) => {
2562
+ if (node.type === "VariableDeclaration") {
2563
+ if (parent && (parent.type === "ForStatement" || parent.type === "ForInStatement" || parent.type === "ForOfStatement")) return;
2564
+ const trackers = track(node.declarations.flatMap((d) => declaredNames(d.id)));
2565
+ if (trackers) {
2566
+ const semi = ctx.code[node.end - 1] === ";" ? "" : ";";
2567
+ ctx.ms.appendRight(node.end, `${semi}${trackers}`);
2568
+ }
2569
+ return;
2570
+ }
2571
+ if (node.type === "FunctionDeclaration" || node.type === "ArrowFunctionExpression") {
2572
+ const trackers = track(paramNames(node.params));
2573
+ if (!trackers) return;
2574
+ const body = node.body;
2575
+ if (body.type === "BlockStatement") ctx.ms.appendRight(body.start + 1, trackers);
2576
+ else {
2577
+ ctx.ms.appendLeft(body.start, `{${trackers}return (`);
2578
+ ctx.ms.appendRight(body.end, ");}");
2579
+ }
2580
+ }
2581
+ });
2582
+ }
2583
+ //#endregion
2584
+ //#region src/compiler/compiler.ts
2585
+ const Identifiers = {
2586
+ ConsoleObjIdentifier: "console",
2587
+ LineTrackingFnIdentifier,
2588
+ VariableTrackingFnIdentifier,
2589
+ ToolCallTrackerFnIdentifier,
2590
+ ToolTrackerRetIdentifier,
2591
+ CommentFnIdentifier
2592
+ };
2593
+ const FUNCTION_TYPES = /* @__PURE__ */ new Set([
2594
+ "FunctionDeclaration",
2595
+ "FunctionExpression",
2596
+ "ArrowFunctionExpression"
2597
+ ]);
2598
+ /**
2599
+ * Whether the code contains a top-level `return` statement (one that would
2600
+ * return from the generated code itself, not from a nested function). Unlike a
2601
+ * regex, this ignores `return` inside comments, strings and nested functions.
2602
+ * Falls back to a word-boundary match if the code cannot be parsed.
2603
+ */
2604
+ function hasTopLevelReturn(code) {
2605
+ try {
2606
+ const ast = parseScript(code);
2607
+ let found = false;
2608
+ walk(ast, (node, _parent, ancestors) => {
2609
+ if (node.type === "ReturnStatement" && !ancestors.some((a) => FUNCTION_TYPES.has(a.type))) found = true;
2610
+ });
2611
+ return found;
2612
+ } catch {
2613
+ return /\breturn\b/.test(code);
2614
+ }
2615
+ }
2616
+ /**
2617
+ * Compiles the agent's generated JavaScript for VM execution:
2618
+ *
2619
+ * 1. wraps it in an async `__fn__` so top-level `await`/`return` parse
2620
+ * 2. instruments it in a single parse + text-edit pass:
2621
+ * line tracking, last-line return, tool-call tracking, comment tracing
2622
+ * and variable tracking
2623
+ * 3. unwraps it — the VM drivers re-wrap the bare statements themselves
2624
+ *
2625
+ * All edits preserve line numbers 1:1 with the wrapped source, so positions
2626
+ * reported at runtime map straight back to the user code.
2627
+ */
2628
+ function compile(code) {
2629
+ const wrapped = AsyncWrapper.preProcessing(code);
2630
+ const comments = [];
2631
+ const ast = parseScript(wrapped, { comments });
2632
+ const variables = /* @__PURE__ */ new Set();
2633
+ const toolCalls = /* @__PURE__ */ new Map();
2634
+ const lastLine = planLastLineInstrumentation(ast);
2635
+ const msMarkers = new MagicString(wrapped);
2636
+ if (lastLine) {
2637
+ msMarkers.appendLeft(lastLine.prefixPos, lastLine.prefix);
2638
+ msMarkers.appendRight(lastLine.suffixPos, lastLine.suffix);
2639
+ }
2640
+ const codeWithMarkers = msMarkers.toString();
2641
+ const ms = new MagicString(wrapped);
2642
+ const ctx = {
2643
+ code: wrapped,
2644
+ ms,
2645
+ ast,
2646
+ comments
2647
+ };
2648
+ applyLineTracking(ctx);
2649
+ if (lastLine) ms.appendLeft(lastLine.prefixPos, lastLine.prefix);
2650
+ applyCommentReplacement(ctx, applyToolCallTracking(ctx, toolCalls));
2651
+ applyVariableTracking(ctx, variables);
2652
+ if (lastLine) ms.appendRight(lastLine.suffixPos, lastLine.suffix);
2653
+ return {
2654
+ code: AsyncWrapper.postProcessing(ms.toString()),
2655
+ codeWithMarkers,
2656
+ map: ms.generateMap({
2657
+ hires: true,
2658
+ source: "<anonymous>"
2659
+ }),
2660
+ variables,
2661
+ toolCalls
2662
+ };
2663
+ }
2664
+ //#endregion
2665
+ //#region src/vm/errors.ts
2666
+ const handleErrorQuickJS = (err, code, _consumer, traces, variables, lines_executed, userCodeStartLine, currentToolCall) => {
2667
+ err = Signals.maybeDeserializeError(err);
2668
+ const lines = code.split("\n");
2669
+ const stackTrace = err.stack || "";
2670
+ const LINE_OFFSET = 1;
2671
+ const regex = /<quickjs>:(\d+)/g;
2672
+ const QUICKJS_WRAPPER_OFFSET = 9;
2673
+ const matches = Array.from(stackTrace.matchAll(regex)).map((x) => {
2674
+ const transformedCodeLine = Number(x[1]) - QUICKJS_WRAPPER_OFFSET;
2675
+ const line = Math.max(1, transformedCodeLine - userCodeStartLine + 1);
2676
+ const actualLine = lines[line - LINE_OFFSET] ?? "";
2677
+ return {
2678
+ line,
2679
+ column: actualLine.length - actualLine.trimStart().length
2680
+ };
2681
+ });
2682
+ if (matches.length === 0 && lines_executed.size > 0) {
2683
+ const lastLine = Math.max(...Array.from(lines_executed.keys()));
2684
+ const actualLine = lines[lastLine - LINE_OFFSET] ?? "";
2685
+ const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
2686
+ matches.push({
2687
+ line: lastLine,
2688
+ column: whiteSpacesCount
2689
+ });
2690
+ }
2691
+ return formatError(err, lines, matches, traces, variables, lines_executed, currentToolCall, code);
2692
+ };
2693
+ const handleErrorNode = (err, code, consumer, traces, variables, _lines_executed, currentToolCall) => {
2694
+ err = Signals.maybeDeserializeError(err);
2695
+ const lines = code.split("\n");
2696
+ const stackTrace = err.stack || "";
2697
+ const LINE_OFFSET = 1;
2698
+ const regex = /<anonymous>:(\d+):(\d+)/g;
2699
+ const RUNTIME_TO_MAP_OFFSET = -1;
2700
+ const WRAPPED_HEADER_LINES = 3;
2701
+ const matches = [...stackTrace.matchAll(regex)].map((x) => {
2702
+ const mapLine = Number(x[1]) + RUNTIME_TO_MAP_OFFSET;
2703
+ const originalLine = consumer.originalPositionFor({
2704
+ line: mapLine,
2705
+ column: Number(x[2])
2706
+ });
2707
+ const line = (originalLine.line ?? mapLine) - WRAPPED_HEADER_LINES;
2708
+ const actualLine = lines[line - LINE_OFFSET] ?? "";
2709
+ const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
2710
+ const minColumn = Math.max(whiteSpacesCount, originalLine.column);
2711
+ return {
2712
+ line,
2713
+ column: Math.min(minColumn, Number(x[2]))
2714
+ };
2715
+ });
2716
+ const { debugUserCode, truncatedCode } = buildDebugCode(lines, matches);
2717
+ if (err instanceof VMSignal) {
2718
+ err.stack = debugUserCode;
2719
+ err.truncatedCode = truncatedCode;
2720
+ err.variables = mapValues(variables, (getter) => isFunction(getter) ? getter() : getter);
2721
+ err.toolCall = currentToolCall;
2722
+ throw err;
2723
+ } else {
2724
+ var _matches$, _matches$2;
2725
+ traces.push({
2726
+ type: "code_execution_exception",
2727
+ position: [((_matches$ = matches[0]) === null || _matches$ === void 0 ? void 0 : _matches$.line) ?? 0, ((_matches$2 = matches[0]) === null || _matches$2 === void 0 ? void 0 : _matches$2.column) ?? 0],
2728
+ message: err.message,
2729
+ stackTrace: debugUserCode,
2730
+ started_at: Date.now()
2731
+ });
2732
+ throw new CodeExecutionError(err.message, code, debugUserCode);
2733
+ }
2734
+ };
2735
+ const handleCatch = (err, traces, variables, lines_executed) => {
2736
+ err = Signals.maybeDeserializeError(err);
2737
+ return {
2738
+ success: err instanceof VMSignal ? true : false,
2739
+ variables: mapValues(variables, (getter) => isFunction(getter) ? getter() : getter),
2740
+ error: err,
2741
+ signal: err instanceof VMSignal ? err : void 0,
2742
+ traces,
2743
+ lines_executed: Array.from(lines_executed)
2744
+ };
2745
+ };
2746
+ function buildDebugCode(lines, matches) {
2747
+ var _maxBy;
2748
+ const LINE_OFFSET = 1;
2749
+ const lastLine = ((_maxBy = maxBy(matches, (x) => x.line ?? 0)) === null || _maxBy === void 0 ? void 0 : _maxBy.line) ?? 0;
2750
+ let debugUserCode = "";
2751
+ let truncatedCode = "";
2752
+ let truncated = false;
2753
+ const appendCode = (line) => {
2754
+ debugUserCode += line;
2755
+ if (!truncated) truncatedCode += line;
2756
+ };
2757
+ for (let i = 0; i < lines.length; i++) {
2758
+ const VM_OFFSET = 2;
2759
+ const DISPLAY_OFFSET = 0;
2760
+ const line = lines[i];
2761
+ const correctedStackLineIndex = i + LINE_OFFSET + VM_OFFSET;
2762
+ const match = matches.find((x) => x.line + VM_OFFSET === correctedStackLineIndex);
2763
+ const paddedLineNumber = String(correctedStackLineIndex - VM_OFFSET - DISPLAY_OFFSET).padStart(3, "0");
2764
+ if (match) {
2765
+ appendCode(`> ${paddedLineNumber} | ${line}\n`);
2766
+ appendCode(` ${" ".repeat(paddedLineNumber.length + match.column)}^^^^^^^^^^\n`);
2767
+ if (match.line >= lastLine) truncated = true;
2768
+ } else appendCode(` ${paddedLineNumber} | ${line}\n`);
2769
+ }
2770
+ return {
2771
+ debugUserCode: cleanStackTrace(debugUserCode).trim(),
2772
+ truncatedCode: cleanStackTrace(truncatedCode).trim()
2773
+ };
2774
+ }
2775
+ function formatError(err, lines, matches, traces, variables, lines_executed, currentToolCall, code) {
2776
+ const { debugUserCode, truncatedCode } = buildDebugCode(lines, matches);
2777
+ if (err instanceof VMSignal) {
2778
+ const signalError = err;
2779
+ signalError.stack = debugUserCode;
2780
+ signalError.truncatedCode = truncatedCode;
2781
+ signalError.variables = mapValues(variables, (getter) => isFunction(getter) ? getter() : getter);
2782
+ signalError.toolCall = currentToolCall;
2783
+ return {
2784
+ success: true,
2785
+ variables: mapValues(variables, (getter) => isFunction(getter) ? getter() : getter),
2786
+ signal: err,
2787
+ lines_executed: Array.from(lines_executed)
2788
+ };
2789
+ } else {
2790
+ var _matches$3, _matches$4;
2791
+ traces.push({
2792
+ type: "code_execution_exception",
2793
+ position: [((_matches$3 = matches[0]) === null || _matches$3 === void 0 ? void 0 : _matches$3.line) ?? 0, ((_matches$4 = matches[0]) === null || _matches$4 === void 0 ? void 0 : _matches$4.column) ?? 0],
2794
+ message: err.message,
2795
+ stackTrace: debugUserCode,
2796
+ started_at: Date.now()
2797
+ });
2798
+ const codeError = new CodeExecutionError(err.message, code, debugUserCode);
2799
+ const deserializedError = Signals.maybeDeserializeError(codeError);
2800
+ return {
2801
+ success: false,
2802
+ variables: mapValues(variables, (getter) => isFunction(getter) ? getter() : getter),
2803
+ error: deserializedError,
2804
+ traces,
2805
+ lines_executed: Array.from(lines_executed)
2806
+ };
2807
+ }
2808
+ }
2809
+ //#endregion
2810
+ //#region src/vm/instrument.ts
2811
+ const USER_CODE_MARKER_TAG_START = "__LLMZ_USER_CODE_START__";
2812
+ const USER_CODE_MARKER_TAG_END = "__LLMZ_USER_CODE_END__";
2813
+ const NO_TRACKING = [
2814
+ Identifiers.CommentFnIdentifier,
2815
+ Identifiers.ToolCallTrackerFnIdentifier,
2816
+ Identifiers.ToolTrackerRetIdentifier,
2817
+ Identifiers.VariableTrackingFnIdentifier,
2818
+ Identifiers.ConsoleObjIdentifier
2819
+ ];
2820
+ function instrumentContext(context, transformed, traces, variables, lines_executed, consumer, userCodeStartLine) {
2821
+ const state = { currentToolCall: void 0 };
2822
+ context[Identifiers.CommentFnIdentifier] = (comment, line) => {
2823
+ if (comment.includes(USER_CODE_MARKER_TAG_START) || comment.includes(USER_CODE_MARKER_TAG_END)) return;
2824
+ traces.push({
2825
+ type: "comment",
2826
+ comment,
2827
+ line,
2828
+ started_at: Date.now()
2829
+ });
2830
+ };
2831
+ context[Identifiers.LineTrackingFnIdentifier] = (line) => {
2832
+ const mappedLine = consumer.originalPositionFor({
2833
+ line,
2834
+ column: 0
2835
+ }).line ?? line;
2836
+ const userCodeLine = Math.max(1, mappedLine - userCodeStartLine);
2837
+ lines_executed.set(userCodeLine, (lines_executed.get(userCodeLine) ?? 0) + 1);
2838
+ };
2839
+ context[Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
2840
+ if (NO_TRACKING.includes(name)) return;
2841
+ variables[name] = () => {
2842
+ try {
2843
+ const value = getter();
2844
+ if (typeof value === "function") return "[[non-primitive]]";
2845
+ return value;
2846
+ } catch {
2847
+ return "[[non-primitive]]";
2848
+ }
2849
+ };
2850
+ };
2851
+ context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
2852
+ const temp = Signals.maybeDeserializeError(outputOrError === null || outputOrError === void 0 ? void 0 : outputOrError.message);
2853
+ if (type === "end" && temp instanceof SnapshotSignal && (temp === null || temp === void 0 ? void 0 : temp.toolCall)) {
2854
+ var _transformed$toolCall;
2855
+ state.currentToolCall = {
2856
+ ...temp.toolCall,
2857
+ assignment: (_transformed$toolCall = transformed.toolCalls.get(callId)) === null || _transformed$toolCall === void 0 ? void 0 : _transformed$toolCall.assignment
2858
+ };
2859
+ }
2860
+ };
2861
+ context[Identifiers.ConsoleObjIdentifier] = { log: (...args) => {
2862
+ const message = args.shift();
2863
+ traces.push({
2864
+ type: "log",
2865
+ message,
2866
+ args,
2867
+ started_at: Date.now()
2868
+ });
2869
+ } };
2870
+ return state;
2871
+ }
2872
+ function findUserCodeStartLine(transformed) {
2873
+ const markerLines = (transformed.codeWithMarkers || transformed.code).split("\n");
2874
+ for (let i = 0; i < markerLines.length; i++) {
2875
+ var _markerLines$i;
2876
+ if ((_markerLines$i = markerLines[i]) === null || _markerLines$i === void 0 ? void 0 : _markerLines$i.includes("/* __LLMZ_USER_CODE_START__ */")) return i + 1;
2877
+ }
2878
+ return -1;
2879
+ }
2880
+ //#endregion
2881
+ //#region src/vm/drivers/node.ts
2882
+ var NodeDriver = class {
2883
+ async execute(ctx) {
2884
+ const { transformed, consumer, context, traces, code, lines_executed, variables } = ctx;
2885
+ const state = instrumentContext(context, transformed, traces, variables, lines_executed, consumer, 0);
2886
+ const AsyncFunction = async function() {}.constructor;
2887
+ return await (async () => {
2888
+ const descriptors = Object.getOwnPropertyDescriptors(context);
2889
+ const topLevelProperties = Object.keys(descriptors).filter((x) => !NO_TRACKING.includes(x) && descriptors[x] && typeof descriptors[x].value !== "function" && typeof descriptors[x].value !== "object");
2890
+ const __report = (name, value) => {
2891
+ if (context[name] !== void 0 && context[name] !== value) context[name] = value;
2892
+ };
2893
+ context.__report = __report;
2894
+ const reportAll = topLevelProperties.map((x) => `__report("${x}", ${x})`).join(";");
2895
+ const wrapper = `"use strict"; try { ${`let __${Identifiers.LineTrackingFnIdentifier} = ${Identifiers.LineTrackingFnIdentifier}; ${Identifiers.LineTrackingFnIdentifier} = function(line) { ${reportAll}; __${Identifiers.LineTrackingFnIdentifier}(line);}`};${transformed.code} } finally { ${reportAll} };`;
2896
+ return await AsyncFunction(...Object.keys(context), wrapper)(...Object.values(context));
2897
+ })().then((res) => {
2898
+ res = Signals.maybeDeserializeError(res);
2899
+ return {
2900
+ success: true,
2901
+ variables: mapValues(variables, (getter) => isFunction(getter) ? getter() : getter),
2902
+ signal: res instanceof VMSignal ? res : void 0,
2903
+ lines_executed: Array.from(lines_executed),
2904
+ return_value: res
2905
+ };
2906
+ }).catch((err) => handleErrorNode(err, code, consumer, traces, variables, lines_executed, state.currentToolCall)).catch((err) => handleCatch(err, traces, variables, lines_executed));
2907
+ }
2908
+ };
2909
+ //#endregion
2910
+ //#region src/vm/drivers/quickjs.ts
2911
+ let _quickJSModule;
2912
+ let _loadedVariant;
2913
+ const loadQuickJSModule = () => {
2914
+ const variant = getQuickJSVariant();
2915
+ if (!_quickJSModule || _loadedVariant !== variant) {
2916
+ _loadedVariant = variant;
2917
+ _quickJSModule = newQuickJSWASMModuleFromVariant(variant);
2918
+ }
2919
+ return _quickJSModule;
2920
+ };
2921
+ var QuickJSDriver = class {
2922
+ async execute(ctx) {
2923
+ const { transformed, consumer, context, traces, signal, timeout, code, lines_executed, variables } = ctx;
2924
+ const userCodeStartLine = findUserCodeStartLine(transformed);
2925
+ const state = instrumentContext(context, transformed, traces, variables, lines_executed, consumer, userCodeStartLine);
2926
+ const runtime = (await loadQuickJSModule()).newRuntime();
2927
+ runtime.setMemoryLimit(134217728);
2928
+ const timeoutHandler = shouldInterruptAfterDeadline(Date.now() + timeout);
2929
+ runtime.setInterruptHandler(() => {
2930
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) return true;
2931
+ return timeoutHandler(runtime);
2932
+ });
2933
+ const vm = runtime.newContext();
2934
+ const trackedProperties = /* @__PURE__ */ new Set();
2935
+ const referenceProperties = /* @__PURE__ */ new Set();
2936
+ const pendingPromises = [];
2937
+ const toVmValue = (value) => {
2938
+ if (typeof value === "string") return vm.newString(value);
2939
+ else if (typeof value === "number") return vm.newNumber(value);
2940
+ else if (typeof value === "boolean") return value ? vm.true : vm.false;
2941
+ else if (value === null) return vm.null;
2942
+ else if (value === void 0) return vm.undefined;
2943
+ else if (Array.isArray(value)) {
2944
+ const items = value.map((item) => {
2945
+ if (typeof item === "string") return JSON.stringify(item);
2946
+ else if (typeof item === "number" || typeof item === "boolean") return String(item);
2947
+ else if (item === null) return "null";
2948
+ else if (item === void 0) return "undefined";
2949
+ else if (typeof item === "object") return JSON.stringify(item);
2950
+ return "undefined";
2951
+ });
2952
+ const result = vm.evalCode(`[${items.join(",")}]`);
2953
+ if ("error" in result) {
2954
+ var _result$error;
2955
+ (_result$error = result.error) === null || _result$error === void 0 || _result$error.dispose();
2956
+ return vm.undefined;
2957
+ }
2958
+ return result.value;
2959
+ } else if (typeof value === "object") {
2960
+ const obj = vm.newObject();
2961
+ for (const [k, v] of Object.entries(value)) if (typeof v !== "function") {
2962
+ const propHandle = toVmValue(v);
2963
+ vm.setProp(obj, k, propHandle);
2964
+ disposeIfNeeded(propHandle);
2965
+ }
2966
+ return obj;
2967
+ }
2968
+ return vm.undefined;
2969
+ };
2970
+ const disposeIfNeeded = (handle) => {
2971
+ if (handle !== vm.true && handle !== vm.false && handle !== vm.null && handle !== vm.undefined) handle.dispose();
2972
+ };
2973
+ const bridgeFunction = (fn, _fnName = "anonymous") => {
2974
+ return (...argHandles) => {
2975
+ const args = argHandles.map((h) => vm.dump(h));
2976
+ try {
2977
+ const result = fn(...args);
2978
+ if (result && typeof result.then === "function") {
2979
+ const promise = vm.newPromise();
2980
+ pendingPromises.push({
2981
+ hostPromise: result,
2982
+ deferredPromise: promise
2983
+ });
2984
+ promise.settled.then(() => {
2985
+ if (runtime.alive) runtime.executePendingJobs();
2986
+ });
2987
+ return promise.handle;
2988
+ }
2989
+ return toVmValue(result);
2990
+ } catch (err) {
2991
+ const serialized = err instanceof Error ? err.message : String(err);
2992
+ throw new Error(serialized);
2993
+ }
2994
+ };
2995
+ };
2996
+ try {
2997
+ bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction);
2998
+ setupVariableTrackingBridge(vm, variables);
2999
+ const scriptCode = buildScriptCode(transformed.code);
3000
+ const copyBackContextFromVM = () => {
3001
+ for (const key of trackedProperties) {
3002
+ if (referenceProperties.has(key)) continue;
3003
+ try {
3004
+ const valueResult = vm.evalCode(`globalThis['${key}']`);
3005
+ const vmValue = vm.dump(valueResult.unwrap());
3006
+ valueResult.unwrap().dispose();
3007
+ try {
3008
+ context[key] = vmValue;
3009
+ } catch {}
3010
+ } catch {}
3011
+ }
3012
+ };
3013
+ const execResult = vm.evalCode(scriptCode, "<quickjs>");
3014
+ if ("error" in execResult) {
3015
+ if (execResult.error) {
3016
+ const err = vm.dump(execResult.error);
3017
+ execResult.error.dispose();
3018
+ throw new Error((err === null || err === void 0 ? void 0 : err.message) || "Execution failed");
3019
+ }
3020
+ throw new Error("Execution failed");
3021
+ }
3022
+ execResult.value.dispose();
3023
+ await this._pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded);
3024
+ const errorResult = vm.evalCode("globalThis.__llmz_error");
3025
+ const errorValue = vm.dump(errorResult.unwrap());
3026
+ errorResult.unwrap().dispose();
3027
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
3028
+ const reason = signal.reason;
3029
+ if (reason instanceof Error) throw reason;
3030
+ throw new Error(reason ? String(reason) : "Execution was aborted");
3031
+ }
3032
+ if (errorValue !== null && errorValue !== "") {
3033
+ try {
3034
+ copyBackContextFromVM();
3035
+ } catch {}
3036
+ const errorStackResult = vm.evalCode("globalThis.__llmz_error_stack");
3037
+ const errorStack = vm.dump(errorStackResult.unwrap()) || "";
3038
+ errorStackResult.unwrap().dispose();
3039
+ const deserializedError = Signals.maybeDeserializeError(errorValue);
3040
+ if (deserializedError instanceof VMSignal) {
3041
+ deserializedError.stack = errorStack;
3042
+ throw deserializedError;
3043
+ }
3044
+ const error = new Error(errorValue);
3045
+ error.stack = errorStack;
3046
+ throw error;
3047
+ }
3048
+ copyBackContextFromVM();
3049
+ const resultSetResult = vm.evalCode("globalThis.__llmz_result_set");
3050
+ const resultSet = vm.dump(resultSetResult.unwrap());
3051
+ resultSetResult.unwrap().dispose();
3052
+ let returnValue = void 0;
3053
+ if (resultSet) {
3054
+ const resultResult = vm.evalCode("globalThis.__llmz_result");
3055
+ returnValue = vm.dump(resultResult.unwrap());
3056
+ resultResult.unwrap().dispose();
3057
+ }
3058
+ returnValue = Signals.maybeDeserializeError(returnValue);
3059
+ return {
3060
+ success: true,
3061
+ variables: mapValues(variables, (getter) => isFunction(getter) ? getter() : getter),
3062
+ signal: returnValue instanceof VMSignal ? returnValue : void 0,
3063
+ lines_executed: Array.from(lines_executed),
3064
+ return_value: returnValue
3065
+ };
3066
+ } catch (err) {
3067
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
3068
+ const reason = signal.reason;
3069
+ const abortError = reason instanceof Error ? reason : new Error(reason ? String(reason) : "Execution was aborted");
3070
+ return handleErrorQuickJS(abortError, code, consumer, traces, variables, lines_executed, userCodeStartLine, ctx.currentToolCall ?? state.currentToolCall);
3071
+ }
3072
+ await Promise.all(pendingPromises.map(async ({ hostPromise, deferredPromise }) => {
3073
+ try {
3074
+ const value = await hostPromise;
3075
+ const vmValue = toVmValue(value);
3076
+ deferredPromise.resolve(vmValue);
3077
+ disposeIfNeeded(vmValue);
3078
+ } catch (err2) {
3079
+ const serialized = err2 instanceof Error ? err2.message : String(err2);
3080
+ const errValue = vm.newString(serialized);
3081
+ deferredPromise.reject(errValue);
3082
+ errValue.dispose();
3083
+ }
3084
+ })).catch(() => {});
3085
+ return handleErrorQuickJS(err, code, consumer, traces, variables, lines_executed, userCodeStartLine, ctx.currentToolCall ?? state.currentToolCall);
3086
+ } finally {
3087
+ try {
3088
+ vm.dispose();
3089
+ } catch {}
3090
+ try {
3091
+ runtime.dispose();
3092
+ } catch {}
3093
+ }
3094
+ }
3095
+ async _pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded) {
3096
+ const maxIterations = 1e3;
3097
+ let iteration = 0;
3098
+ while (iteration < maxIterations) {
3099
+ let hasJobs = false;
3100
+ const maxJobs = 1e4;
3101
+ for (let i = 0; i < maxJobs; i++) {
3102
+ var _runtime$executePendi;
3103
+ const pending = (_runtime$executePendi = runtime.executePendingJobs) === null || _runtime$executePendi === void 0 ? void 0 : _runtime$executePendi.call(runtime, -1);
3104
+ if ((pending === void 0 ? 0 : pending.unwrap()) <= 0) break;
3105
+ hasJobs = true;
3106
+ }
3107
+ const currentPromises = [...pendingPromises];
3108
+ pendingPromises.length = 0;
3109
+ if (currentPromises.length > 0) {
3110
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
3111
+ const reason = signal.reason;
3112
+ const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3113
+ for (const { deferredPromise } of currentPromises) {
3114
+ const errValue = vm.newString(abortMessage);
3115
+ deferredPromise.reject(errValue);
3116
+ errValue.dispose();
3117
+ }
3118
+ runtime.executePendingJobs();
3119
+ break;
3120
+ }
3121
+ let abortListener = null;
3122
+ if (signal) {
3123
+ abortListener = () => {
3124
+ const reason = signal.reason;
3125
+ const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3126
+ for (const { deferredPromise } of currentPromises) {
3127
+ const errValue = vm.newString(abortMessage);
3128
+ deferredPromise.reject(errValue);
3129
+ errValue.dispose();
3130
+ }
3131
+ runtime.executePendingJobs();
3132
+ };
3133
+ signal.addEventListener("abort", abortListener);
3134
+ }
3135
+ try {
3136
+ await Promise.all(currentPromises.map(async ({ hostPromise, deferredPromise }) => {
3137
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) return;
3138
+ try {
3139
+ const value = await hostPromise;
3140
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) return;
3141
+ const vmValue = toVmValue(value);
3142
+ deferredPromise.resolve(vmValue);
3143
+ disposeIfNeeded(vmValue);
3144
+ } catch (err) {
3145
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) return;
3146
+ const serialized = err instanceof Error ? err.message : String(err);
3147
+ const createErrorResult = vm.evalCode(`new Error(${JSON.stringify(serialized)})`);
3148
+ if ("error" in createErrorResult) {
3149
+ const errValue = vm.newString(serialized);
3150
+ deferredPromise.reject(errValue);
3151
+ errValue.dispose();
3152
+ } else {
3153
+ const errorHandle = createErrorResult.value;
3154
+ deferredPromise.reject(errorHandle);
3155
+ errorHandle.dispose();
3156
+ }
3157
+ }
3158
+ }));
3159
+ } finally {
3160
+ if (signal && abortListener) signal.removeEventListener("abort", abortListener);
3161
+ }
3162
+ runtime.executePendingJobs();
3163
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) break;
3164
+ }
3165
+ if (!hasJobs && pendingPromises.length === 0) break;
3166
+ iteration++;
3167
+ }
3168
+ if (iteration >= maxIterations) throw new Error("Maximum event loop iterations exceeded");
3169
+ }
3170
+ };
3171
+ function bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction) {
3172
+ for (const [key, value] of Object.entries(context)) {
3173
+ const descriptor = Object.getOwnPropertyDescriptor(context, key);
3174
+ if (descriptor && (descriptor.get || descriptor.set)) {
3175
+ referenceProperties.add(key);
3176
+ trackedProperties.add(key);
3177
+ bridgeGetterSetter(vm, key, void 0, descriptor, context, toVmValue);
3178
+ continue;
3179
+ }
3180
+ if (typeof value === "function") {
3181
+ const fnHandle = vm.newFunction(key, bridgeFunction(value, key));
3182
+ vm.setProp(vm.global, key, fnHandle);
3183
+ fnHandle.dispose();
3184
+ } else if (Array.isArray(value)) {
3185
+ trackedProperties.add(key);
3186
+ const arrayHandle = toVmValue(value);
3187
+ vm.setProp(vm.global, key, arrayHandle);
3188
+ disposeIfNeeded(arrayHandle);
3189
+ } else if (typeof value === "object" && value !== null) {
3190
+ trackedProperties.add(key);
3191
+ const objHandle = vm.newObject();
3192
+ const props = /* @__PURE__ */ new Set([...Object.keys(value), ...Object.getOwnPropertyNames(value)]);
3193
+ const getterSetterProps = [];
3194
+ for (const prop of props) {
3195
+ const propDescriptor = Object.getOwnPropertyDescriptor(value, prop);
3196
+ if (propDescriptor && (propDescriptor.get || propDescriptor.set)) {
3197
+ referenceProperties.add(`${key}.${prop}`);
3198
+ getterSetterProps.push({
3199
+ prop,
3200
+ descriptor: propDescriptor
3201
+ });
3202
+ } else if (typeof value[prop] === "function") {
3203
+ const propFnHandle = vm.newFunction(prop, bridgeFunction(value[prop], `${key}.${prop}`));
3204
+ vm.setProp(objHandle, prop, propFnHandle);
3205
+ propFnHandle.dispose();
3206
+ } else {
3207
+ const propHandle = toVmValue(value[prop]);
3208
+ vm.setProp(objHandle, prop, propHandle);
3209
+ disposeIfNeeded(propHandle);
3210
+ }
3211
+ }
3212
+ vm.setProp(vm.global, key, objHandle);
3213
+ objHandle.dispose();
3214
+ for (const { prop, descriptor } of getterSetterProps) bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue);
3215
+ if (Object.isSealed(value)) {
3216
+ var _sealResult$error;
3217
+ const sealResult = vm.evalCode(`Object.seal(globalThis['${key}']);`);
3218
+ if ("error" in sealResult) (_sealResult$error = sealResult.error) === null || _sealResult$error === void 0 || _sealResult$error.dispose();
3219
+ else sealResult.value.dispose();
3220
+ }
3221
+ if (!Object.isExtensible(value)) {
3222
+ var _preventResult$error;
3223
+ const preventResult = vm.evalCode(`Object.preventExtensions(globalThis['${key}']);`);
3224
+ if ("error" in preventResult) (_preventResult$error = preventResult.error) === null || _preventResult$error === void 0 || _preventResult$error.dispose();
3225
+ else preventResult.value.dispose();
3226
+ }
3227
+ } else {
3228
+ trackedProperties.add(key);
3229
+ const valueHandle = toVmValue(value);
3230
+ vm.setProp(vm.global, key, valueHandle);
3231
+ disposeIfNeeded(valueHandle);
3232
+ }
3233
+ }
3234
+ }
3235
+ function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue) {
3236
+ var _result$error2;
3237
+ const target = prop ? `${key}` : "globalThis";
3238
+ const propName = prop ?? key;
3239
+ const prefix = prop ? `${key}_${prop}` : key;
3240
+ let getterCode = "undefined";
3241
+ if (descriptor.get) {
3242
+ const getterBridge = vm.newFunction(`get_${propName}`, () => {
3243
+ try {
3244
+ return toVmValue(prop ? context[key][prop] : context[key]);
3245
+ } catch (err) {
3246
+ throw new Error(err instanceof Error ? err.message : String(err));
3247
+ }
3248
+ });
3249
+ const getterName = `__getter_${prefix}__`;
3250
+ vm.setProp(vm.global, getterName, getterBridge);
3251
+ getterBridge.dispose();
3252
+ getterCode = getterName;
3253
+ }
3254
+ let setterCode = "undefined";
3255
+ if (descriptor.set) {
3256
+ const setterBridge = vm.newFunction(`set_${propName}`, (valueHandle) => {
3257
+ try {
3258
+ const jsValue = vm.dump(valueHandle);
3259
+ if (prop) context[key][prop] = jsValue;
3260
+ else context[key] = jsValue;
3261
+ return vm.undefined;
3262
+ } catch (err) {
3263
+ throw new Error(err instanceof Error ? err.message : String(err));
3264
+ }
3265
+ });
3266
+ const setterName = `__setter_${prefix}__`;
3267
+ vm.setProp(vm.global, setterName, setterBridge);
3268
+ setterBridge.dispose();
3269
+ setterCode = setterName;
3270
+ }
3271
+ const definePropertyCode = `
3272
+ Object.defineProperty(${target}, '${propName}', {
3273
+ enumerable: true,
3274
+ configurable: ${descriptor.configurable !== false},
3275
+ get: ${getterCode},
3276
+ set: ${setterCode}
3277
+ });
3278
+ `;
3279
+ const result = vm.evalCode(definePropertyCode);
3280
+ if ("error" in result) (_result$error2 = result.error) === null || _result$error2 === void 0 || _result$error2.dispose();
3281
+ else result.value.dispose();
3282
+ }
3283
+ function setupVariableTrackingBridge(vm, variables) {
3284
+ const varTrackFnHandle = vm.newFunction(Identifiers.VariableTrackingFnIdentifier, (nameHandle, getterHandle) => {
3285
+ const name = vm.getString(nameHandle);
3286
+ if (NO_TRACKING.includes(name)) return;
3287
+ try {
3288
+ const valueResult = vm.callFunction(getterHandle, vm.undefined);
3289
+ if ("error" in valueResult) {
3290
+ var _valueResult$error;
3291
+ variables[name] = "[[non-primitive]]";
3292
+ (_valueResult$error = valueResult.error) === null || _valueResult$error === void 0 || _valueResult$error.dispose();
3293
+ return;
3294
+ }
3295
+ const value = vm.dump(valueResult.value);
3296
+ valueResult.value.dispose();
3297
+ if (typeof value === "function" || typeof value === "string" && value.includes("=>")) variables[name] = "[[non-primitive]]";
3298
+ else variables[name] = value;
3299
+ } catch {
3300
+ variables[name] = "[[non-primitive]]";
3301
+ }
3302
+ });
3303
+ vm.setProp(vm.global, Identifiers.VariableTrackingFnIdentifier, varTrackFnHandle);
3304
+ varTrackFnHandle.dispose();
3305
+ }
3306
+ function buildScriptCode(transformedCode) {
3307
+ return `
3308
+ "use strict";
3309
+ globalThis.__llmz_result = undefined;
3310
+ globalThis.__llmz_result_set = false;
3311
+ globalThis.__llmz_error = null;
3312
+ globalThis.__llmz_error_stack = null;
3313
+
3314
+ (async () => {
3315
+ try {
3316
+ async function __fn__() {
3317
+ ${transformedCode}
3318
+ }
3319
+
3320
+ globalThis.__llmz_result = await __fn__();
3321
+ globalThis.__llmz_result_set = true;
3322
+ } catch (err) {
3323
+ globalThis.__llmz_error = typeof err === 'string' ? err : String(err.message || err || '');
3324
+ globalThis.__llmz_error_stack = '' + (err.stack || '');
3325
+ }
3326
+ })();
3327
+ `.trim();
3328
+ }
3329
+ //#endregion
3330
+ //#region src/vm/index.ts
3331
+ const MAX_VM_EXECUTION_TIME = 6e4;
3332
+ const useQuickJS = () => {
3333
+ var _process;
3334
+ return typeof process === "undefined" || ((_process = process) === null || _process === void 0 || (_process = _process.env) === null || _process === void 0 ? void 0 : _process.USE_QUICKJS) !== "false";
3335
+ };
3336
+ const isWorkerd = () => {
3337
+ var _navigator;
3338
+ return typeof navigator !== "undefined" && ((_navigator = navigator) === null || _navigator === void 0 ? void 0 : _navigator.userAgent) === "Cloudflare-Workers";
3339
+ };
3340
+ /**
3341
+ * Pre-warms the VM so the first execution doesn't pay the QuickJS WASM
3342
+ * instantiation cost. Fire-and-forget: called as soon as the model starts
3343
+ * writing a `■run` block, so the module loads while the code is still being
3344
+ * generated. No-op when the QuickJS driver is disabled or already loaded.
3345
+ */
3346
+ const warmupVM = () => {
3347
+ if (useQuickJS()) loadQuickJSModule().catch(() => {});
3348
+ };
3349
+ async function runAsyncFunction(context, code, traces = [], signal = null, timeout = MAX_VM_EXECUTION_TIME) {
3350
+ const transformed = (() => {
3351
+ try {
3352
+ return compile(code);
3353
+ } catch (err) {
3354
+ traces.push({
3355
+ type: "invalid_code_exception",
3356
+ message: (err === null || err === void 0 ? void 0 : err.message) ?? "Unknown error",
3357
+ code,
3358
+ started_at: Date.now()
3359
+ });
3360
+ throw new InvalidCodeError(err.message, code);
3361
+ }
3362
+ })();
3363
+ const lines_executed = /* @__PURE__ */ new Map();
3364
+ const variables = {};
3365
+ const consumer = new import_source_map.SourceMapConsumer({
3366
+ version: transformed.map.version.toString(),
3367
+ mappings: transformed.map.mappings,
3368
+ names: transformed.map.names,
3369
+ sources: transformed.map.sources,
3370
+ sourcesContent: [transformed.code],
3371
+ file: transformed.map.file
3372
+ });
3373
+ context ??= {};
3374
+ for (const name of Array.from(transformed.variables)) delete context[name];
3375
+ let driver;
3376
+ if (useQuickJS()) try {
3377
+ driver = new QuickJSDriver();
3378
+ return await driver.execute({
3379
+ transformed,
3380
+ consumer,
3381
+ context,
3382
+ traces,
3383
+ signal,
3384
+ timeout,
3385
+ code,
3386
+ lines_executed,
3387
+ variables,
3388
+ currentToolCall: void 0
3389
+ });
3390
+ } catch (quickjsError) {
3391
+ const variant = getQuickJSVariant();
3392
+ const debugInfo = {
3393
+ error: (quickjsError === null || quickjsError === void 0 ? void 0 : quickjsError.message) || String(quickjsError),
3394
+ errorStack: quickjsError === null || quickjsError === void 0 ? void 0 : quickjsError.stack,
3395
+ wasmSource: variant._wasmSource,
3396
+ wasmLoadedSuccessfully: variant._wasmLoadedSuccessfully,
3397
+ wasmSize: variant._wasmSize,
3398
+ wasmLoadError: variant._wasmLoadError,
3399
+ nodeVersion: typeof process !== "undefined" && process.version ? process.version : "undefined",
3400
+ platform: typeof process !== "undefined" && process.platform ? process.platform : "undefined"
3401
+ };
3402
+ if (isWorkerd()) {
3403
+ console.error("QuickJS failed to load and the node driver is unavailable on Cloudflare Workers.");
3404
+ console.error("Debug info:", JSON.stringify(debugInfo, null, 2));
3405
+ if (quickjsError instanceof Error) {
3406
+ quickjsError.debugInfo = debugInfo;
3407
+ throw quickjsError;
3408
+ }
3409
+ throw new Error(`QuickJS failed to load on Cloudflare Workers: ${debugInfo.error}`);
3410
+ }
3411
+ console.warn("QuickJS failed to load, falling back to node driver.");
3412
+ console.warn("Error:", (quickjsError === null || quickjsError === void 0 ? void 0 : quickjsError.message) || quickjsError);
3413
+ console.warn("Debug info:", JSON.stringify(debugInfo, null, 2));
3414
+ }
3415
+ driver = new NodeDriver();
3416
+ return await driver.execute({
3417
+ transformed,
3418
+ consumer,
3419
+ context,
3420
+ traces,
3421
+ signal,
3422
+ timeout,
3423
+ code,
3424
+ lines_executed,
3425
+ variables,
3426
+ currentToolCall: void 0
3427
+ });
3428
+ }
3429
+ //#endregion
3430
+ export { runAsyncFunction, hasTopLevelReturn as t, warmupVM };