poe-code 14.0.80 → 14.0.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/index.js +876 -404
  2. package/dist/index.js.map +4 -4
  3. package/dist/metafile.json +1 -1
  4. package/package.json +1 -1
  5. package/packages/safe-js/dist/chunks/{chunk-34G5WW2O.js → chunk-7LGBDF56.js} +2 -2
  6. package/packages/safe-js/dist/chunks/{chunk-M4L3EZHL.js → chunk-V6LQP64H.js} +733 -334
  7. package/packages/safe-js/dist/chunks/chunk-V6LQP64H.js.map +7 -0
  8. package/packages/safe-js/dist/cli.js +2 -2
  9. package/packages/safe-js/dist/core.js +1 -1
  10. package/packages/safe-js/dist/index.js +2 -2
  11. package/packages/safe-js/dist/interp/async.d.ts +1 -1
  12. package/packages/safe-js/dist/interp/async.js +65 -43
  13. package/packages/safe-js/dist/interp/bound-function-state.d.ts +7 -0
  14. package/packages/safe-js/dist/interp/bound-function-state.js +1 -0
  15. package/packages/safe-js/dist/interp/bound-function.d.ts +4 -0
  16. package/packages/safe-js/dist/interp/bound-function.js +18 -0
  17. package/packages/safe-js/dist/interp/error-prototypes.d.ts +3 -0
  18. package/packages/safe-js/dist/interp/error-prototypes.js +1 -0
  19. package/packages/safe-js/dist/interp/exceptions.d.ts +1 -0
  20. package/packages/safe-js/dist/interp/exceptions.js +39 -15
  21. package/packages/safe-js/dist/interp/generator-prototypes.d.ts +6 -0
  22. package/packages/safe-js/dist/interp/generator-prototypes.js +1 -0
  23. package/packages/safe-js/dist/interp/globals/error.d.ts +2 -0
  24. package/packages/safe-js/dist/interp/globals/error.js +104 -4
  25. package/packages/safe-js/dist/interp/globals/function.d.ts +1 -1
  26. package/packages/safe-js/dist/interp/globals/function.js +10 -2
  27. package/packages/safe-js/dist/interp/globals/generator.d.ts +2 -0
  28. package/packages/safe-js/dist/interp/globals/generator.js +51 -0
  29. package/packages/safe-js/dist/interp/globals/object-array.js +19 -1
  30. package/packages/safe-js/dist/interp/globals.d.ts +2 -0
  31. package/packages/safe-js/dist/interp/globals.js +7 -3
  32. package/packages/safe-js/dist/interp/host-bridge.js +4 -2
  33. package/packages/safe-js/dist/interp/instanceof.d.ts +4 -0
  34. package/packages/safe-js/dist/interp/instanceof.js +59 -0
  35. package/packages/safe-js/dist/interp/interpreter.js +3 -40
  36. package/packages/safe-js/dist/interp/iteration.js +44 -6
  37. package/packages/safe-js/dist/interp/methods/function.d.ts +1 -1
  38. package/packages/safe-js/dist/interp/methods/function.js +53 -40
  39. package/packages/safe-js/dist/interp/methods/generator.d.ts +4 -1
  40. package/packages/safe-js/dist/interp/methods/generator.js +12 -6
  41. package/packages/safe-js/dist/interp/object-model.js +13 -0
  42. package/packages/safe-js/dist/interp/values.js +47 -2
  43. package/packages/safe-js/dist/snapshot/guest-heap-validation.js +28 -3
  44. package/packages/safe-js/dist/snapshot/guest-heap.d.ts +10 -0
  45. package/packages/safe-js/dist/snapshot/guest-heap.js +13 -2
  46. package/packages/safe-js/dist/snapshot/restore.js +69 -8
  47. package/packages/safe-js/dist/snapshot/validation.js +1 -1
  48. package/packages/safe-js/dist/chunks/chunk-M4L3EZHL.js.map +0 -7
  49. /package/packages/safe-js/dist/chunks/{chunk-34G5WW2O.js.map → chunk-7LGBDF56.js.map} +0 -0
@@ -22,7 +22,7 @@ import {
22
22
  resolveFsConfig,
23
23
  splitFrontmatter,
24
24
  withBrokenPipeGuard
25
- } from "./chunks/chunk-34G5WW2O.js";
25
+ } from "./chunks/chunk-7LGBDF56.js";
26
26
  import {
27
27
  Budget,
28
28
  SandboxError,
@@ -34,7 +34,7 @@ import {
34
34
  replaceErrorStack,
35
35
  restore,
36
36
  run
37
- } from "./chunks/chunk-M4L3EZHL.js";
37
+ } from "./chunks/chunk-V6LQP64H.js";
38
38
  import "./chunks/chunk-M2DLCGEF.js";
39
39
  import "./chunks/chunk-Q7USUEL7.js";
40
40
  import "./chunks/chunk-4YIDX44G.js";
