@enclave-vm/core 2.19.1 → 2.20.0-rc.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.
- package/README.md +291 -105
- package/adapters/worker-pool/config.d.ts +15 -5
- package/adapters/worker-pool/protocol.d.ts +27 -1
- package/adapters/worker-pool/worker-pool-adapter.d.ts +24 -0
- package/adapters/worker-pool/worker-slot.d.ts +35 -6
- package/async-context.d.ts +34 -0
- package/babel/babel-wrapper.d.ts +21 -12
- package/babel/multi-file-transform.d.ts +3 -0
- package/babel/text-scan.d.ts +54 -0
- package/bounded-json.d.ts +33 -0
- package/deadline-guard.d.ts +16 -0
- package/dynamic-import.d.ts +25 -0
- package/enclave-options.d.ts +62 -0
- package/enclave.d.ts +35 -8
- package/esm/index.mjs +5520 -917
- package/esm/worker.mjs +2777 -195
- package/execution-deadline.d.ts +6 -0
- package/global-function-gate.d.ts +34 -1
- package/index.d.ts +3 -3
- package/index.js +5562 -959
- package/interpreter/interpreter.d.ts +207 -10
- package/memory-tracker.d.ts +7 -0
- package/package.json +3 -3
- package/portable-enclave.d.ts +51 -0
- package/portable-globals.d.ts +2 -0
- package/realm-airlock.d.ts +6 -1
- package/realm-memory.d.ts +89 -0
- package/realm-regex-backstop.d.ts +18 -0
- package/realm-stack.d.ts +25 -0
- package/safe-runtime.d.ts +2 -0
- package/sandbox-rejections.d.ts +3 -1
- package/scoring/feature-extractor.d.ts +52 -1
- package/scoring/index.d.ts +2 -1
- package/scoring/scorers/index.d.ts +2 -1
- package/scoring/scorers/local-llm.scorer.d.ts +9 -3
- package/scoring/scorers/progressive.scorer.d.ts +28 -1
- package/scoring/scorers/rule-based.scorer.d.ts +11 -1
- package/scoring/scoring-gate.d.ts +2 -0
- package/scoring/types.d.ts +36 -8
- package/secure-proxy.d.ts +17 -3
- package/session/session.d.ts +8 -1
- package/session-types.d.ts +6 -4
- package/sidecar/index.d.ts +1 -1
- package/sidecar/reference-config.d.ts +18 -1
- package/sidecar/reference-resolver.d.ts +26 -3
- package/sidecar/reference-sidecar.d.ts +37 -0
- package/src/adapters/worker-pool/package.json +3 -3
- package/src/adapters/worker-pool/worker-script.js +2835 -465
- package/thrown-value.d.ts +59 -0
- package/types.d.ts +85 -19
- package/value-sanitizer.d.ts +6 -1
- package/worker.d.ts +2 -0
- package/worker.js +2767 -195
package/esm/worker.mjs
CHANGED
|
@@ -45,15 +45,73 @@ var CONSOLE_FACTORY_SOURCE = `
|
|
|
45
45
|
var toText = ''.constructor;
|
|
46
46
|
var freeze = Object.freeze;
|
|
47
47
|
var RealmError = Error;
|
|
48
|
+
var apply = Reflect.apply;
|
|
49
|
+
var isArray = Array.isArray;
|
|
50
|
+
var stringValueOf = ''.constructor.prototype.valueOf;
|
|
51
|
+
var numberValueOf = (0).constructor.prototype.valueOf;
|
|
48
52
|
|
|
49
|
-
|
|
53
|
+
// Whether a value has the internal slot that a built-in's valueOf reads.
|
|
54
|
+
function hasSlot(valueOf, value) {
|
|
55
|
+
try {
|
|
56
|
+
apply(valueOf, value, []);
|
|
57
|
+
return true;
|
|
58
|
+
} catch (e) {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// The JSON text of a value, given up as soon as it would be longer than limit characters. A
|
|
64
|
+
// value referenced many times is written as many times, so the text can be far longer than the
|
|
65
|
+
// value is large. What each member adds is counted as JSON.stringify writes it, and the count
|
|
66
|
+
// is a lower bound of its length (an escape only adds), so a text within the limit is never
|
|
67
|
+
// given up. The members JSON.stringify visits are counted as well, also those it leaves out (a
|
|
68
|
+
// function, undefined): at most as many as the limit has characters.
|
|
69
|
+
var TOO_LARGE = {};
|
|
70
|
+
function stringifyWithin(value, limit) {
|
|
71
|
+
var length = 0;
|
|
72
|
+
var visits = 0;
|
|
73
|
+
var root = true;
|
|
74
|
+
return stringify(value, function (key, member) {
|
|
75
|
+
if (++visits > limit) throw TOO_LARGE;
|
|
76
|
+
// A String or Number object is written as what it converts to; converted here, the way
|
|
77
|
+
// JSON.stringify converts it and once, so the count is of what is written.
|
|
78
|
+
if (member !== null && typeof member === 'object') {
|
|
79
|
+
if (hasSlot(stringValueOf, member)) member = toText(member);
|
|
80
|
+
else if (hasSlot(numberValueOf, member)) member = +member;
|
|
81
|
+
}
|
|
82
|
+
var added;
|
|
83
|
+
var kind = typeof member;
|
|
84
|
+
if (kind === 'string') added = member.length + 2;
|
|
85
|
+
else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
|
|
86
|
+
else if (kind === 'boolean') added = member ? 4 : 5;
|
|
87
|
+
else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
|
|
88
|
+
else added = 0;
|
|
89
|
+
if (!root) {
|
|
90
|
+
// An element of an array is written, as null if nothing else; a member of an object
|
|
91
|
+
// that is written has its key in front of it.
|
|
92
|
+
if (isArray(this)) added = added || 4;
|
|
93
|
+
else if (added > 0) added += key.length + 3;
|
|
94
|
+
}
|
|
95
|
+
root = false;
|
|
96
|
+
length += added;
|
|
97
|
+
if (length > limit) throw TOO_LARGE;
|
|
98
|
+
return member;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// An argument as it is written in the line, in at most room characters for an object: an
|
|
103
|
+
// object is written only when the line has room left, and its text within that room. TOO_LARGE
|
|
104
|
+
// when it does not fit.
|
|
105
|
+
function formatArgument(value, room) {
|
|
50
106
|
if (value === undefined) return 'undefined';
|
|
51
107
|
if (value === null) return 'null';
|
|
52
108
|
if (typeof value === 'object') {
|
|
109
|
+
if (room <= 0) throw TOO_LARGE;
|
|
53
110
|
try {
|
|
54
|
-
var json =
|
|
111
|
+
var json = stringifyWithin(value, room);
|
|
55
112
|
return json === undefined ? '' : json;
|
|
56
113
|
} catch (e) {
|
|
114
|
+
if (e === TOO_LARGE) throw e;
|
|
57
115
|
return toText(value);
|
|
58
116
|
}
|
|
59
117
|
}
|
|
@@ -64,19 +122,38 @@ var CONSOLE_FACTORY_SOURCE = `
|
|
|
64
122
|
var callCount = 0;
|
|
65
123
|
var totalBytes = 0;
|
|
66
124
|
|
|
125
|
+
function tooLarge() {
|
|
126
|
+
return new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
|
|
127
|
+
}
|
|
128
|
+
|
|
67
129
|
function method(level) {
|
|
68
130
|
return (...args) => {
|
|
69
131
|
callCount++;
|
|
70
132
|
if (callCount > maxCalls) {
|
|
71
133
|
throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
|
|
72
134
|
}
|
|
135
|
+
// The line is measured as it is built: what an argument may add is the room the limit
|
|
136
|
+
// leaves, so the work done on a line that does not fit is in proportion to the limit.
|
|
73
137
|
var line = '';
|
|
74
138
|
for (var i = 0; i < args.length; i++) {
|
|
75
|
-
|
|
139
|
+
var separator = i === 0 ? '' : ' ';
|
|
140
|
+
var text;
|
|
141
|
+
try {
|
|
142
|
+
text = formatArgument(args[i], maxBytes - totalBytes - line.length - separator.length);
|
|
143
|
+
} catch (e) {
|
|
144
|
+
if (e !== TOO_LARGE) throw e;
|
|
145
|
+
totalBytes = maxBytes + 1;
|
|
146
|
+
throw tooLarge();
|
|
147
|
+
}
|
|
148
|
+
line += separator + text;
|
|
149
|
+
if (totalBytes + line.length > maxBytes) {
|
|
150
|
+
totalBytes = maxBytes + 1;
|
|
151
|
+
throw tooLarge();
|
|
152
|
+
}
|
|
76
153
|
}
|
|
77
154
|
totalBytes += line.length;
|
|
78
155
|
if (totalBytes > maxBytes) {
|
|
79
|
-
throw
|
|
156
|
+
throw tooLarge();
|
|
80
157
|
}
|
|
81
158
|
try {
|
|
82
159
|
write(level, line);
|
|
@@ -116,11 +193,65 @@ function readProperty(object, key) {
|
|
|
116
193
|
if (key === "__proto__" || BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
117
194
|
return object[key];
|
|
118
195
|
}
|
|
196
|
+
var ENGINE_CALLED_KEYS = /* @__PURE__ */ new Set(["then", "toString", "valueOf", "toJSON", "toLocaleString", "toISOString"]);
|
|
197
|
+
function isEngineCalledKey(key) {
|
|
198
|
+
return ENGINE_CALLED_KEYS.has(key);
|
|
199
|
+
}
|
|
200
|
+
function assertStorable(target, key, value) {
|
|
201
|
+
if (typeof value !== "function") return;
|
|
202
|
+
if (ENGINE_CALLED_KEYS.has(key) || key === "join" && Array.isArray(target)) {
|
|
203
|
+
throw new InterpreterError(
|
|
204
|
+
`A function cannot be stored under '${key}': the sandbox runs a function only where the script calls it`
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
119
208
|
var MAX_STRING_OP_LENGTH = 1e6;
|
|
120
209
|
var MAX_JOIN_LENGTH = 16e6;
|
|
121
210
|
var MAX_TEXT_NESTING = 64;
|
|
122
211
|
var MAX_TEXT_ITEMS = 8e6;
|
|
123
212
|
var MAX_ARRAY_LENGTH = 1e6;
|
|
213
|
+
var CLOCK_CHECK_STEPS = 256;
|
|
214
|
+
var WORK_PER_STEP = 16384;
|
|
215
|
+
var WRITE_WORK = 8;
|
|
216
|
+
var LOCALE_COMPARE_WORK = 64;
|
|
217
|
+
var SEARCH_PIECE_WORK = 2 ** 20;
|
|
218
|
+
var LONG_SEARCH_TEXT = 64;
|
|
219
|
+
var MAX_CALL_WORK = 2 ** 33;
|
|
220
|
+
var MAX_BIGINT_BITS = 2 ** 20;
|
|
221
|
+
var MAX_BIGINT_DIGITS = Math.ceil(MAX_BIGINT_BITS * Math.log10(2)) + 1;
|
|
222
|
+
var WORD_BITS = 64;
|
|
223
|
+
var BIGINT_WORK = 64;
|
|
224
|
+
var BIGINT_TEXT_WORK = 1024;
|
|
225
|
+
var COMPARISONS = /* @__PURE__ */ new Set(["==", "!=", "<", "<=", ">", ">="]);
|
|
226
|
+
function bitsOf(value) {
|
|
227
|
+
const hex = value.toString(16);
|
|
228
|
+
const start = value < 0n ? 1 : 0;
|
|
229
|
+
return (hex.length - start - 1) * 4 + (32 - Math.clz32(Number.parseInt(hex[start], 16)));
|
|
230
|
+
}
|
|
231
|
+
function bigIntTooLarge() {
|
|
232
|
+
return new InterpreterError(`A BigInt cannot be larger than ${MAX_BIGINT_BITS} bits`);
|
|
233
|
+
}
|
|
234
|
+
var CONSTANT_STRING_METHODS = /* @__PURE__ */ new Set([
|
|
235
|
+
"at",
|
|
236
|
+
"charAt",
|
|
237
|
+
"charCodeAt",
|
|
238
|
+
"codePointAt",
|
|
239
|
+
"valueOf",
|
|
240
|
+
"toString",
|
|
241
|
+
"slice",
|
|
242
|
+
"substring",
|
|
243
|
+
"substr",
|
|
244
|
+
"concat",
|
|
245
|
+
"startsWith",
|
|
246
|
+
"endsWith",
|
|
247
|
+
"padStart",
|
|
248
|
+
"padEnd",
|
|
249
|
+
"repeat"
|
|
250
|
+
]);
|
|
251
|
+
var CONSTANT_ARRAY_METHODS = /* @__PURE__ */ new Set(["at", "push", "pop", "slice", "keys", "values", "entries"]);
|
|
252
|
+
var TEXT_SEARCHES = /* @__PURE__ */ new Set(["indexOf", "lastIndexOf", "includes", "split", "replace", "replaceAll"]);
|
|
253
|
+
var ARRAY_SEARCHES = /* @__PURE__ */ new Set(["indexOf", "lastIndexOf", "includes"]);
|
|
254
|
+
var NOT_SEARCHED = /* @__PURE__ */ Symbol("not searched");
|
|
124
255
|
var HIGHER_ORDER_ARRAY_METHODS = /* @__PURE__ */ new Set([
|
|
125
256
|
"map",
|
|
126
257
|
"flatMap",
|
|
@@ -141,10 +272,12 @@ var FunctionProtoCall = Function.prototype.call;
|
|
|
141
272
|
var FunctionProtoApply = Function.prototype.apply;
|
|
142
273
|
var FunctionProtoBind = Function.prototype.bind;
|
|
143
274
|
var FunctionProtoToString = Function.prototype.toString;
|
|
275
|
+
var ArrayProtoToLocaleString = Array.prototype.toLocaleString;
|
|
276
|
+
var StringProtoIndexOf = String.prototype.indexOf;
|
|
144
277
|
function methodsOf(prototype) {
|
|
145
278
|
const methods = /* @__PURE__ */ new Map();
|
|
146
279
|
for (const name of Object.getOwnPropertyNames(prototype)) {
|
|
147
|
-
if (name
|
|
280
|
+
if (isBlockedKey(name)) continue;
|
|
148
281
|
const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
|
|
149
282
|
if (descriptor && typeof descriptor.value === "function") methods.set(descriptor.value, name);
|
|
150
283
|
}
|
|
@@ -152,6 +285,34 @@ function methodsOf(prototype) {
|
|
|
152
285
|
}
|
|
153
286
|
var ARRAY_METHODS = methodsOf(Array.prototype);
|
|
154
287
|
var STRING_METHODS = methodsOf(String.prototype);
|
|
288
|
+
var OTHER_METHODS = (() => {
|
|
289
|
+
const prototypes = [
|
|
290
|
+
["Number", Number.prototype],
|
|
291
|
+
["Boolean", Boolean.prototype],
|
|
292
|
+
["BigInt", BigInt.prototype],
|
|
293
|
+
["Date", Date.prototype],
|
|
294
|
+
["Object", Object.prototype]
|
|
295
|
+
];
|
|
296
|
+
const methods = /* @__PURE__ */ new Map();
|
|
297
|
+
for (const [kind, prototype] of prototypes) {
|
|
298
|
+
for (const [method, name] of methodsOf(prototype)) {
|
|
299
|
+
if (!methods.has(method)) methods.set(method, { kind, name });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return methods;
|
|
303
|
+
})();
|
|
304
|
+
var RECEIVERS = {
|
|
305
|
+
Number: { noun: "a number", accepts: (receiver) => typeof receiver === "number" },
|
|
306
|
+
Boolean: { noun: "a boolean", accepts: (receiver) => typeof receiver === "boolean" },
|
|
307
|
+
BigInt: { noun: "a BigInt", accepts: (receiver) => typeof receiver === "bigint" },
|
|
308
|
+
Date: { noun: "a date", accepts: (receiver) => receiver instanceof Date },
|
|
309
|
+
Object: {
|
|
310
|
+
noun: "an object",
|
|
311
|
+
accepts: (receiver, name) => name !== "valueOf" || receiver !== null && (typeof receiver === "object" || typeof receiver === "function")
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
var ARRAY_ITERATOR_NEXT = Object.getPrototypeOf([][Symbol.iterator]()).next;
|
|
315
|
+
var LIBRARY_FUNCTIONS = /* @__PURE__ */ new WeakSet();
|
|
155
316
|
var ARRAY_DATA_ARGUMENTS = /* @__PURE__ */ new Map([
|
|
156
317
|
["push", () => true],
|
|
157
318
|
["unshift", () => true],
|
|
@@ -176,13 +337,18 @@ function convertsArguments(fn, count) {
|
|
|
176
337
|
CONVERTED_ARGUMENTS.set(fn, count);
|
|
177
338
|
return fn;
|
|
178
339
|
}
|
|
340
|
+
var ARGUMENT_CONVERSIONS = /* @__PURE__ */ new WeakMap();
|
|
341
|
+
function convertsBeforeCall(fn, convert) {
|
|
342
|
+
ARGUMENT_CONVERSIONS.set(fn, convert);
|
|
343
|
+
return fn;
|
|
344
|
+
}
|
|
179
345
|
var CALL_COSTS = /* @__PURE__ */ new WeakMap();
|
|
180
346
|
function chargedBeforeCall(fn, cost) {
|
|
181
347
|
CALL_COSTS.set(fn, cost);
|
|
182
348
|
return fn;
|
|
183
349
|
}
|
|
184
350
|
function newTextMeasure() {
|
|
185
|
-
return { length: 0, items: 0, active: /* @__PURE__ */ new Set(), functions: /* @__PURE__ */ new Map() };
|
|
351
|
+
return { length: 0, items: 0, active: /* @__PURE__ */ new Set(), functions: /* @__PURE__ */ new Map(), work: 0 };
|
|
186
352
|
}
|
|
187
353
|
function scalarTextLength(item, measure) {
|
|
188
354
|
switch (typeof item) {
|
|
@@ -190,8 +356,11 @@ function scalarTextLength(item, measure) {
|
|
|
190
356
|
case "boolean":
|
|
191
357
|
return 32;
|
|
192
358
|
// also covers a number in the longest locale format
|
|
193
|
-
case "bigint":
|
|
194
|
-
|
|
359
|
+
case "bigint": {
|
|
360
|
+
const bits = bitsOf(item);
|
|
361
|
+
if (bits > WORD_BITS) measure.work += bits * BIGINT_TEXT_WORK;
|
|
362
|
+
return Math.ceil(bits * Math.log10(2)) + 2;
|
|
363
|
+
}
|
|
195
364
|
case "function": {
|
|
196
365
|
let length = measure.functions.get(item);
|
|
197
366
|
if (length === void 0) {
|
|
@@ -255,6 +424,7 @@ function assertArrayTextWithinLimit(...values) {
|
|
|
255
424
|
measureArrayText(value, 1, measure, 0);
|
|
256
425
|
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
257
426
|
}
|
|
427
|
+
return measure?.length ?? 0;
|
|
258
428
|
}
|
|
259
429
|
var StepLimitError = class extends Error {
|
|
260
430
|
constructor(limit) {
|
|
@@ -262,17 +432,34 @@ var StepLimitError = class extends Error {
|
|
|
262
432
|
this.name = "StepLimitError";
|
|
263
433
|
}
|
|
264
434
|
};
|
|
435
|
+
var DeadlineError = class extends Error {
|
|
436
|
+
constructor() {
|
|
437
|
+
super("Execution deadline exceeded");
|
|
438
|
+
this.name = "TimeoutError";
|
|
439
|
+
}
|
|
440
|
+
};
|
|
265
441
|
var InterpreterError = class extends Error {
|
|
266
442
|
constructor(message) {
|
|
267
443
|
super(message);
|
|
268
444
|
this.name = "InterpreterError";
|
|
269
445
|
}
|
|
270
446
|
};
|
|
447
|
+
var AccumulatedText = class {
|
|
448
|
+
constructor(value, owed) {
|
|
449
|
+
this.value = value;
|
|
450
|
+
this.owed = owed;
|
|
451
|
+
}
|
|
452
|
+
};
|
|
271
453
|
var ReturnSignal = class {
|
|
272
454
|
constructor(value) {
|
|
273
455
|
this.value = value;
|
|
274
456
|
}
|
|
275
457
|
};
|
|
458
|
+
var ScriptThrown = class {
|
|
459
|
+
constructor(value) {
|
|
460
|
+
this.value = value;
|
|
461
|
+
}
|
|
462
|
+
};
|
|
276
463
|
var BreakSignal = class {
|
|
277
464
|
};
|
|
278
465
|
var ContinueSignal = class {
|
|
@@ -288,12 +475,11 @@ function createScriptError(name, message, code) {
|
|
|
288
475
|
error["name"] = name;
|
|
289
476
|
error["message"] = message;
|
|
290
477
|
if (code !== void 0) error["code"] = code;
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
});
|
|
478
|
+
const toString = function toString2() {
|
|
479
|
+
return message ? `${name}: ${message}` : name;
|
|
480
|
+
};
|
|
481
|
+
LIBRARY_FUNCTIONS.add(toString);
|
|
482
|
+
Object.defineProperty(error, "toString", { value: toString, enumerable: false });
|
|
297
483
|
SCRIPT_ERRORS.add(error);
|
|
298
484
|
return Object.freeze(error);
|
|
299
485
|
}
|
|
@@ -301,9 +487,10 @@ function isScriptError(value) {
|
|
|
301
487
|
return typeof value === "object" && value !== null && SCRIPT_ERRORS.has(value);
|
|
302
488
|
}
|
|
303
489
|
var Scope = class _Scope {
|
|
304
|
-
constructor(parent, depth) {
|
|
490
|
+
constructor(parent, depth, settle) {
|
|
305
491
|
this.parent = parent;
|
|
306
492
|
this.depth = depth ?? parent?.depth ?? 0;
|
|
493
|
+
this.settle = settle ?? parent?.settle ?? (() => void 0);
|
|
307
494
|
}
|
|
308
495
|
vars = /* @__PURE__ */ new Map();
|
|
309
496
|
/**
|
|
@@ -311,39 +498,69 @@ var Scope = class _Scope {
|
|
|
311
498
|
* function one more than where it was called from. A block inside has the depth around it.
|
|
312
499
|
*/
|
|
313
500
|
depth;
|
|
501
|
+
/** Charges what is still owed for the value of a variable that is read */
|
|
502
|
+
settle;
|
|
503
|
+
/**
|
|
504
|
+
* In the body of a callback that `reduce` called with a text: the name of the parameter that
|
|
505
|
+
* holds it. A block inside has the name around it; a function inside does not.
|
|
506
|
+
*/
|
|
507
|
+
accumulator;
|
|
314
508
|
child() {
|
|
315
|
-
|
|
509
|
+
const scope = new _Scope(this);
|
|
510
|
+
scope.accumulator = this.accumulator;
|
|
511
|
+
return scope;
|
|
316
512
|
}
|
|
317
513
|
/** The scope of one call of a function defined in this scope, running `depth` calls deep. */
|
|
318
514
|
activation(depth) {
|
|
319
515
|
return new _Scope(this, depth);
|
|
320
516
|
}
|
|
321
517
|
declare(name, value, mutable) {
|
|
322
|
-
this.vars.set(name, { value, mutable });
|
|
518
|
+
this.vars.set(name, { value, mutable, owed: 0 });
|
|
323
519
|
}
|
|
324
520
|
has(name) {
|
|
325
521
|
return this.vars.has(name) || (this.parent?.has(name) ?? false);
|
|
326
522
|
}
|
|
523
|
+
/**
|
|
524
|
+
* The variable as it is stored, or nothing when there is none. For the few readers that
|
|
525
|
+
* neither keep its value nor look into a text (its length, whether it is empty, appending to
|
|
526
|
+
* it): everything else reads through {@link get}.
|
|
527
|
+
*/
|
|
528
|
+
slot(name) {
|
|
529
|
+
return this.vars.get(name) ?? this.parent?.slot(name);
|
|
530
|
+
}
|
|
531
|
+
/** The value of a variable, for any use: what is still owed for it is charged first. */
|
|
327
532
|
get(name) {
|
|
328
|
-
const slot = this.
|
|
329
|
-
if (slot)
|
|
330
|
-
if (
|
|
331
|
-
|
|
533
|
+
const slot = this.slot(name);
|
|
534
|
+
if (!slot) throw new InterpreterError(`'${name}' is not defined`);
|
|
535
|
+
if (slot.owed > 0) {
|
|
536
|
+
const owed = slot.owed;
|
|
537
|
+
slot.owed = 0;
|
|
538
|
+
this.settle(owed);
|
|
539
|
+
}
|
|
540
|
+
return slot.value;
|
|
332
541
|
}
|
|
333
542
|
set(name, value) {
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
}
|
|
340
|
-
if (
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
}
|
|
344
|
-
throw new InterpreterError(`'${name}' is not defined`);
|
|
543
|
+
this.append(name, value, 0);
|
|
544
|
+
}
|
|
545
|
+
/** Assign a variable a text that was appended to its value, with what a reader still owes for it. */
|
|
546
|
+
append(name, value, owed) {
|
|
547
|
+
const slot = this.slot(name);
|
|
548
|
+
if (!slot) throw new InterpreterError(`'${name}' is not defined`);
|
|
549
|
+
if (!slot.mutable) throw new InterpreterError(`Assignment to constant '${name}'`);
|
|
550
|
+
slot.value = value;
|
|
551
|
+
slot.owed = owed;
|
|
345
552
|
}
|
|
346
553
|
};
|
|
554
|
+
function appendedTo(name, node) {
|
|
555
|
+
const operands = [];
|
|
556
|
+
let first = node;
|
|
557
|
+
while (first.type === "BinaryExpression" && first.operator === "+") {
|
|
558
|
+
operands.push(first.right);
|
|
559
|
+
first = first.left;
|
|
560
|
+
}
|
|
561
|
+
if (operands.length === 0 || first.type !== "Identifier" || first.name !== name) return void 0;
|
|
562
|
+
return operands.reverse();
|
|
563
|
+
}
|
|
347
564
|
var DEFAULT_MAX_PENDING_CALLS = 4096;
|
|
348
565
|
function ignoreRejection2() {
|
|
349
566
|
}
|
|
@@ -352,6 +569,7 @@ var Interpreter = class {
|
|
|
352
569
|
this.options = options;
|
|
353
570
|
this.globals = options.globals;
|
|
354
571
|
this.maxPendingCalls = options.maxPendingCalls ?? DEFAULT_MAX_PENDING_CALLS;
|
|
572
|
+
this.provide(this.globals, 2);
|
|
355
573
|
}
|
|
356
574
|
steps = 0;
|
|
357
575
|
/** Calls that have not returned: the running ones and the ones waiting on an `await` */
|
|
@@ -367,50 +585,101 @@ var Interpreter = class {
|
|
|
367
585
|
callerDepth = 0;
|
|
368
586
|
maxPendingCalls;
|
|
369
587
|
globals;
|
|
370
|
-
/**
|
|
588
|
+
/**
|
|
589
|
+
* What is owed for the text `reduce` is handing to its callback, for that function to read as
|
|
590
|
+
* it starts (in the same synchronous step, like {@link callerDepth}); otherwise nothing.
|
|
591
|
+
*/
|
|
592
|
+
accumulatorOwed;
|
|
593
|
+
/** The step count at which the clock is read next */
|
|
594
|
+
nextClockCheck = CLOCK_CHECK_STEPS;
|
|
595
|
+
/** What built-ins worked through that has not made a full step yet (see {@link work}) */
|
|
596
|
+
workDone = 0;
|
|
597
|
+
/** The error that ended the run (step budget, deadline, abort, allocation budget); set once, never caught */
|
|
371
598
|
fatal;
|
|
372
599
|
interpretedFunctions = /* @__PURE__ */ new WeakSet();
|
|
600
|
+
/** The functions the host provides: the globals, their members, and what `bind` made of them */
|
|
601
|
+
provided = /* @__PURE__ */ new WeakSet();
|
|
373
602
|
errorCopies = /* @__PURE__ */ new WeakMap();
|
|
603
|
+
/** BigInt literals of the program that were found to be within the size a BigInt may have */
|
|
604
|
+
checkedLiterals = /* @__PURE__ */ new WeakSet();
|
|
605
|
+
/**
|
|
606
|
+
* Remember the functions among the properties of `holder`, `depth` levels down: a global
|
|
607
|
+
* (`parseInt`) or a member of one (`Math.max`, a method of a tool namespace). Read from the
|
|
608
|
+
* property itself, so that nothing of the host runs for it. An array holds data.
|
|
609
|
+
*/
|
|
610
|
+
provide(holder, depth) {
|
|
611
|
+
if (holder === null || typeof holder !== "object" && typeof holder !== "function" || Array.isArray(holder))
|
|
612
|
+
return;
|
|
613
|
+
for (const name of Object.getOwnPropertyNames(holder)) {
|
|
614
|
+
const descriptor = Object.getOwnPropertyDescriptor(holder, name);
|
|
615
|
+
if (!descriptor || !("value" in descriptor)) continue;
|
|
616
|
+
const value = descriptor.value;
|
|
617
|
+
if (typeof value === "function") this.provided.add(value);
|
|
618
|
+
if (depth > 1) this.provide(value, depth - 1);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
374
621
|
/**
|
|
375
622
|
* Call a function for a script, with the checks that apply to a call the script writes itself.
|
|
376
623
|
* For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
|
|
377
624
|
* of the script, or a built-in or host function the script passed along.
|
|
378
625
|
*/
|
|
379
|
-
call(fn, args) {
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
626
|
+
async call(fn, args) {
|
|
627
|
+
try {
|
|
628
|
+
if (this.fatal !== void 0) throw this.fatal;
|
|
629
|
+
if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
|
|
630
|
+
if (this.interpretedFunctions.has(fn)) return await fn(...args);
|
|
631
|
+
return await this.callFunction(fn, void 0, args, this.callerDepth);
|
|
632
|
+
} catch (thrown) {
|
|
633
|
+
if (thrown instanceof ScriptThrown) throw thrown.value;
|
|
634
|
+
if (!(thrown instanceof Error)) throw new InterpreterError("Host operation failed");
|
|
635
|
+
throw thrown;
|
|
636
|
+
}
|
|
383
637
|
}
|
|
384
638
|
/** Number of AST nodes evaluated so far (for execution stats). */
|
|
385
639
|
get stepCount() {
|
|
386
640
|
return this.steps;
|
|
387
641
|
}
|
|
388
642
|
async run(program) {
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
643
|
+
try {
|
|
644
|
+
const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
|
|
645
|
+
for (const stmt of program.body) {
|
|
646
|
+
if (stmt.type === "FunctionDeclaration" && stmt.id) {
|
|
647
|
+
root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
|
|
648
|
+
}
|
|
393
649
|
}
|
|
650
|
+
let last;
|
|
651
|
+
for (const stmt of program.body) {
|
|
652
|
+
if (stmt.type === "FunctionDeclaration") continue;
|
|
653
|
+
last = await this.execStatement(stmt, root);
|
|
654
|
+
}
|
|
655
|
+
if (root.has("__ag_main")) {
|
|
656
|
+
const main = root.get("__ag_main");
|
|
657
|
+
if (typeof main === "function") return await main();
|
|
658
|
+
}
|
|
659
|
+
return last;
|
|
660
|
+
} catch (thrown) {
|
|
661
|
+
if (thrown instanceof ScriptThrown) throw thrown.value;
|
|
662
|
+
throw thrown;
|
|
394
663
|
}
|
|
395
|
-
let last;
|
|
396
|
-
for (const stmt of program.body) {
|
|
397
|
-
if (stmt.type === "FunctionDeclaration") continue;
|
|
398
|
-
last = await this.execStatement(stmt, root);
|
|
399
|
-
}
|
|
400
|
-
if (root.has("__ag_main")) {
|
|
401
|
-
const main = root.get("__ag_main");
|
|
402
|
-
if (typeof main === "function") return main();
|
|
403
|
-
}
|
|
404
|
-
return last;
|
|
405
664
|
}
|
|
406
665
|
/**
|
|
407
|
-
* End the run from outside: whatever of the script is still going (a
|
|
408
|
-
*
|
|
409
|
-
* host calls this when the execution has returned, so that no
|
|
666
|
+
* End the run from outside: whatever of the script is still going (a callback waiting for a
|
|
667
|
+
* tool call, a run that timed out while it waited) stops at its next step or its next call,
|
|
668
|
+
* whichever comes first. The host calls this when the execution has returned, so that no
|
|
669
|
+
* script code runs and no host function is called after it.
|
|
410
670
|
*/
|
|
411
671
|
stop() {
|
|
412
672
|
if (this.fatal === void 0) this.fatal = new InterpreterError("Execution ended");
|
|
413
673
|
}
|
|
674
|
+
/**
|
|
675
|
+
* Charge an allocation that a runtime helper of the host made for the script (the helpers a
|
|
676
|
+
* transformed `+` or template literal calls). The budget is one budget wherever it is asked:
|
|
677
|
+
* a refusal ends the run here as it does for what the interpreter charges itself, and no
|
|
678
|
+
* `catch` or `finally` of the script runs after it.
|
|
679
|
+
*/
|
|
680
|
+
chargeAllocation(bytes) {
|
|
681
|
+
this.charge(bytes);
|
|
682
|
+
}
|
|
414
683
|
/** End the run with an error no `catch` of the script can stop. */
|
|
415
684
|
end(error) {
|
|
416
685
|
if (this.fatal === void 0) this.fatal = error;
|
|
@@ -420,6 +689,90 @@ var Interpreter = class {
|
|
|
420
689
|
if (this.fatal !== void 0) throw this.fatal;
|
|
421
690
|
if (this.options.signal?.aborted) this.end(new InterpreterError("Execution aborted"));
|
|
422
691
|
if (++this.steps > this.options.maxSteps) this.end(new StepLimitError(this.options.maxSteps));
|
|
692
|
+
if (this.steps >= this.nextClockCheck) this.checkClock();
|
|
693
|
+
}
|
|
694
|
+
/** End the run when its deadline has passed. */
|
|
695
|
+
checkClock() {
|
|
696
|
+
this.nextClockCheck = this.steps + CLOCK_CHECK_STEPS;
|
|
697
|
+
const deadline = this.options.deadline;
|
|
698
|
+
if (deadline !== void 0 && Date.now() >= deadline) this.end(new DeadlineError());
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Count what a built-in works through for the script, in chars or items: the engine does it
|
|
702
|
+
* in one step of its own, however large the operands are. {@link WORK_PER_STEP} units are a
|
|
703
|
+
* step of the budget, and the clock is read whenever that adds a step.
|
|
704
|
+
*/
|
|
705
|
+
work(units) {
|
|
706
|
+
if (!(units > 0)) return;
|
|
707
|
+
this.workDone += units;
|
|
708
|
+
if (this.workDone < WORK_PER_STEP) return;
|
|
709
|
+
const steps = Math.floor(this.workDone / WORK_PER_STEP);
|
|
710
|
+
this.workDone -= steps * WORK_PER_STEP;
|
|
711
|
+
this.steps += steps;
|
|
712
|
+
if (this.steps > this.options.maxSteps) this.end(new StepLimitError(this.options.maxSteps));
|
|
713
|
+
this.checkClock();
|
|
714
|
+
}
|
|
715
|
+
/** {@link assertArrayTextWithinLimit}, and the text the arrays are written as counted as work. */
|
|
716
|
+
arrayOperands(...values) {
|
|
717
|
+
let measure;
|
|
718
|
+
for (const value of values) {
|
|
719
|
+
if (!Array.isArray(value)) continue;
|
|
720
|
+
measure ??= newTextMeasure();
|
|
721
|
+
measureArrayText(value, 1, measure, 0);
|
|
722
|
+
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
723
|
+
}
|
|
724
|
+
if (measure) this.work(measure.length * WRITE_WORK + measure.work);
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Count a BigInt an operation made: it is held to the size a BigInt may have, and beyond the
|
|
728
|
+
* size of a number what it holds is charged to the budget and making it counts as work. Also
|
|
729
|
+
* for the runtime helper that adds for a transformed `+`.
|
|
730
|
+
*
|
|
731
|
+
* @throws InterpreterError when the value is larger than {@link MAX_BIGINT_BITS}
|
|
732
|
+
*/
|
|
733
|
+
countBigInt(value) {
|
|
734
|
+
const bits = bitsOf(value);
|
|
735
|
+
if (bits > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
736
|
+
if (bits <= WORD_BITS) return;
|
|
737
|
+
this.work(bits * BIGINT_WORK);
|
|
738
|
+
this.charge(Math.ceil(bits / 8));
|
|
739
|
+
}
|
|
740
|
+
/** Count the work of writing a value as text, when it is a BigInt: the engine writes it in decimal. */
|
|
741
|
+
bigIntAsText(value) {
|
|
742
|
+
if (typeof value !== "bigint") return;
|
|
743
|
+
const bits = bitsOf(value);
|
|
744
|
+
if (bits > WORD_BITS) this.work(bits * BIGINT_TEXT_WORK);
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* What is checked before an operator is applied to a BigInt: the operations whose result can
|
|
748
|
+
* be far larger than their operands are refused from the operands, and what the engine reads
|
|
749
|
+
* to compare a BigInt with a text is bounded and counted.
|
|
750
|
+
*/
|
|
751
|
+
checkBigIntOperands(operator, left, right) {
|
|
752
|
+
if (typeof left === "bigint" && typeof right === "bigint") {
|
|
753
|
+
if (operator === "<<" || operator === ">>") {
|
|
754
|
+
const count = Number(operator === "<<" ? right : -right);
|
|
755
|
+
if (count > 0 && left !== 0n && bitsOf(left) + count > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
756
|
+
} else if (operator === "**") {
|
|
757
|
+
const bits = bitsOf(left);
|
|
758
|
+
if (bits > 1 && (bits - 1) * Number(right) + 1 > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
759
|
+
} else if (operator === "/" || operator === "%") {
|
|
760
|
+
const bits = bitsOf(left);
|
|
761
|
+
if (bits > WORD_BITS) this.work(bits * BIGINT_WORK);
|
|
762
|
+
}
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
const other = typeof left === "bigint" ? right : left;
|
|
766
|
+
if (COMPARISONS.has(operator)) {
|
|
767
|
+
const chars = typeof other === "string" ? other.length : assertArrayTextWithinLimit(other);
|
|
768
|
+
if (chars > MAX_BIGINT_DIGITS) {
|
|
769
|
+
throw new InterpreterError(`A BigInt cannot be compared with a text of more than ${MAX_BIGINT_DIGITS} chars`);
|
|
770
|
+
}
|
|
771
|
+
this.work(chars * BIGINT_TEXT_WORK);
|
|
772
|
+
} else if (operator === "+") {
|
|
773
|
+
this.bigIntAsText(left);
|
|
774
|
+
this.bigIntAsText(right);
|
|
775
|
+
}
|
|
423
776
|
}
|
|
424
777
|
/** Charge an allocation to the host's budget. */
|
|
425
778
|
charge(bytes) {
|
|
@@ -451,12 +804,19 @@ var Interpreter = class {
|
|
|
451
804
|
case "FunctionDeclaration":
|
|
452
805
|
if (node.id) scope.declare(node.id.name, this.makeFunction(node, scope), false);
|
|
453
806
|
return void 0;
|
|
454
|
-
case "ExpressionStatement":
|
|
455
|
-
|
|
807
|
+
case "ExpressionStatement": {
|
|
808
|
+
const expression = node.expression;
|
|
809
|
+
if (expression.type === "AssignmentExpression" && expression.left.type === "Identifier") {
|
|
810
|
+
const name = expression.left.name;
|
|
811
|
+
const appended = expression.operator === "+=" ? [expression.right] : expression.operator === "=" ? appendedTo(name, expression.right) : void 0;
|
|
812
|
+
if (appended !== void 0 && scope.has(name)) return this.execAppend(name, appended, scope);
|
|
813
|
+
}
|
|
814
|
+
return this.evalExpr(expression, scope);
|
|
815
|
+
}
|
|
456
816
|
case "BlockStatement":
|
|
457
817
|
return this.execBlock(node.body, scope.child());
|
|
458
818
|
case "IfStatement":
|
|
459
|
-
if (
|
|
819
|
+
if (await this.evalTest(node.test, scope)) return this.execStatement(node.consequent, scope);
|
|
460
820
|
if (node.alternate) return this.execStatement(node.alternate, scope);
|
|
461
821
|
return void 0;
|
|
462
822
|
case "ForOfStatement":
|
|
@@ -474,9 +834,9 @@ var Interpreter = class {
|
|
|
474
834
|
case "TryStatement":
|
|
475
835
|
return this.execTry(node, scope);
|
|
476
836
|
case "ThrowStatement":
|
|
477
|
-
throw await this.evalExpr(node.argument, scope);
|
|
837
|
+
throw new ScriptThrown(await this.evalExpr(node.argument, scope));
|
|
478
838
|
case "ReturnStatement":
|
|
479
|
-
throw new ReturnSignal(node.argument ? await this.
|
|
839
|
+
throw new ReturnSignal(node.argument ? await this.evalReturned(node.argument, scope) : void 0);
|
|
480
840
|
case "BreakStatement":
|
|
481
841
|
if (node.label) throw new InterpreterError("Labeled break is not supported");
|
|
482
842
|
throw new BreakSignal();
|
|
@@ -547,14 +907,14 @@ var Interpreter = class {
|
|
|
547
907
|
if (node.init.type === "VariableDeclaration") await this.execStatement(node.init, inner);
|
|
548
908
|
else await this.evalExpr(node.init, inner);
|
|
549
909
|
}
|
|
550
|
-
while (node.test ?
|
|
910
|
+
while (node.test ? await this.evalTest(node.test, inner) : true) {
|
|
551
911
|
this.tick();
|
|
552
912
|
if (!await this.runLoopBody(node.body, inner.child())) break;
|
|
553
913
|
if (node.update) await this.evalExpr(node.update, inner);
|
|
554
914
|
}
|
|
555
915
|
}
|
|
556
916
|
async execWhile(node, scope) {
|
|
557
|
-
while (
|
|
917
|
+
while (await this.evalTest(node.test, scope)) {
|
|
558
918
|
this.tick();
|
|
559
919
|
if (!await this.runLoopBody(node.body, scope.child())) break;
|
|
560
920
|
}
|
|
@@ -563,7 +923,7 @@ var Interpreter = class {
|
|
|
563
923
|
do {
|
|
564
924
|
this.tick();
|
|
565
925
|
if (!await this.runLoopBody(node.body, scope.child())) break;
|
|
566
|
-
} while (
|
|
926
|
+
} while (await this.evalTest(node.test, scope));
|
|
567
927
|
}
|
|
568
928
|
async execSwitch(node, scope) {
|
|
569
929
|
const value = await this.evalExpr(node.discriminant, scope);
|
|
@@ -596,12 +956,12 @@ var Interpreter = class {
|
|
|
596
956
|
}
|
|
597
957
|
}
|
|
598
958
|
/**
|
|
599
|
-
* What a `catch` clause receives. A value the script threw is its own. A host Error
|
|
600
|
-
*
|
|
601
|
-
* copy with its name, message and code.
|
|
959
|
+
* What a `catch` clause receives. A value the script threw is its own. A host Error is copied
|
|
960
|
+
* with its name, message and code; every other host rejection reason becomes a generic error.
|
|
602
961
|
*/
|
|
603
962
|
toScriptValue(thrown) {
|
|
604
|
-
if (
|
|
963
|
+
if (thrown instanceof ScriptThrown) return thrown.value;
|
|
964
|
+
if (!(thrown instanceof Error)) return createScriptError("Error", "Host operation failed");
|
|
605
965
|
const known = this.errorCopies.get(thrown);
|
|
606
966
|
if (known) return known;
|
|
607
967
|
const code = thrown.code;
|
|
@@ -621,6 +981,10 @@ var Interpreter = class {
|
|
|
621
981
|
if (node.regex) {
|
|
622
982
|
throw new InterpreterError("Regular expressions are not supported");
|
|
623
983
|
}
|
|
984
|
+
if (typeof node.value === "bigint" && !this.checkedLiterals.has(node)) {
|
|
985
|
+
if (bitsOf(node.value) > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
986
|
+
this.checkedLiterals.add(node);
|
|
987
|
+
}
|
|
624
988
|
return node.value;
|
|
625
989
|
case "Identifier":
|
|
626
990
|
return scope.has(node.name) ? scope.get(node.name) : this.readGlobal(node.name);
|
|
@@ -650,6 +1014,7 @@ var Interpreter = class {
|
|
|
650
1014
|
for (const [k, v] of Object.entries(spread)) {
|
|
651
1015
|
this.tick();
|
|
652
1016
|
if (!BLOCKED_KEYS.has(k)) {
|
|
1017
|
+
assertStorable(obj, k, v);
|
|
653
1018
|
obj[k] = v;
|
|
654
1019
|
count++;
|
|
655
1020
|
}
|
|
@@ -660,7 +1025,9 @@ var Interpreter = class {
|
|
|
660
1025
|
if (prop.kind !== "init") throw new InterpreterError("Getters and setters are not supported");
|
|
661
1026
|
const key = await this.propKey(prop, scope);
|
|
662
1027
|
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property key: ${key}`);
|
|
663
|
-
|
|
1028
|
+
const member = await this.evalExpr(prop.value, scope);
|
|
1029
|
+
assertStorable(obj, key, member);
|
|
1030
|
+
obj[key] = member;
|
|
664
1031
|
count++;
|
|
665
1032
|
}
|
|
666
1033
|
this.charge(count * 16);
|
|
@@ -671,7 +1038,8 @@ var Interpreter = class {
|
|
|
671
1038
|
case "UpdateExpression": {
|
|
672
1039
|
const ref = await this.resolveReference(node.argument, scope);
|
|
673
1040
|
const current = ref.get();
|
|
674
|
-
|
|
1041
|
+
this.arrayOperands(current);
|
|
1042
|
+
this.work(operandSize(current));
|
|
675
1043
|
const before = Number(current);
|
|
676
1044
|
const after = node.operator === "++" ? before + 1 : before - 1;
|
|
677
1045
|
ref.set(after);
|
|
@@ -686,7 +1054,7 @@ var Interpreter = class {
|
|
|
686
1054
|
return left ?? await this.evalExpr(node.right, scope);
|
|
687
1055
|
}
|
|
688
1056
|
case "ConditionalExpression":
|
|
689
|
-
return
|
|
1057
|
+
return await this.evalTest(node.test, scope) ? this.evalExpr(node.consequent, scope) : this.evalExpr(node.alternate, scope);
|
|
690
1058
|
case "SequenceExpression": {
|
|
691
1059
|
let last;
|
|
692
1060
|
for (const expression of node.expressions) last = await this.evalExpr(expression, scope);
|
|
@@ -718,17 +1086,107 @@ var Interpreter = class {
|
|
|
718
1086
|
throw new InterpreterError(`Unsupported expression: ${node.type}`);
|
|
719
1087
|
}
|
|
720
1088
|
}
|
|
1089
|
+
/**
|
|
1090
|
+
* `s += x` or `s = s + x…` as a statement: append to a variable.
|
|
1091
|
+
*
|
|
1092
|
+
* The engine does not copy a text to append to it: the new text links to the old one, and is
|
|
1093
|
+
* written out as a text of its own when something first looks into it. A loop that appends to
|
|
1094
|
+
* one variable therefore allocates what it appends, and is charged that. What is not charged
|
|
1095
|
+
* yet, the length of the text that was appended to, stays owed on the variable: it is paid by
|
|
1096
|
+
* the first read that could look into the new text or keep it (`Scope.get`), because from then
|
|
1097
|
+
* on it can exist as a full copy next to the texts it was built from. Nothing else can get
|
|
1098
|
+
* hold of the new text: as a statement, the assignment has no value.
|
|
1099
|
+
*/
|
|
1100
|
+
async execAppend(name, operands, scope) {
|
|
1101
|
+
this.tick();
|
|
1102
|
+
const { sum, owed } = await this.appendTo(name, operands, scope);
|
|
1103
|
+
scope.append(name, sum, owed);
|
|
1104
|
+
return sum;
|
|
1105
|
+
}
|
|
1106
|
+
/**
|
|
1107
|
+
* The value of the variable `name` with the operands appended, charged for what is appended.
|
|
1108
|
+
*
|
|
1109
|
+
* @returns The sum, and what is still owed for it when it is a text that was appended to a text
|
|
1110
|
+
*/
|
|
1111
|
+
async appendTo(name, operands, scope) {
|
|
1112
|
+
const variable = scope.slot(name);
|
|
1113
|
+
if (!variable) throw new InterpreterError(`'${name}' is not defined`);
|
|
1114
|
+
const start = variable.value;
|
|
1115
|
+
const owedAtStart = variable.owed;
|
|
1116
|
+
let sum = start;
|
|
1117
|
+
for (const operand of operands) {
|
|
1118
|
+
this.tick();
|
|
1119
|
+
const right = await this.evalExpr(operand, scope);
|
|
1120
|
+
const left = sum;
|
|
1121
|
+
sum = this.binary("+", left, right, true);
|
|
1122
|
+
if (typeof sum === "string") this.charge((sum.length - (typeof left === "string" ? left.length : 0)) * 2);
|
|
1123
|
+
}
|
|
1124
|
+
let owed = 0;
|
|
1125
|
+
if (typeof sum === "string" && typeof start === "string") {
|
|
1126
|
+
owed = owedAtStart > 0 && variable.owed === owedAtStart ? owedAtStart : start.length * 2;
|
|
1127
|
+
}
|
|
1128
|
+
return { sum, owed };
|
|
1129
|
+
}
|
|
1130
|
+
/**
|
|
1131
|
+
* The value a function returns. In a callback that `reduce` called with a text, the
|
|
1132
|
+
* accumulator itself and what is appended to it (`return text + item`) are returned as an
|
|
1133
|
+
* {@link AccumulatedText}, without paying what is owed for them: `reduce` carries it on.
|
|
1134
|
+
*/
|
|
1135
|
+
async evalReturned(node, scope) {
|
|
1136
|
+
const name = scope.accumulator;
|
|
1137
|
+
if (name === void 0) return this.evalExpr(node, scope);
|
|
1138
|
+
if (node.type === "ConditionalExpression") {
|
|
1139
|
+
this.tick();
|
|
1140
|
+
const branch = await this.evalTest(node.test, scope) ? node.consequent : node.alternate;
|
|
1141
|
+
return this.evalReturned(branch, scope);
|
|
1142
|
+
}
|
|
1143
|
+
if (node.type === "Identifier" && node.name === name) {
|
|
1144
|
+
const variable = scope.slot(name);
|
|
1145
|
+
if (variable !== void 0 && typeof variable.value === "string") {
|
|
1146
|
+
this.tick();
|
|
1147
|
+
return new AccumulatedText(variable.value, variable.owed);
|
|
1148
|
+
}
|
|
1149
|
+
} else {
|
|
1150
|
+
const appended = appendedTo(name, node);
|
|
1151
|
+
if (appended !== void 0 && scope.has(name)) {
|
|
1152
|
+
this.tick();
|
|
1153
|
+
const { sum, owed } = await this.appendTo(name, appended, scope);
|
|
1154
|
+
return typeof sum === "string" ? new AccumulatedText(sum, owed) : sum;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
return this.evalExpr(node, scope);
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* The variable an identifier names when it holds an appended text that is still owed for.
|
|
1161
|
+
* For the readers that learn nothing but its length or that it is a text.
|
|
1162
|
+
*/
|
|
1163
|
+
appendedText(node, scope) {
|
|
1164
|
+
if (node.type !== "Identifier") return void 0;
|
|
1165
|
+
const variable = scope.slot(node.name);
|
|
1166
|
+
return variable !== void 0 && variable.owed > 0 && typeof variable.value === "string" ? variable.value : void 0;
|
|
1167
|
+
}
|
|
1168
|
+
/** Evaluate a condition. Whether a text is empty is known from its length. */
|
|
1169
|
+
async evalTest(node, scope) {
|
|
1170
|
+
const text = this.appendedText(node, scope);
|
|
1171
|
+
if (text !== void 0) {
|
|
1172
|
+
this.tick();
|
|
1173
|
+
return text.length > 0;
|
|
1174
|
+
}
|
|
1175
|
+
return truthy(await this.evalExpr(node, scope));
|
|
1176
|
+
}
|
|
721
1177
|
async evalTemplate(node, scope) {
|
|
722
1178
|
let out = "";
|
|
723
1179
|
for (let i = 0; i < node.quasis.length; i++) {
|
|
724
1180
|
out += node.quasis[i].value.cooked ?? "";
|
|
725
1181
|
if (i < node.expressions.length) {
|
|
726
1182
|
const value = await this.evalExpr(node.expressions[i], scope);
|
|
727
|
-
|
|
1183
|
+
this.arrayOperands(value);
|
|
1184
|
+
this.bigIntAsText(value);
|
|
728
1185
|
out += String(value);
|
|
729
1186
|
if (out.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
730
1187
|
}
|
|
731
1188
|
}
|
|
1189
|
+
this.work(out.length * WRITE_WORK);
|
|
732
1190
|
this.charge(out.length * 2);
|
|
733
1191
|
return out;
|
|
734
1192
|
}
|
|
@@ -743,37 +1201,67 @@ var Interpreter = class {
|
|
|
743
1201
|
assertKeyAllowed(key);
|
|
744
1202
|
return delete object[key];
|
|
745
1203
|
}
|
|
1204
|
+
if (node.operator === "!" || node.operator === "typeof") {
|
|
1205
|
+
const text = this.appendedText(node.argument, scope);
|
|
1206
|
+
if (text !== void 0) {
|
|
1207
|
+
this.tick();
|
|
1208
|
+
return node.operator === "!" ? text.length === 0 : "string";
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
746
1211
|
const v = await this.evalExpr(node.argument, scope);
|
|
747
1212
|
switch (node.operator) {
|
|
748
1213
|
case "!":
|
|
749
1214
|
return !truthy(v);
|
|
750
|
-
case "-":
|
|
751
|
-
|
|
752
|
-
|
|
1215
|
+
case "-": {
|
|
1216
|
+
this.numericOperand(v);
|
|
1217
|
+
const negated = -v;
|
|
1218
|
+
if (typeof negated === "bigint") this.countBigInt(negated);
|
|
1219
|
+
return negated;
|
|
1220
|
+
}
|
|
753
1221
|
case "+":
|
|
754
|
-
|
|
1222
|
+
this.numericOperand(v);
|
|
755
1223
|
return +v;
|
|
756
1224
|
case "typeof":
|
|
757
1225
|
return typeof v;
|
|
758
|
-
case "~":
|
|
759
|
-
|
|
760
|
-
|
|
1226
|
+
case "~": {
|
|
1227
|
+
this.numericOperand(v);
|
|
1228
|
+
const inverted = ~v;
|
|
1229
|
+
if (typeof inverted === "bigint") this.countBigInt(inverted);
|
|
1230
|
+
return inverted;
|
|
1231
|
+
}
|
|
761
1232
|
case "void":
|
|
762
1233
|
return void 0;
|
|
763
1234
|
default:
|
|
764
1235
|
throw new InterpreterError(`Unsupported unary operator: ${node.operator}`);
|
|
765
1236
|
}
|
|
766
1237
|
}
|
|
1238
|
+
/** An operand the engine reads a number from: an array is joined first, a text is read through. */
|
|
1239
|
+
numericOperand(value) {
|
|
1240
|
+
this.arrayOperands(value);
|
|
1241
|
+
this.work(operandSize(value));
|
|
1242
|
+
}
|
|
767
1243
|
async evalBinary(node, scope) {
|
|
768
1244
|
if (node.left.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
1245
|
+
if (node.operator === "+") return this.evalSum(node, scope);
|
|
1246
|
+
if (node.operator === "===" || node.operator === "!==") {
|
|
1247
|
+
const literal = node.left.type === "Literal" ? node.left : node.right.type === "Literal" ? node.right : void 0;
|
|
1248
|
+
const text = this.appendedText(literal === node.left ? node.right : node.left, scope);
|
|
1249
|
+
if (literal !== void 0 && text !== void 0 && !literal.regex) {
|
|
1250
|
+
const value = literal.value;
|
|
1251
|
+
if (typeof value !== "string" || value.length !== text.length) {
|
|
1252
|
+
this.tick();
|
|
1253
|
+
this.tick();
|
|
1254
|
+
return node.operator === "!==";
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
769
1258
|
const l = await this.evalExpr(node.left, scope);
|
|
770
1259
|
const r = await this.evalExpr(node.right, scope);
|
|
771
1260
|
if (node.operator === "in") {
|
|
772
1261
|
if (r === null || typeof r !== "object" && typeof r !== "function") {
|
|
773
1262
|
throw new InterpreterError("Cannot use 'in' on a value that is not an object");
|
|
774
1263
|
}
|
|
775
|
-
|
|
776
|
-
const key = String(l);
|
|
1264
|
+
const key = this.keyText(l);
|
|
777
1265
|
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
778
1266
|
return key in r;
|
|
779
1267
|
}
|
|
@@ -784,15 +1272,56 @@ var Interpreter = class {
|
|
|
784
1272
|
}
|
|
785
1273
|
return this.binary(node.operator, l, r);
|
|
786
1274
|
}
|
|
787
|
-
/**
|
|
788
|
-
|
|
789
|
-
|
|
1275
|
+
/**
|
|
1276
|
+
* `a + b + c`: the operands from left to right, and one sum after the other. Only the last
|
|
1277
|
+
* sum is a value the script gets hold of, and it is charged in full; the ones before it are
|
|
1278
|
+
* part of it.
|
|
1279
|
+
*/
|
|
1280
|
+
async evalSum(node, scope) {
|
|
1281
|
+
const operands = [];
|
|
1282
|
+
let first = node;
|
|
1283
|
+
while (first.type === "BinaryExpression" && first.operator === "+") {
|
|
1284
|
+
operands.push(first.right);
|
|
1285
|
+
first = first.left;
|
|
1286
|
+
}
|
|
1287
|
+
if (first.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
1288
|
+
let sum = await this.evalExpr(first, scope);
|
|
1289
|
+
for (let i = operands.length - 1; i >= 0; i--) {
|
|
1290
|
+
if (i < operands.length - 1) this.tick();
|
|
1291
|
+
const right = await this.evalExpr(operands[i], scope);
|
|
1292
|
+
sum = this.binary("+", sum, right, i > 0);
|
|
1293
|
+
}
|
|
1294
|
+
return sum;
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* Apply a binary operator to two values.
|
|
1298
|
+
*
|
|
1299
|
+
* @param partOfSum - The result of `+` is an operand of the next `+` and nothing else: the
|
|
1300
|
+
* caller charges for the text that comes of it
|
|
1301
|
+
*/
|
|
1302
|
+
binary(operator, left, right, partOfSum = false) {
|
|
1303
|
+
if (typeof left !== "bigint" && typeof right !== "bigint") return this.operate(operator, left, right, partOfSum);
|
|
1304
|
+
this.checkBigIntOperands(operator, left, right);
|
|
1305
|
+
const result = this.operate(operator, left, right, partOfSum);
|
|
1306
|
+
if (typeof result === "bigint") this.countBigInt(result);
|
|
1307
|
+
return result;
|
|
1308
|
+
}
|
|
1309
|
+
operate(operator, left, right, partOfSum) {
|
|
1310
|
+
const strict = operator === "===" || operator === "!==";
|
|
1311
|
+
const loose = operator === "==" || operator === "!=";
|
|
1312
|
+
const convertsNextTo = (other) => !strict && (!loose || other !== null && other !== void 0 && typeof other !== "object" && typeof other !== "function");
|
|
1313
|
+
this.arrayOperands(convertsNextTo(right) ? left : void 0, convertsNextTo(left) ? right : void 0);
|
|
1314
|
+
if (operator !== "+") {
|
|
1315
|
+
if (typeof left === "string" && typeof right === "string") this.work(Math.min(left.length, right.length));
|
|
1316
|
+
else if (typeof left === "string" && convertsNextTo(right)) this.work(left.length);
|
|
1317
|
+
else if (typeof right === "string" && convertsNextTo(left)) this.work(right.length);
|
|
1318
|
+
}
|
|
790
1319
|
const l = left;
|
|
791
1320
|
const r = right;
|
|
792
1321
|
switch (operator) {
|
|
793
1322
|
case "+": {
|
|
794
1323
|
const sum = l + r;
|
|
795
|
-
if (typeof sum === "string") this.charge(
|
|
1324
|
+
if (typeof sum === "string" && !partOfSum) this.charge(sum.length * 2);
|
|
796
1325
|
return sum;
|
|
797
1326
|
}
|
|
798
1327
|
case "-":
|
|
@@ -843,6 +1372,11 @@ var Interpreter = class {
|
|
|
843
1372
|
*/
|
|
844
1373
|
async evalMemberTarget(node, scope) {
|
|
845
1374
|
if (node.object.type === "Super") throw new InterpreterError("super is not supported");
|
|
1375
|
+
const text = !node.computed && node.property.type === "Identifier" && node.property.name === "length" ? this.appendedText(node.object, scope) : void 0;
|
|
1376
|
+
if (text !== void 0) {
|
|
1377
|
+
this.tick();
|
|
1378
|
+
return { object: text, key: "length" };
|
|
1379
|
+
}
|
|
846
1380
|
const object = await this.evalExpr(node.object, scope);
|
|
847
1381
|
if (node.optional && (object === null || object === void 0)) throw new ChainShortCircuit();
|
|
848
1382
|
if (node.property.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
@@ -883,12 +1417,11 @@ var Interpreter = class {
|
|
|
883
1417
|
writeMember(object, key, value) {
|
|
884
1418
|
this.assertChangeable(object);
|
|
885
1419
|
assertKeyAllowed(key);
|
|
1420
|
+
assertStorable(object, key, value);
|
|
886
1421
|
if (Array.isArray(object)) {
|
|
887
|
-
const
|
|
888
|
-
if (
|
|
889
|
-
|
|
890
|
-
}
|
|
891
|
-
if (grownTo > object.length) this.charge((grownTo - object.length) * 8);
|
|
1422
|
+
const checked = checkArrayWrite(object, key, value);
|
|
1423
|
+
if (checked.length > object.length) this.charge((checked.length - object.length) * 8);
|
|
1424
|
+
value = checked.value;
|
|
892
1425
|
}
|
|
893
1426
|
object[key] = value;
|
|
894
1427
|
}
|
|
@@ -917,7 +1450,10 @@ var Interpreter = class {
|
|
|
917
1450
|
const construct = this.options.constructors?.get(callee);
|
|
918
1451
|
if (!construct) throw new InterpreterError("new works with the built-in types the sandbox provides only");
|
|
919
1452
|
const args = await this.evalArguments(node.arguments, scope);
|
|
920
|
-
if (!ARRAY_DATA_FUNCTIONS.has(callee))
|
|
1453
|
+
if (!ARRAY_DATA_FUNCTIONS.has(callee)) {
|
|
1454
|
+
this.arrayOperands(...args);
|
|
1455
|
+
for (const arg of args) this.work(typeof arg === "string" ? arg.length : 0);
|
|
1456
|
+
}
|
|
921
1457
|
const value = construct(args);
|
|
922
1458
|
this.chargeValue(value);
|
|
923
1459
|
return value;
|
|
@@ -952,6 +1488,7 @@ var Interpreter = class {
|
|
|
952
1488
|
* @param depth - How many calls deep the code that makes this call runs
|
|
953
1489
|
*/
|
|
954
1490
|
async callFunction(fn, thisArg, args, depth) {
|
|
1491
|
+
if (this.fatal !== void 0) throw this.fatal;
|
|
955
1492
|
for (let hops = 0; fn === FunctionProtoCall || fn === FunctionProtoApply || fn === FunctionProtoBind; hops++) {
|
|
956
1493
|
const name = fn === FunctionProtoCall ? "call" : fn === FunctionProtoApply ? "apply" : "bind";
|
|
957
1494
|
if (typeof thisArg !== "function" || hops >= 8) {
|
|
@@ -971,6 +1508,7 @@ var Interpreter = class {
|
|
|
971
1508
|
const interpreted = fn;
|
|
972
1509
|
return await this.withCallerDepth(depth, () => interpreted.apply(thisArg, args));
|
|
973
1510
|
}
|
|
1511
|
+
this.checkClock();
|
|
974
1512
|
const own = this.enterCall(depth);
|
|
975
1513
|
try {
|
|
976
1514
|
args = this.checkBuiltinCall(fn, thisArg, args);
|
|
@@ -978,20 +1516,228 @@ var Interpreter = class {
|
|
|
978
1516
|
if (arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function") {
|
|
979
1517
|
return await this.callArrayMethod(thisArg, arrayMethod, args, own);
|
|
980
1518
|
}
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
1519
|
+
if (arrayMethod === "toLocaleString") {
|
|
1520
|
+
const text = this.arrayLocaleText(thisArg, args, /* @__PURE__ */ new Set(), { length: 0 }, 0);
|
|
1521
|
+
this.chargeValue(text);
|
|
1522
|
+
return text;
|
|
1523
|
+
}
|
|
1524
|
+
const stringMethod = arrayMethod === void 0 ? STRING_METHODS.get(fn) : void 0;
|
|
1525
|
+
this.countRead(fn, arrayMethod, stringMethod, thisArg, args);
|
|
1526
|
+
let result = this.searchInPieces(arrayMethod, stringMethod, thisArg, args);
|
|
1527
|
+
if (result === NOT_SEARCHED) {
|
|
1528
|
+
const asIndex = stringMethod === "includes" && typeof thisArg === "string";
|
|
1529
|
+
const builtin = asIndex ? StringProtoIndexOf : fn;
|
|
1530
|
+
const builtinArgs = args;
|
|
1531
|
+
result = await this.withCallerDepth(own, () => builtin.apply(thisArg, builtinArgs));
|
|
1532
|
+
this.countSearched(arrayMethod, stringMethod, thisArg, args, result);
|
|
1533
|
+
if (asIndex) result = result !== -1;
|
|
1534
|
+
}
|
|
1535
|
+
if (stringMethod === "split" && Array.isArray(result)) {
|
|
985
1536
|
if (result.length > MAX_ARRAY_LENGTH) {
|
|
986
1537
|
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
987
1538
|
}
|
|
988
1539
|
}
|
|
1540
|
+
this.work(typeof result === "string" ? result.length * WRITE_WORK : operandSize(result));
|
|
989
1541
|
this.chargeValue(result);
|
|
990
1542
|
return result;
|
|
991
1543
|
} finally {
|
|
992
1544
|
this.pendingCalls--;
|
|
993
1545
|
}
|
|
994
1546
|
}
|
|
1547
|
+
/**
|
|
1548
|
+
* Count what a built-in or host function reads before it is called: its receiver, where the
|
|
1549
|
+
* method goes through it (a search, a conversion, a copy; not a method that reads one char or
|
|
1550
|
+
* works at the end of an array), and the texts among the arguments it converts or searches
|
|
1551
|
+
* for. A value a function only keeps is not read: an item to push, the array a callback is
|
|
1552
|
+
* handed with every item. An array that is read as text was counted where it was measured,
|
|
1553
|
+
* and what the call makes is counted when it returns.
|
|
1554
|
+
*/
|
|
1555
|
+
countRead(fn, arrayMethod, stringMethod, receiver, args) {
|
|
1556
|
+
let read = 0;
|
|
1557
|
+
if (typeof receiver === "string") {
|
|
1558
|
+
const counted = stringMethod === void 0 || !ARRAY_SEARCHES.has(stringMethod);
|
|
1559
|
+
if (counted && (stringMethod === void 0 || !CONSTANT_STRING_METHODS.has(stringMethod))) {
|
|
1560
|
+
read += receiver.length;
|
|
1561
|
+
}
|
|
1562
|
+
} else if (Array.isArray(receiver)) {
|
|
1563
|
+
const counted = arrayMethod !== "indexOf" && arrayMethod !== "lastIndexOf";
|
|
1564
|
+
if (counted && (arrayMethod === void 0 || !CONSTANT_ARRAY_METHODS.has(arrayMethod))) read += receiver.length;
|
|
1565
|
+
} else if (typeof receiver === "bigint") {
|
|
1566
|
+
this.bigIntAsText(receiver);
|
|
1567
|
+
}
|
|
1568
|
+
if (!ARRAY_DATA_FUNCTIONS.has(fn)) {
|
|
1569
|
+
const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
|
|
1570
|
+
const converted = CONVERTED_ARGUMENTS.get(fn) ?? args.length;
|
|
1571
|
+
for (let i = 0; i < args.length && i < converted; i++) {
|
|
1572
|
+
if (isData?.(i)) continue;
|
|
1573
|
+
const arg = args[i];
|
|
1574
|
+
if (typeof arg === "string") read += arg.length;
|
|
1575
|
+
else this.bigIntAsText(arg);
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
if (stringMethod === "localeCompare" && typeof receiver === "string") {
|
|
1579
|
+
const other = args[0];
|
|
1580
|
+
read = Math.min(receiver.length, typeof other === "string" ? other.length : receiver.length) * LOCALE_COMPARE_WORK;
|
|
1581
|
+
}
|
|
1582
|
+
this.work(read);
|
|
1583
|
+
}
|
|
1584
|
+
/**
|
|
1585
|
+
* Count a search for a place by how far the engine went: from where it started to where it
|
|
1586
|
+
* found what it looked for, or to the end. A script that goes through a long text with
|
|
1587
|
+
* `indexOf(text, position)` pays for the text once, not once per call.
|
|
1588
|
+
*
|
|
1589
|
+
* @param index - What the engine answered: the place, or -1
|
|
1590
|
+
*/
|
|
1591
|
+
countSearched(arrayMethod, stringMethod, receiver, args, index) {
|
|
1592
|
+
if (typeof index !== "number") return;
|
|
1593
|
+
const position = args[1];
|
|
1594
|
+
if (typeof receiver === "string" && stringMethod !== void 0 && ARRAY_SEARCHES.has(stringMethod)) {
|
|
1595
|
+
const length = receiver.length;
|
|
1596
|
+
if (stringMethod === "lastIndexOf") {
|
|
1597
|
+
const given = Number(position);
|
|
1598
|
+
const from = Number.isNaN(given) ? length : Math.min(Math.max(Math.trunc(given), 0), length);
|
|
1599
|
+
this.work(index === -1 ? from : from - index);
|
|
1600
|
+
} else {
|
|
1601
|
+
const from = Math.min(Math.max(integerOf(position), 0), length);
|
|
1602
|
+
this.work(index === -1 ? length - from : index - from);
|
|
1603
|
+
}
|
|
1604
|
+
} else if (Array.isArray(receiver) && (arrayMethod === "indexOf" || arrayMethod === "lastIndexOf")) {
|
|
1605
|
+
const length = receiver.length;
|
|
1606
|
+
if (arrayMethod === "lastIndexOf") {
|
|
1607
|
+
const given = args.length > 1 ? integerOf(position) : length - 1;
|
|
1608
|
+
const from = given >= 0 ? Math.min(given, length - 1) : length + given;
|
|
1609
|
+
this.work(index === -1 ? from + 1 : from - index);
|
|
1610
|
+
} else {
|
|
1611
|
+
const given = integerOf(position);
|
|
1612
|
+
const from = Math.min(given >= 0 ? given : Math.max(length + given, 0), length);
|
|
1613
|
+
this.work(index === -1 ? length - from : index - from);
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* Make a search whose cost in the engine is the product of two lengths, piece by piece: a text
|
|
1619
|
+
* in a text (the engine can need a comparison of the whole pattern at every position of a
|
|
1620
|
+
* text that nearly matches everywhere), or a long text among the items of an array (every
|
|
1621
|
+
* item of the same length can be compared to its end). Between the pieces a step is counted
|
|
1622
|
+
* and the clock is read, so that one such call ends with the budget or the deadline like any
|
|
1623
|
+
* other code. The answer is the engine's.
|
|
1624
|
+
*
|
|
1625
|
+
* @returns The result, or {@link NOT_SEARCHED} for a call that is not such a search or small
|
|
1626
|
+
* enough to be one piece: the engine makes it
|
|
1627
|
+
*/
|
|
1628
|
+
searchInPieces(arrayMethod, stringMethod, receiver, args) {
|
|
1629
|
+
const wanted = args[0];
|
|
1630
|
+
if (typeof wanted !== "string") return NOT_SEARCHED;
|
|
1631
|
+
const method = arrayMethod ?? stringMethod;
|
|
1632
|
+
if (typeof args[1] === "bigint" && method !== void 0 && ARRAY_SEARCHES.has(method)) return NOT_SEARCHED;
|
|
1633
|
+
if (stringMethod !== void 0 && typeof receiver === "string" && TEXT_SEARCHES.has(stringMethod)) {
|
|
1634
|
+
const small = receiver.length * wanted.length <= SEARCH_PIECE_WORK;
|
|
1635
|
+
if (small || wanted.length === 0 || wanted.length > receiver.length) return NOT_SEARCHED;
|
|
1636
|
+
return this.searchText(stringMethod, receiver, wanted, args);
|
|
1637
|
+
}
|
|
1638
|
+
if (arrayMethod !== void 0 && Array.isArray(receiver) && ARRAY_SEARCHES.has(arrayMethod)) {
|
|
1639
|
+
const small = receiver.length * wanted.length <= SEARCH_PIECE_WORK;
|
|
1640
|
+
if (small || wanted.length <= LONG_SEARCH_TEXT) return NOT_SEARCHED;
|
|
1641
|
+
return this.searchArray(arrayMethod, receiver, wanted, args);
|
|
1642
|
+
}
|
|
1643
|
+
return NOT_SEARCHED;
|
|
1644
|
+
}
|
|
1645
|
+
/** The first place at or after `from` where `pattern` starts in `text`, or -1. */
|
|
1646
|
+
findForward(text, pattern, from) {
|
|
1647
|
+
const last = text.length - pattern.length;
|
|
1648
|
+
const starts = Math.max(1, Math.floor(SEARCH_PIECE_WORK / pattern.length));
|
|
1649
|
+
for (let at = from; at <= last; at += starts) {
|
|
1650
|
+
if (at !== from) {
|
|
1651
|
+
this.tick();
|
|
1652
|
+
this.checkClock();
|
|
1653
|
+
}
|
|
1654
|
+
const end = Math.min(at + starts - 1, last) + pattern.length;
|
|
1655
|
+
const found = text.substring(at, end).indexOf(pattern);
|
|
1656
|
+
this.work(found === -1 ? end - at : found + pattern.length);
|
|
1657
|
+
if (found !== -1) return at + found;
|
|
1658
|
+
}
|
|
1659
|
+
return -1;
|
|
1660
|
+
}
|
|
1661
|
+
/** The last place at or before `from` where `pattern` starts in `text`, or -1. */
|
|
1662
|
+
findBackward(text, pattern, from) {
|
|
1663
|
+
const starts = Math.max(1, Math.floor(SEARCH_PIECE_WORK / pattern.length));
|
|
1664
|
+
for (let high = from; high >= 0; high -= starts) {
|
|
1665
|
+
if (high !== from) {
|
|
1666
|
+
this.tick();
|
|
1667
|
+
this.checkClock();
|
|
1668
|
+
}
|
|
1669
|
+
const low = Math.max(0, high - starts + 1);
|
|
1670
|
+
const end = high + pattern.length;
|
|
1671
|
+
const found = text.substring(low, end).lastIndexOf(pattern);
|
|
1672
|
+
this.work(found === -1 ? end - low : end - low - found);
|
|
1673
|
+
if (found !== -1) return low + found;
|
|
1674
|
+
}
|
|
1675
|
+
return -1;
|
|
1676
|
+
}
|
|
1677
|
+
/** `text.indexOf(pattern)` and the other searches for a text in a text, as the engine answers them. */
|
|
1678
|
+
searchText(name, text, pattern, args) {
|
|
1679
|
+
const length = text.length;
|
|
1680
|
+
const patternLength = pattern.length;
|
|
1681
|
+
switch (name) {
|
|
1682
|
+
case "indexOf":
|
|
1683
|
+
return this.findForward(text, pattern, Math.min(Math.max(integerOf(args[1]), 0), length));
|
|
1684
|
+
case "includes":
|
|
1685
|
+
return this.findForward(text, pattern, Math.min(Math.max(integerOf(args[1]), 0), length)) !== -1;
|
|
1686
|
+
case "lastIndexOf": {
|
|
1687
|
+
const position = Number(args[1]);
|
|
1688
|
+
const from = Number.isNaN(position) ? Number.POSITIVE_INFINITY : Math.trunc(position);
|
|
1689
|
+
return this.findBackward(text, pattern, Math.min(Math.max(from, 0), length - patternLength));
|
|
1690
|
+
}
|
|
1691
|
+
case "split": {
|
|
1692
|
+
const limit = args[1];
|
|
1693
|
+
const pieces = [];
|
|
1694
|
+
if (limit === 0) return pieces;
|
|
1695
|
+
let at = 0;
|
|
1696
|
+
for (let hit = this.findForward(text, pattern, 0); hit !== -1; hit = this.findForward(text, pattern, at)) {
|
|
1697
|
+
pieces.push(text.substring(at, hit));
|
|
1698
|
+
if (pieces.length >= limit) return pieces;
|
|
1699
|
+
at = hit + patternLength;
|
|
1700
|
+
}
|
|
1701
|
+
pieces.push(text.substring(at));
|
|
1702
|
+
return pieces;
|
|
1703
|
+
}
|
|
1704
|
+
default: {
|
|
1705
|
+
const replacement = String(args[1]);
|
|
1706
|
+
const parts = [];
|
|
1707
|
+
let at = 0;
|
|
1708
|
+
let hit = this.findForward(text, pattern, 0);
|
|
1709
|
+
while (hit !== -1) {
|
|
1710
|
+
parts.push(text.substring(at, hit), expandReplacement(replacement, text, hit, pattern));
|
|
1711
|
+
at = hit + patternLength;
|
|
1712
|
+
hit = name === "replace" ? -1 : this.findForward(text, pattern, at);
|
|
1713
|
+
}
|
|
1714
|
+
parts.push(text.substring(at));
|
|
1715
|
+
return parts.join("");
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
/** `array.indexOf(text)`, `lastIndexOf` and `includes` for a long text, as the engine answers them. */
|
|
1720
|
+
searchArray(name, array, wanted, args) {
|
|
1721
|
+
const length = array.length;
|
|
1722
|
+
const same = (item) => {
|
|
1723
|
+
if (typeof item !== "string" || item.length !== wanted.length) {
|
|
1724
|
+
this.work(1);
|
|
1725
|
+
return false;
|
|
1726
|
+
}
|
|
1727
|
+
this.work(wanted.length);
|
|
1728
|
+
return item === wanted;
|
|
1729
|
+
};
|
|
1730
|
+
if (name === "lastIndexOf") {
|
|
1731
|
+
let index2 = args.length > 1 ? integerOf(args[1]) : length - 1;
|
|
1732
|
+
index2 = index2 >= 0 ? Math.min(index2, length - 1) : length + index2;
|
|
1733
|
+
for (; index2 >= 0; index2--) if (same(array[index2])) return index2;
|
|
1734
|
+
return -1;
|
|
1735
|
+
}
|
|
1736
|
+
let index = integerOf(args[1]);
|
|
1737
|
+
if (index < 0) index = Math.max(length + index, 0);
|
|
1738
|
+
for (; index < length; index++) if (same(array[index])) return name === "includes" ? true : index;
|
|
1739
|
+
return name === "includes" ? false : -1;
|
|
1740
|
+
}
|
|
995
1741
|
/**
|
|
996
1742
|
* Count a call that starts `callerDepth` calls deep, until it returns.
|
|
997
1743
|
*
|
|
@@ -1034,11 +1780,13 @@ var Interpreter = class {
|
|
|
1034
1780
|
*/
|
|
1035
1781
|
bindFunction(target, boundThis, boundArgs) {
|
|
1036
1782
|
this.charge((boundArgs.length + 2) * 8);
|
|
1037
|
-
|
|
1783
|
+
const bound = (...rest) => {
|
|
1038
1784
|
const result = this.callFunction(target, boundThis, [...boundArgs, ...rest], this.callerDepth);
|
|
1039
1785
|
result.then(void 0, ignoreRejection2);
|
|
1040
1786
|
return result;
|
|
1041
1787
|
};
|
|
1788
|
+
this.provided.add(bound);
|
|
1789
|
+
return bound;
|
|
1042
1790
|
}
|
|
1043
1791
|
/**
|
|
1044
1792
|
* The checks before a built-in or host function runs. The engine performs such a call in one
|
|
@@ -1050,6 +1798,15 @@ var Interpreter = class {
|
|
|
1050
1798
|
checkBuiltinCall(fn, thisArg, args) {
|
|
1051
1799
|
const arrayMethod = ARRAY_METHODS.get(fn);
|
|
1052
1800
|
const stringMethod = arrayMethod === void 0 ? STRING_METHODS.get(fn) : void 0;
|
|
1801
|
+
const otherMethod = arrayMethod === void 0 && stringMethod === void 0 ? OTHER_METHODS.get(fn) : void 0;
|
|
1802
|
+
const engineMethod = arrayMethod !== void 0 || stringMethod !== void 0 || otherMethod !== void 0;
|
|
1803
|
+
if (!engineMethod && fn !== ARRAY_ITERATOR_NEXT && fn !== FunctionProtoToString && !this.provided.has(fn) && !LIBRARY_FUNCTIONS.has(fn)) {
|
|
1804
|
+
throw new InterpreterError("This built-in function is not available in the sandbox");
|
|
1805
|
+
}
|
|
1806
|
+
if (otherMethod !== void 0 && !RECEIVERS[otherMethod.kind].accepts(thisArg, otherMethod.name)) {
|
|
1807
|
+
const { kind, name } = otherMethod;
|
|
1808
|
+
throw new InterpreterError(`${kind} '${name}' works on ${RECEIVERS[kind].noun} only`);
|
|
1809
|
+
}
|
|
1053
1810
|
let arrayText = 0;
|
|
1054
1811
|
if (!ARRAY_DATA_FUNCTIONS.has(fn)) {
|
|
1055
1812
|
const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
|
|
@@ -1065,10 +1822,24 @@ var Interpreter = class {
|
|
|
1065
1822
|
if (Array.isArray(arg) && !isData?.(i)) measureArray(arg);
|
|
1066
1823
|
}
|
|
1067
1824
|
if (arrayMethod === void 0 && stringMethod === void 0 && Array.isArray(thisArg)) measureArray(thisArg);
|
|
1068
|
-
|
|
1825
|
+
const measured = measure;
|
|
1826
|
+
arrayText = measured?.length ?? 0;
|
|
1827
|
+
this.work(arrayText * WRITE_WORK + (measured?.work ?? 0));
|
|
1069
1828
|
}
|
|
1070
1829
|
if (stringMethod !== void 0) args = this.checkStringMethod(stringMethod, thisArg, args, arrayText);
|
|
1071
|
-
else if (arrayMethod !== void 0) this.checkArrayMethod(arrayMethod, thisArg, args);
|
|
1830
|
+
else if (arrayMethod !== void 0) args = this.checkArrayMethod(arrayMethod, thisArg, args);
|
|
1831
|
+
const callbackTaken = arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function";
|
|
1832
|
+
if (engineMethod && !callbackTaken) {
|
|
1833
|
+
const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
|
|
1834
|
+
for (let i = 0; i < args.length; i++) {
|
|
1835
|
+
if (typeof args[i] !== "function" || isData?.(i)) continue;
|
|
1836
|
+
const kind = arrayMethod !== void 0 ? "Array" : stringMethod !== void 0 ? "String" : otherMethod?.kind;
|
|
1837
|
+
const name = arrayMethod ?? stringMethod ?? otherMethod?.name;
|
|
1838
|
+
throw new InterpreterError(`${kind} '${name}' does not take a function in the sandbox`);
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
const convert = ARGUMENT_CONVERSIONS.get(fn);
|
|
1842
|
+
if (convert) args = convert(args);
|
|
1072
1843
|
const cost = CALL_COSTS.get(fn);
|
|
1073
1844
|
if (cost) this.charge(cost(args));
|
|
1074
1845
|
return args;
|
|
@@ -1078,6 +1849,10 @@ var Interpreter = class {
|
|
|
1078
1849
|
if (name === "match" || name === "matchAll" || name === "search") {
|
|
1079
1850
|
throw new InterpreterError(`String '${name}' is not supported: it runs a regular expression`);
|
|
1080
1851
|
}
|
|
1852
|
+
if (TEXT_SEARCHES.has(name) && args.length > 0) {
|
|
1853
|
+
const pattern = convertedOnce(args[0], String);
|
|
1854
|
+
if (pattern !== args[0]) args = [pattern, ...args.slice(1)];
|
|
1855
|
+
}
|
|
1081
1856
|
if (name === "replace" || name === "replaceAll") {
|
|
1082
1857
|
const replacement = args[1];
|
|
1083
1858
|
if (typeof replacement === "function") {
|
|
@@ -1101,14 +1876,15 @@ var Interpreter = class {
|
|
|
1101
1876
|
return args;
|
|
1102
1877
|
}
|
|
1103
1878
|
if (name === "repeat" || name === "padStart" || name === "padEnd") {
|
|
1104
|
-
const
|
|
1879
|
+
const count = convertedOnce(args[0], Number);
|
|
1880
|
+
const n = Number(count);
|
|
1105
1881
|
const produced = name === "repeat" ? receiver.length * (n > 0 ? n : 0) : Math.max(receiver.length, n > 0 ? n : 0);
|
|
1106
1882
|
if (produced > MAX_STRING_OP_LENGTH) {
|
|
1107
1883
|
throw new InterpreterError(
|
|
1108
1884
|
`String '${name}' would produce ${produced} chars, exceeding the ${MAX_STRING_OP_LENGTH} limit`
|
|
1109
1885
|
);
|
|
1110
1886
|
}
|
|
1111
|
-
return args;
|
|
1887
|
+
return args.length === 0 ? args : [count, ...args.slice(1)];
|
|
1112
1888
|
}
|
|
1113
1889
|
if (name === "concat") {
|
|
1114
1890
|
let produced = receiver.length + arrayText;
|
|
@@ -1122,6 +1898,20 @@ var Interpreter = class {
|
|
|
1122
1898
|
}
|
|
1123
1899
|
return args;
|
|
1124
1900
|
}
|
|
1901
|
+
if (name === "normalize") {
|
|
1902
|
+
const form = convertedOnce(args[0], String);
|
|
1903
|
+
const growth = form === "NFKC" || form === "NFKD" ? 18 : 4;
|
|
1904
|
+
if (receiver.length * growth > MAX_JOIN_LENGTH) {
|
|
1905
|
+
let produced = 0;
|
|
1906
|
+
for (let i = 0; i < receiver.length && produced <= MAX_JOIN_LENGTH; i++) {
|
|
1907
|
+
produced += receiver.charCodeAt(i) < 128 ? 1 : growth;
|
|
1908
|
+
}
|
|
1909
|
+
if (produced > MAX_JOIN_LENGTH) {
|
|
1910
|
+
throw new InterpreterError(`String 'normalize' could produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
return args.length === 0 ? args : [form, ...args.slice(1)];
|
|
1914
|
+
}
|
|
1125
1915
|
if (name === "split") {
|
|
1126
1916
|
const asked = args[1] === void 0 ? Number.POSITIVE_INFINITY : Number(args[1]) >>> 0;
|
|
1127
1917
|
return [args[0], Math.min(asked, MAX_ARRAY_LENGTH + 1)];
|
|
@@ -1134,44 +1924,56 @@ var Interpreter = class {
|
|
|
1134
1924
|
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
1135
1925
|
};
|
|
1136
1926
|
switch (name) {
|
|
1927
|
+
// Written by the interpreter itself, one item at a time (see arrayLocaleText): how long
|
|
1928
|
+
// the text of a number or a date is depends on the locale and the options.
|
|
1929
|
+
case "toLocaleString":
|
|
1930
|
+
return args;
|
|
1137
1931
|
// `join` writes every item and a separator between them into one string, in one step; so
|
|
1138
|
-
//
|
|
1932
|
+
// does the conversion to text.
|
|
1139
1933
|
case "join":
|
|
1140
|
-
case "toString":
|
|
1141
|
-
|
|
1142
|
-
const separator =
|
|
1934
|
+
case "toString": {
|
|
1935
|
+
const given = name !== "join" || args.length === 0 ? void 0 : convertedOnce(args[0], String);
|
|
1936
|
+
const separator = given === void 0 ? "," : String(given);
|
|
1143
1937
|
const measure = newTextMeasure();
|
|
1144
1938
|
measureArrayText(receiver, separator.length, measure, 0);
|
|
1145
1939
|
if (measure.length > MAX_JOIN_LENGTH) {
|
|
1146
1940
|
throw new InterpreterError(`Array '${name}' would produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
1147
1941
|
}
|
|
1148
|
-
|
|
1942
|
+
this.work(measure.work);
|
|
1943
|
+
return name === "join" && args.length > 0 ? [given, ...args.slice(1)] : args;
|
|
1149
1944
|
}
|
|
1150
1945
|
// Without a comparison function the engine compares the items as text: strings as they
|
|
1151
1946
|
// are, and an array among the items joined, again for every comparison.
|
|
1152
1947
|
case "sort":
|
|
1153
1948
|
case "toSorted": {
|
|
1154
|
-
if (typeof args[0] === "function") return;
|
|
1949
|
+
if (typeof args[0] === "function") return args;
|
|
1155
1950
|
const measure = newTextMeasure();
|
|
1951
|
+
let chars = 0;
|
|
1156
1952
|
for (let i = 0; i < receiver.length && measure.length <= MAX_JOIN_LENGTH; i++) {
|
|
1157
1953
|
const item = receiver[i];
|
|
1158
1954
|
if (Array.isArray(item)) measureArrayText(item, 1, measure, 1);
|
|
1955
|
+
else chars += typeof item === "string" ? item.length : 32;
|
|
1159
1956
|
}
|
|
1160
1957
|
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
1161
|
-
|
|
1958
|
+
const compared = (chars + measure.length) * (Math.ceil(Math.log2(receiver.length + 1)) + 6);
|
|
1959
|
+
if (compared > MAX_CALL_WORK) {
|
|
1960
|
+
throw new InterpreterError(`Array '${name}' would compare more text than one call may`);
|
|
1961
|
+
}
|
|
1962
|
+
this.work(compared);
|
|
1963
|
+
return args;
|
|
1162
1964
|
}
|
|
1163
1965
|
// Growth by the arguments (a spread makes them many): charged before it happens.
|
|
1164
1966
|
case "push":
|
|
1165
1967
|
case "unshift":
|
|
1166
1968
|
if (receiver.length + args.length > MAX_ARRAY_LENGTH) tooLong2();
|
|
1167
1969
|
this.charge(args.length * 8);
|
|
1168
|
-
return;
|
|
1970
|
+
return args;
|
|
1169
1971
|
case "splice":
|
|
1170
1972
|
case "toSpliced": {
|
|
1171
1973
|
const added = Math.max(0, args.length - 2);
|
|
1172
1974
|
if (receiver.length + added > MAX_ARRAY_LENGTH) tooLong2();
|
|
1173
1975
|
if (name === "splice") this.charge(added * 8);
|
|
1174
|
-
return;
|
|
1976
|
+
return args;
|
|
1175
1977
|
}
|
|
1176
1978
|
// A new array of the receiver and every array among the arguments: one array, given many
|
|
1177
1979
|
// times, is small in memory and large once copied.
|
|
@@ -1182,16 +1984,50 @@ var Interpreter = class {
|
|
|
1182
1984
|
length += Array.isArray(arg) ? arg.length : 1;
|
|
1183
1985
|
}
|
|
1184
1986
|
if (length > MAX_ARRAY_LENGTH) tooLong2();
|
|
1185
|
-
return;
|
|
1987
|
+
return args;
|
|
1186
1988
|
}
|
|
1187
1989
|
case "flat": {
|
|
1188
|
-
const
|
|
1990
|
+
const given = convertedOnce(args[0], Number);
|
|
1991
|
+
const depth = given === void 0 ? 1 : Number(given);
|
|
1189
1992
|
if (flatLength(receiver, Number.isNaN(depth) ? 0 : depth, MAX_ARRAY_LENGTH) > MAX_ARRAY_LENGTH) tooLong2();
|
|
1190
|
-
return;
|
|
1993
|
+
return args.length === 0 ? args : [given, ...args.slice(1)];
|
|
1191
1994
|
}
|
|
1192
1995
|
default:
|
|
1193
|
-
return;
|
|
1996
|
+
return args;
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
/**
|
|
2000
|
+
* `array.toLocaleString(locales, options)`: the text of every item in the locale's format,
|
|
2001
|
+
* joined by commas, as the engine writes it. The engine does it in one step and the length of
|
|
2002
|
+
* what an item becomes is not known beforehand (a number can take hundreds of chars with the
|
|
2003
|
+
* right options), so the items are converted here one at a time: each counts as a step, and
|
|
2004
|
+
* the text is refused as soon as it is longer than a script's longest text.
|
|
2005
|
+
*/
|
|
2006
|
+
arrayLocaleText(array, args, active, written, depth) {
|
|
2007
|
+
if (depth > MAX_TEXT_NESTING) throw new InterpreterError(TEXT_TOO_LONG);
|
|
2008
|
+
const parts = [];
|
|
2009
|
+
active.add(array);
|
|
2010
|
+
try {
|
|
2011
|
+
for (let i = 0; i < array.length; i++) {
|
|
2012
|
+
this.tick();
|
|
2013
|
+
const item = array[i];
|
|
2014
|
+
let text = "";
|
|
2015
|
+
if (Array.isArray(item) && item.toLocaleString === ArrayProtoToLocaleString) {
|
|
2016
|
+
if (!active.has(item)) text = this.arrayLocaleText(item, args, active, written, depth + 1);
|
|
2017
|
+
} else if (item !== null && item !== void 0) {
|
|
2018
|
+
text = String(item.toLocaleString(...args));
|
|
2019
|
+
written.length += text.length;
|
|
2020
|
+
}
|
|
2021
|
+
if (i > 0) written.length += 1;
|
|
2022
|
+
if (written.length > MAX_JOIN_LENGTH) {
|
|
2023
|
+
throw new InterpreterError(`Array 'toLocaleString' would produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
2024
|
+
}
|
|
2025
|
+
parts.push(text);
|
|
2026
|
+
}
|
|
2027
|
+
} finally {
|
|
2028
|
+
active.delete(array);
|
|
1194
2029
|
}
|
|
2030
|
+
return parts.join(",");
|
|
1195
2031
|
}
|
|
1196
2032
|
/**
|
|
1197
2033
|
* Async implementations of the higher-order array methods, so interpreter
|
|
@@ -1264,10 +2100,30 @@ var Interpreter = class {
|
|
|
1264
2100
|
acc = arr[order[0]];
|
|
1265
2101
|
start = 1;
|
|
1266
2102
|
}
|
|
2103
|
+
let owed = 0;
|
|
1267
2104
|
for (let n = start; n < order.length; n++) {
|
|
1268
2105
|
this.tick();
|
|
1269
|
-
|
|
2106
|
+
let pending;
|
|
2107
|
+
if (interpreted !== void 0 && typeof acc === "string") {
|
|
2108
|
+
this.accumulatorOwed = owed;
|
|
2109
|
+
try {
|
|
2110
|
+
pending = reducer(acc, arr[order[n]], order[n], arr);
|
|
2111
|
+
} finally {
|
|
2112
|
+
this.accumulatorOwed = void 0;
|
|
2113
|
+
}
|
|
2114
|
+
} else {
|
|
2115
|
+
pending = reducer(acc, arr[order[n]], order[n], arr);
|
|
2116
|
+
}
|
|
2117
|
+
const next = await pending;
|
|
2118
|
+
if (next instanceof AccumulatedText) {
|
|
2119
|
+
acc = next.value;
|
|
2120
|
+
owed = next.owed;
|
|
2121
|
+
} else {
|
|
2122
|
+
acc = next;
|
|
2123
|
+
owed = 0;
|
|
2124
|
+
}
|
|
1270
2125
|
}
|
|
2126
|
+
if (owed > 0) this.charge(owed);
|
|
1271
2127
|
return acc;
|
|
1272
2128
|
}
|
|
1273
2129
|
case "sort":
|
|
@@ -1365,7 +2221,9 @@ var Interpreter = class {
|
|
|
1365
2221
|
const rest = {};
|
|
1366
2222
|
for (const key2 of Object.keys(source)) {
|
|
1367
2223
|
this.tick();
|
|
1368
|
-
if (
|
|
2224
|
+
if (taken.has(key2) || BLOCKED_KEYS.has(key2)) continue;
|
|
2225
|
+
assertStorable(rest, key2, source[key2]);
|
|
2226
|
+
rest[key2] = source[key2];
|
|
1369
2227
|
}
|
|
1370
2228
|
await this.applyPattern(prop.argument, rest, scope, mode);
|
|
1371
2229
|
continue;
|
|
@@ -1390,7 +2248,7 @@ var Interpreter = class {
|
|
|
1390
2248
|
if (node.generator) throw new InterpreterError("Generator functions are not supported");
|
|
1391
2249
|
const selfName = node.type === "FunctionExpression" && node.id ? node.id.name : void 0;
|
|
1392
2250
|
const outer = selfName === void 0 ? closure : closure.child();
|
|
1393
|
-
const call = async (args, callerDepth) => {
|
|
2251
|
+
const call = async (args, callerDepth, accumulatorOwed) => {
|
|
1394
2252
|
const fnScope = outer.activation(this.enterCall(callerDepth));
|
|
1395
2253
|
try {
|
|
1396
2254
|
for (let i = 0; i < node.params.length; i++) {
|
|
@@ -1401,11 +2259,19 @@ var Interpreter = class {
|
|
|
1401
2259
|
}
|
|
1402
2260
|
await this.applyPattern(param, args[i], fnScope, "let");
|
|
1403
2261
|
}
|
|
2262
|
+
const first = node.params[0];
|
|
2263
|
+
if (accumulatorOwed !== void 0 && first?.type === "Identifier" && typeof args[0] === "string") {
|
|
2264
|
+
const accumulator = fnScope.slot(first.name);
|
|
2265
|
+
if (accumulator !== void 0) {
|
|
2266
|
+
accumulator.owed = accumulatorOwed;
|
|
2267
|
+
fnScope.accumulator = first.name;
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
1404
2270
|
if (node.body.type === "BlockStatement") {
|
|
1405
2271
|
await this.execBlock(node.body.body, fnScope);
|
|
1406
2272
|
return void 0;
|
|
1407
2273
|
}
|
|
1408
|
-
return await this.
|
|
2274
|
+
return await this.evalReturned(node.body, fnScope);
|
|
1409
2275
|
} catch (e) {
|
|
1410
2276
|
if (e instanceof ReturnSignal) return e.value;
|
|
1411
2277
|
throw e;
|
|
@@ -1414,8 +2280,13 @@ var Interpreter = class {
|
|
|
1414
2280
|
}
|
|
1415
2281
|
};
|
|
1416
2282
|
const depthOfCaller = () => this.callerDepth;
|
|
2283
|
+
const takeAccumulatorOwed = () => {
|
|
2284
|
+
const owed = this.accumulatorOwed;
|
|
2285
|
+
this.accumulatorOwed = void 0;
|
|
2286
|
+
return owed;
|
|
2287
|
+
};
|
|
1417
2288
|
const interpreted = function interpreted2(...args) {
|
|
1418
|
-
const result = call(args, depthOfCaller());
|
|
2289
|
+
const result = call(args, depthOfCaller(), takeAccumulatorOwed());
|
|
1419
2290
|
result.then(void 0, ignoreRejection2);
|
|
1420
2291
|
return result;
|
|
1421
2292
|
};
|
|
@@ -1425,7 +2296,9 @@ var Interpreter = class {
|
|
|
1425
2296
|
}
|
|
1426
2297
|
/** A computed property key as text. An array as a key is its items, joined. */
|
|
1427
2298
|
keyText(value) {
|
|
1428
|
-
|
|
2299
|
+
this.arrayOperands(value);
|
|
2300
|
+
this.bigIntAsText(value);
|
|
2301
|
+
this.work(operandSize(value));
|
|
1429
2302
|
return String(value);
|
|
1430
2303
|
}
|
|
1431
2304
|
async propKey(prop, scope) {
|
|
@@ -1452,19 +2325,55 @@ function isScriptData(value) {
|
|
|
1452
2325
|
const prototype = Object.getPrototypeOf(value);
|
|
1453
2326
|
return prototype === Object.prototype || prototype === null;
|
|
1454
2327
|
}
|
|
1455
|
-
function
|
|
2328
|
+
function operandSize(value) {
|
|
2329
|
+
return typeof value === "string" || Array.isArray(value) ? value.length : 0;
|
|
2330
|
+
}
|
|
2331
|
+
function integerOf(value) {
|
|
2332
|
+
const number = Number(value);
|
|
2333
|
+
return Number.isNaN(number) ? 0 : Math.trunc(number);
|
|
2334
|
+
}
|
|
2335
|
+
function expandReplacement(template, text, at, matched) {
|
|
2336
|
+
if (!template.includes("$")) return template;
|
|
2337
|
+
let out = "";
|
|
2338
|
+
for (let i = 0; i < template.length; i++) {
|
|
2339
|
+
const next = template[i] === "$" ? template[i + 1] : void 0;
|
|
2340
|
+
if (next === "$") out += "$";
|
|
2341
|
+
else if (next === "&") out += matched;
|
|
2342
|
+
else if (next === "`") out += text.substring(0, at);
|
|
2343
|
+
else if (next === "'") out += text.substring(at + matched.length);
|
|
2344
|
+
else {
|
|
2345
|
+
out += template[i];
|
|
2346
|
+
continue;
|
|
2347
|
+
}
|
|
2348
|
+
i++;
|
|
2349
|
+
}
|
|
2350
|
+
return out;
|
|
2351
|
+
}
|
|
2352
|
+
function convertedOnce(value, convert) {
|
|
2353
|
+
return typeof value === "object" && value !== null ? convert(value) : value;
|
|
2354
|
+
}
|
|
2355
|
+
function checkArrayWrite(array, key, value, currentLength = array.length) {
|
|
2356
|
+
if (key === "length") value = convertedOnce(value, Number);
|
|
2357
|
+
const length = arrayLengthAfterWrite(currentLength, key, value);
|
|
2358
|
+
if (length > MAX_ARRAY_LENGTH) {
|
|
2359
|
+
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
2360
|
+
}
|
|
2361
|
+
return { value, length };
|
|
2362
|
+
}
|
|
2363
|
+
function arrayLengthAfterWrite(currentLength, key, value) {
|
|
1456
2364
|
if (key === "length") {
|
|
1457
2365
|
const length = Number(value);
|
|
1458
2366
|
if (!Number.isInteger(length) || length < 0) throw new InterpreterError("Invalid array length");
|
|
1459
2367
|
return length;
|
|
1460
2368
|
}
|
|
1461
2369
|
const index = Number(key);
|
|
1462
|
-
if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(
|
|
1463
|
-
return
|
|
2370
|
+
if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(currentLength, index + 1);
|
|
2371
|
+
return currentLength;
|
|
1464
2372
|
}
|
|
1465
2373
|
|
|
1466
2374
|
// libs/core/src/value-sanitizer.ts
|
|
1467
2375
|
var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
|
|
2376
|
+
var CIRCULAR_MARKER_BYTES = 12;
|
|
1468
2377
|
var ReflectApply2 = Reflect.apply;
|
|
1469
2378
|
var ReflectGet = Reflect.get;
|
|
1470
2379
|
var ArrayIsArray = Array.isArray;
|
|
@@ -1513,8 +2422,6 @@ function isPlainObject(value) {
|
|
|
1513
2422
|
function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
|
|
1514
2423
|
const maxDepth = options.maxDepth ?? 20;
|
|
1515
2424
|
const maxProperties = options.maxProperties ?? 1e4;
|
|
1516
|
-
const allowDates = options.allowDates ?? true;
|
|
1517
|
-
const allowErrors = options.allowErrors ?? true;
|
|
1518
2425
|
if (depth > maxDepth) {
|
|
1519
2426
|
throw new Error(
|
|
1520
2427
|
`Tool handler return value exceeds maximum depth (${maxDepth}). This limit prevents deeply nested objects that could cause stack overflow.`
|
|
@@ -1550,10 +2457,22 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1550
2457
|
return "[Circular]";
|
|
1551
2458
|
}
|
|
1552
2459
|
context.visited.add(value);
|
|
2460
|
+
try {
|
|
2461
|
+
return sanitizeObjectValue(value, options, depth, context);
|
|
2462
|
+
} finally {
|
|
2463
|
+
context.visited.delete(value);
|
|
2464
|
+
}
|
|
1553
2465
|
}
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
2466
|
+
return String(value);
|
|
2467
|
+
}
|
|
2468
|
+
function sanitizeObjectValue(value, options, depth, context) {
|
|
2469
|
+
const maxProperties = options.maxProperties ?? 1e4;
|
|
2470
|
+
const allowDates = options.allowDates ?? true;
|
|
2471
|
+
const allowErrors = options.allowErrors ?? true;
|
|
2472
|
+
const type = typeof value;
|
|
2473
|
+
if (ArrayIsArray(value)) {
|
|
2474
|
+
const rawLen = ReflectGet(value, "length");
|
|
2475
|
+
const len = typeof rawLen === "number" && NumberIsFinite(rawLen) && rawLen >= 0 ? MathFloor(rawLen) : 0;
|
|
1557
2476
|
context.propCount.count += len;
|
|
1558
2477
|
if (context.propCount.count > maxProperties) {
|
|
1559
2478
|
throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
|
|
@@ -1600,9 +2519,12 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1600
2519
|
const sanitizedMap = ObjectCreate(null);
|
|
1601
2520
|
const entries = ReflectApply2(MapProtoEntries, inspected, []);
|
|
1602
2521
|
for (const [key, val] of entries) {
|
|
2522
|
+
context.propCount.count++;
|
|
2523
|
+
if (context.propCount.count > maxProperties) {
|
|
2524
|
+
throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
|
|
2525
|
+
}
|
|
1603
2526
|
if (typeof key !== "string") continue;
|
|
1604
2527
|
if (DANGEROUS_KEYS.has(key)) continue;
|
|
1605
|
-
context.propCount.count++;
|
|
1606
2528
|
sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
|
|
1607
2529
|
}
|
|
1608
2530
|
return sanitizedMap;
|
|
@@ -1612,6 +2534,9 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1612
2534
|
const result = [];
|
|
1613
2535
|
for (const item of iter) {
|
|
1614
2536
|
context.propCount.count++;
|
|
2537
|
+
if (context.propCount.count > maxProperties) {
|
|
2538
|
+
throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
|
|
2539
|
+
}
|
|
1615
2540
|
result.push(sanitizeValue(item, options, depth + 1, context));
|
|
1616
2541
|
}
|
|
1617
2542
|
return result;
|
|
@@ -1699,7 +2624,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
|
|
|
1699
2624
|
}
|
|
1700
2625
|
if (ArrayIsArray(value)) {
|
|
1701
2626
|
if (currentPath.has(value)) {
|
|
1702
|
-
return
|
|
2627
|
+
return CIRCULAR_MARKER_BYTES;
|
|
1703
2628
|
}
|
|
1704
2629
|
currentPath.add(value);
|
|
1705
2630
|
try {
|
|
@@ -1725,7 +2650,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
|
|
|
1725
2650
|
if (type === "object") {
|
|
1726
2651
|
const object = value;
|
|
1727
2652
|
if (currentPath.has(object)) {
|
|
1728
|
-
return
|
|
2653
|
+
return CIRCULAR_MARKER_BYTES;
|
|
1729
2654
|
}
|
|
1730
2655
|
if (!isPlainObject(object)) {
|
|
1731
2656
|
if (hasBrand(DateProtoGetTime, object)) {
|
|
@@ -1905,7 +2830,8 @@ var SafeJSON = frozenRecord({
|
|
|
1905
2830
|
}
|
|
1906
2831
|
const size = checkSerializedSize(value, MAX_JSON_TEXT_BYTES);
|
|
1907
2832
|
if (!size.ok) throw new RangeError(`JSON.stringify: the text would be too large (${size.error})`);
|
|
1908
|
-
const
|
|
2833
|
+
const indentation = typeof space === "number" || typeof space === "string" ? space : void 0;
|
|
2834
|
+
const indent = indentOf(indentation);
|
|
1909
2835
|
if (indent > 0) {
|
|
1910
2836
|
const budget = MAX_JSON_TEXT_BYTES - size.estimatedBytes;
|
|
1911
2837
|
if (indentationSize(value, indent, budget, 0, /* @__PURE__ */ new Set()) > budget) {
|
|
@@ -1915,10 +2841,14 @@ var SafeJSON = frozenRecord({
|
|
|
1915
2841
|
return JSON.stringify(
|
|
1916
2842
|
value,
|
|
1917
2843
|
Array.isArray(replacer) ? replacer : void 0,
|
|
1918
|
-
|
|
2844
|
+
indentation
|
|
1919
2845
|
);
|
|
1920
2846
|
}
|
|
1921
2847
|
});
|
|
2848
|
+
convertsBeforeCall(
|
|
2849
|
+
SafeJSON["parse"],
|
|
2850
|
+
(args) => args.length === 0 ? args : [String(args[0]), ...args.slice(1)]
|
|
2851
|
+
);
|
|
1922
2852
|
chargedBeforeCall(SafeJSON["parse"], (args) => parsedJsonCost(String(args[0])));
|
|
1923
2853
|
takesArraysAsData(SafeJSON["stringify"]);
|
|
1924
2854
|
var SafeObject = frozenRecord({
|
|
@@ -1933,7 +2863,10 @@ var SafeObject = frozenRecord({
|
|
|
1933
2863
|
if (entry === null || typeof entry !== "object") throw new TypeError("Each entry must be a [key, value] pair");
|
|
1934
2864
|
assertArrayTextWithinLimit(entry[0]);
|
|
1935
2865
|
const key = String(entry[0]);
|
|
1936
|
-
if (
|
|
2866
|
+
if (isBlockedKey(key)) continue;
|
|
2867
|
+
const value = entry[1];
|
|
2868
|
+
assertStorable(result, key, value);
|
|
2869
|
+
result[key] = value;
|
|
1937
2870
|
}
|
|
1938
2871
|
return result;
|
|
1939
2872
|
},
|
|
@@ -1941,10 +2874,26 @@ var SafeObject = frozenRecord({
|
|
|
1941
2874
|
if (!isScriptData(target) || Object.isFrozen(target)) {
|
|
1942
2875
|
throw new TypeError("Object.assign needs an object or array the script created as its target");
|
|
1943
2876
|
}
|
|
2877
|
+
const targetIsArray = Array.isArray(target);
|
|
2878
|
+
const lengths = [];
|
|
2879
|
+
let length = targetIsArray ? target.length : 0;
|
|
2880
|
+
for (const source of sources) {
|
|
2881
|
+
if (source === null || source === void 0) continue;
|
|
2882
|
+
for (const key of dataKeys(source)) {
|
|
2883
|
+
const value = source[key];
|
|
2884
|
+
assertStorable(target, key, value);
|
|
2885
|
+
if (targetIsArray) {
|
|
2886
|
+
const checked = checkArrayWrite(target, key, value, length);
|
|
2887
|
+
length = checked.length;
|
|
2888
|
+
if (key === "length") lengths.push(checked.value);
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
}
|
|
2892
|
+
let nextLength = 0;
|
|
1944
2893
|
for (const source of sources) {
|
|
1945
2894
|
if (source === null || source === void 0) continue;
|
|
1946
2895
|
for (const key of dataKeys(source)) {
|
|
1947
|
-
target[key] = source[key];
|
|
2896
|
+
target[key] = targetIsArray && key === "length" ? lengths[nextLength++] : source[key];
|
|
1948
2897
|
}
|
|
1949
2898
|
}
|
|
1950
2899
|
return target;
|
|
@@ -2019,6 +2968,23 @@ var SafeDate = frozenFunction(() => (/* @__PURE__ */ new Date()).toString(), {
|
|
|
2019
2968
|
parse: (text) => Date.parse(String(text)),
|
|
2020
2969
|
UTC: (...parts) => Date.UTC(...parts)
|
|
2021
2970
|
});
|
|
2971
|
+
function encodedText(encode, value) {
|
|
2972
|
+
const text = String(value);
|
|
2973
|
+
if (text.length * 9 > MAX_JOIN_LENGTH) {
|
|
2974
|
+
let produced = 0;
|
|
2975
|
+
for (let index = 0; index < text.length && produced <= MAX_JOIN_LENGTH; index++) {
|
|
2976
|
+
const code = text.charCodeAt(index);
|
|
2977
|
+
if (code >= 2048) produced += 9;
|
|
2978
|
+
else if (code >= 128) produced += 6;
|
|
2979
|
+
else if (code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122) produced += 1;
|
|
2980
|
+
else produced += 3;
|
|
2981
|
+
}
|
|
2982
|
+
if (produced > MAX_JOIN_LENGTH) {
|
|
2983
|
+
throw new RangeError(`The encoded text would be too long (more than ${MAX_JOIN_LENGTH} chars)`);
|
|
2984
|
+
}
|
|
2985
|
+
}
|
|
2986
|
+
return encode(text);
|
|
2987
|
+
}
|
|
2022
2988
|
var ERROR_TYPES = ["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError"];
|
|
2023
2989
|
function errorType(name) {
|
|
2024
2990
|
const make = (args) => createScriptError(name, args.length === 0 || args[0] === void 0 ? "" : toStringValue(args[0]));
|
|
@@ -2049,8 +3015,8 @@ var SAFE_GLOBALS = Object.freeze({
|
|
|
2049
3015
|
parseInt: Object.freeze(
|
|
2050
3016
|
(value, radix) => Number.parseInt(String(value), radix)
|
|
2051
3017
|
),
|
|
2052
|
-
encodeURI: Object.freeze((value) => encodeURI
|
|
2053
|
-
encodeURIComponent: Object.freeze((value) => encodeURIComponent
|
|
3018
|
+
encodeURI: Object.freeze((value) => encodedText(encodeURI, value)),
|
|
3019
|
+
encodeURIComponent: Object.freeze((value) => encodedText(encodeURIComponent, value)),
|
|
2054
3020
|
decodeURI: Object.freeze((value) => decodeURI(String(value))),
|
|
2055
3021
|
decodeURIComponent: Object.freeze((value) => decodeURIComponent(String(value)))
|
|
2056
3022
|
});
|
|
@@ -2164,6 +3130,8 @@ var MemoryTracker = class {
|
|
|
2164
3130
|
trackedBytes = 0;
|
|
2165
3131
|
peakTrackedBytes = 0;
|
|
2166
3132
|
allocationCount = 0;
|
|
3133
|
+
/** Whether this tracker has refused an allocation since it was started */
|
|
3134
|
+
limitExceeded = false;
|
|
2167
3135
|
config;
|
|
2168
3136
|
constructor(config = {}) {
|
|
2169
3137
|
this.config = {
|
|
@@ -2180,6 +3148,14 @@ var MemoryTracker = class {
|
|
|
2180
3148
|
this.trackedBytes = 0;
|
|
2181
3149
|
this.peakTrackedBytes = 0;
|
|
2182
3150
|
this.allocationCount = 0;
|
|
3151
|
+
this.limitExceeded = false;
|
|
3152
|
+
}
|
|
3153
|
+
/**
|
|
3154
|
+
* Whether the limit was exceeded since tracking started: the tracker itself refused an
|
|
3155
|
+
* allocation. An error that only says so about itself is not evidence of that.
|
|
3156
|
+
*/
|
|
3157
|
+
hasExceededLimit() {
|
|
3158
|
+
return this.limitExceeded;
|
|
2183
3159
|
}
|
|
2184
3160
|
/**
|
|
2185
3161
|
* Track an allocation
|
|
@@ -2190,6 +3166,7 @@ var MemoryTracker = class {
|
|
|
2190
3166
|
track(bytes) {
|
|
2191
3167
|
if (typeof bytes !== "number" || Number.isNaN(bytes)) {
|
|
2192
3168
|
if (this.config.memoryLimit > 0) {
|
|
3169
|
+
this.limitExceeded = true;
|
|
2193
3170
|
throw new MemoryLimitError(
|
|
2194
3171
|
"Memory limit exceeded: allocation size is not a number",
|
|
2195
3172
|
this.trackedBytes,
|
|
@@ -2205,6 +3182,7 @@ var MemoryTracker = class {
|
|
|
2205
3182
|
this.peakTrackedBytes = this.trackedBytes;
|
|
2206
3183
|
}
|
|
2207
3184
|
if (this.config.memoryLimit > 0 && this.trackedBytes > this.config.memoryLimit) {
|
|
3185
|
+
this.limitExceeded = true;
|
|
2208
3186
|
throw new MemoryLimitError(
|
|
2209
3187
|
`Memory limit exceeded: ${this.formatBytes(this.trackedBytes)} used > ${this.formatBytes(
|
|
2210
3188
|
this.config.memoryLimit
|
|
@@ -2391,10 +3369,270 @@ var REFERENCE_CONFIGS = {
|
|
|
2391
3369
|
// Very deep resolution
|
|
2392
3370
|
}
|
|
2393
3371
|
};
|
|
3372
|
+
var REF_ID_PREFIX = "__REF_";
|
|
3373
|
+
var REF_ID_SUFFIX = "__";
|
|
2394
3374
|
var REF_ID_PATTERN = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
|
|
2395
3375
|
function isReferenceId(value) {
|
|
2396
3376
|
return typeof value === "string" && REF_ID_PATTERN.test(value);
|
|
2397
3377
|
}
|
|
3378
|
+
function getMaxTotalResolvedSize(config) {
|
|
3379
|
+
const configured = config.maxTotalResolvedSize;
|
|
3380
|
+
if (typeof configured === "number" && configured >= 0) {
|
|
3381
|
+
return configured;
|
|
3382
|
+
}
|
|
3383
|
+
return 2 * config.maxTotalSize;
|
|
3384
|
+
}
|
|
3385
|
+
|
|
3386
|
+
// libs/core/src/sidecar/reference-sidecar.ts
|
|
3387
|
+
var SidecarLimitError = class _SidecarLimitError extends Error {
|
|
3388
|
+
constructor(message, code, limit, current) {
|
|
3389
|
+
super(message);
|
|
3390
|
+
this.code = code;
|
|
3391
|
+
this.limit = limit;
|
|
3392
|
+
this.current = current;
|
|
3393
|
+
this.name = "SidecarLimitError";
|
|
3394
|
+
Object.setPrototypeOf(this, _SidecarLimitError.prototype);
|
|
3395
|
+
}
|
|
3396
|
+
};
|
|
3397
|
+
var ReferenceSidecar = class {
|
|
3398
|
+
constructor(config) {
|
|
3399
|
+
this.config = config;
|
|
3400
|
+
this.maxTotalResolvedSize = getMaxTotalResolvedSize(config);
|
|
3401
|
+
}
|
|
3402
|
+
storage = /* @__PURE__ */ new Map();
|
|
3403
|
+
metadata = /* @__PURE__ */ new Map();
|
|
3404
|
+
/** The stored values that were resolved for a tool call, as the string they were resolved to */
|
|
3405
|
+
resolved = /* @__PURE__ */ new Map();
|
|
3406
|
+
totalSize = 0;
|
|
3407
|
+
/** Bytes of resolved data built for the tool calls of this execution so far */
|
|
3408
|
+
resolvedSize = 0;
|
|
3409
|
+
maxTotalResolvedSize;
|
|
3410
|
+
disposed = false;
|
|
3411
|
+
/**
|
|
3412
|
+
* Store data and return a reference ID
|
|
3413
|
+
*
|
|
3414
|
+
* @param data - The data to store (string or Buffer)
|
|
3415
|
+
* @param source - Where this data came from
|
|
3416
|
+
* @param options - Optional metadata
|
|
3417
|
+
* @returns The reference ID (format: __REF_uuid__)
|
|
3418
|
+
* @throws SidecarLimitError if limits are exceeded
|
|
3419
|
+
*/
|
|
3420
|
+
store(data, source, options) {
|
|
3421
|
+
if (this.disposed) {
|
|
3422
|
+
throw new Error("Cannot store: sidecar has been disposed");
|
|
3423
|
+
}
|
|
3424
|
+
const buffer = typeof data === "string" ? Buffer.from(data, "utf-8") : data;
|
|
3425
|
+
const size = buffer.length;
|
|
3426
|
+
if (this.storage.size >= this.config.maxReferenceCount) {
|
|
3427
|
+
throw new SidecarLimitError(
|
|
3428
|
+
`Maximum reference count exceeded (${this.config.maxReferenceCount})`,
|
|
3429
|
+
"MAX_REFERENCE_COUNT",
|
|
3430
|
+
this.config.maxReferenceCount,
|
|
3431
|
+
this.storage.size
|
|
3432
|
+
);
|
|
3433
|
+
}
|
|
3434
|
+
if (size > this.config.maxReferenceSize) {
|
|
3435
|
+
throw new SidecarLimitError(
|
|
3436
|
+
`Reference size ${size} bytes exceeds maximum ${this.config.maxReferenceSize} bytes`,
|
|
3437
|
+
"MAX_REFERENCE_SIZE",
|
|
3438
|
+
this.config.maxReferenceSize,
|
|
3439
|
+
size
|
|
3440
|
+
);
|
|
3441
|
+
}
|
|
3442
|
+
if (this.totalSize + size > this.config.maxTotalSize) {
|
|
3443
|
+
throw new SidecarLimitError(
|
|
3444
|
+
`Total sidecar size would exceed maximum: ${this.totalSize + size} > ${this.config.maxTotalSize}`,
|
|
3445
|
+
"MAX_TOTAL_SIZE",
|
|
3446
|
+
this.config.maxTotalSize,
|
|
3447
|
+
this.totalSize + size
|
|
3448
|
+
);
|
|
3449
|
+
}
|
|
3450
|
+
const randomUUID = globalThis.crypto?.randomUUID?.bind(globalThis.crypto);
|
|
3451
|
+
if (!randomUUID) throw new Error("Secure random UUID generation is unavailable");
|
|
3452
|
+
const refId = `${REF_ID_PREFIX}${randomUUID()}${REF_ID_SUFFIX}`;
|
|
3453
|
+
this.storage.set(refId, Buffer.from(buffer));
|
|
3454
|
+
this.totalSize += size;
|
|
3455
|
+
this.metadata.set(refId, {
|
|
3456
|
+
createdAt: Date.now(),
|
|
3457
|
+
size,
|
|
3458
|
+
source,
|
|
3459
|
+
mimeType: options?.mimeType,
|
|
3460
|
+
origin: options?.origin
|
|
3461
|
+
});
|
|
3462
|
+
return refId;
|
|
3463
|
+
}
|
|
3464
|
+
/**
|
|
3465
|
+
* Retrieve data by reference ID
|
|
3466
|
+
*
|
|
3467
|
+
* @param refId - The reference ID to look up
|
|
3468
|
+
* @returns The stored data or undefined if not found
|
|
3469
|
+
*/
|
|
3470
|
+
retrieve(refId) {
|
|
3471
|
+
if (this.disposed) {
|
|
3472
|
+
return void 0;
|
|
3473
|
+
}
|
|
3474
|
+
const data = this.storage.get(refId);
|
|
3475
|
+
return data ? Buffer.from(data) : void 0;
|
|
3476
|
+
}
|
|
3477
|
+
/**
|
|
3478
|
+
* Retrieve data as a string
|
|
3479
|
+
*
|
|
3480
|
+
* @param refId - The reference ID to look up
|
|
3481
|
+
* @param encoding - String encoding (default: utf-8)
|
|
3482
|
+
* @returns The stored data as a string or undefined
|
|
3483
|
+
*/
|
|
3484
|
+
retrieveString(refId, encoding = "utf-8") {
|
|
3485
|
+
const data = this.retrieve(refId);
|
|
3486
|
+
return data?.toString(encoding);
|
|
3487
|
+
}
|
|
3488
|
+
/**
|
|
3489
|
+
* Resolve a reference for a tool call: the stored data as a string
|
|
3490
|
+
*
|
|
3491
|
+
* A stored value is decoded once in the life of the sidecar (one execution) and counted
|
|
3492
|
+
* against `maxTotalResolvedSize` then. Every later resolution, in the same call or in another,
|
|
3493
|
+
* returns the same string and counts nothing: a string cannot be changed, so handing it out
|
|
3494
|
+
* again takes no memory.
|
|
3495
|
+
*
|
|
3496
|
+
* @param refId - The reference ID to resolve
|
|
3497
|
+
* @returns The stored data as a string, or undefined if the reference is not known
|
|
3498
|
+
* @throws SidecarLimitError if the execution's total of resolved data would be exceeded
|
|
3499
|
+
*/
|
|
3500
|
+
resolveString(refId) {
|
|
3501
|
+
if (this.disposed) {
|
|
3502
|
+
return void 0;
|
|
3503
|
+
}
|
|
3504
|
+
const known = this.resolved.get(refId);
|
|
3505
|
+
if (known !== void 0) {
|
|
3506
|
+
return known;
|
|
3507
|
+
}
|
|
3508
|
+
const data = this.storage.get(refId);
|
|
3509
|
+
if (data === void 0) {
|
|
3510
|
+
return void 0;
|
|
3511
|
+
}
|
|
3512
|
+
this.countResolved(data.length);
|
|
3513
|
+
const text = data.toString("utf-8");
|
|
3514
|
+
this.resolved.set(refId, text);
|
|
3515
|
+
return text;
|
|
3516
|
+
}
|
|
3517
|
+
/**
|
|
3518
|
+
* Whether a reference was resolved before, so that resolving it again counts nothing
|
|
3519
|
+
*/
|
|
3520
|
+
isResolved(refId) {
|
|
3521
|
+
return !this.disposed && this.resolved.has(refId);
|
|
3522
|
+
}
|
|
3523
|
+
/**
|
|
3524
|
+
* Count resolved data that is about to be built for a tool call of this execution
|
|
3525
|
+
*
|
|
3526
|
+
* @param bytes - Size of the data in bytes
|
|
3527
|
+
* @throws SidecarLimitError if the total would exceed `maxTotalResolvedSize`; nothing is counted then
|
|
3528
|
+
*/
|
|
3529
|
+
countResolved(bytes) {
|
|
3530
|
+
if (!this.canResolve(bytes)) {
|
|
3531
|
+
throw new SidecarLimitError(
|
|
3532
|
+
`Total resolved size would exceed maximum: ${this.resolvedSize + bytes} > ${this.maxTotalResolvedSize}`,
|
|
3533
|
+
"MAX_TOTAL_RESOLVED_SIZE",
|
|
3534
|
+
this.maxTotalResolvedSize,
|
|
3535
|
+
this.resolvedSize + bytes
|
|
3536
|
+
);
|
|
3537
|
+
}
|
|
3538
|
+
this.resolvedSize += bytes;
|
|
3539
|
+
}
|
|
3540
|
+
/**
|
|
3541
|
+
* Whether `bytes` more of resolved data fit in what this execution may resolve in total
|
|
3542
|
+
*/
|
|
3543
|
+
canResolve(bytes) {
|
|
3544
|
+
return bytes >= 0 && this.resolvedSize + bytes <= this.maxTotalResolvedSize;
|
|
3545
|
+
}
|
|
3546
|
+
/**
|
|
3547
|
+
* Bytes of resolved data built for the tool calls of this execution so far
|
|
3548
|
+
*/
|
|
3549
|
+
getResolvedSize() {
|
|
3550
|
+
return this.resolvedSize;
|
|
3551
|
+
}
|
|
3552
|
+
/**
|
|
3553
|
+
* Check if a reference ID exists
|
|
3554
|
+
*/
|
|
3555
|
+
has(refId) {
|
|
3556
|
+
return !this.disposed && this.storage.has(refId);
|
|
3557
|
+
}
|
|
3558
|
+
/**
|
|
3559
|
+
* Get metadata for a reference
|
|
3560
|
+
*/
|
|
3561
|
+
getMetadata(refId) {
|
|
3562
|
+
if (this.disposed) {
|
|
3563
|
+
return void 0;
|
|
3564
|
+
}
|
|
3565
|
+
return this.metadata.get(refId);
|
|
3566
|
+
}
|
|
3567
|
+
/**
|
|
3568
|
+
* Get the size of a reference without retrieving data
|
|
3569
|
+
*/
|
|
3570
|
+
getSize(refId) {
|
|
3571
|
+
return this.getMetadata(refId)?.size;
|
|
3572
|
+
}
|
|
3573
|
+
/**
|
|
3574
|
+
* Get total size of all stored references
|
|
3575
|
+
*/
|
|
3576
|
+
getTotalSize() {
|
|
3577
|
+
return this.totalSize;
|
|
3578
|
+
}
|
|
3579
|
+
/**
|
|
3580
|
+
* Get number of stored references
|
|
3581
|
+
*/
|
|
3582
|
+
getCount() {
|
|
3583
|
+
return this.storage.size;
|
|
3584
|
+
}
|
|
3585
|
+
/**
|
|
3586
|
+
* Get the configuration
|
|
3587
|
+
*/
|
|
3588
|
+
getConfig() {
|
|
3589
|
+
return { ...this.config };
|
|
3590
|
+
}
|
|
3591
|
+
/**
|
|
3592
|
+
* Check if a value is a reference ID
|
|
3593
|
+
*/
|
|
3594
|
+
isReference(value) {
|
|
3595
|
+
return isReferenceId(value);
|
|
3596
|
+
}
|
|
3597
|
+
/**
|
|
3598
|
+
* Get all reference IDs (for debugging/auditing)
|
|
3599
|
+
*/
|
|
3600
|
+
getAllReferenceIds() {
|
|
3601
|
+
return Array.from(this.storage.keys());
|
|
3602
|
+
}
|
|
3603
|
+
/**
|
|
3604
|
+
* Get audit log of all stored references
|
|
3605
|
+
*/
|
|
3606
|
+
getAuditLog() {
|
|
3607
|
+
const log = [];
|
|
3608
|
+
for (const [refId, metadata] of this.metadata) {
|
|
3609
|
+
log.push({ refId, metadata });
|
|
3610
|
+
}
|
|
3611
|
+
return log;
|
|
3612
|
+
}
|
|
3613
|
+
/**
|
|
3614
|
+
* Check if the sidecar has been disposed
|
|
3615
|
+
*/
|
|
3616
|
+
isDisposed() {
|
|
3617
|
+
return this.disposed;
|
|
3618
|
+
}
|
|
3619
|
+
/**
|
|
3620
|
+
* Dispose the sidecar and release all memory
|
|
3621
|
+
*
|
|
3622
|
+
* MUST be called after each execution to prevent memory leaks.
|
|
3623
|
+
* After disposal, the sidecar cannot be used.
|
|
3624
|
+
*/
|
|
3625
|
+
dispose() {
|
|
3626
|
+
if (this.disposed) {
|
|
3627
|
+
return;
|
|
3628
|
+
}
|
|
3629
|
+
this.storage.clear();
|
|
3630
|
+
this.metadata.clear();
|
|
3631
|
+
this.resolved.clear();
|
|
3632
|
+
this.totalSize = 0;
|
|
3633
|
+
this.disposed = true;
|
|
3634
|
+
}
|
|
3635
|
+
};
|
|
2398
3636
|
|
|
2399
3637
|
// libs/core/src/sidecar/reference-resolver.ts
|
|
2400
3638
|
var ReflectGet2 = Reflect.get;
|
|
@@ -2503,17 +3741,88 @@ var ReferenceResolver = class {
|
|
|
2503
3741
|
/**
|
|
2504
3742
|
* Check if resolution would exceed size limits
|
|
2505
3743
|
*
|
|
3744
|
+
* Two limits apply: `maxResolvedSize` to what this value expands to, and
|
|
3745
|
+
* `maxTotalResolvedSize` to what the execution has had resolved so far plus what resolving
|
|
3746
|
+
* this value would add (see `predictAddedSize`).
|
|
3747
|
+
*
|
|
2506
3748
|
* @param value - The value to check
|
|
2507
|
-
* @returns true if resolution would exceed maxResolvedSize
|
|
3749
|
+
* @returns true if resolution would exceed maxResolvedSize or the execution's total
|
|
2508
3750
|
*/
|
|
2509
3751
|
wouldExceedLimit(value) {
|
|
2510
3752
|
try {
|
|
2511
3753
|
const size = this.predictExpandedSize(value);
|
|
2512
|
-
|
|
3754
|
+
if (size > this.config.maxResolvedSize) {
|
|
3755
|
+
return true;
|
|
3756
|
+
}
|
|
3757
|
+
return !this.sidecar.canResolve(this.predictAddedSize(value, 0, /* @__PURE__ */ new Set()));
|
|
2513
3758
|
} catch {
|
|
2514
3759
|
return true;
|
|
2515
3760
|
}
|
|
2516
3761
|
}
|
|
3762
|
+
/**
|
|
3763
|
+
* Predict what resolving a value would add to the execution's total of resolved data,
|
|
3764
|
+
* WITHOUT allocating memory
|
|
3765
|
+
*
|
|
3766
|
+
* A stored value adds its size the first time it is resolved in the execution and nothing
|
|
3767
|
+
* afterwards (`counted` holds the ones this walk has seen). A composite adds the size of the
|
|
3768
|
+
* string it is joined into, every time, besides what its parts add.
|
|
3769
|
+
*/
|
|
3770
|
+
predictAddedSize(value, depth, counted) {
|
|
3771
|
+
if (depth > this.config.maxResolutionDepth) {
|
|
3772
|
+
throw new ResolutionLimitError(
|
|
3773
|
+
`Maximum resolution depth exceeded (${this.config.maxResolutionDepth})`,
|
|
3774
|
+
"MAX_RESOLUTION_DEPTH",
|
|
3775
|
+
this.config.maxResolutionDepth,
|
|
3776
|
+
depth
|
|
3777
|
+
);
|
|
3778
|
+
}
|
|
3779
|
+
if (isReferenceId(value)) {
|
|
3780
|
+
if (counted.has(value) || this.sidecar.isResolved(value)) {
|
|
3781
|
+
return 0;
|
|
3782
|
+
}
|
|
3783
|
+
counted.add(value);
|
|
3784
|
+
return this.sidecar.getSize(value) ?? 0;
|
|
3785
|
+
}
|
|
3786
|
+
if (isCompositeHandle(value)) {
|
|
3787
|
+
const parts = value.__parts;
|
|
3788
|
+
const len = untrustedLength(parts);
|
|
3789
|
+
let sum = this.predictExpandedSize(value, depth);
|
|
3790
|
+
for (let i = 0; i < len; i++) {
|
|
3791
|
+
sum += this.predictAddedSize(untrustedAt(parts, i), depth + 1, counted);
|
|
3792
|
+
}
|
|
3793
|
+
return sum;
|
|
3794
|
+
}
|
|
3795
|
+
if (Array.isArray(value)) {
|
|
3796
|
+
const len = untrustedLength(value);
|
|
3797
|
+
let sum = 0;
|
|
3798
|
+
for (let i = 0; i < len; i++) {
|
|
3799
|
+
sum += this.predictAddedSize(untrustedAt(value, i), depth + 1, counted);
|
|
3800
|
+
}
|
|
3801
|
+
return sum;
|
|
3802
|
+
}
|
|
3803
|
+
if (value !== null && typeof value === "object") {
|
|
3804
|
+
let sum = 0;
|
|
3805
|
+
for (const val of Object.values(value)) {
|
|
3806
|
+
sum += this.predictAddedSize(val, depth + 1, counted);
|
|
3807
|
+
}
|
|
3808
|
+
return sum;
|
|
3809
|
+
}
|
|
3810
|
+
return 0;
|
|
3811
|
+
}
|
|
3812
|
+
/**
|
|
3813
|
+
* Run a step that counts resolved data against the execution's total; when the sidecar
|
|
3814
|
+
* refuses it, the refusal is thrown as the resolution error callers of `resolve` handle
|
|
3815
|
+
*/
|
|
3816
|
+
withinTotal(count) {
|
|
3817
|
+
try {
|
|
3818
|
+
count();
|
|
3819
|
+
} catch (error) {
|
|
3820
|
+
if (error instanceof SidecarLimitError) {
|
|
3821
|
+
throw new ResolutionLimitError(error.message, error.code, error.limit, error.current);
|
|
3822
|
+
}
|
|
3823
|
+
throw error;
|
|
3824
|
+
}
|
|
3825
|
+
}
|
|
2517
3826
|
/**
|
|
2518
3827
|
* Resolve all reference IDs in a value tree
|
|
2519
3828
|
*
|
|
@@ -2536,7 +3845,10 @@ var ReferenceResolver = class {
|
|
|
2536
3845
|
);
|
|
2537
3846
|
}
|
|
2538
3847
|
if (isReferenceId(value)) {
|
|
2539
|
-
|
|
3848
|
+
let data;
|
|
3849
|
+
this.withinTotal(() => {
|
|
3850
|
+
data = this.sidecar.resolveString(value);
|
|
3851
|
+
});
|
|
2540
3852
|
if (data === void 0) {
|
|
2541
3853
|
throw new Error(`Unknown reference: ${value}`);
|
|
2542
3854
|
}
|
|
@@ -2574,6 +3886,8 @@ var ReferenceResolver = class {
|
|
|
2574
3886
|
* Resolve a composite handle by concatenating its parts
|
|
2575
3887
|
*/
|
|
2576
3888
|
resolveComposite(handle, depth) {
|
|
3889
|
+
const joinedSize = this.predictExpandedSize(handle, depth);
|
|
3890
|
+
this.withinTotal(() => this.sidecar.countResolved(joinedSize));
|
|
2577
3891
|
const out = [];
|
|
2578
3892
|
const source = handle.__parts;
|
|
2579
3893
|
const len = untrustedLength(source);
|
|
@@ -2589,28 +3903,38 @@ var ReferenceResolver = class {
|
|
|
2589
3903
|
/**
|
|
2590
3904
|
* Check if a value contains any reference IDs
|
|
2591
3905
|
*
|
|
3906
|
+
* Every value is looked at, at any depth: a reference or composite past `maxResolutionDepth`
|
|
3907
|
+
* cannot be resolved, and it must still be found, so that `resolve()` refuses the call rather
|
|
3908
|
+
* than the handler receiving it unresolved. The value is walked with a list instead of by
|
|
3909
|
+
* recursion, so a deep value cannot exhaust the stack, and an object is looked at once.
|
|
3910
|
+
*
|
|
2592
3911
|
* @param value - The value to check
|
|
2593
|
-
* @param
|
|
3912
|
+
* @param _depth - Unused; kept for callers that pass a depth
|
|
2594
3913
|
* @returns true if the value or any nested value is a reference
|
|
2595
3914
|
*/
|
|
2596
|
-
containsReferences(value,
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
3915
|
+
containsReferences(value, _depth = 0) {
|
|
3916
|
+
const pending = [value];
|
|
3917
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3918
|
+
while (pending.length > 0) {
|
|
3919
|
+
const current = pending.pop();
|
|
3920
|
+
if (isReferenceId(current) || isCompositeHandle(current)) {
|
|
3921
|
+
return true;
|
|
3922
|
+
}
|
|
3923
|
+
if (current === null || typeof current !== "object" || seen.has(current)) {
|
|
3924
|
+
continue;
|
|
3925
|
+
}
|
|
3926
|
+
seen.add(current);
|
|
3927
|
+
if (Array.isArray(current)) {
|
|
3928
|
+
const len = untrustedLength(current);
|
|
3929
|
+
for (let i = 0; i < len; i++) {
|
|
3930
|
+
pending.push(untrustedAt(current, i));
|
|
2608
3931
|
}
|
|
3932
|
+
continue;
|
|
3933
|
+
}
|
|
3934
|
+
const members = Object.values(current);
|
|
3935
|
+
for (let i = 0; i < members.length; i++) {
|
|
3936
|
+
pending.push(members[i]);
|
|
2609
3937
|
}
|
|
2610
|
-
return false;
|
|
2611
|
-
}
|
|
2612
|
-
if (value !== null && typeof value === "object") {
|
|
2613
|
-
return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
|
|
2614
3938
|
}
|
|
2615
3939
|
return false;
|
|
2616
3940
|
}
|
|
@@ -2807,6 +4131,79 @@ function sanitizeStackTrace(stack, sanitize = true) {
|
|
|
2807
4131
|
return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
|
|
2808
4132
|
}
|
|
2809
4133
|
|
|
4134
|
+
// libs/core/src/thrown-value.ts
|
|
4135
|
+
var MAX_THROWN_MESSAGE_LENGTH = 16 * 1024;
|
|
4136
|
+
var MAX_THROWN_STACK_LENGTH = 64 * 1024;
|
|
4137
|
+
|
|
4138
|
+
// libs/core/src/bounded-json.ts
|
|
4139
|
+
var JSONStringify = JSON.stringify;
|
|
4140
|
+
var ReflectApply3 = Reflect.apply;
|
|
4141
|
+
var ArrayIsArray2 = Array.isArray;
|
|
4142
|
+
var StringValueOf = String.prototype.valueOf;
|
|
4143
|
+
var NumberValueOf = Number.prototype.valueOf;
|
|
4144
|
+
var JsonTooLargeError = class extends Error {
|
|
4145
|
+
constructor(limit) {
|
|
4146
|
+
super(`JSON text exceeds ${limit} bytes`);
|
|
4147
|
+
this.name = "JsonTooLargeError";
|
|
4148
|
+
}
|
|
4149
|
+
};
|
|
4150
|
+
var JsonTraversalLimitError = class extends Error {
|
|
4151
|
+
constructor(limit) {
|
|
4152
|
+
super(`JSON traversal exceeds ${limit} members`);
|
|
4153
|
+
this.name = "JsonTraversalLimitError";
|
|
4154
|
+
}
|
|
4155
|
+
};
|
|
4156
|
+
function hasSlot(valueOf, value) {
|
|
4157
|
+
try {
|
|
4158
|
+
ReflectApply3(valueOf, value, []);
|
|
4159
|
+
return true;
|
|
4160
|
+
} catch {
|
|
4161
|
+
return false;
|
|
4162
|
+
}
|
|
4163
|
+
}
|
|
4164
|
+
function stringifyWithin(value, limit) {
|
|
4165
|
+
let bytes = 0;
|
|
4166
|
+
let visits = 0;
|
|
4167
|
+
const maxVisits = Math.max(1e4, Math.min(1e6, limit * 10));
|
|
4168
|
+
let root = true;
|
|
4169
|
+
return JSONStringify(value, function(key, member) {
|
|
4170
|
+
if (++visits > maxVisits) throw new JsonTraversalLimitError(maxVisits);
|
|
4171
|
+
if (member !== null && typeof member === "object") {
|
|
4172
|
+
if (hasSlot(StringValueOf, member)) member = String(member);
|
|
4173
|
+
else if (hasSlot(NumberValueOf, member)) member = Number(member);
|
|
4174
|
+
}
|
|
4175
|
+
let added;
|
|
4176
|
+
switch (typeof member) {
|
|
4177
|
+
case "string":
|
|
4178
|
+
added = member.length + 2;
|
|
4179
|
+
break;
|
|
4180
|
+
case "number":
|
|
4181
|
+
added = Number.isFinite(member) ? String(member).length : 4;
|
|
4182
|
+
break;
|
|
4183
|
+
case "boolean":
|
|
4184
|
+
added = member ? 4 : 5;
|
|
4185
|
+
break;
|
|
4186
|
+
case "object":
|
|
4187
|
+
case "bigint":
|
|
4188
|
+
added = member === null ? 4 : 2;
|
|
4189
|
+
break;
|
|
4190
|
+
default:
|
|
4191
|
+
added = 0;
|
|
4192
|
+
}
|
|
4193
|
+
if (!root) {
|
|
4194
|
+
if (ArrayIsArray2(this)) added = added || 4;
|
|
4195
|
+
else if (added > 0) added += key.length + 3;
|
|
4196
|
+
}
|
|
4197
|
+
root = false;
|
|
4198
|
+
bytes += added;
|
|
4199
|
+
if (bytes > limit) throw new JsonTooLargeError(limit);
|
|
4200
|
+
return member;
|
|
4201
|
+
});
|
|
4202
|
+
}
|
|
4203
|
+
function utf8Length2(value) {
|
|
4204
|
+
return Buffer.byteLength(value, "utf8");
|
|
4205
|
+
}
|
|
4206
|
+
|
|
2810
4207
|
// libs/core/src/tool-bridge.ts
|
|
2811
4208
|
var TOOL_BRIDGE_PROTOCOL_VERSION = 1;
|
|
2812
4209
|
function utf8ByteLength(value) {
|
|
@@ -2962,9 +4359,9 @@ function createHostToolBridge(executionContext, options) {
|
|
|
2962
4359
|
if (typeof executionContext.hostToolBridge === "function") {
|
|
2963
4360
|
return createRelayedToolBridge(executionContext, options, executionContext.hostToolBridge);
|
|
2964
4361
|
}
|
|
2965
|
-
const { config, stats, toolHandler, sidecar, referenceConfig } = executionContext;
|
|
4362
|
+
const { config, stats, toolHandler, sidecar, referenceConfig: referenceConfig2 } = executionContext;
|
|
2966
4363
|
const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
|
|
2967
|
-
const resolver = sidecar &&
|
|
4364
|
+
const resolver = sidecar && referenceConfig2 ? new ReferenceResolver(sidecar, referenceConfig2) : void 0;
|
|
2968
4365
|
return async (requestJson) => {
|
|
2969
4366
|
try {
|
|
2970
4367
|
if (typeof requestJson !== "string") {
|
|
@@ -3142,6 +4539,7 @@ function createHostToolBridge(executionContext, options) {
|
|
|
3142
4539
|
"Tool returned an unsupported value",
|
|
3143
4540
|
"TOOL_RESULT_NOT_SAFE"
|
|
3144
4541
|
);
|
|
4542
|
+
executionContext.onToolBridgeFailure?.();
|
|
3145
4543
|
return serializeResponse(
|
|
3146
4544
|
{
|
|
3147
4545
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
@@ -3151,13 +4549,55 @@ function createHostToolBridge(executionContext, options) {
|
|
|
3151
4549
|
maxPayloadBytes
|
|
3152
4550
|
);
|
|
3153
4551
|
}
|
|
3154
|
-
|
|
4552
|
+
const resultLimit = executionContext.maxToolResultBytes;
|
|
4553
|
+
if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
|
|
4554
|
+
let tooLarge = false;
|
|
4555
|
+
let tooComplex = false;
|
|
4556
|
+
try {
|
|
4557
|
+
const resultJson = stringifyWithin(sanitizedResult, resultLimit);
|
|
4558
|
+
tooLarge = resultJson !== void 0 && utf8ByteLength(resultJson) > resultLimit;
|
|
4559
|
+
} catch (error) {
|
|
4560
|
+
tooLarge = error instanceof JsonTooLargeError;
|
|
4561
|
+
tooComplex = error instanceof JsonTraversalLimitError;
|
|
4562
|
+
}
|
|
4563
|
+
if (tooLarge || tooComplex) {
|
|
4564
|
+
executionContext.onToolBridgeFailure?.();
|
|
4565
|
+
return serializeResponse(
|
|
4566
|
+
{
|
|
4567
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
4568
|
+
ok: false,
|
|
4569
|
+
error: {
|
|
4570
|
+
name: "ToolBridgeError",
|
|
4571
|
+
message: tooComplex ? "Tool result exceeds the traversal limit" : `Tool result exceeds the limit of ${resultLimit} bytes`,
|
|
4572
|
+
code: tooComplex ? "TOOL_RESULT_TOO_COMPLEX" : "TOOL_RESULT_TOO_LARGE",
|
|
4573
|
+
toolError: true
|
|
4574
|
+
}
|
|
4575
|
+
},
|
|
4576
|
+
maxPayloadBytes
|
|
4577
|
+
);
|
|
4578
|
+
}
|
|
4579
|
+
}
|
|
4580
|
+
if (sidecar && referenceConfig2 && typeof sanitizedResult === "string") {
|
|
3155
4581
|
const size = utf8ByteLength(sanitizedResult);
|
|
3156
|
-
if (size >=
|
|
4582
|
+
if (size >= referenceConfig2.extractionThreshold) {
|
|
3157
4583
|
try {
|
|
3158
4584
|
const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
|
|
3159
4585
|
sanitizedResult = refId;
|
|
3160
4586
|
} catch {
|
|
4587
|
+
executionContext.onToolBridgeFailure?.();
|
|
4588
|
+
return serializeResponse(
|
|
4589
|
+
{
|
|
4590
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
4591
|
+
ok: false,
|
|
4592
|
+
error: {
|
|
4593
|
+
name: "ToolBridgeError",
|
|
4594
|
+
message: "Tool result could not be stored in the reference sidecar",
|
|
4595
|
+
code: "TOOL_RESULT_NOT_STORED",
|
|
4596
|
+
toolError: true
|
|
4597
|
+
}
|
|
4598
|
+
},
|
|
4599
|
+
maxPayloadBytes
|
|
4600
|
+
);
|
|
3161
4601
|
}
|
|
3162
4602
|
}
|
|
3163
4603
|
}
|
|
@@ -3172,6 +4612,7 @@ function createHostToolBridge(executionContext, options) {
|
|
|
3172
4612
|
"Tool result must be JSON-serializable",
|
|
3173
4613
|
"TOOL_RESULT_NOT_JSON"
|
|
3174
4614
|
);
|
|
4615
|
+
executionContext.onToolBridgeFailure?.();
|
|
3175
4616
|
return serializeResponse(
|
|
3176
4617
|
{
|
|
3177
4618
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
@@ -3182,6 +4623,7 @@ function createHostToolBridge(executionContext, options) {
|
|
|
3182
4623
|
);
|
|
3183
4624
|
}
|
|
3184
4625
|
if (utf8ByteLength(okJson) > maxPayloadBytes) {
|
|
4626
|
+
executionContext.onToolBridgeFailure?.();
|
|
3185
4627
|
return serializeResponse(
|
|
3186
4628
|
{
|
|
3187
4629
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
@@ -3219,12 +4661,29 @@ var MAX_PARALLEL_ITEMS = 100;
|
|
|
3219
4661
|
var MAX_SERIALIZED_RESULT_BYTES = 50 * 1024 * 1024;
|
|
3220
4662
|
var DEFAULT_MAX_CONSOLE_CALLS = 100;
|
|
3221
4663
|
var DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;
|
|
4664
|
+
var DEFAULT_MAX_TOOL_PAYLOAD_BYTES = 5 * 1024 * 1024;
|
|
4665
|
+
function certainlyLargerThan(value, bytes) {
|
|
4666
|
+
if (!Number.isFinite(bytes) || bytes <= 0) return false;
|
|
4667
|
+
return !checkSerializedSize(value, bytes).ok;
|
|
4668
|
+
}
|
|
4669
|
+
function executionOver() {
|
|
4670
|
+
return sandboxError("Execution ended");
|
|
4671
|
+
}
|
|
3222
4672
|
function sandboxError(message, name = "Error", code) {
|
|
3223
4673
|
const error = new Error(message);
|
|
3224
4674
|
error.name = name;
|
|
3225
4675
|
if (code !== void 0) error.code = code;
|
|
3226
4676
|
return error;
|
|
3227
4677
|
}
|
|
4678
|
+
function ignoreRejection3() {
|
|
4679
|
+
}
|
|
4680
|
+
function observed(helper) {
|
|
4681
|
+
return (...args) => {
|
|
4682
|
+
const result = helper(...args);
|
|
4683
|
+
result.then(void 0, ignoreRejection3);
|
|
4684
|
+
return result;
|
|
4685
|
+
};
|
|
4686
|
+
}
|
|
3228
4687
|
function frozenRecord2(members) {
|
|
3229
4688
|
const record = /* @__PURE__ */ Object.create(null);
|
|
3230
4689
|
for (const key of Object.keys(members)) record[key] = members[key];
|
|
@@ -3291,15 +4750,20 @@ var InterpreterAdapter = class {
|
|
|
3291
4750
|
const allocationLimit = typeof memoryLimit === "number" && memoryLimit > 0 ? Math.min(memoryLimit, adapterLimit) : adapterLimit;
|
|
3292
4751
|
const tracker = new MemoryTracker({ memoryLimit: Number.isFinite(allocationLimit) ? allocationLimit : 0 });
|
|
3293
4752
|
const charge = (bytes) => tracker.track(bytes);
|
|
4753
|
+
let chargeForHelper = (_bytes) => {
|
|
4754
|
+
throw sandboxError("The interpreter is not running");
|
|
4755
|
+
};
|
|
4756
|
+
const timeout = context.config.timeout;
|
|
4757
|
+
const deadlineAt = timeout && timeout > 0 ? Date.now() + timeout : void 0;
|
|
3294
4758
|
let interpreter;
|
|
4759
|
+
const callbacks = {
|
|
4760
|
+
call: () => {
|
|
4761
|
+
throw sandboxError("The interpreter is not running");
|
|
4762
|
+
}
|
|
4763
|
+
};
|
|
3295
4764
|
try {
|
|
3296
4765
|
const safe = createSafeGlobals();
|
|
3297
|
-
const
|
|
3298
|
-
call: () => {
|
|
3299
|
-
throw sandboxError("The interpreter is not running");
|
|
3300
|
-
}
|
|
3301
|
-
};
|
|
3302
|
-
const runtime = this.runtimeGlobals(context, charge, callbacks);
|
|
4766
|
+
const runtime = this.runtimeGlobals(context, (bytes) => chargeForHelper(bytes), callbacks);
|
|
3303
4767
|
for (const name of Object.keys(runtime)) {
|
|
3304
4768
|
if (!Object.prototype.hasOwnProperty.call(safe.globals, name)) safe.globals[name] = runtime[name];
|
|
3305
4769
|
}
|
|
@@ -3311,37 +4775,40 @@ var InterpreterAdapter = class {
|
|
|
3311
4775
|
maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
|
|
3312
4776
|
maxPendingCalls: this.options.maxPendingCalls,
|
|
3313
4777
|
signal: context.abortController.signal,
|
|
4778
|
+
deadline: deadlineAt,
|
|
3314
4779
|
charge
|
|
3315
4780
|
});
|
|
3316
|
-
const
|
|
3317
|
-
callbacks.call = (fn, args) =>
|
|
4781
|
+
const running2 = interpreter;
|
|
4782
|
+
callbacks.call = (fn, args) => running2.call(fn, args);
|
|
4783
|
+
callbacks.countBigInt = (value) => running2.countBigInt(value);
|
|
4784
|
+
chargeForHelper = (bytes) => running2.chargeAllocation(bytes);
|
|
3318
4785
|
} catch (error) {
|
|
3319
4786
|
return this.fail(error, startTime, stats.toolCallCount, 0, sanitizeStacks);
|
|
3320
4787
|
}
|
|
3321
|
-
const timeout = context.config.timeout;
|
|
3322
4788
|
const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
|
|
3323
4789
|
let timeoutHandle;
|
|
3324
4790
|
const TIMED_OUT = /* @__PURE__ */ Symbol("timeout");
|
|
3325
4791
|
const deadline = timeout && timeout > 0 ? new Promise((resolve) => {
|
|
3326
4792
|
timeoutHandle = setTimeout(() => resolve(TIMED_OUT), timeout);
|
|
3327
4793
|
}) : void 0;
|
|
4794
|
+
const running = interpreter;
|
|
4795
|
+
const timedOut = () => this.fail(
|
|
4796
|
+
new Error(`Execution timed out after ${timeout}ms`),
|
|
4797
|
+
startTime,
|
|
4798
|
+
stats.toolCallCount,
|
|
4799
|
+
running.stepCount,
|
|
4800
|
+
sanitizeStacks,
|
|
4801
|
+
"TimeoutError",
|
|
4802
|
+
"EXECUTION_TIMEOUT"
|
|
4803
|
+
);
|
|
3328
4804
|
try {
|
|
3329
4805
|
const run = interpreter.run(program);
|
|
3330
4806
|
run.catch(() => void 0);
|
|
3331
4807
|
const outcome = deadline ? await Promise.race([run, deadline]) : await run;
|
|
3332
|
-
if (outcome === TIMED_OUT)
|
|
3333
|
-
return this.fail(
|
|
3334
|
-
new Error(`Execution timed out after ${timeout}ms`),
|
|
3335
|
-
startTime,
|
|
3336
|
-
stats.toolCallCount,
|
|
3337
|
-
interpreter.stepCount,
|
|
3338
|
-
sanitizeStacks,
|
|
3339
|
-
"TimeoutError",
|
|
3340
|
-
"EXECUTION_TIMEOUT"
|
|
3341
|
-
);
|
|
3342
|
-
}
|
|
4808
|
+
if (outcome === TIMED_OUT) return timedOut();
|
|
3343
4809
|
return this.succeed(outcome, context, startTime, stats.toolCallCount, interpreter.stepCount);
|
|
3344
4810
|
} catch (error) {
|
|
4811
|
+
if (error instanceof DeadlineError) return timedOut();
|
|
3345
4812
|
const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
|
|
3346
4813
|
return this.fail(
|
|
3347
4814
|
error,
|
|
@@ -3355,6 +4822,7 @@ var InterpreterAdapter = class {
|
|
|
3355
4822
|
} finally {
|
|
3356
4823
|
if (timer) clearTimeout(timer);
|
|
3357
4824
|
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
4825
|
+
callbacks.over = true;
|
|
3358
4826
|
interpreter.stop();
|
|
3359
4827
|
}
|
|
3360
4828
|
}
|
|
@@ -3366,7 +4834,7 @@ var InterpreterAdapter = class {
|
|
|
3366
4834
|
*/
|
|
3367
4835
|
runtimeGlobals(context, charge, callbacks) {
|
|
3368
4836
|
const { config } = context;
|
|
3369
|
-
const callTool = this.createCallTool(context);
|
|
4837
|
+
const callTool = observed(this.createCallTool(context, callbacks, charge));
|
|
3370
4838
|
const resolver = context.sidecar && context.referenceConfig ? new ReferenceResolver(context.sidecar, context.referenceConfig) : void 0;
|
|
3371
4839
|
const joinReferences = (parts) => {
|
|
3372
4840
|
if (!resolver) {
|
|
@@ -3384,6 +4852,8 @@ var InterpreterAdapter = class {
|
|
|
3384
4852
|
const result = left + right;
|
|
3385
4853
|
if (typeof result === "string") {
|
|
3386
4854
|
charge((result.length - (typeof left === "string" ? left.length : 0)) * 2);
|
|
4855
|
+
} else if (typeof result === "bigint") {
|
|
4856
|
+
callbacks.countBigInt?.(result);
|
|
3387
4857
|
}
|
|
3388
4858
|
return result;
|
|
3389
4859
|
};
|
|
@@ -3391,12 +4861,20 @@ var InterpreterAdapter = class {
|
|
|
3391
4861
|
if (!Array.isArray(quasis)) throw sandboxError("Template pieces must be an array", "TypeError");
|
|
3392
4862
|
const parts = [];
|
|
3393
4863
|
let hasReference = false;
|
|
4864
|
+
let length = 0;
|
|
4865
|
+
const add = (part) => {
|
|
4866
|
+
length += part.length;
|
|
4867
|
+
if (length > MAX_JOIN_LENGTH) {
|
|
4868
|
+
throw sandboxError(`A template literal cannot produce more than ${MAX_JOIN_LENGTH} chars`, "RangeError");
|
|
4869
|
+
}
|
|
4870
|
+
parts.push(part);
|
|
4871
|
+
};
|
|
3394
4872
|
for (let i = 0; i < quasis.length; i++) {
|
|
3395
|
-
|
|
4873
|
+
add(String(quasis[i]));
|
|
3396
4874
|
if (i < values.length) {
|
|
3397
4875
|
const value = values[i];
|
|
3398
4876
|
if (typeof value === "string" && isReferenceId(value)) hasReference = true;
|
|
3399
|
-
|
|
4877
|
+
add(String(value));
|
|
3400
4878
|
}
|
|
3401
4879
|
}
|
|
3402
4880
|
if (hasReference) return joinReferences(parts.filter((part) => part !== ""));
|
|
@@ -3418,7 +4896,7 @@ var InterpreterAdapter = class {
|
|
|
3418
4896
|
yield item;
|
|
3419
4897
|
}
|
|
3420
4898
|
}
|
|
3421
|
-
const parallel = async (first, second) => {
|
|
4899
|
+
const parallel = observed(async (first, second) => {
|
|
3422
4900
|
let tasks;
|
|
3423
4901
|
if (typeof second === "function") {
|
|
3424
4902
|
if (!Array.isArray(first)) throw sandboxError("parallel requires an array of items", "TypeError");
|
|
@@ -3438,12 +4916,24 @@ var InterpreterAdapter = class {
|
|
|
3438
4916
|
const settled = await Promise.allSettled(tasks.map(async (task) => task()));
|
|
3439
4917
|
const failures = settled.filter((result) => result.status === "rejected");
|
|
3440
4918
|
if (failures.length > 0) {
|
|
3441
|
-
|
|
3442
|
-
|
|
3443
|
-
|
|
4919
|
+
let messages = "";
|
|
4920
|
+
let listed = 0;
|
|
4921
|
+
for (const failure of failures) {
|
|
4922
|
+
const room = MAX_THROWN_MESSAGE_LENGTH - messages.length - (listed === 0 ? 0 : 1);
|
|
4923
|
+
if (room <= 0) break;
|
|
4924
|
+
const message = this.describe(failure.reason).message;
|
|
4925
|
+
messages += (listed === 0 ? "" : "\n") + (message.length > room ? message.slice(0, room) : message);
|
|
4926
|
+
listed++;
|
|
4927
|
+
}
|
|
4928
|
+
const unlisted = failures.length - listed;
|
|
4929
|
+
throw sandboxError(
|
|
4930
|
+
`${failures.length} of ${tasks.length} parallel operations failed:
|
|
4931
|
+
${messages}` + (unlisted > 0 ? `
|
|
4932
|
+
(${unlisted} more not shown)` : "")
|
|
4933
|
+
);
|
|
3444
4934
|
}
|
|
3445
4935
|
return settled.map((result) => result.value);
|
|
3446
|
-
};
|
|
4936
|
+
});
|
|
3447
4937
|
const globals = {
|
|
3448
4938
|
__safe_callTool: callTool,
|
|
3449
4939
|
__safe_concat: concat,
|
|
@@ -3461,19 +4951,23 @@ ${messages}`);
|
|
|
3461
4951
|
let consoleCalls = 0;
|
|
3462
4952
|
let consoleLength = 0;
|
|
3463
4953
|
const write = (level) => (...args) => {
|
|
4954
|
+
if (callbacks.over) throw executionOver();
|
|
3464
4955
|
consoleCalls++;
|
|
3465
4956
|
if (consoleCalls > maxConsoleCalls) {
|
|
3466
4957
|
throw sandboxError(
|
|
3467
4958
|
`Console call limit exceeded (max: ${maxConsoleCalls}). This limit prevents I/O flood attacks.`
|
|
3468
4959
|
);
|
|
3469
4960
|
}
|
|
4961
|
+
const outputLimit = () => sandboxError(
|
|
4962
|
+
`Console output size limit exceeded (max: ${maxConsoleOutputBytes} bytes). This limit prevents I/O flood attacks.`
|
|
4963
|
+
);
|
|
4964
|
+
const room = (maxConsoleOutputBytes - consoleLength) * 16 + 64 * 1024;
|
|
4965
|
+
for (const arg of args) {
|
|
4966
|
+
if (arg !== null && typeof arg === "object" && certainlyLargerThan(arg, room)) throw outputLimit();
|
|
4967
|
+
}
|
|
3470
4968
|
const line = args.map(consoleText).join(" ");
|
|
3471
4969
|
consoleLength += line.length;
|
|
3472
|
-
if (consoleLength > maxConsoleOutputBytes)
|
|
3473
|
-
throw sandboxError(
|
|
3474
|
-
`Console output size limit exceeded (max: ${maxConsoleOutputBytes} bytes). This limit prevents I/O flood attacks.`
|
|
3475
|
-
);
|
|
3476
|
-
}
|
|
4970
|
+
if (consoleLength > maxConsoleOutputBytes) throw outputLimit();
|
|
3477
4971
|
sink(level, line);
|
|
3478
4972
|
};
|
|
3479
4973
|
globals["__safe_console"] = frozenRecord2({
|
|
@@ -3486,16 +4980,88 @@ ${messages}`);
|
|
|
3486
4980
|
for (const namespace of context.toolNamespaces ?? []) {
|
|
3487
4981
|
const methods = {};
|
|
3488
4982
|
for (const method of namespace.methods) {
|
|
3489
|
-
if (isBlockedKey(method.name)) continue;
|
|
4983
|
+
if (isBlockedKey(method.name) || isEngineCalledKey(method.name)) continue;
|
|
3490
4984
|
methods[method.name] = (args, options) => callTool(method.toolName, args === void 0 ? {} : args, options);
|
|
3491
4985
|
}
|
|
3492
4986
|
globals[namespace.name] = frozenRecord2(methods);
|
|
3493
4987
|
}
|
|
3494
4988
|
const custom = config.globals;
|
|
3495
4989
|
if (custom && typeof custom === "object") {
|
|
4990
|
+
const maxGlobalCalls = config.maxGlobalFunctionCalls ?? Math.max(10, config.maxToolCalls * 10);
|
|
4991
|
+
const payloadLimit = config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_TOOL_PAYLOAD_BYTES;
|
|
4992
|
+
let globalCalls = 0;
|
|
4993
|
+
const serialize = (value) => {
|
|
4994
|
+
const sanitized = sanitizeValue(value, {
|
|
4995
|
+
maxDepth: config.maxSanitizeDepth,
|
|
4996
|
+
maxProperties: config.maxSanitizeProperties,
|
|
4997
|
+
allowDates: false,
|
|
4998
|
+
allowErrors: true
|
|
4999
|
+
});
|
|
5000
|
+
const json = stringifyWithin(sanitized, payloadLimit);
|
|
5001
|
+
if (json === void 0) return void 0;
|
|
5002
|
+
if (utf8Length2(json) > payloadLimit) throw sandboxError("Global function value exceeds bridge limit");
|
|
5003
|
+
return json;
|
|
5004
|
+
};
|
|
5005
|
+
const copy = (value) => {
|
|
5006
|
+
const json = serialize(value);
|
|
5007
|
+
return json === void 0 ? void 0 : JSON.parse(json);
|
|
5008
|
+
};
|
|
5009
|
+
const safeHostCall = (name, fn) => (...args) => {
|
|
5010
|
+
if (callbacks.over || context.aborted) throw executionOver();
|
|
5011
|
+
if (++globalCalls > maxGlobalCalls)
|
|
5012
|
+
throw sandboxError(`Global function call limit exceeded (${maxGlobalCalls})`);
|
|
5013
|
+
if (context.beforeGlobalCall && context.beforeGlobalCall() !== true) {
|
|
5014
|
+
throw sandboxError("Global function policy refused the call");
|
|
5015
|
+
}
|
|
5016
|
+
let safeArgs;
|
|
5017
|
+
try {
|
|
5018
|
+
safeArgs = copy(args);
|
|
5019
|
+
} catch {
|
|
5020
|
+
throw sandboxError(`Global function ${name} received unsupported arguments`, "TypeError");
|
|
5021
|
+
}
|
|
5022
|
+
let outcome;
|
|
5023
|
+
try {
|
|
5024
|
+
outcome = fn(...safeArgs);
|
|
5025
|
+
} catch {
|
|
5026
|
+
throw sandboxError("Global function failed");
|
|
5027
|
+
}
|
|
5028
|
+
const settle = (value) => {
|
|
5029
|
+
if (callbacks.over || context.aborted) throw executionOver();
|
|
5030
|
+
let json;
|
|
5031
|
+
try {
|
|
5032
|
+
json = serialize(value);
|
|
5033
|
+
} catch {
|
|
5034
|
+
throw sandboxError(`Global function ${name} returned an unsupported value`);
|
|
5035
|
+
}
|
|
5036
|
+
if (json === void 0) return void 0;
|
|
5037
|
+
if (value !== null && typeof value === "object") charge(Math.max(json.length * 2, utf8Length2(json)));
|
|
5038
|
+
return JSON.parse(json);
|
|
5039
|
+
};
|
|
5040
|
+
if (outcome !== null && (typeof outcome === "object" || typeof outcome === "function")) {
|
|
5041
|
+
let then;
|
|
5042
|
+
try {
|
|
5043
|
+
then = outcome.then;
|
|
5044
|
+
} catch {
|
|
5045
|
+
throw sandboxError(`Global function ${name} returned an unsupported value`);
|
|
5046
|
+
}
|
|
5047
|
+
if (typeof then === "function") {
|
|
5048
|
+
return observed(async () => {
|
|
5049
|
+
let value;
|
|
5050
|
+
try {
|
|
5051
|
+
value = await Promise.resolve(outcome);
|
|
5052
|
+
} catch {
|
|
5053
|
+
throw sandboxError("Global function failed");
|
|
5054
|
+
}
|
|
5055
|
+
return settle(value);
|
|
5056
|
+
})();
|
|
5057
|
+
}
|
|
5058
|
+
}
|
|
5059
|
+
return settle(outcome);
|
|
5060
|
+
};
|
|
3496
5061
|
for (const name of Object.keys(custom)) {
|
|
3497
5062
|
if (name.startsWith("__") || Object.prototype.hasOwnProperty.call(globals, name)) continue;
|
|
3498
|
-
|
|
5063
|
+
const value = custom[name];
|
|
5064
|
+
globals[name] = typeof value === "function" ? safeHostCall(name, value) : frozenDataCopy(name, value);
|
|
3499
5065
|
}
|
|
3500
5066
|
}
|
|
3501
5067
|
return globals;
|
|
@@ -3505,11 +5071,13 @@ ${messages}`);
|
|
|
3505
5071
|
* and the response cross as JSON, so the handler never receives a value of the script and the
|
|
3506
5072
|
* script never receives an object of the handler.
|
|
3507
5073
|
*/
|
|
3508
|
-
createCallTool(context) {
|
|
5074
|
+
createCallTool(context, execution, charge) {
|
|
3509
5075
|
const configured = context.config.toolHandler;
|
|
3510
5076
|
const bridgeContext = context.toolHandler === void 0 && typeof configured === "function" ? Object.create(context, { toolHandler: { value: configured } }) : context;
|
|
3511
5077
|
const bridge = createHostToolBridge(bridgeContext, { updateStats: true });
|
|
5078
|
+
const maxPayloadBytes = context.config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_TOOL_PAYLOAD_BYTES;
|
|
3512
5079
|
return async (toolName, args, options) => {
|
|
5080
|
+
if (execution.over) throw executionOver();
|
|
3513
5081
|
let throwOnError = true;
|
|
3514
5082
|
if (options !== void 0 && options !== null) {
|
|
3515
5083
|
if (typeof options !== "object") throw sandboxError("callTool options must be an object", "TypeError");
|
|
@@ -3521,15 +5089,33 @@ ${messages}`);
|
|
|
3521
5089
|
if (typeof args !== "object" || args === null || Array.isArray(args)) {
|
|
3522
5090
|
throw sandboxError("Tool arguments must be an object", "TypeError");
|
|
3523
5091
|
}
|
|
5092
|
+
if (certainlyLargerThan(args, maxPayloadBytes * 2 + 1024)) {
|
|
5093
|
+
throw sandboxError(
|
|
5094
|
+
`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`,
|
|
5095
|
+
"ToolBridgeError",
|
|
5096
|
+
"TOOL_BRIDGE_REQUEST_TOO_LARGE"
|
|
5097
|
+
);
|
|
5098
|
+
}
|
|
3524
5099
|
let requestJson;
|
|
3525
5100
|
try {
|
|
3526
5101
|
requestJson = encodeToolBridgeRequest(toolName, args);
|
|
3527
5102
|
} catch {
|
|
3528
5103
|
throw sandboxError("Tool arguments must be JSON-serializable", "TypeError");
|
|
3529
5104
|
}
|
|
5105
|
+
if (utf8Length2(requestJson) > maxPayloadBytes) {
|
|
5106
|
+
throw sandboxError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "ToolBridgeError");
|
|
5107
|
+
}
|
|
5108
|
+
if (context.beforeToolCall) {
|
|
5109
|
+
const request = JSON.parse(requestJson);
|
|
5110
|
+
if (context.beforeToolCall(toolName, request.args) !== true) {
|
|
5111
|
+
throw sandboxError("Tool policy refused the call");
|
|
5112
|
+
}
|
|
5113
|
+
}
|
|
3530
5114
|
let response;
|
|
5115
|
+
let responseJson;
|
|
3531
5116
|
try {
|
|
3532
|
-
|
|
5117
|
+
responseJson = await bridge(requestJson);
|
|
5118
|
+
response = JSON.parse(responseJson);
|
|
3533
5119
|
} catch {
|
|
3534
5120
|
throw sandboxError("Tool bridge returned invalid JSON");
|
|
3535
5121
|
}
|
|
@@ -3538,6 +5124,15 @@ ${messages}`);
|
|
|
3538
5124
|
}
|
|
3539
5125
|
const reply = response;
|
|
3540
5126
|
if (reply.ok === true) {
|
|
5127
|
+
try {
|
|
5128
|
+
charge(Math.max(responseJson.length * 2, utf8Length2(responseJson)));
|
|
5129
|
+
} catch (error) {
|
|
5130
|
+
try {
|
|
5131
|
+
context.onToolBridgeFailure?.();
|
|
5132
|
+
} catch {
|
|
5133
|
+
}
|
|
5134
|
+
throw error;
|
|
5135
|
+
}
|
|
3541
5136
|
return throwOnError ? reply.value : { success: true, data: reply.value };
|
|
3542
5137
|
}
|
|
3543
5138
|
if (reply.ok === false && reply.error && typeof reply.error === "object") {
|
|
@@ -3624,9 +5219,996 @@ ${messages}`);
|
|
|
3624
5219
|
return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };
|
|
3625
5220
|
}
|
|
3626
5221
|
};
|
|
5222
|
+
|
|
5223
|
+
// libs/core/src/portable-enclave.ts
|
|
5224
|
+
import {
|
|
5225
|
+
JSAstValidator,
|
|
5226
|
+
PreScanner,
|
|
5227
|
+
ValidationSeverity,
|
|
5228
|
+
createAgentScriptPreset,
|
|
5229
|
+
extractLargeStrings,
|
|
5230
|
+
getAgentScriptGlobals,
|
|
5231
|
+
isWrappedInMain,
|
|
5232
|
+
normalizeToolNamespaces,
|
|
5233
|
+
transformAgentScript,
|
|
5234
|
+
transformConcatenation,
|
|
5235
|
+
transformTemplateLiterals
|
|
5236
|
+
} from "@enclave-vm/ast";
|
|
5237
|
+
import * as acorn3 from "acorn";
|
|
5238
|
+
import { generate } from "astring";
|
|
5239
|
+
|
|
5240
|
+
// libs/core/src/types.ts
|
|
5241
|
+
var SECURITY_LEVEL_CONFIGS = {
|
|
5242
|
+
/**
|
|
5243
|
+
* STRICT: Maximum security for untrusted code
|
|
5244
|
+
*
|
|
5245
|
+
* Use for:
|
|
5246
|
+
* - AI-generated code from external sources
|
|
5247
|
+
* - User-submitted scripts
|
|
5248
|
+
* - Untrusted third-party integrations
|
|
5249
|
+
*
|
|
5250
|
+
* Characteristics:
|
|
5251
|
+
* - Short timeout (5s)
|
|
5252
|
+
* - Low iteration limits (1000)
|
|
5253
|
+
* - Limited tool calls (10)
|
|
5254
|
+
* - Deep value sanitization
|
|
5255
|
+
* - Full stack trace sanitization
|
|
5256
|
+
*/
|
|
5257
|
+
STRICT: {
|
|
5258
|
+
timeout: 5e3,
|
|
5259
|
+
maxIterations: 1e3,
|
|
5260
|
+
maxToolCalls: 10,
|
|
5261
|
+
maxSanitizeDepth: 5,
|
|
5262
|
+
maxSanitizeProperties: 50,
|
|
5263
|
+
sanitizeStackTraces: true,
|
|
5264
|
+
blockTimingAPIs: true,
|
|
5265
|
+
allowUnboundedLoops: false,
|
|
5266
|
+
unicodeSecurityCheck: true,
|
|
5267
|
+
allowFunctionsInGlobals: false,
|
|
5268
|
+
maxConsoleOutputBytes: 64 * 1024,
|
|
5269
|
+
// 64KB - prevent I/O flood attacks
|
|
5270
|
+
maxConsoleCalls: 100,
|
|
5271
|
+
secureProxy: {
|
|
5272
|
+
blockConstructor: true,
|
|
5273
|
+
blockPrototype: true,
|
|
5274
|
+
blockLegacyAccessors: true,
|
|
5275
|
+
proxyMaxDepth: 5,
|
|
5276
|
+
throwOnBlocked: true
|
|
5277
|
+
}
|
|
5278
|
+
},
|
|
5279
|
+
/**
|
|
5280
|
+
* SECURE: High security with more headroom
|
|
5281
|
+
*
|
|
5282
|
+
* Use for:
|
|
5283
|
+
* - AI-generated code from trusted models
|
|
5284
|
+
* - Internal automation scripts
|
|
5285
|
+
* - Controlled multi-tenant environments
|
|
5286
|
+
*
|
|
5287
|
+
* Characteristics:
|
|
5288
|
+
* - Moderate timeout (15s)
|
|
5289
|
+
* - Moderate iteration limits (5000)
|
|
5290
|
+
* - Moderate tool calls (50)
|
|
5291
|
+
* - Standard value sanitization
|
|
5292
|
+
* - Stack trace sanitization
|
|
5293
|
+
*/
|
|
5294
|
+
SECURE: {
|
|
5295
|
+
timeout: 15e3,
|
|
5296
|
+
maxIterations: 5e3,
|
|
5297
|
+
maxToolCalls: 50,
|
|
5298
|
+
maxSanitizeDepth: 10,
|
|
5299
|
+
maxSanitizeProperties: 100,
|
|
5300
|
+
sanitizeStackTraces: true,
|
|
5301
|
+
blockTimingAPIs: false,
|
|
5302
|
+
allowUnboundedLoops: false,
|
|
5303
|
+
unicodeSecurityCheck: true,
|
|
5304
|
+
allowFunctionsInGlobals: false,
|
|
5305
|
+
maxConsoleOutputBytes: 256 * 1024,
|
|
5306
|
+
// 256KB
|
|
5307
|
+
maxConsoleCalls: 500,
|
|
5308
|
+
secureProxy: {
|
|
5309
|
+
blockConstructor: true,
|
|
5310
|
+
blockPrototype: true,
|
|
5311
|
+
blockLegacyAccessors: true,
|
|
5312
|
+
proxyMaxDepth: 10,
|
|
5313
|
+
throwOnBlocked: true
|
|
5314
|
+
}
|
|
5315
|
+
},
|
|
5316
|
+
/**
|
|
5317
|
+
* STANDARD: Balanced security and functionality (DEFAULT)
|
|
5318
|
+
*
|
|
5319
|
+
* Use for:
|
|
5320
|
+
* - Internal tools and scripts
|
|
5321
|
+
* - Development and testing
|
|
5322
|
+
* - Trusted environments
|
|
5323
|
+
*
|
|
5324
|
+
* Characteristics:
|
|
5325
|
+
* - Standard timeout (30s)
|
|
5326
|
+
* - Standard iteration limits (10000)
|
|
5327
|
+
* - Standard tool calls (100)
|
|
5328
|
+
* - Basic value sanitization
|
|
5329
|
+
* - Minimal stack trace sanitization
|
|
5330
|
+
*/
|
|
5331
|
+
STANDARD: {
|
|
5332
|
+
timeout: 3e4,
|
|
5333
|
+
maxIterations: 1e4,
|
|
5334
|
+
maxToolCalls: 100,
|
|
5335
|
+
maxSanitizeDepth: 20,
|
|
5336
|
+
maxSanitizeProperties: 500,
|
|
5337
|
+
sanitizeStackTraces: false,
|
|
5338
|
+
blockTimingAPIs: false,
|
|
5339
|
+
allowUnboundedLoops: true,
|
|
5340
|
+
unicodeSecurityCheck: false,
|
|
5341
|
+
allowFunctionsInGlobals: false,
|
|
5342
|
+
maxConsoleOutputBytes: 1024 * 1024,
|
|
5343
|
+
// 1MB
|
|
5344
|
+
maxConsoleCalls: 1e3,
|
|
5345
|
+
secureProxy: {
|
|
5346
|
+
blockConstructor: true,
|
|
5347
|
+
blockPrototype: true,
|
|
5348
|
+
blockLegacyAccessors: true,
|
|
5349
|
+
proxyMaxDepth: 15,
|
|
5350
|
+
throwOnBlocked: true
|
|
5351
|
+
}
|
|
5352
|
+
},
|
|
5353
|
+
/**
|
|
5354
|
+
* PERMISSIVE: Minimal restrictions
|
|
5355
|
+
*
|
|
5356
|
+
* Use for:
|
|
5357
|
+
* - Local development only
|
|
5358
|
+
* - Debugging
|
|
5359
|
+
* - Performance testing
|
|
5360
|
+
*
|
|
5361
|
+
* WARNING: Not recommended for production use with untrusted code
|
|
5362
|
+
*
|
|
5363
|
+
* Characteristics:
|
|
5364
|
+
* - Long timeout (60s)
|
|
5365
|
+
* - High iteration limits (100000)
|
|
5366
|
+
* - High tool calls (1000)
|
|
5367
|
+
* - Minimal sanitization
|
|
5368
|
+
* - No stack trace sanitization
|
|
5369
|
+
* - All features enabled
|
|
5370
|
+
*/
|
|
5371
|
+
PERMISSIVE: {
|
|
5372
|
+
timeout: 6e4,
|
|
5373
|
+
maxIterations: 1e5,
|
|
5374
|
+
maxToolCalls: 1e3,
|
|
5375
|
+
maxSanitizeDepth: 50,
|
|
5376
|
+
maxSanitizeProperties: 1e3,
|
|
5377
|
+
sanitizeStackTraces: false,
|
|
5378
|
+
blockTimingAPIs: false,
|
|
5379
|
+
allowUnboundedLoops: true,
|
|
5380
|
+
unicodeSecurityCheck: false,
|
|
5381
|
+
allowFunctionsInGlobals: true,
|
|
5382
|
+
maxConsoleOutputBytes: 10 * 1024 * 1024,
|
|
5383
|
+
// 10MB
|
|
5384
|
+
maxConsoleCalls: 1e4,
|
|
5385
|
+
secureProxy: {
|
|
5386
|
+
blockConstructor: false,
|
|
5387
|
+
// Allow constructor access for development/debugging
|
|
5388
|
+
blockPrototype: true,
|
|
5389
|
+
// Still block prototype for safety
|
|
5390
|
+
blockLegacyAccessors: true,
|
|
5391
|
+
proxyMaxDepth: 20,
|
|
5392
|
+
throwOnBlocked: false
|
|
5393
|
+
// Return undefined instead of throwing for development
|
|
5394
|
+
}
|
|
5395
|
+
}
|
|
5396
|
+
};
|
|
5397
|
+
var DEFAULT_DOUBLE_VM_CONFIG = {
|
|
5398
|
+
enabled: true,
|
|
5399
|
+
parentTimeoutBuffer: 1e3,
|
|
5400
|
+
parentValidation: {
|
|
5401
|
+
validateOperationNames: true,
|
|
5402
|
+
maxOperationsPerSecond: 100,
|
|
5403
|
+
blockSuspiciousSequences: true,
|
|
5404
|
+
rapidEnumerationThreshold: 30,
|
|
5405
|
+
rapidEnumerationOverrides: {},
|
|
5406
|
+
suspiciousPatterns: []
|
|
5407
|
+
// Default patterns added at runtime
|
|
5408
|
+
}
|
|
5409
|
+
};
|
|
5410
|
+
|
|
5411
|
+
// libs/core/src/enclave-options.ts
|
|
5412
|
+
var MAX_TIMEOUT_MS = 2147483647;
|
|
5413
|
+
function withoutUndefined(value) {
|
|
5414
|
+
const result = {};
|
|
5415
|
+
for (const key of Object.keys(value)) {
|
|
5416
|
+
const member = value[key];
|
|
5417
|
+
if (member !== void 0) result[key] = member;
|
|
5418
|
+
}
|
|
5419
|
+
return result;
|
|
5420
|
+
}
|
|
5421
|
+
function describe(value) {
|
|
5422
|
+
if (value === null) return "null";
|
|
5423
|
+
if (typeof value === "number") return String(value);
|
|
5424
|
+
if (Array.isArray(value)) return "an array";
|
|
5425
|
+
if (typeof value === "string") return "a string";
|
|
5426
|
+
return `a value of type ${typeof value}`;
|
|
5427
|
+
}
|
|
5428
|
+
function assertIntegerOption(name, value, min, max = Number.MAX_SAFE_INTEGER) {
|
|
5429
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
|
|
5430
|
+
const range = max === Number.MAX_SAFE_INTEGER ? `an integer of at least ${min}` : `an integer from ${min} to ${max}`;
|
|
5431
|
+
throw new TypeError(`${name} must be ${range}, got ${describe(value)}`);
|
|
5432
|
+
}
|
|
5433
|
+
}
|
|
5434
|
+
function assertFiniteNumberOption(name, value, min) {
|
|
5435
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < min) {
|
|
5436
|
+
throw new TypeError(`${name} must be a finite number of at least ${min}, got ${describe(value)}`);
|
|
5437
|
+
}
|
|
5438
|
+
}
|
|
5439
|
+
function assertBooleanOption(name, value) {
|
|
5440
|
+
if (typeof value !== "boolean") {
|
|
5441
|
+
throw new TypeError(`${name} must be true or false, got ${describe(value)}`);
|
|
5442
|
+
}
|
|
5443
|
+
}
|
|
5444
|
+
function assertSecurityLevel(value) {
|
|
5445
|
+
if (typeof value !== "string" || !Object.hasOwn(SECURITY_LEVEL_CONFIGS, value)) {
|
|
5446
|
+
throw new TypeError(
|
|
5447
|
+
`securityLevel must be one of ${Object.keys(SECURITY_LEVEL_CONFIGS).join(", ")}, got ${typeof value === "string" ? JSON.stringify(value.slice(0, 40)) : describe(value)}`
|
|
5448
|
+
);
|
|
5449
|
+
}
|
|
5450
|
+
}
|
|
5451
|
+
function isPlainRecord(value) {
|
|
5452
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5453
|
+
}
|
|
5454
|
+
function assertRecordOption(name, value) {
|
|
5455
|
+
if (!isPlainRecord(value)) {
|
|
5456
|
+
throw new TypeError(`${name} must be an object, got ${describe(value)}`);
|
|
5457
|
+
}
|
|
5458
|
+
}
|
|
5459
|
+
function assertKnownKeys(name, value, known) {
|
|
5460
|
+
for (const key of Object.keys(value)) {
|
|
5461
|
+
if (!known.includes(key)) {
|
|
5462
|
+
throw new TypeError(`${name} has no option ${JSON.stringify(key.slice(0, 40))}`);
|
|
5463
|
+
}
|
|
5464
|
+
}
|
|
5465
|
+
}
|
|
5466
|
+
function isOneOf(values, value) {
|
|
5467
|
+
return typeof value === "string" && values.includes(value);
|
|
5468
|
+
}
|
|
5469
|
+
var PRE_SCAN_PRESETS = ["agentscript", "strict", "secure", "standard", "permissive"];
|
|
5470
|
+
var PRE_SCAN_INTEGERS = [
|
|
5471
|
+
"maxInputSize",
|
|
5472
|
+
"maxLineLength",
|
|
5473
|
+
"maxLines",
|
|
5474
|
+
"maxNestingDepth",
|
|
5475
|
+
"maxConsecutiveOperators",
|
|
5476
|
+
"maxRegexLength",
|
|
5477
|
+
"maxRegexCount",
|
|
5478
|
+
"maxStringLength",
|
|
5479
|
+
"maxTotalStringContent"
|
|
5480
|
+
];
|
|
5481
|
+
var PRE_SCAN_BOOLEANS = ["unicodePreCheck", "blockBidiPatterns", "blockInvisibleChars"];
|
|
5482
|
+
var PRE_SCAN_REGEX_MODES = ["allow", "analyze", "block"];
|
|
5483
|
+
var PRE_SCAN_REGEX_ANALYSIS_LEVELS = ["catastrophic", "polynomial"];
|
|
5484
|
+
var INTEGER_OPTIONS = [
|
|
5485
|
+
// What a timer can hold (see MAX_TIMEOUT_MS)
|
|
5486
|
+
["timeout", 1, MAX_TIMEOUT_MS],
|
|
5487
|
+
["maxIterations", 1],
|
|
5488
|
+
["maxToolCalls", 0],
|
|
5489
|
+
// 0: no memory limit
|
|
5490
|
+
["memoryLimit", 0],
|
|
5491
|
+
["maxSanitizeDepth", 1],
|
|
5492
|
+
["maxSanitizeProperties", 1],
|
|
5493
|
+
["maxConsoleOutputBytes", 0],
|
|
5494
|
+
["maxConsoleCalls", 0]
|
|
5495
|
+
];
|
|
5496
|
+
var BOOLEAN_OPTIONS = [
|
|
5497
|
+
"validate",
|
|
5498
|
+
"transform",
|
|
5499
|
+
"sanitizeStackTraces",
|
|
5500
|
+
"allowFunctionsInGlobals",
|
|
5501
|
+
"allowBuiltins"
|
|
5502
|
+
];
|
|
5503
|
+
var SECURE_PROXY_BOOLEANS = ["blockConstructor", "blockPrototype", "blockLegacyAccessors", "throwOnBlocked"];
|
|
5504
|
+
var PARENT_VALIDATION_BOOLEANS = ["validateOperationNames", "blockSuspiciousSequences"];
|
|
5505
|
+
function normalizeEnclaveOptions(options) {
|
|
5506
|
+
if (!isPlainRecord(options)) {
|
|
5507
|
+
throw new TypeError(`Enclave options must be an object, got ${describe(options)}`);
|
|
5508
|
+
}
|
|
5509
|
+
const result = withoutUndefined(options);
|
|
5510
|
+
if (result.securityLevel !== void 0) assertSecurityLevel(result.securityLevel);
|
|
5511
|
+
for (const [name, min, max] of INTEGER_OPTIONS) {
|
|
5512
|
+
if (result[name] !== void 0) assertIntegerOption(name, result[name], min, max);
|
|
5513
|
+
}
|
|
5514
|
+
for (const name of BOOLEAN_OPTIONS) {
|
|
5515
|
+
if (result[name] !== void 0) assertBooleanOption(name, result[name]);
|
|
5516
|
+
}
|
|
5517
|
+
if (result.secureProxyConfig !== void 0) {
|
|
5518
|
+
assertRecordOption("secureProxyConfig", result.secureProxyConfig);
|
|
5519
|
+
const proxy = withoutUndefined(result.secureProxyConfig);
|
|
5520
|
+
for (const name of SECURE_PROXY_BOOLEANS) {
|
|
5521
|
+
if (proxy[name] !== void 0) assertBooleanOption(`secureProxyConfig.${name}`, proxy[name]);
|
|
5522
|
+
}
|
|
5523
|
+
if (proxy["proxyMaxDepth"] !== void 0) {
|
|
5524
|
+
assertIntegerOption("secureProxyConfig.proxyMaxDepth", proxy["proxyMaxDepth"], 1);
|
|
5525
|
+
}
|
|
5526
|
+
result.secureProxyConfig = proxy;
|
|
5527
|
+
}
|
|
5528
|
+
if (result.toolBridge !== void 0) {
|
|
5529
|
+
assertRecordOption("toolBridge", result.toolBridge);
|
|
5530
|
+
const bridge = withoutUndefined(result.toolBridge);
|
|
5531
|
+
if (bridge["acknowledgeInsecureDirect"] !== void 0) {
|
|
5532
|
+
assertBooleanOption("toolBridge.acknowledgeInsecureDirect", bridge["acknowledgeInsecureDirect"]);
|
|
5533
|
+
}
|
|
5534
|
+
result.toolBridge = bridge;
|
|
5535
|
+
}
|
|
5536
|
+
if (result.preScan !== void 0) {
|
|
5537
|
+
assertRecordOption("preScan", result.preScan);
|
|
5538
|
+
const preScan = withoutUndefined(result.preScan);
|
|
5539
|
+
assertKnownKeys("preScan", preScan, ["preset", "config"]);
|
|
5540
|
+
if (preScan["preset"] !== void 0 && !isOneOf(PRE_SCAN_PRESETS, preScan["preset"])) {
|
|
5541
|
+
throw new TypeError(
|
|
5542
|
+
`preScan.preset must be one of ${PRE_SCAN_PRESETS.join(", ")}, got ${describe(preScan["preset"])}`
|
|
5543
|
+
);
|
|
5544
|
+
}
|
|
5545
|
+
if (preScan["config"] !== void 0) {
|
|
5546
|
+
assertRecordOption("preScan.config", preScan["config"]);
|
|
5547
|
+
const config = withoutUndefined(preScan["config"]);
|
|
5548
|
+
assertKnownKeys("preScan.config", config, [
|
|
5549
|
+
...PRE_SCAN_INTEGERS,
|
|
5550
|
+
...PRE_SCAN_BOOLEANS,
|
|
5551
|
+
"regexMode",
|
|
5552
|
+
"regexAnalysisLevel"
|
|
5553
|
+
]);
|
|
5554
|
+
for (const name of PRE_SCAN_INTEGERS) {
|
|
5555
|
+
if (config[name] !== void 0) assertIntegerOption(`preScan.config.${name}`, config[name], 0);
|
|
5556
|
+
}
|
|
5557
|
+
for (const name of PRE_SCAN_BOOLEANS) {
|
|
5558
|
+
if (config[name] !== void 0) assertBooleanOption(`preScan.config.${name}`, config[name]);
|
|
5559
|
+
}
|
|
5560
|
+
if (config["regexMode"] !== void 0 && !isOneOf(PRE_SCAN_REGEX_MODES, config["regexMode"])) {
|
|
5561
|
+
throw new TypeError(
|
|
5562
|
+
`preScan.config.regexMode must be one of ${PRE_SCAN_REGEX_MODES.join(", ")}, got ${describe(config["regexMode"])}`
|
|
5563
|
+
);
|
|
5564
|
+
}
|
|
5565
|
+
if (config["regexAnalysisLevel"] !== void 0 && !isOneOf(PRE_SCAN_REGEX_ANALYSIS_LEVELS, config["regexAnalysisLevel"])) {
|
|
5566
|
+
throw new TypeError(
|
|
5567
|
+
`preScan.config.regexAnalysisLevel must be one of ${PRE_SCAN_REGEX_ANALYSIS_LEVELS.join(", ")}, got ${describe(config["regexAnalysisLevel"])}`
|
|
5568
|
+
);
|
|
5569
|
+
}
|
|
5570
|
+
preScan["config"] = config;
|
|
5571
|
+
}
|
|
5572
|
+
result.preScan = preScan;
|
|
5573
|
+
}
|
|
5574
|
+
if (result.doubleVm !== void 0) {
|
|
5575
|
+
assertRecordOption("doubleVm", result.doubleVm);
|
|
5576
|
+
const doubleVm = withoutUndefined(result.doubleVm);
|
|
5577
|
+
if (doubleVm["enabled"] !== void 0) assertBooleanOption("doubleVm.enabled", doubleVm["enabled"]);
|
|
5578
|
+
if (doubleVm["parentTimeoutBuffer"] !== void 0) {
|
|
5579
|
+
assertIntegerOption("doubleVm.parentTimeoutBuffer", doubleVm["parentTimeoutBuffer"], 0, MAX_TIMEOUT_MS);
|
|
5580
|
+
}
|
|
5581
|
+
if (doubleVm["parentValidation"] !== void 0) {
|
|
5582
|
+
assertRecordOption("doubleVm.parentValidation", doubleVm["parentValidation"]);
|
|
5583
|
+
const validation = withoutUndefined(doubleVm["parentValidation"]);
|
|
5584
|
+
for (const name of PARENT_VALIDATION_BOOLEANS) {
|
|
5585
|
+
if (validation[name] !== void 0) {
|
|
5586
|
+
assertBooleanOption(`doubleVm.parentValidation.${name}`, validation[name]);
|
|
5587
|
+
}
|
|
5588
|
+
}
|
|
5589
|
+
if (validation["maxOperationsPerSecond"] !== void 0) {
|
|
5590
|
+
assertFiniteNumberOption(
|
|
5591
|
+
"doubleVm.parentValidation.maxOperationsPerSecond",
|
|
5592
|
+
validation["maxOperationsPerSecond"],
|
|
5593
|
+
1
|
|
5594
|
+
);
|
|
5595
|
+
}
|
|
5596
|
+
if (validation["rapidEnumerationThreshold"] !== void 0) {
|
|
5597
|
+
assertIntegerOption(
|
|
5598
|
+
"doubleVm.parentValidation.rapidEnumerationThreshold",
|
|
5599
|
+
validation["rapidEnumerationThreshold"],
|
|
5600
|
+
1
|
|
5601
|
+
);
|
|
5602
|
+
}
|
|
5603
|
+
if (validation["rapidEnumerationOverrides"] !== void 0) {
|
|
5604
|
+
assertRecordOption(
|
|
5605
|
+
"doubleVm.parentValidation.rapidEnumerationOverrides",
|
|
5606
|
+
validation["rapidEnumerationOverrides"]
|
|
5607
|
+
);
|
|
5608
|
+
for (const [operation, threshold] of Object.entries(validation["rapidEnumerationOverrides"])) {
|
|
5609
|
+
assertIntegerOption(
|
|
5610
|
+
`doubleVm.parentValidation.rapidEnumerationOverrides[${JSON.stringify(operation.slice(0, 40))}]`,
|
|
5611
|
+
threshold,
|
|
5612
|
+
1
|
|
5613
|
+
);
|
|
5614
|
+
}
|
|
5615
|
+
}
|
|
5616
|
+
doubleVm["parentValidation"] = validation;
|
|
5617
|
+
}
|
|
5618
|
+
result.doubleVm = doubleVm;
|
|
5619
|
+
}
|
|
5620
|
+
return result;
|
|
5621
|
+
}
|
|
5622
|
+
|
|
5623
|
+
// libs/core/src/portable-globals.ts
|
|
5624
|
+
var MAX_GLOBAL_DEPTH = 10;
|
|
5625
|
+
var MAX_GLOBAL_PROPERTIES = 1e4;
|
|
5626
|
+
var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
5627
|
+
var BLOCKED_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
5628
|
+
function copyPortableGlobals(globals, allowFunctions, maxBytes) {
|
|
5629
|
+
const result = /* @__PURE__ */ Object.create(null);
|
|
5630
|
+
if (globals === void 0) return result;
|
|
5631
|
+
if (globals === null || typeof globals !== "object" || Array.isArray(globals)) {
|
|
5632
|
+
throw new TypeError("globals must be a record");
|
|
5633
|
+
}
|
|
5634
|
+
let properties = 0;
|
|
5635
|
+
let bytes = 0;
|
|
5636
|
+
const active = /* @__PURE__ */ new Set();
|
|
5637
|
+
const charge = (value) => {
|
|
5638
|
+
bytes += value.length * 6 + 8;
|
|
5639
|
+
if (bytes > maxBytes) throw new TypeError("globals exceed the portable bridge size limit");
|
|
5640
|
+
};
|
|
5641
|
+
const copy = (value, depth) => {
|
|
5642
|
+
if (depth > MAX_GLOBAL_DEPTH) throw new TypeError("globals exceed the portable depth limit");
|
|
5643
|
+
if (value === null || typeof value === "boolean") return value;
|
|
5644
|
+
if (typeof value === "string") {
|
|
5645
|
+
charge(value);
|
|
5646
|
+
return value;
|
|
5647
|
+
}
|
|
5648
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
5649
|
+
if (typeof value !== "object") throw new TypeError("portable globals must contain JSON data only");
|
|
5650
|
+
if (active.has(value)) throw new TypeError("portable globals cannot contain cycles");
|
|
5651
|
+
const array = Array.isArray(value);
|
|
5652
|
+
if (array && value.length > MAX_GLOBAL_PROPERTIES) {
|
|
5653
|
+
throw new TypeError("portable globals exceed the array length limit");
|
|
5654
|
+
}
|
|
5655
|
+
const prototype = Object.getPrototypeOf(value);
|
|
5656
|
+
if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {
|
|
5657
|
+
throw new TypeError("portable globals must contain plain records or arrays");
|
|
5658
|
+
}
|
|
5659
|
+
active.add(value);
|
|
5660
|
+
try {
|
|
5661
|
+
const destination = array ? [] : /* @__PURE__ */ Object.create(null);
|
|
5662
|
+
const keys = Reflect.ownKeys(value);
|
|
5663
|
+
if (array && keys.length - 1 !== value.length) {
|
|
5664
|
+
throw new TypeError("portable globals cannot contain sparse arrays");
|
|
5665
|
+
}
|
|
5666
|
+
for (const key of keys) {
|
|
5667
|
+
if (typeof key !== "string") throw new TypeError("portable globals cannot contain symbol properties");
|
|
5668
|
+
if (array && key === "length") continue;
|
|
5669
|
+
if (BLOCKED_KEYS2.has(key)) throw new TypeError("portable globals contain a blocked property");
|
|
5670
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
5671
|
+
if (!descriptor || !Object.hasOwn(descriptor, "value")) {
|
|
5672
|
+
throw new TypeError("portable globals cannot contain accessors");
|
|
5673
|
+
}
|
|
5674
|
+
if (++properties > MAX_GLOBAL_PROPERTIES) throw new TypeError("globals exceed the portable property limit");
|
|
5675
|
+
charge(key);
|
|
5676
|
+
if (array) {
|
|
5677
|
+
const index = Number(key);
|
|
5678
|
+
if (!Number.isSafeInteger(index) || index < 0 || index >= value.length || String(index) !== key) {
|
|
5679
|
+
throw new TypeError("portable global arrays cannot contain named properties");
|
|
5680
|
+
}
|
|
5681
|
+
destination[index] = copy(descriptor.value, depth + 1);
|
|
5682
|
+
} else {
|
|
5683
|
+
destination[key] = copy(descriptor.value, depth + 1);
|
|
5684
|
+
}
|
|
5685
|
+
}
|
|
5686
|
+
return destination;
|
|
5687
|
+
} finally {
|
|
5688
|
+
active.delete(value);
|
|
5689
|
+
}
|
|
5690
|
+
};
|
|
5691
|
+
for (const key of Reflect.ownKeys(globals)) {
|
|
5692
|
+
if (typeof key !== "string" || !IDENTIFIER.test(key) || BLOCKED_KEYS2.has(key) || key.startsWith("__")) {
|
|
5693
|
+
throw new TypeError("portable globals contain an invalid name");
|
|
5694
|
+
}
|
|
5695
|
+
const descriptor = Object.getOwnPropertyDescriptor(globals, key);
|
|
5696
|
+
if (!descriptor || !Object.hasOwn(descriptor, "value")) {
|
|
5697
|
+
throw new TypeError("portable globals cannot contain accessors");
|
|
5698
|
+
}
|
|
5699
|
+
if (++properties > MAX_GLOBAL_PROPERTIES) throw new TypeError("globals exceed the portable property limit");
|
|
5700
|
+
charge(key);
|
|
5701
|
+
if (typeof descriptor.value === "function") {
|
|
5702
|
+
if (!allowFunctions) throw new TypeError("portable host functions require allowFunctionsInGlobals");
|
|
5703
|
+
result[key] = descriptor.value;
|
|
5704
|
+
} else {
|
|
5705
|
+
result[key] = copy(descriptor.value, 0);
|
|
5706
|
+
}
|
|
5707
|
+
}
|
|
5708
|
+
return result;
|
|
5709
|
+
}
|
|
5710
|
+
|
|
5711
|
+
// libs/core/src/double-vm/suspicious-patterns.ts
|
|
5712
|
+
var EXFIL_LIST_SEND = {
|
|
5713
|
+
id: "EXFIL_LIST_SEND",
|
|
5714
|
+
description: "List/query followed by send/export (potential exfiltration)",
|
|
5715
|
+
detect: (operationName, _args, history) => {
|
|
5716
|
+
const recentQueries = history.filter(
|
|
5717
|
+
(h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 5e3
|
|
5718
|
+
);
|
|
5719
|
+
const isSendOperation = /send|export|post|write|upload|publish|emit|transmit|forward/i.test(operationName);
|
|
5720
|
+
return recentQueries.length > 0 && isSendOperation;
|
|
5721
|
+
}
|
|
5722
|
+
};
|
|
5723
|
+
var RAPID_ENUMERATION = {
|
|
5724
|
+
id: "RAPID_ENUMERATION",
|
|
5725
|
+
description: "Rapid enumeration of resources (same operation called too many times in 5s)",
|
|
5726
|
+
detect: (operationName, _args, history) => {
|
|
5727
|
+
const now = Date.now();
|
|
5728
|
+
const recentSameOperation = history.filter((h) => h.operationName === operationName && now - h.timestamp < 5e3);
|
|
5729
|
+
let threshold = 30;
|
|
5730
|
+
try {
|
|
5731
|
+
const localConfig = typeof validationConfig !== "undefined" ? validationConfig : null;
|
|
5732
|
+
if (localConfig) {
|
|
5733
|
+
const defaultThreshold = localConfig.rapidEnumerationThreshold ?? 30;
|
|
5734
|
+
const overrides = localConfig.rapidEnumerationOverrides ?? {};
|
|
5735
|
+
const override = Object.prototype.hasOwnProperty.call(overrides, operationName) ? overrides[operationName] : void 0;
|
|
5736
|
+
threshold = typeof override === "number" ? override : defaultThreshold;
|
|
5737
|
+
}
|
|
5738
|
+
} catch {
|
|
5739
|
+
threshold = 30;
|
|
5740
|
+
}
|
|
5741
|
+
return recentSameOperation.length > threshold;
|
|
5742
|
+
}
|
|
5743
|
+
};
|
|
5744
|
+
var CREDENTIAL_EXFIL = {
|
|
5745
|
+
id: "CREDENTIAL_EXFIL",
|
|
5746
|
+
description: "Credential access followed by external operation",
|
|
5747
|
+
detect: (operationName, _args, history) => {
|
|
5748
|
+
const recentCredentialAccess = history.filter(
|
|
5749
|
+
(h) => /secret|credential|password|token|key|auth|api[_-]?key/i.test(h.operationName) && Date.now() - h.timestamp < 1e4
|
|
5750
|
+
);
|
|
5751
|
+
const isExternalOperation = /http|api|external|webhook|slack|email|sms|notification/i.test(operationName);
|
|
5752
|
+
return recentCredentialAccess.length > 0 && isExternalOperation;
|
|
5753
|
+
}
|
|
5754
|
+
};
|
|
5755
|
+
var BULK_OPERATION = {
|
|
5756
|
+
id: "BULK_OPERATION",
|
|
5757
|
+
description: "Bulk/batch operation detected",
|
|
5758
|
+
detect: (operationName, args, _history) => {
|
|
5759
|
+
const isBulkOperation = /\b(bulk|batch|mass|dump)\b|export[_-]all\b/i.test(operationName);
|
|
5760
|
+
if (typeof args === "object" && args !== null) {
|
|
5761
|
+
try {
|
|
5762
|
+
const argStr = JSON.stringify(args).toLowerCase();
|
|
5763
|
+
const firstLimit = argStr.indexOf("limit");
|
|
5764
|
+
const hasBulkArgs = firstLimit >= 0 && /[0-9]{4}/.test(argStr.slice(firstLimit + 5)) || argStr.indexOf('"*"') >= 0 || argStr.indexOf("nolimit") >= 0 || argStr.indexOf("no_limit") >= 0 || argStr.indexOf("no-limit") >= 0;
|
|
5765
|
+
if (hasBulkArgs) return true;
|
|
5766
|
+
} catch {
|
|
5767
|
+
}
|
|
5768
|
+
}
|
|
5769
|
+
return isBulkOperation;
|
|
5770
|
+
}
|
|
5771
|
+
};
|
|
5772
|
+
var DELETE_AFTER_ACCESS = {
|
|
5773
|
+
id: "DELETE_AFTER_ACCESS",
|
|
5774
|
+
description: "Delete operation after data access (potential cover-up)",
|
|
5775
|
+
detect: (operationName, _args, history) => {
|
|
5776
|
+
const isDeleteOperation = /delete|remove|destroy|purge|clear|wipe|erase/i.test(operationName);
|
|
5777
|
+
if (!isDeleteOperation) return false;
|
|
5778
|
+
const recentDataAccess = history.filter(
|
|
5779
|
+
(h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 3e4
|
|
5780
|
+
);
|
|
5781
|
+
return recentDataAccess.length > 0;
|
|
5782
|
+
}
|
|
5783
|
+
};
|
|
5784
|
+
var DEFAULT_SUSPICIOUS_PATTERNS = [
|
|
5785
|
+
EXFIL_LIST_SEND,
|
|
5786
|
+
RAPID_ENUMERATION,
|
|
5787
|
+
CREDENTIAL_EXFIL,
|
|
5788
|
+
BULK_OPERATION,
|
|
5789
|
+
DELETE_AFTER_ACCESS
|
|
5790
|
+
];
|
|
5791
|
+
|
|
5792
|
+
// libs/core/src/dynamic-import.ts
|
|
5793
|
+
import * as acorn2 from "acorn";
|
|
5794
|
+
import * as walk from "acorn-walk";
|
|
5795
|
+
var DYNAMIC_IMPORT_MESSAGE = "Dynamic import() is not available in the sandbox";
|
|
5796
|
+
function refuseDynamicImport(code) {
|
|
5797
|
+
if (typeof code !== "string" || !code.includes("import")) {
|
|
5798
|
+
return void 0;
|
|
5799
|
+
}
|
|
5800
|
+
let ast;
|
|
5801
|
+
try {
|
|
5802
|
+
ast = acorn2.parse(code, {
|
|
5803
|
+
ecmaVersion: "latest",
|
|
5804
|
+
sourceType: "script",
|
|
5805
|
+
allowHashBang: true,
|
|
5806
|
+
allowReturnOutsideFunction: true,
|
|
5807
|
+
allowAwaitOutsideFunction: true
|
|
5808
|
+
});
|
|
5809
|
+
} catch {
|
|
5810
|
+
return `${DYNAMIC_IMPORT_MESSAGE} (the script contains the word "import" and could not be parsed to rule it out)`;
|
|
5811
|
+
}
|
|
5812
|
+
let found = false;
|
|
5813
|
+
try {
|
|
5814
|
+
walk.full(ast, (node) => {
|
|
5815
|
+
if (node.type === "ImportExpression") found = true;
|
|
5816
|
+
if (node.type === "MetaProperty" && node.meta?.name === "import") {
|
|
5817
|
+
found = true;
|
|
5818
|
+
}
|
|
5819
|
+
});
|
|
5820
|
+
} catch {
|
|
5821
|
+
return DYNAMIC_IMPORT_MESSAGE;
|
|
5822
|
+
}
|
|
5823
|
+
return found ? DYNAMIC_IMPORT_MESSAGE : void 0;
|
|
5824
|
+
}
|
|
5825
|
+
|
|
5826
|
+
// libs/core/src/portable-enclave.ts
|
|
5827
|
+
var MAX_SCRIPT_LENGTH = 5 * 1024 * 1024;
|
|
5828
|
+
var MAX_PORTABLE_ALLOCATION_BYTES = 64 * 1024 * 1024;
|
|
5829
|
+
var MAX_PORTABLE_STEPS = 2e7;
|
|
5830
|
+
var MAX_PORTABLE_PENDING_CALLS = 4096;
|
|
5831
|
+
var MAX_PORTABLE_CALL_DEPTH = 1024;
|
|
5832
|
+
var DEFAULT_BRIDGE_BYTES = 5 * 1024 * 1024;
|
|
5833
|
+
function boundedInteger(name, value, max) {
|
|
5834
|
+
if (value !== void 0 && (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max)) {
|
|
5835
|
+
throw new TypeError(`${name} must be an integer from 1 to ${max}`);
|
|
5836
|
+
}
|
|
5837
|
+
}
|
|
5838
|
+
function referenceConfig(level, sidecar) {
|
|
5839
|
+
if (!sidecar?.enabled) return void 0;
|
|
5840
|
+
const base = REFERENCE_CONFIGS[level];
|
|
5841
|
+
return {
|
|
5842
|
+
maxTotalSize: sidecar.maxTotalSize ?? base.maxTotalSize,
|
|
5843
|
+
maxReferenceSize: sidecar.maxReferenceSize ?? base.maxReferenceSize,
|
|
5844
|
+
extractionThreshold: sidecar.extractionThreshold ?? base.extractionThreshold,
|
|
5845
|
+
maxResolvedSize: sidecar.maxResolvedSize ?? base.maxResolvedSize,
|
|
5846
|
+
maxTotalResolvedSize: sidecar.maxTotalResolvedSize ?? base.maxTotalResolvedSize,
|
|
5847
|
+
allowComposites: sidecar.allowComposites ?? base.allowComposites,
|
|
5848
|
+
maxReferenceCount: sidecar.maxReferenceCount ?? base.maxReferenceCount,
|
|
5849
|
+
maxResolutionDepth: base.maxResolutionDepth
|
|
5850
|
+
};
|
|
5851
|
+
}
|
|
5852
|
+
function validateReferenceConfig(config) {
|
|
5853
|
+
if (!config) return;
|
|
5854
|
+
for (const key of [
|
|
5855
|
+
"maxTotalSize",
|
|
5856
|
+
"maxReferenceSize",
|
|
5857
|
+
"extractionThreshold",
|
|
5858
|
+
"maxResolvedSize",
|
|
5859
|
+
"maxTotalResolvedSize",
|
|
5860
|
+
"maxReferenceCount",
|
|
5861
|
+
"maxResolutionDepth"
|
|
5862
|
+
]) {
|
|
5863
|
+
const value = config[key];
|
|
5864
|
+
if (value !== void 0 && (!Number.isSafeInteger(value) || value <= 0)) {
|
|
5865
|
+
throw new TypeError(`sidecar.${key} must be a positive finite integer`);
|
|
5866
|
+
}
|
|
5867
|
+
}
|
|
5868
|
+
if (config.maxReferenceSize > config.maxTotalSize || config.extractionThreshold > config.maxReferenceSize) {
|
|
5869
|
+
throw new TypeError("sidecar size limits must be ordered: threshold <= reference <= total");
|
|
5870
|
+
}
|
|
5871
|
+
}
|
|
5872
|
+
var PortableOperationPolicy = class {
|
|
5873
|
+
constructor(config) {
|
|
5874
|
+
this.config = config;
|
|
5875
|
+
}
|
|
5876
|
+
history = [];
|
|
5877
|
+
globalCallTimes = [];
|
|
5878
|
+
rate(now) {
|
|
5879
|
+
while (this.history.length && now - this.history[0].timestamp > 6e4) this.history.shift();
|
|
5880
|
+
while (this.globalCallTimes.length && now - this.globalCallTimes[0] > 2e3) this.globalCallTimes.shift();
|
|
5881
|
+
const recentTools = this.history.filter((entry) => now - entry.timestamp < 1e3).length;
|
|
5882
|
+
const recentGlobals = this.globalCallTimes.filter((at) => now - at < 1e3).length;
|
|
5883
|
+
if (recentTools + recentGlobals >= this.config.maxOperationsPerSecond) {
|
|
5884
|
+
throw new Error(`Operation rate limit exceeded (${this.config.maxOperationsPerSecond} operations/second)`);
|
|
5885
|
+
}
|
|
5886
|
+
}
|
|
5887
|
+
globalCall() {
|
|
5888
|
+
const now = Date.now();
|
|
5889
|
+
this.rate(now);
|
|
5890
|
+
this.globalCallTimes.push(now);
|
|
5891
|
+
}
|
|
5892
|
+
toolCall(name, args) {
|
|
5893
|
+
const now = Date.now();
|
|
5894
|
+
this.rate(now);
|
|
5895
|
+
if (typeof name !== "string" || name.length === 0) throw new TypeError("Operation name must be a non-empty string");
|
|
5896
|
+
if (this.config.validateOperationNames) {
|
|
5897
|
+
const allowed = this.config.allowedOperationPattern;
|
|
5898
|
+
if (allowed) {
|
|
5899
|
+
allowed.lastIndex = 0;
|
|
5900
|
+
if (!allowed.test(name)) throw new Error(`Operation "${name}" does not match allowed pattern`);
|
|
5901
|
+
}
|
|
5902
|
+
for (const blocked of this.config.blockedOperationPatterns ?? []) {
|
|
5903
|
+
blocked.lastIndex = 0;
|
|
5904
|
+
if (blocked.test(name)) throw new Error(`Operation "${name}" matches blocked pattern`);
|
|
5905
|
+
}
|
|
5906
|
+
}
|
|
5907
|
+
if (this.config.blockSuspiciousSequences) {
|
|
5908
|
+
const override = Object.hasOwn(this.config.rapidEnumerationOverrides, name) ? this.config.rapidEnumerationOverrides[name] : void 0;
|
|
5909
|
+
const threshold = override ?? this.config.rapidEnumerationThreshold;
|
|
5910
|
+
const recentSame = this.history.filter((entry) => entry.operationName === name && now - entry.timestamp < 5e3);
|
|
5911
|
+
if (recentSame.length >= threshold) {
|
|
5912
|
+
throw new Error("Suspicious pattern detected: Rapid enumeration of resources [RAPID_ENUMERATION]");
|
|
5913
|
+
}
|
|
5914
|
+
for (const pattern of DEFAULT_SUSPICIOUS_PATTERNS) {
|
|
5915
|
+
if (pattern.id === "RAPID_ENUMERATION") continue;
|
|
5916
|
+
let detected = false;
|
|
5917
|
+
try {
|
|
5918
|
+
detected = pattern.detect(name, args, this.history);
|
|
5919
|
+
} catch {
|
|
5920
|
+
}
|
|
5921
|
+
if (detected) throw new Error(`Suspicious pattern detected: ${pattern.description} [${pattern.id}]`);
|
|
5922
|
+
}
|
|
5923
|
+
}
|
|
5924
|
+
this.history.push({ operationName: name, timestamp: now, argKeys: Object.keys(args) });
|
|
5925
|
+
}
|
|
5926
|
+
};
|
|
5927
|
+
var PortableEnclave = class {
|
|
5928
|
+
options;
|
|
5929
|
+
config;
|
|
5930
|
+
preScanner;
|
|
5931
|
+
validator;
|
|
5932
|
+
adapter;
|
|
5933
|
+
namespaces;
|
|
5934
|
+
references;
|
|
5935
|
+
policyConfig;
|
|
5936
|
+
customNames;
|
|
5937
|
+
disposed = false;
|
|
5938
|
+
constructor(rawOptions = {}) {
|
|
5939
|
+
const { interpreter, ...rawEnclaveOptions } = rawOptions;
|
|
5940
|
+
const options = normalizeEnclaveOptions(rawEnclaveOptions);
|
|
5941
|
+
const level = options.securityLevel ?? "STANDARD";
|
|
5942
|
+
if (level === "PERMISSIVE") throw new TypeError("Portable AgentScript requires STANDARD, SECURE or STRICT");
|
|
5943
|
+
if (options.preset !== void 0 && options.preset !== "agentscript") {
|
|
5944
|
+
throw new TypeError("PortableEnclave supports the AgentScript preset only");
|
|
5945
|
+
}
|
|
5946
|
+
if (options.validate === false || options.transform === false) {
|
|
5947
|
+
throw new TypeError("PortableEnclave requires validation, transformation and pre-scan");
|
|
5948
|
+
}
|
|
5949
|
+
if (options.preScan?.preset !== void 0 && options.preScan.preset !== "agentscript") {
|
|
5950
|
+
throw new TypeError("PortableEnclave requires the AgentScript pre-scan preset");
|
|
5951
|
+
}
|
|
5952
|
+
if (options.preScan?.config !== void 0) {
|
|
5953
|
+
throw new TypeError("PortableEnclave does not allow pre-scan overrides");
|
|
5954
|
+
}
|
|
5955
|
+
if (options.toolBridge?.mode === "direct") throw new TypeError("PortableEnclave requires the string tool bridge");
|
|
5956
|
+
if (options.toolBridge?.acknowledgeInsecureDirect === true) {
|
|
5957
|
+
throw new TypeError("PortableEnclave does not support direct bridge acknowledgement");
|
|
5958
|
+
}
|
|
5959
|
+
if (options.adapter || options.sandboxAdapter || options.workerPoolConfig || options.scoringGate) {
|
|
5960
|
+
throw new TypeError("PortableEnclave does not support VM adapters or scoring gates");
|
|
5961
|
+
}
|
|
5962
|
+
if (options.allowBuiltins === true || options.toolCallGraceMs !== void 0) {
|
|
5963
|
+
throw new TypeError("PortableEnclave does not support VM builtin or tool grace overrides");
|
|
5964
|
+
}
|
|
5965
|
+
if (options.secureProxyConfig || options.realmGlobals === "security-level") {
|
|
5966
|
+
throw new TypeError("PortableEnclave does not support VM realm proxy overrides");
|
|
5967
|
+
}
|
|
5968
|
+
if (options.doubleVm?.enabled === false || options.doubleVm?.parentTimeoutBuffer !== void 0 || options.doubleVm?.parentValidation?.suspiciousPatterns?.length) {
|
|
5969
|
+
throw new TypeError("PortableEnclave cannot disable or replace its tool policy");
|
|
5970
|
+
}
|
|
5971
|
+
boundedInteger("interpreter.maxSteps", interpreter?.maxSteps, MAX_PORTABLE_STEPS);
|
|
5972
|
+
boundedInteger("interpreter.maxCallDepth", interpreter?.maxCallDepth, MAX_PORTABLE_CALL_DEPTH);
|
|
5973
|
+
boundedInteger("interpreter.maxPendingCalls", interpreter?.maxPendingCalls, MAX_PORTABLE_PENDING_CALLS);
|
|
5974
|
+
boundedInteger("interpreter.maxAllocationBytes", interpreter?.maxAllocationBytes, MAX_PORTABLE_ALLOCATION_BYTES);
|
|
5975
|
+
const memoryLimit = options.memoryLimit ?? 1024 * 1024;
|
|
5976
|
+
boundedInteger("memoryLimit", memoryLimit, MAX_PORTABLE_ALLOCATION_BYTES);
|
|
5977
|
+
const maxPayloadBytes = options.toolBridge?.maxPayloadBytes ?? DEFAULT_BRIDGE_BYTES;
|
|
5978
|
+
boundedInteger("toolBridge.maxPayloadBytes", maxPayloadBytes, MAX_PORTABLE_ALLOCATION_BYTES);
|
|
5979
|
+
const security = SECURITY_LEVEL_CONFIGS[level];
|
|
5980
|
+
const maxToolCalls = options.maxToolCalls ?? security.maxToolCalls;
|
|
5981
|
+
if (maxToolCalls > 1e5) throw new TypeError("maxToolCalls cannot exceed 100000 in PortableEnclave");
|
|
5982
|
+
if ((options.maxIterations ?? security.maxIterations) > MAX_PORTABLE_STEPS) {
|
|
5983
|
+
throw new TypeError(`maxIterations cannot exceed ${MAX_PORTABLE_STEPS} in PortableEnclave`);
|
|
5984
|
+
}
|
|
5985
|
+
if ((options.maxSanitizeDepth ?? security.maxSanitizeDepth) > 100) {
|
|
5986
|
+
throw new TypeError("maxSanitizeDepth cannot exceed 100 in PortableEnclave");
|
|
5987
|
+
}
|
|
5988
|
+
if ((options.maxSanitizeProperties ?? security.maxSanitizeProperties) > 2e4) {
|
|
5989
|
+
throw new TypeError("maxSanitizeProperties cannot exceed 20000 in PortableEnclave");
|
|
5990
|
+
}
|
|
5991
|
+
const maxGlobalFunctionCalls = options.maxGlobalFunctionCalls ?? Math.max(10, maxToolCalls * 10);
|
|
5992
|
+
boundedInteger("maxGlobalFunctionCalls", maxGlobalFunctionCalls, 1e6);
|
|
5993
|
+
options.globals = copyPortableGlobals(options.globals, options.allowFunctionsInGlobals === true, maxPayloadBytes);
|
|
5994
|
+
const standardNames = /* @__PURE__ */ new Set([...Object.keys(createSafeGlobals().globals), "callTool", "parallel", "console"]);
|
|
5995
|
+
for (const name of Object.keys(options.globals)) {
|
|
5996
|
+
if (standardNames.has(name)) throw new TypeError(`PortableEnclave cannot replace standard global ${name}`);
|
|
5997
|
+
}
|
|
5998
|
+
this.namespaces = normalizeToolNamespaces(options.toolNamespaces, {
|
|
5999
|
+
reservedNames: Object.keys(options.globals ?? {})
|
|
6000
|
+
});
|
|
6001
|
+
this.customNames = [...Object.keys(options.globals ?? {}), ...this.namespaces.map((entry) => entry.name)];
|
|
6002
|
+
const allowed = [
|
|
6003
|
+
...getAgentScriptGlobals(level),
|
|
6004
|
+
"parallel",
|
|
6005
|
+
"__safe_parallel",
|
|
6006
|
+
"__safe_concat",
|
|
6007
|
+
"__safe_template",
|
|
6008
|
+
...options.consoleHandler ? ["console", "__safe_console"] : [],
|
|
6009
|
+
...this.customNames.flatMap((name) => [name, `__safe_${name}`])
|
|
6010
|
+
];
|
|
6011
|
+
const hostObjects = [
|
|
6012
|
+
...Object.keys(options.globals ?? {}).filter((name) => typeof options.globals?.[name] !== "string"),
|
|
6013
|
+
...this.namespaces.map((entry) => entry.name)
|
|
6014
|
+
];
|
|
6015
|
+
this.preScanner = new PreScanner({
|
|
6016
|
+
preset: options.preScan?.preset ?? "agentscript",
|
|
6017
|
+
config: options.preScan?.config
|
|
6018
|
+
});
|
|
6019
|
+
this.validator = new JSAstValidator(
|
|
6020
|
+
createAgentScriptPreset({
|
|
6021
|
+
securityLevel: level,
|
|
6022
|
+
allowedGlobals: allowed,
|
|
6023
|
+
hostObjectGlobals: hostObjects,
|
|
6024
|
+
allowDynamicArrayFill: true
|
|
6025
|
+
})
|
|
6026
|
+
);
|
|
6027
|
+
this.references = referenceConfig(level, options.sidecar);
|
|
6028
|
+
validateReferenceConfig(this.references);
|
|
6029
|
+
this.policyConfig = {
|
|
6030
|
+
...DEFAULT_DOUBLE_VM_CONFIG.parentValidation,
|
|
6031
|
+
...options.doubleVm?.parentValidation,
|
|
6032
|
+
rapidEnumerationOverrides: { ...options.doubleVm?.parentValidation?.rapidEnumerationOverrides },
|
|
6033
|
+
blockedOperationPatterns: [...options.doubleVm?.parentValidation?.blockedOperationPatterns ?? []],
|
|
6034
|
+
suspiciousPatterns: []
|
|
6035
|
+
};
|
|
6036
|
+
this.config = {
|
|
6037
|
+
timeout: options.timeout ?? security.timeout,
|
|
6038
|
+
maxIterations: options.maxIterations ?? security.maxIterations,
|
|
6039
|
+
maxToolCalls,
|
|
6040
|
+
memoryLimit,
|
|
6041
|
+
maxSanitizeDepth: options.maxSanitizeDepth ?? security.maxSanitizeDepth,
|
|
6042
|
+
maxSanitizeProperties: options.maxSanitizeProperties ?? security.maxSanitizeProperties,
|
|
6043
|
+
maxConsoleCalls: options.maxConsoleCalls ?? security.maxConsoleCalls,
|
|
6044
|
+
maxConsoleOutputBytes: options.maxConsoleOutputBytes ?? security.maxConsoleOutputBytes,
|
|
6045
|
+
sanitizeStackTraces: options.sanitizeStackTraces ?? true,
|
|
6046
|
+
maxGlobalFunctionCalls,
|
|
6047
|
+
toolBridge: { mode: "string", maxPayloadBytes },
|
|
6048
|
+
globals: options.globals ?? {},
|
|
6049
|
+
toolHandler: options.toolHandler
|
|
6050
|
+
};
|
|
6051
|
+
this.adapter = new InterpreterAdapter({
|
|
6052
|
+
maxSteps: interpreter?.maxSteps,
|
|
6053
|
+
maxCallDepth: interpreter?.maxCallDepth,
|
|
6054
|
+
maxPendingCalls: interpreter?.maxPendingCalls,
|
|
6055
|
+
maxAllocationBytes: interpreter?.maxAllocationBytes
|
|
6056
|
+
});
|
|
6057
|
+
this.options = options;
|
|
6058
|
+
}
|
|
6059
|
+
async run(code, toolHandler, runOptions = {}) {
|
|
6060
|
+
if (this.disposed) throw new Error("PortableEnclave has been disposed");
|
|
6061
|
+
boundedInteger("maxToolResultBytes", runOptions.maxToolResultBytes, MAX_PORTABLE_ALLOCATION_BYTES);
|
|
6062
|
+
const startTime = Date.now();
|
|
6063
|
+
const stats = { duration: 0, startTime, endTime: startTime, toolCallCount: 0, iterationCount: 0 };
|
|
6064
|
+
const failure = (name, message, code2, issues) => ({
|
|
6065
|
+
success: false,
|
|
6066
|
+
error: { name, message, code: code2, ...issues ? { data: { issues } } : {} },
|
|
6067
|
+
stats: { ...stats, duration: Date.now() - startTime, endTime: Date.now() }
|
|
6068
|
+
});
|
|
6069
|
+
if (typeof code !== "string" || code.length > MAX_SCRIPT_LENGTH) {
|
|
6070
|
+
return failure("ValidationError", "The script must be a string of at most 5 MiB", "VALIDATION_ERROR");
|
|
6071
|
+
}
|
|
6072
|
+
if (code.length > 0) {
|
|
6073
|
+
const scanned = this.preScanner.scan(code);
|
|
6074
|
+
if (!scanned.success) {
|
|
6075
|
+
const issues = scanned.issues.map((issue) => ({
|
|
6076
|
+
code: issue.code,
|
|
6077
|
+
severity: issue.severity === "error" ? ValidationSeverity.ERROR : issue.severity === "warning" ? ValidationSeverity.WARNING : ValidationSeverity.INFO,
|
|
6078
|
+
message: issue.message,
|
|
6079
|
+
location: issue.line === void 0 ? void 0 : { line: issue.line, column: issue.column ?? 0 },
|
|
6080
|
+
data: issue.data
|
|
6081
|
+
}));
|
|
6082
|
+
return failure("ValidationError", "AgentScript pre-scan failed", "VALIDATION_ERROR", issues);
|
|
6083
|
+
}
|
|
6084
|
+
}
|
|
6085
|
+
let transformed;
|
|
6086
|
+
try {
|
|
6087
|
+
transformed = transformAgentScript(code, {
|
|
6088
|
+
wrapInMain: !isWrappedInMain(code),
|
|
6089
|
+
transformCallTool: true,
|
|
6090
|
+
transformLoops: true,
|
|
6091
|
+
maxIterations: this.config.maxIterations,
|
|
6092
|
+
additionalIdentifiers: this.customNames
|
|
6093
|
+
});
|
|
6094
|
+
} catch (error) {
|
|
6095
|
+
const message = error?.message;
|
|
6096
|
+
return failure(
|
|
6097
|
+
"ValidationError",
|
|
6098
|
+
typeof message === "string" ? message.slice(0, 2048) : "AgentScript parse failed",
|
|
6099
|
+
"VALIDATION_ERROR"
|
|
6100
|
+
);
|
|
6101
|
+
}
|
|
6102
|
+
const validation = await this.validator.validate(transformed, { preScan: { enabled: false } });
|
|
6103
|
+
if (!validation.valid) {
|
|
6104
|
+
return failure("ValidationError", "AgentScript validation failed", "VALIDATION_ERROR", validation.issues);
|
|
6105
|
+
}
|
|
6106
|
+
if (refuseDynamicImport(transformed)) {
|
|
6107
|
+
return failure("SecurityError", "Dynamic imports are unavailable", "SECURITY_VIOLATION");
|
|
6108
|
+
}
|
|
6109
|
+
const sidecar = this.references ? new ReferenceSidecar(this.references) : void 0;
|
|
6110
|
+
try {
|
|
6111
|
+
if (sidecar && this.references) {
|
|
6112
|
+
const ast = acorn3.parse(transformed, { ecmaVersion: "latest", sourceType: "script" });
|
|
6113
|
+
extractLargeStrings(ast, {
|
|
6114
|
+
threshold: this.references.extractionThreshold,
|
|
6115
|
+
onExtract: (value) => sidecar.store(value, "extraction")
|
|
6116
|
+
});
|
|
6117
|
+
transformConcatenation(ast, { arraySpread: false });
|
|
6118
|
+
transformTemplateLiterals(ast);
|
|
6119
|
+
transformed = generate(ast);
|
|
6120
|
+
}
|
|
6121
|
+
const policy = new PortableOperationPolicy(this.policyConfig);
|
|
6122
|
+
let closed = false;
|
|
6123
|
+
const deadline = Date.now() + this.config.timeout;
|
|
6124
|
+
const abortController = new AbortController();
|
|
6125
|
+
const context = {
|
|
6126
|
+
config: this.config,
|
|
6127
|
+
stats,
|
|
6128
|
+
abortController,
|
|
6129
|
+
get aborted() {
|
|
6130
|
+
return closed || abortController.signal.aborted || Date.now() >= deadline;
|
|
6131
|
+
},
|
|
6132
|
+
set aborted(value) {
|
|
6133
|
+
if (value) abortController.abort();
|
|
6134
|
+
},
|
|
6135
|
+
toolHandler: toolHandler ?? this.options.toolHandler,
|
|
6136
|
+
toolNamespaces: this.namespaces,
|
|
6137
|
+
beforeToolCall: (name, args) => {
|
|
6138
|
+
policy.toolCall(name, args);
|
|
6139
|
+
return true;
|
|
6140
|
+
},
|
|
6141
|
+
beforeGlobalCall: () => {
|
|
6142
|
+
policy.globalCall();
|
|
6143
|
+
return true;
|
|
6144
|
+
},
|
|
6145
|
+
maxToolResultBytes: runOptions.maxToolResultBytes,
|
|
6146
|
+
onToolBridgeFailure: runOptions.onToolBridgeFailure,
|
|
6147
|
+
sidecar,
|
|
6148
|
+
referenceConfig: this.references,
|
|
6149
|
+
consoleHandler: this.options.consoleHandler
|
|
6150
|
+
};
|
|
6151
|
+
try {
|
|
6152
|
+
return await this.adapter.execute(transformed, context);
|
|
6153
|
+
} finally {
|
|
6154
|
+
closed = true;
|
|
6155
|
+
abortController.abort();
|
|
6156
|
+
}
|
|
6157
|
+
} catch (error) {
|
|
6158
|
+
const message = error?.message;
|
|
6159
|
+
return failure(
|
|
6160
|
+
"ExecutionError",
|
|
6161
|
+
typeof message === "string" ? message.slice(0, 2048) : "Portable execution failed",
|
|
6162
|
+
"EXECUTION_ERROR"
|
|
6163
|
+
);
|
|
6164
|
+
} finally {
|
|
6165
|
+
sidecar?.dispose();
|
|
6166
|
+
}
|
|
6167
|
+
}
|
|
6168
|
+
dispose() {
|
|
6169
|
+
this.disposed = true;
|
|
6170
|
+
this.adapter.dispose();
|
|
6171
|
+
}
|
|
6172
|
+
};
|
|
6173
|
+
var AgentScriptRunner = class extends PortableEnclave {
|
|
6174
|
+
static capabilities = Object.freeze([
|
|
6175
|
+
"validated-agentscript",
|
|
6176
|
+
"host-functions",
|
|
6177
|
+
"tool-namespaces",
|
|
6178
|
+
"sidecar",
|
|
6179
|
+
"console",
|
|
6180
|
+
"rapid-enumeration"
|
|
6181
|
+
]);
|
|
6182
|
+
constructor(options) {
|
|
6183
|
+
const {
|
|
6184
|
+
hostFunctions,
|
|
6185
|
+
maxHostFunctionCalls,
|
|
6186
|
+
maxSteps,
|
|
6187
|
+
maxCallDepth,
|
|
6188
|
+
maxPendingCalls,
|
|
6189
|
+
rapidEnumeration,
|
|
6190
|
+
...enclaveOptions
|
|
6191
|
+
} = options;
|
|
6192
|
+
super({
|
|
6193
|
+
...enclaveOptions,
|
|
6194
|
+
allowFunctionsInGlobals: true,
|
|
6195
|
+
globals: { ...hostFunctions },
|
|
6196
|
+
maxGlobalFunctionCalls: maxHostFunctionCalls,
|
|
6197
|
+
doubleVm: {
|
|
6198
|
+
parentValidation: {
|
|
6199
|
+
...rapidEnumeration?.threshold !== void 0 && { rapidEnumerationThreshold: rapidEnumeration.threshold },
|
|
6200
|
+
...rapidEnumeration?.overrides !== void 0 && { rapidEnumerationOverrides: rapidEnumeration.overrides }
|
|
6201
|
+
}
|
|
6202
|
+
},
|
|
6203
|
+
interpreter: { maxSteps, maxCallDepth, maxPendingCalls }
|
|
6204
|
+
});
|
|
6205
|
+
}
|
|
6206
|
+
};
|
|
3627
6207
|
export {
|
|
6208
|
+
AgentScriptRunner,
|
|
3628
6209
|
Interpreter,
|
|
3629
6210
|
InterpreterAdapter,
|
|
3630
6211
|
InterpreterError,
|
|
6212
|
+
PortableEnclave,
|
|
3631
6213
|
StepLimitError
|
|
3632
6214
|
};
|