@@ -5,7 +5,7 @@ import {
5
5
  defineExtension,
6
6
  lint,
7
7
  run
8
- } from "./chunks/chunk-M4L3EZHL.js";
8
+ } from "./chunks/chunk-V6LQP64H.js";
9
9
  import "./chunks/chunk-4YIDX44G.js";
10
10
  export {
11
11
  Budget,
@@ -26,7 +26,7 @@ import {
26
26
  runWithSpawnUsageAccumulator,
27
27
  splitFrontmatter,
28
28
  supportsSpawnMode
29
- } from "./chunks/chunk-34G5WW2O.js";
29
+ } from "./chunks/chunk-7LGBDF56.js";
30
30
  import {
31
31
  Budget,
32
32
  FileSnapshotBackend,
@@ -50,7 +50,7 @@ import {
50
50
  registerPendingHostCallPolicy,
51
51
  restore,
52
52
  run
53
- } from "./chunks/chunk-M4L3EZHL.js";
53
+ } from "./chunks/chunk-V6LQP64H.js";
54
54
  import "./chunks/chunk-M2DLCGEF.js";
55
55
  import "./chunks/chunk-Q7USUEL7.js";
56
56
  import "./chunks/chunk-4YIDX44G.js";
@@ -70,7 +70,7 @@ export type EvaluateAsyncNode = (node: ParseResult, context: AsyncEvaluationCont
70
70
  export declare function emitResumeBreakpoint(context: AsyncEvaluationContext, breakpoint: ResumeBreakpoint): void;
71
71
  export declare function evaluateArrowFunctionExpression(node: ArrowFunctionExpression, context: AsyncEvaluationContext, evaluateNode: EvaluateAsyncNode): Promise<AsyncEvaluationResult>;
72
72
  export declare function evaluateFunctionExpression(node: FunctionExpression, context: AsyncEvaluationContext, evaluateNode: EvaluateAsyncNode): Promise<AsyncEvaluationResult>;
73
- export declare function createInterpretedClosure(node: ArrowFunctionExpression | FunctionDeclaration | FunctionExpression, context: AsyncEvaluationContext, evaluateNode: EvaluateAsyncNode, homeObject?: SandboxObject | SandboxClosure): SandboxClosure;
73
+ export declare function createInterpretedClosure(node: ArrowFunctionExpression | FunctionDeclaration | FunctionExpression, context: AsyncEvaluationContext, evaluateNode: EvaluateAsyncNode, homeObject?: SandboxObject | SandboxClosure, initializeGeneratorPrototype?: boolean): SandboxClosure;
74
74
  export declare function executeAsyncFunction(execute: (onSuspend: () => void) => Promise<SandboxValue>, budget: Budget, signal?: AbortSignal, callContext?: SandboxCallContext): import("./values.js").SandboxPromise;
75
75
  export declare function evaluateAwaitExpression(node: AwaitExpression, context: AsyncEvaluationContext, evaluateNode: EvaluateAsyncNode): Promise<AsyncEvaluationResult>;
76
76
  export declare function executeClosure(node: ArrowFunctionExpression | FunctionDeclaration | FunctionExpression, args: readonly SandboxValue[], thisValue: SandboxValue, context: AsyncEvaluationContext, evaluateNode: EvaluateAsyncNode): Promise<SandboxValue>;
@@ -7,7 +7,9 @@ import { CompileScope } from "./regex/compile-guard.js";
7
7
  import { awaitSandboxValue } from "./cancel.js";
8
8
  import { hoistVarDeclarations } from "./var-hoist.js";
9
9
  import { createCoercionContext, createPatternContext } from "./interpreter.js";
10
- import { getGuestFunctionProperty, setSandboxPrototype } from "./object-model.js";
10
+ import { getGuestFunctionProperty, markDescriptorObject, materializeFunctionProperties, setSandboxPrototype } from "./object-model.js";
11
+ import { generatorPrototypes } from "./generator-prototypes.js";
12
+ import { retainValues, runResources } from "./resources.js";
11
13
  import { functionSources } from "../parse/function-source.js";
12
14
  import { registerClosureOrigin, registerGeneratorOrigin } from "./closure-origin.js";
13
15
  import { boundIdentifiers, containsParameterExpression, getFunctionLength, hoistedVarDeclarations } from "../parse/bindings.js";
@@ -42,12 +44,12 @@ export async function evaluateFunctionExpression(node, context, evaluateNode) {
42
44
  value: closure
43
45
  };
44
46
  }
45
- export function createInterpretedClosure(node, context, evaluateNode, homeObject) {
47
+ export function createInterpretedClosure(node, context, evaluateNode, homeObject, initializeGeneratorPrototype = true) {
46
48
  if (node.type !== "ArrowFunctionExpression") {
47
49
  context = { ...context, functionEnvironment: { homeObject } };
48
50
  }
49
51
  if (node.type !== "ArrowFunctionExpression" && node.generator) {
50
- return createGeneratorClosure(node, context, evaluateNode);
52
+ return createGeneratorClosure(node, context, evaluateNode, initializeGeneratorPrototype);
51
53
  }
52
54
  const construct = node.type !== "ArrowFunctionExpression" &&
53
55
  !(node.type === "FunctionExpression" && node.method === true) &&
@@ -123,7 +125,9 @@ export function executeAsyncFunction(execute, budget, signal, callContext) {
123
125
  });
124
126
  return createSandboxPromise(promise, { synchronousPrefix });
125
127
  }
126
- function createGeneratorClosure(node, context, evaluateNode) {
128
+ function createGeneratorClosure(node, context, evaluateNode, initializePrototype) {
129
+ const prototypes = !initializePrototype || runResources.getStore()?.functionSourceText === false ? undefined
130
+ : generatorPrototypes.get(context.budget)?.get(node.async === true);
127
131
  const closure = createSandboxClosure({
128
132
  sourceRange: functionSources.get(node),
129
133
  guest: true,
@@ -133,48 +137,66 @@ function createGeneratorClosure(node, context, evaluateNode) {
133
137
  ...(node.id === undefined ? { name: context.inferredName } : { name: node.id.name }),
134
138
  retainedValues: () => [...context.scope.retainedValues(), context.functionEnvironment?.homeObject, context.functionEnvironment?.newTarget],
135
139
  call: async (args, callContext) => {
136
- const closureContext = {
137
- ...context,
138
- compilation: callContext?.compilation ?? context.compilation,
139
- callStack: [...(callContext?.stack ?? context.callStack)]
140
- };
141
- const scope = await createClosureScope(node, args, callContext?.thisValue, closureContext, evaluateNode);
142
- const channel = createGeneratorChannel((generatorYield) => {
143
- const execute = async () => {
144
- const result = await evaluateNode(node.body, {
145
- ...closureContext,
146
- functionBody: node.body,
147
- asyncGenerator: node.async,
148
- generatorBlockScopes: new Map(),
149
- generatorExpressionStates: new Map(),
150
- captureGeneratorScope: (suspendedScope, blocks, completions, expressions) => {
151
- origin.suspendedScope = suspendedScope;
152
- origin.blockScopes = blocks;
153
- origin.finallyCompletions = completions;
154
- origin.expressionStates = expressions;
155
- },
156
- generatorYield: (value, yieldNodeId) => {
157
- generator.state = "suspended";
158
- return generatorYield(value, yieldNodeId);
159
- },
160
- scope
161
- });
162
- if (result.kind === "error") {
163
- throw result.error;
164
- }
165
- if (result.kind === "throw") {
166
- throw result.value;
167
- }
168
- const value = result.hasValue ? result.value : undefined;
169
- return node.async ? awaitSandboxValue(value, context.signal, context.budget, createCoercionContext(context)) : value;
140
+ // Native generators select their instance prototype before initializing parameters.
141
+ const candidate = prototypes === undefined ? undefined : getGuestFunctionProperty(closure, "prototype");
142
+ const prototype = typeof candidate === "object" && candidate !== null ? candidate : prototypes?.instancePrototype;
143
+ const releasePrototype = prototype === undefined ? undefined : retainValues(context.budget, () => [prototype]);
144
+ try {
145
+ const closureContext = {
146
+ ...context,
147
+ compilation: callContext?.compilation ?? context.compilation,
148
+ callStack: [...(callContext?.stack ?? context.callStack)]
170
149
  };
171
- return node.async ? runAsyncPrefix(execute) : execute();
172
- });
173
- const generator = createSandboxGenerator(channel, { async: node.async });
174
- const origin = registerGeneratorOrigin(generator, node, scope, closureContext);
175
- return generator;
150
+ const scope = await createClosureScope(node, args, callContext?.thisValue, closureContext, evaluateNode);
151
+ const channel = createGeneratorChannel((generatorYield) => {
152
+ const execute = async () => {
153
+ const result = await evaluateNode(node.body, {
154
+ ...closureContext,
155
+ functionBody: node.body,
156
+ asyncGenerator: node.async,
157
+ generatorBlockScopes: new Map(),
158
+ generatorExpressionStates: new Map(),
159
+ captureGeneratorScope: (suspendedScope, blocks, completions, expressions) => {
160
+ origin.suspendedScope = suspendedScope;
161
+ origin.blockScopes = blocks;
162
+ origin.finallyCompletions = completions;
163
+ origin.expressionStates = expressions;
164
+ },
165
+ generatorYield: (value, yieldNodeId) => {
166
+ generator.state = "suspended";
167
+ return generatorYield(value, yieldNodeId);
168
+ },
169
+ scope
170
+ });
171
+ if (result.kind === "error") {
172
+ throw result.error;
173
+ }
174
+ if (result.kind === "throw") {
175
+ throw result.value;
176
+ }
177
+ const value = result.hasValue ? result.value : undefined;
178
+ return node.async ? awaitSandboxValue(value, context.signal, context.budget, createCoercionContext(context)) : value;
179
+ };
180
+ return node.async ? runAsyncPrefix(execute) : execute();
181
+ });
182
+ const generator = createSandboxGenerator(channel, { async: node.async });
183
+ if (prototype !== undefined)
184
+ setSandboxPrototype(generator, prototype, context.budget);
185
+ const origin = registerGeneratorOrigin(generator, node, scope, closureContext);
186
+ return generator;
187
+ }
188
+ finally {
189
+ releasePrototype?.();
190
+ }
176
191
  }
177
192
  });
193
+ if (prototypes !== undefined) {
194
+ const prototype = Object.create(null);
195
+ markDescriptorObject(prototype);
196
+ setSandboxPrototype(prototype, prototypes.instancePrototype);
197
+ Object.defineProperty(materializeFunctionProperties(closure), "prototype", { value: prototype, writable: true });
198
+ setSandboxPrototype(closure, prototypes.functionPrototype);
199
+ }
178
200
  registerClosureOrigin(closure, node, context);
179
201
  return closure;
180
202
  }
@@ -0,0 +1,7 @@
1
+ import type { SandboxClosure, SandboxValue } from "./values.js";
2
+ export type BoundFunctionState = {
3
+ target: SandboxClosure;
4
+ thisValue: SandboxValue;
5
+ args: SandboxValue[];
6
+ };
7
+ export declare const boundFunctionStates: WeakMap<object, BoundFunctionState>;
@@ -0,0 +1 @@
1
+ export const boundFunctionStates = new WeakMap();
@@ -0,0 +1,4 @@
1
+ import { type SandboxClosure } from "./values.js";
2
+ import { type BoundFunctionState } from "./bound-function-state.js";
3
+ import type { FunctionMethodOptions } from "./methods/function.js";
4
+ export declare function createBoundFunction(state: BoundFunctionState, name: string | undefined, length: number | undefined, callClosure: FunctionMethodOptions["callClosure"]): SandboxClosure;
@@ -0,0 +1,18 @@
1
+ import { createSandboxClosure } from "./values.js";
2
+ import { boundFunctionStates } from "./bound-function-state.js";
3
+ export function createBoundFunction(state, name, length, callClosure) {
4
+ const bound = createSandboxClosure({
5
+ guest: true,
6
+ sandbox: true,
7
+ name,
8
+ length,
9
+ boundTarget: state.target,
10
+ retainedValues: () => [state.target, state.thisValue, ...state.args, bound.name],
11
+ call: (args, context) => callClosure(state.target, [...state.args, ...args], context?.stack ?? [], state.thisValue),
12
+ ...(state.target.construct === undefined ? {} : {
13
+ construct: (args, context) => callClosure(state.target, [...state.args, ...args], context?.stack ?? [], undefined, true, context?.newTarget === bound ? state.target : context?.newTarget)
14
+ })
15
+ });
16
+ boundFunctionStates.set(bound, state);
17
+ return bound;
18
+ }
@@ -0,0 +1,3 @@
1
+ import type { Budget } from "./budget.js";
2
+ import type { SandboxObject } from "./values.js";
3
+ export declare const errorPrototypes: WeakMap<Budget, Map<"Error" | "TypeError" | "RangeError" | "ReferenceError" | "SyntaxError" | "URIError" | "EvalError" | "AbortError" | "AggregateError" | "HarnessFailure", SandboxObject>>;
@@ -0,0 +1 @@
1
+ export const errorPrototypes = new WeakMap();
@@ -55,5 +55,6 @@ export declare function createSubsetErrorValue(name: string, message: SandboxVal
55
55
  cause?: unknown;
56
56
  chargeBudget?: boolean;
57
57
  span?: ErrorSourceSpan;
58
+ transport?: boolean;
58
59
  }): SandboxObject;
59
60
  export declare function isSandboxErrorConstructorInstance(value: SandboxValue, name: SandboxErrorName): boolean;
@@ -5,7 +5,8 @@ import { withFatalPromiseCleanup } from "./promise-tracker.js";
5
5
  import { deepCopyToSandbox, ownEnumerableSandboxKeys } from "./values.js";
6
6
  import { hasOwnSandboxProperty } from "./globals/object.js";
7
7
  import { retainValues } from "./resources.js";
8
- import { getSandboxDataProperty } from "./object-model.js";
8
+ import { getSandboxDataProperty, setSandboxPrototype } from "./object-model.js";
9
+ import { errorPrototypes } from "./error-prototypes.js";
9
10
  import { toPropertyKey } from "./property-key.js";
10
11
  import { internalSymbols } from "./internal-symbols.js";
11
12
  import { containsResumeTarget } from "./resume-target.js";
@@ -162,8 +163,7 @@ export function surfaceThrownValue(reason, budget, stackFrames = [], span) {
162
163
  throw reason;
163
164
  }
164
165
  if (isSubsetErrorValue(reason)) {
165
- normalizeSurfacedSubsetError(reason, budget, stackFrames, span);
166
- return reason;
166
+ return normalizeSurfacedSubsetError(reason, budget, stackFrames, span);
167
167
  }
168
168
  if (reason instanceof Error) {
169
169
  const error = createSubsetErrorValue(reason.name || "Error", reason.message, stackFrames, budget, {
@@ -171,8 +171,7 @@ export function surfaceThrownValue(reason, budget, stackFrames = [], span) {
171
171
  chargeBudget: false,
172
172
  span
173
173
  });
174
- normalizeSurfacedSubsetError(error, budget, stackFrames, span);
175
- return error;
174
+ return normalizeSurfacedSubsetError(error, budget, stackFrames, span);
176
175
  }
177
176
  if (isErrorLikeValue(reason)) {
178
177
  const error = createSubsetErrorValue(reason.name || "Error", reason.message, stackFrames, budget, {
@@ -180,13 +179,13 @@ export function surfaceThrownValue(reason, budget, stackFrames = [], span) {
180
179
  chargeBudget: false,
181
180
  span
182
181
  });
183
- normalizeSurfacedSubsetError(error, budget, stackFrames, span);
184
- return error;
182
+ return normalizeSurfacedSubsetError(error, budget, stackFrames, span);
185
183
  }
186
- return createSubsetErrorValue("Error", describeThrownValue(reason), stackFrames, budget, {
184
+ const error = createSubsetErrorValue("Error", describeThrownValue(reason), stackFrames, budget, {
187
185
  chargeBudget: false,
188
186
  span
189
187
  });
188
+ return normalizeSurfacedSubsetError(error, budget, stackFrames, span);
190
189
  }
191
190
  export function createSubsetErrorValue(name, message, stackFrames, budget, options = {}) {
192
191
  const resumeChecks = options.chargeBudget === false ? budget.suspendChecks() : undefined;
@@ -195,11 +194,16 @@ export function createSubsetErrorValue(name, message, stackFrames, budget, optio
195
194
  const errorMessage = budget.allocateString(coerceErrorMessage(message));
196
195
  const header = errorMessage === "" ? errorName : `${errorName}: ${errorMessage}`;
197
196
  const stack = budget.allocateString([header, ...[...stackFrames].reverse()].join("\n"));
198
- const error = {
199
- name: errorName,
200
- message: errorMessage,
201
- stack
202
- };
197
+ const prototype = options.transport ? undefined : errorPrototypes.get(budget)?.get(toSandboxErrorName(errorName));
198
+ const error = prototype === undefined ? { name: errorName, message: errorMessage, stack } : {};
199
+ if (prototype !== undefined) {
200
+ if (message !== undefined)
201
+ Object.defineProperty(error, "message", { value: errorMessage, writable: true, configurable: true });
202
+ if (!errorPrototypes.get(budget).has(errorName))
203
+ Object.defineProperty(error, "name", { value: errorName, writable: true, configurable: true });
204
+ Object.defineProperty(error, "stack", { value: stack, writable: true, configurable: true });
205
+ setSandboxPrototype(error, prototype, budget);
206
+ }
203
207
  sandboxErrorTypes.set(error, toSandboxErrorName(errorName));
204
208
  attachErrorSpan(error, options.span);
205
209
  attachWrappedErrorCause(error, options.cause);
@@ -224,6 +228,8 @@ function isSubsetErrorValue(value) {
224
228
  if (typeof value !== "object" || value === null) {
225
229
  return false;
226
230
  }
231
+ if (sandboxErrorTypes.has(value))
232
+ return true;
227
233
  const prototype = Object.getPrototypeOf(value);
228
234
  return ((prototype === Object.prototype || prototype === null) &&
229
235
  typeof value.name === "string" &&
@@ -236,20 +242,38 @@ function normalizeSurfacedSubsetError(error, budget, stackFrames, span) {
236
242
  const name = budget.allocateString(toSandboxErrorName(readErrorName(error)));
237
243
  const message = budget.allocateString(readSurfacedErrorMessage(error, name));
238
244
  const frames = readSandboxStackFrames(error.stack);
245
+ if (!Object.isExtensible(error) || ["name", "message", "stack"].some(key => {
246
+ const descriptor = Object.getOwnPropertyDescriptor(error, key);
247
+ return descriptor !== undefined && (!("value" in descriptor) || !descriptor.writable);
248
+ })) {
249
+ // Public diagnostics must not mutate frozen guest state or invoke setters.
250
+ const original = error;
251
+ const descriptors = Object.getOwnPropertyDescriptors(original);
252
+ delete descriptors.name;
253
+ delete descriptors.message;
254
+ delete descriptors.stack;
255
+ error = Object.defineProperties({}, descriptors);
256
+ const errorType = sandboxErrorTypes.get(original);
257
+ if (errorType !== undefined)
258
+ sandboxErrorTypes.set(error, errorType);
259
+ }
239
260
  error.name = name;
240
261
  error.message = message;
241
262
  error.stack = budget.allocateString(formatErrorStack(name, message, frames.length > 0 ? frames : [...stackFrames].reverse()));
242
263
  attachErrorSpan(error, readErrorSpan(error) ?? span);
264
+ return error;
243
265
  }
244
266
  finally {
245
267
  resumeChecks();
246
268
  }
247
269
  }
248
270
  function readErrorName(error) {
249
- return typeof error.name === "string" && error.name.length > 0 ? error.name : "Error";
271
+ const name = getSandboxDataProperty(error, "name");
272
+ return typeof name === "string" && name.length > 0 ? name : sandboxErrorTypes.get(error) ?? "Error";
250
273
  }
251
274
  function readSurfacedErrorMessage(error, name) {
252
- const message = typeof error.message === "string" ? error.message : "";
275
+ const value = getSandboxDataProperty(error, "message");
276
+ const message = typeof value === "string" ? value : "";
253
277
  if (message === "") {
254
278
  return `${name} thrown`;
255
279
  }
@@ -0,0 +1,6 @@
1
+ import type { Budget } from "./budget.js";
2
+ import type { SandboxObject } from "./values.js";
3
+ export declare const generatorPrototypes: WeakMap<Budget, Map<boolean, {
4
+ functionPrototype: SandboxObject;
5
+ instancePrototype: SandboxObject;
6
+ }>>;
@@ -0,0 +1 @@
1
+ export const generatorPrototypes = new WeakMap();
@@ -5,7 +5,9 @@ export type ErrorName = (typeof errorNames)[number];
5
5
  export type ErrorGlobals = Record<ErrorName, ReturnType<typeof createSandboxClosure>>;
6
6
  export declare function createErrorGlobals(options: {
7
7
  budget: Budget;
8
+ errorPrototypes?: boolean;
8
9
  }): ErrorGlobals;
9
10
  export declare function isSandboxErrorConstructorInstance(value: SandboxValue, constructor: SandboxValue): boolean;
10
11
  export declare function isSandboxErrorConstructor(value: SandboxValue): value is SandboxClosure;
12
+ export declare function createErrorPrototypes(budget: Budget, constructors: ErrorGlobals): void;
11
13
  export {};
@@ -1,3 +1,10 @@
1
+ import { errorPrototypes } from "../error-prototypes.js";
2
+ import { getSandboxPropertyDescriptor, getSandboxPrototype, materializeFunctionProperties, registerIntrinsicFunction, registerIntrinsicObject, setSandboxPrototype } from "../object-model.js";
3
+ import { registerBuiltinIdentities } from "../intrinsics.js";
4
+ import { sandboxString } from "../string-coercion.js";
5
+ import { retainValues } from "../resources.js";
6
+ import { readPropertyDescriptor } from "../accessors.js";
7
+ import { acquireSandboxIterator, getSandboxIterator, readIteratorResult } from "../iteration.js";
1
8
  import { createSubsetErrorValue, isSandboxErrorConstructorInstance as isNamedSandboxErrorConstructorInstance } from "../exceptions.js";
2
9
  import { createSandboxClosure, isSandboxClosure } from "../values.js";
3
10
  const errorConstructorNames = new WeakMap();
@@ -12,7 +19,7 @@ const errorNames = [
12
19
  "AggregateError"
13
20
  ];
14
21
  export function createErrorGlobals(options) {
15
- return Object.fromEntries(errorNames.map((name) => [name, createErrorConstructor(name, options.budget)]));
22
+ return Object.fromEntries(errorNames.map((name) => [name, createErrorConstructor(name, options.budget, options.errorPrototypes === true)]));
16
23
  }
17
24
  export function isSandboxErrorConstructorInstance(value, constructor) {
18
25
  if (!isSandboxClosure(constructor)) {
@@ -27,12 +34,105 @@ export function isSandboxErrorConstructorInstance(value, constructor) {
27
34
  export function isSandboxErrorConstructor(value) {
28
35
  return isSandboxClosure(value) && errorConstructorNames.has(value);
29
36
  }
30
- function createErrorConstructor(name, budget) {
31
- const call = (args, context) => createSubsetError(name, args, context?.stack ?? [], budget);
32
- const closure = createSandboxClosure({ sandbox: true, call, construct: call, name });
37
+ function createErrorConstructor(name, budget, guest) {
38
+ const call = (args, context) => errorPrototypes.has(budget) ? createNativeError(name, args, budget, context, closure)
39
+ : createSubsetError(name, args, context?.stack ?? [], budget);
40
+ const closure = createSandboxClosure({ guest, sandbox: true, call, construct: call, name, length: name === "AggregateError" ? 2 : 1 });
33
41
  errorConstructorNames.set(closure, name);
34
42
  return closure;
35
43
  }
44
+ export function createErrorPrototypes(budget, constructors) {
45
+ const prototypes = new Map();
46
+ for (const name of errorNames)
47
+ prototypes.set(name, Object.create(null));
48
+ errorPrototypes.set(budget, prototypes);
49
+ for (const name of errorNames) {
50
+ const constructor = constructors[name];
51
+ const prototype = prototypes.get(name);
52
+ Object.defineProperties(prototype, {
53
+ name: { value: name, writable: true, configurable: true },
54
+ message: { value: "", writable: true, configurable: true },
55
+ constructor: { value: constructor, writable: true, configurable: true }
56
+ });
57
+ Object.defineProperty(materializeFunctionProperties(constructor), "prototype", { value: prototype, writable: false });
58
+ setSandboxPrototype(prototype, name === "Error" ? getSandboxPrototype(Object.create(null), budget) : prototypes.get("Error"));
59
+ if (name !== "Error")
60
+ setSandboxPrototype(constructor, constructors.Error);
61
+ }
62
+ Object.defineProperty(prototypes.get("Error"), "toString", {
63
+ writable: true, configurable: true,
64
+ value: createSandboxClosure({ guest: true, sandbox: true, name: "toString", length: 0,
65
+ call: async (_args, context) => {
66
+ const receiver = context?.thisValue;
67
+ if (receiver === null || typeof receiver !== "object")
68
+ throw new TypeError("Error.prototype.toString requires an object.");
69
+ let name;
70
+ const release = retainValues(budget, () => [receiver, name]);
71
+ try {
72
+ const rawName = await readErrorProperty(receiver, "name", budget, context);
73
+ name = rawName === undefined ? "Error" : await sandboxString(rawName, budget, context);
74
+ const rawMessage = await readErrorProperty(receiver, "message", budget, context);
75
+ const message = rawMessage === undefined ? "" : await sandboxString(rawMessage, budget, context);
76
+ return budget.allocateString(name === "" ? message : message === "" ? name : `${name}: ${message}`);
77
+ }
78
+ finally {
79
+ release();
80
+ }
81
+ }
82
+ })
83
+ });
84
+ registerBuiltinIdentities(budget, Object.fromEntries(errorNames.map(name => [name, constructors[name]])));
85
+ for (const name of errorNames) {
86
+ registerIntrinsicFunction(budget, constructors[name]);
87
+ registerIntrinsicObject(budget, prototypes.get(name));
88
+ }
89
+ }
90
+ async function readErrorProperty(value, key, budget, context) {
91
+ if (context?.getProperty !== undefined)
92
+ return context.getProperty(value, key);
93
+ const descriptor = getSandboxPropertyDescriptor(value, key, budget);
94
+ return descriptor === undefined ? undefined : readPropertyDescriptor(descriptor, value, context);
95
+ }
96
+ async function createNativeError(name, args, budget, context, constructor) {
97
+ const newTarget = context?.newTarget ?? constructor;
98
+ const candidate = await readErrorProperty(newTarget, "prototype", budget, context);
99
+ const prototype = candidate !== null && typeof candidate === "object" ? candidate : errorPrototypes.get(budget).get(name);
100
+ let error;
101
+ let iterator;
102
+ const errors = [];
103
+ const release = retainValues(budget, () => [prototype, error, iterator?.retainedValue, ...errors, ...args]);
104
+ try {
105
+ const message = name === "AggregateError" ? args[1] : args[0];
106
+ const options = name === "AggregateError" ? args[2] : args[1];
107
+ const text = message === undefined ? undefined : await sandboxString(message, budget, context);
108
+ error = createSubsetErrorValue(name, text, context?.stack ?? [], budget);
109
+ setSandboxPrototype(error, prototype, budget);
110
+ if (options !== null && typeof options === "object" && getSandboxPropertyDescriptor(options, "cause", budget) !== undefined) {
111
+ const cause = await readErrorProperty(options, "cause", budget, context);
112
+ Object.defineProperty(error, "cause", { value: cause, writable: true, configurable: true });
113
+ }
114
+ if (name === "AggregateError") {
115
+ iterator = context === undefined ? getSandboxIterator(args[0], budget) : await acquireSandboxIterator(args[0], budget, context);
116
+ if (iterator === undefined)
117
+ throw new TypeError("AggregateError errors must be iterable.");
118
+ while (true) {
119
+ budget.visitNode();
120
+ const result = await iterator.next();
121
+ if (result === null || typeof result !== "object")
122
+ throw new TypeError("Iterator result must be an object.");
123
+ if ((await readIteratorResult(iterator, result, "done")).value)
124
+ break;
125
+ budget.allocateArrayLength(errors.length + 1);
126
+ errors.push((await readIteratorResult(iterator, result, "value")).value);
127
+ }
128
+ Object.defineProperty(error, "errors", { value: errors, writable: true, configurable: true });
129
+ }
130
+ return error;
131
+ }
132
+ finally {
133
+ release();
134
+ }
135
+ }
36
136
  function createSubsetError(name, args, stackFrames, budget) {
37
137
  const message = name === "AggregateError" ? args[1] : args[0];
38
138
  const options = name === "AggregateError" ? args[2] : args[1];
@@ -1,2 +1,2 @@
1
1
  import type { Budget } from "../budget.js";
2
- export declare function createFunctionPrototype(budget: Budget): void;
2
+ export declare function createFunctionPrototype(budget: Budget, installHasInstance?: boolean): void;
@@ -1,8 +1,9 @@
1
1
  import { invokeBuiltinClosure } from "../builtin-call.js";
2
2
  import { callFunctionMethod } from "../methods/function.js";
3
- import { getSandboxPrototype, installFunctionPrototype, materializeFunctionProperties, setSandboxPrototype } from "../object-model.js";
3
+ import { getSandboxPrototype, installFunctionPrototype, materializeFunctionProperties, registerIntrinsicFunction, setSandboxPrototype } from "../object-model.js";
4
4
  import { createSandboxClosure } from "../values.js";
5
- export function createFunctionPrototype(budget) {
5
+ import { ordinaryHasInstance } from "../instanceof.js";
6
+ export function createFunctionPrototype(budget, installHasInstance = true) {
6
7
  const prototype = createSandboxClosure({ guest: true, sandbox: true, name: "", length: 0, call: () => undefined });
7
8
  const properties = materializeFunctionProperties(prototype);
8
9
  // Invocation support does not grant the host's dynamic source constructor.
@@ -19,6 +20,13 @@ export function createFunctionPrototype(budget) {
19
20
  })
20
21
  });
21
22
  }
23
+ const hasInstance = installHasInstance ? createSandboxClosure({ guest: true, sandbox: true, name: "[Symbol.hasInstance]", length: 1,
24
+ call: ([value], context) => ordinaryHasInstance(value, context?.thisValue, budget, context)
25
+ }) : undefined;
26
+ if (hasInstance !== undefined)
27
+ Object.defineProperty(properties, Symbol.hasInstance, { value: hasInstance });
22
28
  setSandboxPrototype(prototype, getSandboxPrototype(Object.create(null), budget));
23
29
  installFunctionPrototype(budget, prototype);
30
+ if (hasInstance !== undefined)
31
+ registerIntrinsicFunction(budget, hasInstance);
24
32
  }
@@ -0,0 +1,2 @@
1
+ import type { Budget } from "../budget.js";
2
+ export declare function createGeneratorPrototypes(budget: Budget): void;
@@ -0,0 +1,51 @@
1
+ import { generatorPrototypes } from "../generator-prototypes.js";
2
+ import { registerBuiltinIdentities, resolveIntrinsicIdentity } from "../intrinsics.js";
3
+ import { callGeneratorMethod } from "../methods/generator.js";
4
+ import { getSandboxPrototype, registerIntrinsicFunction, registerIntrinsicObject, setSandboxPrototype } from "../object-model.js";
5
+ import { createSandboxClosure } from "../values.js";
6
+ export function createGeneratorPrototypes(budget) {
7
+ const asyncIteratorPrototype = Object.create(null);
8
+ const asyncIterator = createSandboxClosure({ guest: true, sandbox: true,
9
+ name: "[Symbol.asyncIterator]", length: 0, call: (_args, context) => context?.thisValue });
10
+ Object.defineProperty(asyncIteratorPrototype, Symbol.asyncIterator, {
11
+ value: asyncIterator, writable: true, configurable: true
12
+ });
13
+ setSandboxPrototype(asyncIteratorPrototype, getSandboxPrototype(Object.create(null), budget));
14
+ registerBuiltinIdentities(budget, { "%AsyncIteratorPrototype%": asyncIteratorPrototype });
15
+ registerIntrinsicObject(budget, asyncIteratorPrototype);
16
+ registerIntrinsicFunction(budget, asyncIterator);
17
+ const state = new Map();
18
+ for (const async of [false, true]) {
19
+ const tag = async ? "AsyncGenerator" : "Generator";
20
+ const functionPrototype = Object.create(null);
21
+ const instancePrototype = Object.create(null);
22
+ setSandboxPrototype(functionPrototype, resolveIntrinsicIdentity(budget, JSON.stringify(["%FunctionPrototype%"])));
23
+ setSandboxPrototype(instancePrototype, async ? asyncIteratorPrototype
24
+ : resolveIntrinsicIdentity(budget, JSON.stringify(["%IteratorPrototype%"])));
25
+ Object.defineProperties(functionPrototype, {
26
+ prototype: { value: instancePrototype, configurable: true },
27
+ // Do not expose native dynamic-source constructors through this graph.
28
+ constructor: { value: undefined, configurable: true },
29
+ [Symbol.toStringTag]: { value: `${tag}Function`, configurable: true }
30
+ });
31
+ Object.defineProperties(instancePrototype, {
32
+ constructor: { value: functionPrototype, configurable: true },
33
+ [Symbol.toStringTag]: { value: tag, configurable: true }
34
+ });
35
+ for (const method of ["next", "return", "throw"]) {
36
+ Object.defineProperty(instancePrototype, method, { writable: true, configurable: true,
37
+ value: createSandboxClosure({ guest: true, sandbox: true, name: method, length: 1,
38
+ call: ([value], context) => callGeneratorMethod(context?.thisValue, method, value, budget, context, async)
39
+ })
40
+ });
41
+ }
42
+ registerBuiltinIdentities(budget, {
43
+ [`%${tag}Prototype%`]: instancePrototype,
44
+ [`%${tag}FunctionPrototype%`]: functionPrototype
45
+ });
46
+ registerIntrinsicObject(budget, functionPrototype);
47
+ registerIntrinsicObject(budget, instancePrototype);
48
+ state.set(async, { functionPrototype, instancePrototype });
49
+ }
50
+ generatorPrototypes.set(budget, state);
51
+ }