poe-code 4.0.72 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -136874,7 +136874,7 @@ function getEnumerableDataEntries(value) {
136874
136874
  function getEnumerableDataValues(value) {
136875
136875
  return getEnumerableDataEntries(value).map(([, entry]) => entry);
136876
136876
  }
136877
- var DUMP_FORMAT_VERSION, SKIP_VALUE;
136877
+ var DUMP_FORMAT_VERSION, EXECUTION_SEMANTICS, SKIP_VALUE;
136878
136878
  var init_dump_format = __esm({
136879
136879
  "packages/safejs/src/snapshot/dump-format.ts"() {
136880
136880
  "use strict";
@@ -136882,6 +136882,7 @@ var init_dump_format = __esm({
136882
136882
  init_arguments();
136883
136883
  init_arguments2();
136884
136884
  DUMP_FORMAT_VERSION = 1;
136885
+ EXECUTION_SEMANTICS = "jobs-v1";
136885
136886
  SKIP_VALUE = /* @__PURE__ */ Symbol("SafeJS.skip-dump-value");
136886
136887
  }
136887
136888
  });
@@ -137683,11 +137684,17 @@ function createSandboxPromise(promise, metadata = {}) {
137683
137684
  enumerable: false,
137684
137685
  value: true
137685
137686
  });
137687
+ Object.defineProperty(sandboxPromise, Symbol.toStringTag, { value: "Promise" });
137686
137688
  if (metadata.span !== void 0) {
137687
137689
  Object.defineProperty(sandboxPromise, "span", {
137688
137690
  value: metadata.span
137689
137691
  });
137690
137692
  }
137693
+ if (metadata.synchronousPrefix !== void 0) {
137694
+ Object.defineProperty(sandboxPromise, "synchronousPrefix", {
137695
+ value: metadata.synchronousPrefix
137696
+ });
137697
+ }
137691
137698
  if (metadata.hostCall !== void 0) {
137692
137699
  Object.defineProperty(sandboxPromise, "hostCall", { value: metadata.hostCall });
137693
137700
  }
@@ -138430,6 +138437,13 @@ var init_running_state = __esm({
138430
138437
  function restore2(snapshot2, options) {
138431
138438
  assertSnapshotInactive(snapshot2);
138432
138439
  validateDumpEnvelope(snapshot2);
138440
+ if (snapshot2.executionSemantics !== EXECUTION_SEMANTICS && (snapshot2.executionSemantics !== void 0 || snapshot2.promiseReplay !== void 0 || snapshot2.replay !== void 0 || snapshot2.initialInputs !== void 0)) {
138441
+ throw new SnapshotValidationError(
138442
+ "unsupportedVersion",
138443
+ "$.executionSemantics",
138444
+ "incompatible execution semantics; resume with the SafeJS version that created this snapshot. Migration requires explicit reconciliation, not changing its version marker."
138445
+ );
138446
+ }
138433
138447
  const currentSourceHash = hashSource(options.source);
138434
138448
  if (snapshot2.sourceHash !== currentSourceHash) {
138435
138449
  throw new SnapshotMismatchError(snapshot2.sourceHash, currentSourceHash);
@@ -138443,6 +138457,7 @@ var init_restore = __esm({
138443
138457
  init_hash();
138444
138458
  init_shape();
138445
138459
  init_validation();
138460
+ init_dump_format();
138446
138461
  init_running_state();
138447
138462
  SnapshotMismatchError = class extends Error {
138448
138463
  actualHash;
@@ -138460,149 +138475,6 @@ var init_restore = __esm({
138460
138475
  }
138461
138476
  });
138462
138477
 
138463
- // packages/safejs/src/interp/cancel.ts
138464
- function wrapCancelableBindings(bindings, signal) {
138465
- if (signal === void 0) {
138466
- return bindings;
138467
- }
138468
- return wrapCancelableValue(bindings, signal, /* @__PURE__ */ new WeakMap());
138469
- }
138470
- function wrapCancelableValue(value, signal, seen) {
138471
- if (typeof value !== "object" || value === null) {
138472
- return value;
138473
- }
138474
- const existing = seen.get(value);
138475
- if (existing !== void 0) {
138476
- return existing;
138477
- }
138478
- if (isSandboxClosure(value)) {
138479
- const wrapped2 = createSandboxClosure({
138480
- ...value.async === true ? { async: true } : {},
138481
- call: (args, context) => {
138482
- if (signal.aborted) {
138483
- if (value.async === true) {
138484
- return createRejectedSandboxPromise(readAbortReason(signal));
138485
- }
138486
- throw readAbortReason(signal);
138487
- }
138488
- return wrapCancelableResult(value.call(args, context), signal, seen);
138489
- },
138490
- name: value.name
138491
- });
138492
- seen.set(value, wrapped2);
138493
- return wrapped2;
138494
- }
138495
- if (isSandboxPromise(value)) {
138496
- observeSandboxPromise(value);
138497
- const wrapped2 = createSandboxPromise(wrapCancelablePromise(value.promise, signal, seen), {
138498
- trackReplay: false,
138499
- ...value.hostCall === void 0 ? {} : { hostCall: value.hostCall },
138500
- ...value.hostCallJournal === void 0 ? {} : { hostCallJournal: value.hostCallJournal },
138501
- ...value.span === void 0 ? {} : { span: value.span }
138502
- });
138503
- seen.set(value, wrapped2);
138504
- return wrapped2;
138505
- }
138506
- if (Array.isArray(value)) {
138507
- const wrapped2 = new Array(value.length);
138508
- seen.set(value, wrapped2);
138509
- for (let index = 0; index < value.length; index += 1) {
138510
- wrapped2[index] = wrapCancelableValue(value[index], signal, seen);
138511
- }
138512
- return wrapped2;
138513
- }
138514
- const wrapped = Object.create(Object.getPrototypeOf(value));
138515
- seen.set(value, wrapped);
138516
- for (const [key3, entry] of Object.entries(value)) {
138517
- wrapped[key3] = wrapCancelableValue(entry, signal, seen);
138518
- }
138519
- return wrapped;
138520
- }
138521
- function wrapCancelableResult(result, signal, seen) {
138522
- if (!isPromiseLike3(result)) {
138523
- return wrapCancelableValue(result, signal, seen);
138524
- }
138525
- return wrapCancelablePromise(result, signal, seen);
138526
- }
138527
- function wrapCancelablePromise(promise, signal, seen) {
138528
- if (signal.aborted) {
138529
- return Promise.reject(readAbortReason(signal));
138530
- }
138531
- return new Promise((resolve17, reject) => {
138532
- let listenerActive = true;
138533
- let settled = false;
138534
- const onAbort = () => {
138535
- cleanup();
138536
- queueMicrotask(() => {
138537
- settle(() => reject(readAbortReason(signal)));
138538
- });
138539
- };
138540
- const cleanup = () => {
138541
- if (!listenerActive) {
138542
- return;
138543
- }
138544
- listenerActive = false;
138545
- signal.removeEventListener("abort", onAbort);
138546
- };
138547
- const settle = (complete) => {
138548
- if (settled) {
138549
- return;
138550
- }
138551
- settled = true;
138552
- cleanup();
138553
- complete();
138554
- };
138555
- signal.addEventListener("abort", onAbort, { once: true });
138556
- Promise.resolve(promise).then(
138557
- (value) => {
138558
- settle(() => resolve17(wrapCancelableValue(value, signal, seen)));
138559
- },
138560
- (reason) => {
138561
- settle(() => reject(wrapCancelableUnknown(reason, signal, seen)));
138562
- }
138563
- );
138564
- });
138565
- }
138566
- function wrapCancelableUnknown(value, signal, seen) {
138567
- if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
138568
- return value;
138569
- }
138570
- if (isSandboxClosure(value) || isSandboxPromise(value) || Array.isArray(value) || typeof value === "object" && value !== null) {
138571
- return wrapCancelableValue(value, signal, seen);
138572
- }
138573
- return value;
138574
- }
138575
- function readAbortReason(signal) {
138576
- return signal.reason ?? createAbortError11();
138577
- }
138578
- function createAbortError11() {
138579
- if (typeof DOMException === "function") {
138580
- const error4 = new DOMException("This operation was aborted", "AbortError");
138581
- replaceErrorStack(error4);
138582
- return error4;
138583
- }
138584
- const error3 = new Error("This operation was aborted");
138585
- error3.name = "AbortError";
138586
- replaceErrorStack(error3);
138587
- return error3;
138588
- }
138589
- function createRejectedSandboxPromise(reason) {
138590
- const promise = Promise.reject(reason);
138591
- promise.catch(() => void 0);
138592
- return createSandboxPromise(promise);
138593
- }
138594
- function isPromiseLike3(value) {
138595
- return typeof value === "object" && value !== null && "then" in value;
138596
- }
138597
- var init_cancel2 = __esm({
138598
- "packages/safejs/src/interp/cancel.ts"() {
138599
- "use strict";
138600
- init_values();
138601
- init_promise_tracker();
138602
- init_shape();
138603
- }
138604
- });
138605
-
138606
138478
  // packages/safejs/src/snapshot/replay-data.ts
138607
138479
  function encodeReplayData(value, options = {}) {
138608
138480
  const nodes = [];
@@ -139431,1548 +139303,1806 @@ var init_host_call = __esm({
139431
139303
  }
139432
139304
  });
139433
139305
 
139434
- // packages/safejs/src/interp/generator.ts
139435
- function createGeneratorChannel(body) {
139436
- let state = "unstarted";
139437
- let signal = deferred();
139438
- let resume;
139439
- const start = deferred();
139440
- const sent = [];
139441
- let yieldNodeId;
139442
- const bodyPromise = start.promise.then(() => body(yieldValue));
139443
- void bodyPromise.then(
139444
- (value) => {
139445
- if (state === "done") {
139446
- return;
139447
- }
139448
- state = "done";
139449
- signal.resolve({ type: "complete", value });
139450
- },
139451
- (error3) => {
139452
- if (state === "done") {
139453
- return;
139454
- }
139455
- state = "done";
139456
- signal.resolve({ type: "error", error: error3 });
139457
- }
139458
- );
139459
- void bodyPromise.catch(() => void 0);
139460
- async function yieldValue(value, nodeId) {
139461
- resume = deferred();
139462
- yieldNodeId = nodeId;
139463
- state = "suspended";
139464
- signal.resolve({ type: "yield", value });
139465
- return resume.promise;
139466
- }
139467
- async function deliver(completion) {
139468
- const leaveRunning = enterRunningState(channelIdentity);
139469
- try {
139470
- if (state === "done") {
139471
- if (completion.type === "return") {
139472
- return { value: completion.value, done: true };
139473
- }
139474
- if (completion.type === "throw") {
139475
- throw completion.value;
139476
- }
139477
- return { value: void 0, done: true };
139478
- }
139479
- if (state === "unstarted") {
139480
- if (completion.type === "return") {
139481
- state = "done";
139482
- return { value: completion.value, done: true };
139483
- }
139484
- if (completion.type === "throw") {
139485
- state = "done";
139486
- throw completion.value;
139487
- }
139488
- state = "running";
139489
- sent.push(completion);
139490
- start.resolve();
139491
- } else {
139492
- state = "running";
139493
- sent.push(completion);
139494
- signal = deferred();
139495
- const pendingResume = resume;
139496
- resume = void 0;
139497
- pendingResume?.resolve(completion);
139498
- }
139499
- const settled = await signal.promise;
139500
- if (settled.type === "yield") {
139501
- return { value: settled.value, done: false };
139502
- }
139503
- if (settled.type === "error") {
139504
- throw settled.error;
139505
- }
139506
- return { value: settled.value, done: true };
139507
- } finally {
139508
- leaveRunning();
139509
- }
139306
+ // packages/safejs/src/interp/exceptions.ts
139307
+ async function evaluateThrowStatement(node, context, evaluateNode3) {
139308
+ const argument = await evaluateNode3(node.argument, context);
139309
+ if (argument.kind !== "normal") {
139310
+ return argument;
139510
139311
  }
139511
- const channelIdentity = {};
139512
139312
  return {
139513
- next: (value) => deliver({ type: "normal", value }),
139514
- return: (value) => deliver({ type: "return", value }),
139515
- throw: (error3) => deliver({ type: "throw", value: error3 }),
139516
- snapshot: () => ({
139517
- ...yieldNodeId === void 0 ? {} : { yieldNodeId },
139518
- sent: sent.map((completion) => ({ ...completion }))
139519
- })
139313
+ kind: "throw",
139314
+ hasValue: true,
139315
+ span: node.span,
139316
+ stackFrames: context.callStack,
139317
+ value: argument.value
139520
139318
  };
139521
139319
  }
139522
- function deferred() {
139523
- let resolve17;
139524
- let reject;
139525
- const promise = new Promise((innerResolve, innerReject) => {
139526
- resolve17 = innerResolve;
139527
- reject = innerReject;
139528
- });
139529
- return { promise, reject, resolve: resolve17 };
139530
- }
139531
- var init_generator = __esm({
139532
- "packages/safejs/src/interp/generator.ts"() {
139533
- "use strict";
139534
- init_running_state();
139535
- }
139536
- });
139537
-
139538
- // packages/safejs/src/interp/patterns.ts
139539
- async function bindPattern(pattern, value, target, scope, context) {
139540
- switch (pattern.type) {
139541
- case "Identifier":
139542
- bindIdentifier(pattern, value, target, scope);
139543
- return { ok: true };
139544
- case "MemberExpression":
139545
- if ("kind" in target) {
139546
- throw new TypeError("Destructuring declarations cannot bind to member expressions.");
139547
- }
139548
- return bindMemberExpression(pattern, value, scope, context);
139549
- case "AssignmentPattern":
139550
- return bindAssignmentPattern(pattern, value, target, scope, context);
139551
- case "ArrayPattern":
139552
- return bindArrayPattern(pattern, value, target, scope, context);
139553
- case "ObjectPattern":
139554
- return bindObjectPattern(pattern, value, target, scope, context);
139555
- case "RestElement":
139556
- return bindPattern(pattern.argument, value, target, scope, context);
139557
- }
139558
- }
139559
- function bindIdentifier(pattern, value, target, scope) {
139560
- if ("assign" in target || target.kind === "var") {
139561
- if ("assign" in target) {
139562
- const binding = scope.lookup(pattern.name);
139563
- if (!binding.found) {
139564
- throw new ReferenceError(`Cannot assign to undeclared binding '${pattern.name}'.`);
139565
- }
139566
- if (binding.kind === "const") {
139567
- throw new TypeError(`Cannot assign to const '${pattern.name}'`);
139568
- }
139320
+ async function evaluateTryStatement(node, context, evaluateNode3) {
139321
+ let fatalBudgetError;
139322
+ let tryResult;
139323
+ try {
139324
+ tryResult = await evaluateBlockCompletion(node.block, context, evaluateNode3);
139325
+ } catch (error3) {
139326
+ if (!isBudgetExceeded(error3) || node.finalizer === void 0) {
139327
+ throw error3;
139569
139328
  }
139570
- scope.assign(pattern.name, value);
139571
- return;
139572
- }
139573
- scope.declare(pattern.name, target.kind, value);
139574
- }
139575
- async function bindAssignmentPattern(pattern, value, target, scope, context) {
139576
- if (value !== void 0) {
139577
- return bindPattern(pattern.left, value, target, scope, context);
139578
- }
139579
- const defaultValue = await context.evaluate(pattern.right);
139580
- if (defaultValue.kind !== "normal") {
139581
- return { ok: false, result: defaultValue };
139329
+ fatalBudgetError = error3;
139330
+ tryResult = {
139331
+ kind: "throw",
139332
+ hasValue: true,
139333
+ value: void 0
139334
+ };
139582
139335
  }
139583
- return bindPattern(pattern.left, defaultValue.value, target, scope, context);
139584
- }
139585
- async function bindArrayPattern(pattern, value, target, scope, context) {
139586
- const values = getArrayPatternValues(value);
139587
- for (let index = 0; index < pattern.elements.length; index += 1) {
139588
- const element = pattern.elements[index];
139589
- if (element === null) {
139590
- continue;
139591
- }
139592
- const elementValue = element.type === "RestElement" ? values.slice(index) : values[index];
139593
- const binding = await bindPattern(element, elementValue, target, scope, context);
139594
- if (!binding.ok) {
139595
- return binding;
139596
- }
139336
+ const tryOrCatchResult = fatalBudgetError === void 0 && tryResult.kind === "throw" && node.handler !== void 0 ? await evaluateCatchClause(node.handler, tryResult.value, context, evaluateNode3) : tryResult;
139337
+ if (node.finalizer === void 0 || tryOrCatchResult.kind === "error") {
139338
+ return tryOrCatchResult;
139597
139339
  }
139598
- return { ok: true };
139599
- }
139600
- async function bindObjectPattern(pattern, value, target, scope, context) {
139601
- if (typeof value !== "object" || value === null) {
139602
- throw new TypeError("Object destructuring declarations require a non-null object value.");
139340
+ const finalizerResult = fatalBudgetError?.budget === "deadline" ? await evaluateWithoutDeadlineChecks(
139341
+ context,
139342
+ () => evaluateBlockCompletion(node.finalizer, context, evaluateNode3)
139343
+ ) : await evaluateBlockCompletion(node.finalizer, context, evaluateNode3);
139344
+ if (fatalBudgetError !== void 0) {
139345
+ throw fatalBudgetError;
139603
139346
  }
139604
- const excludedKeys = /* @__PURE__ */ new Set();
139605
- for (const property of pattern.properties) {
139606
- if (property.type === "RestElement") {
139607
- const binding2 = await bindPattern(
139608
- property,
139609
- copyObjectRestValue(value, excludedKeys),
139610
- target,
139611
- scope,
139612
- context
139613
- );
139614
- if (!binding2.ok) {
139615
- return binding2;
139616
- }
139617
- continue;
139618
- }
139619
- const key3 = await evaluatePatternKey(property, context);
139620
- if (!key3.ok) {
139621
- return key3;
139622
- }
139623
- excludedKeys.add(String(key3.value));
139624
- const binding = await bindPattern(
139625
- property.value,
139626
- value[key3.value],
139627
- target,
139628
- scope,
139629
- context
139630
- );
139631
- if (!binding.ok) {
139632
- return binding;
139633
- }
139347
+ if (finalizerResult.kind === "normal") {
139348
+ return tryOrCatchResult;
139634
139349
  }
139635
- return { ok: true };
139350
+ return finalizerResult;
139636
139351
  }
139637
- async function bindMemberExpression(pattern, value, scope, context) {
139638
- const object = await context.evaluate(pattern.object);
139639
- if (object.kind !== "normal") {
139640
- return { ok: false, result: object };
139641
- }
139642
- if (object.value === null || object.value === void 0) {
139643
- throw new TypeError("Cannot assign properties of null or undefined.");
139644
- }
139645
- if (!isIndexableValue(object.value)) {
139646
- throw new TypeError("Assignment expressions require a sandbox object property.");
139647
- }
139648
- const property = pattern.computed ? await evaluateProperty(pattern.property, context) : { ok: true, value: getStaticPropertyName(pattern.property) };
139649
- if (!property.ok) {
139650
- return property;
139651
- }
139652
- setProperty(object.value, property.value, value);
139653
- return { ok: true };
139352
+ function createCapturedException(reason, stackFrames) {
139353
+ return {
139354
+ reason,
139355
+ stackFrames,
139356
+ [capturedExceptionBrand]: true
139357
+ };
139654
139358
  }
139655
- async function evaluatePatternKey(property, context) {
139656
- return property.computed ? evaluateProperty(property.key, context) : { ok: true, value: getStaticPropertyName(property.key) };
139359
+ function isCapturedException(value) {
139360
+ return typeof value === "object" && value !== null && capturedExceptionBrand in value;
139657
139361
  }
139658
- async function evaluateProperty(property, context) {
139659
- const result = await context.evaluate(property);
139660
- if (result.kind !== "normal") {
139661
- return { ok: false, result };
139662
- }
139663
- if (typeof result.value !== "string" && typeof result.value !== "number") {
139664
- throw new TypeError("Computed property access requires a string or number key.");
139362
+ function coerceThrownValue(reason, budget, stackFrames, span) {
139363
+ if (isSubsetErrorValue(reason)) {
139364
+ attachErrorSpan(reason, readErrorSpan(reason) ?? span);
139365
+ return reason;
139665
139366
  }
139666
- return { ok: true, value: result.value };
139667
- }
139668
- function getStaticPropertyName(property) {
139669
- if (property.type === "Identifier") {
139670
- return property.name;
139367
+ if (reason instanceof Error) {
139368
+ return createSubsetErrorValue(reason.name || "Error", reason.message, stackFrames, budget, {
139369
+ chargeBudget: false,
139370
+ cause: readErrorCause(reason),
139371
+ span
139372
+ });
139671
139373
  }
139672
- if (property.type === "StringLiteral" || property.type === "NumericLiteral") {
139673
- return property.value;
139374
+ if (isErrorLikeValue(reason)) {
139375
+ return createSubsetErrorValue(reason.name || "Error", reason.message, stackFrames, budget, {
139376
+ chargeBudget: false,
139377
+ cause: readErrorCause(reason),
139378
+ span
139379
+ });
139674
139380
  }
139675
- throw new TypeError(`Unsupported static property node '${property.type}'.`);
139381
+ return deepCopyToSandbox(reason);
139676
139382
  }
139677
- function getArrayPatternValues(value) {
139678
- if (Array.isArray(value)) {
139679
- return value;
139680
- }
139681
- if (typeof value === "string") {
139682
- return Array.from(value);
139383
+ function surfaceThrownValue(reason, budget, stackFrames = [], span) {
139384
+ if (reason instanceof HostCallResumabilityError) {
139385
+ throw reason;
139683
139386
  }
139684
- if (isSandboxMap(value)) {
139685
- return Array.from(value.entries, ([key3, entry]) => [key3, entry]);
139387
+ if (isSubsetErrorValue(reason)) {
139388
+ normalizeSurfacedSubsetError(reason, budget, stackFrames, span);
139389
+ return reason;
139686
139390
  }
139687
- if (isSandboxSet(value)) {
139688
- return [...value.values];
139391
+ if (reason instanceof Error) {
139392
+ const error3 = createSubsetErrorValue(
139393
+ reason.name || "Error",
139394
+ reason.message,
139395
+ stackFrames,
139396
+ budget,
139397
+ {
139398
+ cause: reason,
139399
+ chargeBudget: false,
139400
+ span
139401
+ }
139402
+ );
139403
+ normalizeSurfacedSubsetError(error3, budget, stackFrames, span);
139404
+ return error3;
139689
139405
  }
139690
- if (isIterableValue(value)) {
139691
- throw new TypeError(
139692
- `Array destructuring declarations support only arrays and strings; received ${describeRuntimeValue(value)}.`
139406
+ if (isErrorLikeValue(reason)) {
139407
+ const error3 = createSubsetErrorValue(
139408
+ reason.name || "Error",
139409
+ reason.message,
139410
+ stackFrames,
139411
+ budget,
139412
+ {
139413
+ cause: readErrorCause(reason),
139414
+ chargeBudget: false,
139415
+ span
139416
+ }
139693
139417
  );
139418
+ normalizeSurfacedSubsetError(error3, budget, stackFrames, span);
139419
+ return error3;
139694
139420
  }
139695
- throw new TypeError("Array destructuring declarations require an array or string iterable.");
139696
- }
139697
- function isIterableValue(value) {
139698
- return typeof value === "object" && value !== null && Symbol.iterator in value && typeof value[Symbol.iterator] === "function";
139699
- }
139700
- function describeRuntimeValue(value) {
139701
- if (value === null) return "null";
139702
- if (value === void 0) return "undefined";
139703
- if (typeof value === "object") return value.constructor?.name ?? "Object";
139704
- return typeof value;
139421
+ return createSubsetErrorValue("Error", describeThrownValue(reason), stackFrames, budget, {
139422
+ chargeBudget: false,
139423
+ span
139424
+ });
139705
139425
  }
139706
- function copyObjectRestValue(value, excludedKeys) {
139707
- const rest = /* @__PURE__ */ Object.create(null);
139708
- for (const [key3, entryValue] of Object.entries(value)) {
139709
- if (!excludedKeys.has(key3)) {
139710
- defineProperty(rest, key3, entryValue);
139711
- }
139426
+ function createSubsetErrorValue(name, message2, stackFrames, budget, options = {}) {
139427
+ const resumeChecks = options.chargeBudget === false ? budget.suspendChecks() : void 0;
139428
+ try {
139429
+ const errorName = budget.allocateString(name === "" ? "Error" : name);
139430
+ const errorMessage9 = budget.allocateString(coerceErrorMessage(message2));
139431
+ const header = errorMessage9 === "" ? errorName : `${errorName}: ${errorMessage9}`;
139432
+ const stack = budget.allocateString([header, ...[...stackFrames].reverse()].join("\n"));
139433
+ const error3 = {
139434
+ name: errorName,
139435
+ message: errorMessage9,
139436
+ stack
139437
+ };
139438
+ defineSandboxErrorMetadata(error3, errorName);
139439
+ attachErrorSpan(error3, options.span);
139440
+ attachWrappedErrorCause(error3, options.cause);
139441
+ return error3;
139442
+ } finally {
139443
+ resumeChecks?.();
139712
139444
  }
139713
- return rest;
139714
139445
  }
139715
- function isIndexableValue(value) {
139716
- return typeof value === "object" && value !== null;
139446
+ function isSandboxErrorConstructorInstance(value, name) {
139447
+ return isSandboxErrorObject(value) && value[sandboxErrorBrand].chain.includes(name);
139717
139448
  }
139718
- function setProperty(target, property, value) {
139719
- if (Array.isArray(target)) {
139720
- const key3 = String(property);
139721
- if (key3 === "length" || isArrayIndexKey2(key3)) {
139722
- target[key3] = value;
139723
- return;
139449
+ function defineSandboxErrorMetadata(error3, name) {
139450
+ const metadataName = toSandboxErrorName(name);
139451
+ Object.defineProperty(error3, sandboxErrorBrand, {
139452
+ enumerable: false,
139453
+ value: {
139454
+ chain: metadataName === "Error" ? ["Error"] : [metadataName, "Error"],
139455
+ name: metadataName
139724
139456
  }
139725
- defineProperty(target, key3, value);
139726
- return;
139727
- }
139728
- defineProperty(target, String(property), value);
139457
+ });
139729
139458
  }
139730
- function isArrayIndexKey2(value) {
139731
- if (value === "") {
139732
- return false;
139733
- }
139734
- const index = Number(value);
139735
- return Number.isInteger(index) && index >= 0 && index < 4294967295 && String(index) === value;
139459
+ function toSandboxErrorName(name) {
139460
+ return isSandboxErrorName(name) ? name : "Error";
139736
139461
  }
139737
- function defineProperty(target, key3, value) {
139738
- Object.defineProperty(target, key3, {
139739
- configurable: true,
139740
- enumerable: true,
139741
- value,
139742
- writable: true
139743
- });
139462
+ function isSandboxErrorName(name) {
139463
+ return sandboxErrorNames.includes(name);
139744
139464
  }
139745
- var init_patterns = __esm({
139746
- "packages/safejs/src/interp/patterns.ts"() {
139747
- "use strict";
139748
- init_values();
139749
- }
139750
- });
139751
-
139752
- // packages/safejs/src/interp/promise.ts
139753
- function createPromiseGlobals(options) {
139754
- return {
139755
- Promise: {
139756
- all: createSandboxClosure({
139757
- async: true,
139758
- call: ([values]) => createSandboxPromise(
139759
- settleIterable(values, (entries) => Promise.all(entries), options.budget)
139760
- ),
139761
- name: "all"
139762
- }),
139763
- race: createSandboxClosure({
139764
- async: true,
139765
- call: ([values]) => createSandboxPromise(
139766
- settleIterable(values, (entries) => Promise.race(entries), options.budget)
139767
- ),
139768
- name: "race"
139769
- }),
139770
- allSettled: createSandboxClosure({
139771
- async: true,
139772
- call: ([values]) => createSandboxPromise(
139773
- settleIterable(
139774
- values,
139775
- (entries) => Promise.allSettled(entries).then(
139776
- (results) => budgetSandboxValue(
139777
- results.map(
139778
- (result) => result.status === "fulfilled" ? {
139779
- status: "fulfilled",
139780
- value: result.value
139781
- } : {
139782
- reason: result.reason,
139783
- status: "rejected"
139784
- }
139785
- ),
139786
- options.budget
139787
- )
139788
- ),
139789
- options.budget
139790
- )
139791
- ),
139792
- name: "allSettled"
139793
- }),
139794
- any: createSandboxClosure({
139795
- async: true,
139796
- call: ([values]) => createSandboxPromise(
139797
- settleIterable(
139798
- values,
139799
- (entries) => Promise.any(entries).catch(
139800
- (error3) => Promise.reject(
139801
- budgetSandboxValue(
139802
- {
139803
- errors: Array.isArray(error3.errors) ? error3.errors : [],
139804
- message: "All promises were rejected",
139805
- name: "AggregateError"
139806
- },
139807
- options.budget
139808
- )
139809
- )
139810
- ),
139811
- options.budget
139812
- )
139813
- ),
139814
- name: "any"
139815
- }),
139816
- resolve: createSandboxClosure({
139817
- async: true,
139818
- call: ([value]) => isSandboxPromise(value) ? value : createSandboxPromise(resolveSandboxValue(value, { budget: options.budget })),
139819
- name: "resolve"
139820
- }),
139821
- reject: createSandboxClosure({
139822
- async: true,
139823
- call: ([reason], context) => createRejectedSandboxPromise2(reason, options.budget, context?.span),
139824
- name: "reject"
139825
- })
139826
- }
139827
- };
139465
+ function isSandboxErrorObject(value) {
139466
+ return typeof value === "object" && value !== null && sandboxErrorBrand in value;
139828
139467
  }
139829
- function getPromiseMember(target, property, budget, enqueue = (task) => Promise.resolve().then(task)) {
139830
- if (property === "then") {
139831
- return createSandboxClosure({
139832
- async: true,
139833
- call: ([onFulfilled, onRejected]) => {
139834
- observeSandboxPromise(target);
139835
- const chained = createSandboxPromise(
139836
- enqueue(
139837
- () => target.promise.then(
139838
- (value) => runPromiseReaction(onFulfilled, value, "fulfilled", budget, chained),
139839
- (reason) => runPromiseReaction(onRejected, reason, "rejected", budget, chained)
139840
- )
139841
- )
139842
- );
139843
- return chained;
139844
- },
139845
- name: "then"
139846
- });
139847
- }
139848
- if (property === "catch") {
139849
- return createSandboxClosure({
139850
- async: true,
139851
- call: ([onRejected]) => {
139852
- observeSandboxPromise(target);
139853
- const chained = createSandboxPromise(
139854
- enqueue(
139855
- () => target.promise.then(
139856
- (value) => runPromiseReaction(void 0, value, "fulfilled", budget, chained),
139857
- (reason) => runPromiseReaction(onRejected, reason, "rejected", budget, chained)
139858
- )
139859
- )
139860
- );
139861
- return chained;
139862
- },
139863
- name: "catch"
139864
- });
139468
+ function isSubsetErrorValue(value) {
139469
+ if (typeof value !== "object" || value === null) {
139470
+ return false;
139865
139471
  }
139866
- if (property === "finally") {
139867
- return createSandboxClosure({
139868
- async: true,
139869
- call: ([onFinally]) => {
139870
- observeSandboxPromise(target);
139871
- const chained = createSandboxPromise(
139872
- enqueue(
139873
- () => target.promise.then(
139874
- (value) => runPromiseFinally(onFinally, value, "fulfilled", budget, chained),
139875
- (reason) => runPromiseFinally(onFinally, reason, "rejected", budget, chained)
139876
- )
139877
- )
139878
- );
139879
- return chained;
139880
- },
139881
- name: "finally"
139882
- });
139472
+ const prototype = Object.getPrototypeOf(value);
139473
+ return (prototype === Object.prototype || prototype === null) && typeof value.name === "string" && typeof value.message === "string" && typeof value.stack === "string";
139474
+ }
139475
+ function normalizeSurfacedSubsetError(error3, budget, stackFrames, span) {
139476
+ const resumeChecks = budget.suspendChecks();
139477
+ try {
139478
+ const name = budget.allocateString(toSandboxErrorName(readErrorName(error3)));
139479
+ const message2 = budget.allocateString(readSurfacedErrorMessage(error3, name));
139480
+ const frames = readSandboxStackFrames(error3.stack);
139481
+ error3.name = name;
139482
+ error3.message = message2;
139483
+ error3.stack = budget.allocateString(
139484
+ formatErrorStack(name, message2, frames.length > 0 ? frames : [...stackFrames].reverse())
139485
+ );
139486
+ attachErrorSpan(error3, readErrorSpan(error3) ?? span);
139487
+ } finally {
139488
+ resumeChecks();
139883
139489
  }
139884
- return void 0;
139885
139490
  }
139886
- function settleIterable(iterable, settle, budget) {
139887
- return Promise.resolve().then(
139888
- () => settle(toHostPromiseArray(iterable, budget)).then((value) => budgetSandboxValue(value, budget))
139889
- );
139491
+ function readErrorName(error3) {
139492
+ return typeof error3.name === "string" && error3.name.length > 0 ? error3.name : "Error";
139890
139493
  }
139891
- function toHostPromiseArray(iterable, budget) {
139892
- const iterator = getPromiseIterator(iterable);
139893
- if (iterator === void 0) {
139894
- throw new TypeError("Promise helpers require an iterable.");
139494
+ function readSurfacedErrorMessage(error3, name) {
139495
+ const message2 = typeof error3.message === "string" ? error3.message : "";
139496
+ if (message2 === "") {
139497
+ return `${name} thrown`;
139895
139498
  }
139896
- const entries = [];
139897
- while (true) {
139898
- const next = readIteratorNext(iterator);
139899
- if (next.done === true) {
139900
- return entries;
139901
- }
139902
- entries.push(resolveSandboxValue(next.value, { budget }));
139499
+ if (message2 === "[object Object]") {
139500
+ return `${name} thrown with non-string message`;
139903
139501
  }
139502
+ return message2;
139904
139503
  }
139905
- function getPromiseIterator(iterable) {
139906
- if (typeof iterable === "string") {
139907
- return iterable[Symbol.iterator]();
139504
+ function readSandboxStackFrames(stack) {
139505
+ if (typeof stack !== "string") {
139506
+ return [];
139908
139507
  }
139909
- if (typeof iterable !== "object" && typeof iterable !== "function" || iterable === null) {
139910
- return void 0;
139508
+ const [, ...frames] = stack.split("\n");
139509
+ return frames;
139510
+ }
139511
+ function isErrorLikeValue(value) {
139512
+ return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.message === "string";
139513
+ }
139514
+ function coerceErrorMessage(message2) {
139515
+ if (message2 === void 0) {
139516
+ return "";
139911
139517
  }
139912
- const iteratorMethod = iterable[Symbol.iterator];
139913
- if (typeof iteratorMethod !== "function") {
139914
- return void 0;
139518
+ if (Array.isArray(message2)) {
139519
+ return message2.map((value) => value === null || value === void 0 ? "" : String(value)).join(",");
139915
139520
  }
139916
- const iterator = Reflect.apply(iteratorMethod, iterable, []);
139917
- if (typeof iterator !== "object" && typeof iterator !== "function" || iterator === null) {
139918
- throw new TypeError("Promise helper iterable returned a non-object iterator.");
139521
+ if (typeof message2 === "object" && message2 !== null) {
139522
+ return "[object Object]";
139919
139523
  }
139920
- return iterator;
139524
+ return String(message2);
139921
139525
  }
139922
- function readIteratorNext(iterator) {
139923
- const nextMethod = iterator.next;
139924
- if (typeof nextMethod !== "function") {
139925
- throw new TypeError("Promise helper iterator requires a next method.");
139926
- }
139927
- const next = Reflect.apply(nextMethod, iterator, []);
139928
- if (typeof next !== "object" || next === null) {
139929
- throw new TypeError("Iterator result must be an object.");
139526
+ async function evaluateWithoutDeadlineChecks(context, evaluate) {
139527
+ const resumeDeadlineChecks = context.budget.suspendDeadlineChecks();
139528
+ try {
139529
+ return await evaluate();
139530
+ } finally {
139531
+ resumeDeadlineChecks();
139930
139532
  }
139931
- return next;
139932
- }
139933
- function schedulePromise(promise, budget) {
139934
- return Promise.resolve().then(
139935
- () => promise.then(
139936
- (value) => resolveSandboxValue(value, { budget }),
139937
- (reason) => Promise.reject(budgetSandboxValue(reason, budget))
139938
- )
139939
- );
139940
- }
139941
- function createRejectedSandboxPromise2(reason, budget, span) {
139942
- const promise = schedulePromise(Promise.reject(reason), budget);
139943
- promise.catch(() => void 0);
139944
- return createSandboxPromise(promise, { span });
139945
139533
  }
139946
- function budgetSandboxValue(value, budget) {
139947
- allocateSandboxValue2(value, budget, /* @__PURE__ */ new WeakSet());
139948
- return value;
139534
+ function isBudgetExceeded(error3) {
139535
+ return error3 instanceof SandboxError && error3.code === "budgetExceeded";
139949
139536
  }
139950
- function resolveSandboxValue(value, options = {}) {
139951
- return Promise.resolve().then(() => resolveSandboxValueNow(value, options, /* @__PURE__ */ new WeakSet()));
139952
- }
139953
- function consumeSettledHostCall(value) {
139954
- if (value.hostCall?.lifecycle !== "settled") {
139955
- return;
139537
+ async function evaluateCatchClause(node, thrownValue, context, evaluateNode3) {
139538
+ const scope = context.scope.child();
139539
+ const catchContext = {
139540
+ ...context,
139541
+ scope
139542
+ };
139543
+ if (node.param !== void 0) {
139544
+ const binding = await bindPattern(node.param, thrownValue, catchContext, evaluateNode3);
139545
+ if (!binding.ok) {
139546
+ return binding.result;
139547
+ }
139956
139548
  }
139957
- value.hostCallJournal?.consume(value.hostCall);
139549
+ return evaluateBlockCompletion(node.body, catchContext, evaluateNode3);
139958
139550
  }
139959
- function resolveSandboxValueNow(value, options, seenThenables) {
139960
- if (isPromiseLike4(value)) {
139961
- return Promise.resolve(value).then(
139962
- (resolved) => resolveSandboxValueNow(resolved, options, seenThenables),
139963
- (reason) => Promise.reject(budgetIfNeeded(reason, options.budget))
139964
- );
139965
- }
139966
- if (isSandboxPromise(value)) {
139967
- observeSandboxPromise(value);
139968
- return value.promise.then(
139969
- (resolved) => {
139970
- consumeSettledHostCall(value);
139971
- return resolveSandboxValueNow(resolved, options, seenThenables);
139972
- },
139973
- (reason) => {
139974
- consumeSettledHostCall(value);
139975
- return Promise.reject(budgetIfNeeded(reason, options.budget));
139976
- }
139977
- );
139978
- }
139979
- const then = getThenable(value);
139980
- if (then !== void 0) {
139981
- return resolveThenable(value, then, options, seenThenables);
139551
+ async function evaluateBlockCompletion(node, context, evaluateNode3) {
139552
+ const blockContext = {
139553
+ ...context,
139554
+ scope: context.scope.child()
139555
+ };
139556
+ predeclareBlockBindings(node, blockContext.scope);
139557
+ let result = {
139558
+ kind: "normal",
139559
+ hasValue: false,
139560
+ value: void 0
139561
+ };
139562
+ for (const statement of node.body) {
139563
+ result = await evaluateNode3(statement, blockContext);
139564
+ if (result.kind !== "normal") {
139565
+ return result;
139566
+ }
139982
139567
  }
139983
- return Promise.resolve(budgetIfNeeded(value, options.budget));
139568
+ return result;
139984
139569
  }
139985
- function resolveThenable(value, then, options, seenThenables) {
139986
- if (typeof value !== "object" || value === null) {
139987
- return Promise.resolve(budgetIfNeeded(value, options.budget));
139988
- }
139989
- if (seenThenables.has(value)) {
139990
- return Promise.reject({
139991
- message: "Promise cannot resolve to itself.",
139992
- name: "TypeError"
139993
- });
139994
- }
139995
- seenThenables.add(value);
139996
- return new Promise((resolve17, reject) => {
139997
- let settlement;
139998
- let completed = false;
139999
- const complete = () => {
140000
- if (completed || settlement === void 0) return;
140001
- completed = true;
140002
- if (settlement.state === "fulfilled") {
140003
- resolve17(resolveSandboxValueNow(settlement.value, options, seenThenables));
140004
- } else {
140005
- reject(budgetIfNeeded(settlement.value, options.budget));
140006
- }
140007
- };
140008
- const recordSettlement = (state, settledValue) => {
140009
- if (settlement !== void 0) {
140010
- throw new SandboxError("reentry");
140011
- }
140012
- settlement = { state, value: settledValue };
140013
- queueMicrotask(complete);
140014
- };
140015
- const resolveOnce = (resolved) => {
140016
- recordSettlement("fulfilled", resolved);
140017
- };
140018
- const rejectOnce = (reason) => {
140019
- recordSettlement("rejected", reason);
140020
- };
140021
- try {
140022
- const result = then.call([
140023
- createSandboxClosure({
140024
- call: ([resolved]) => {
140025
- resolveOnce(resolved);
140026
- return void 0;
140027
- },
140028
- name: "resolve"
140029
- }),
140030
- createSandboxClosure({
140031
- call: ([reason]) => {
140032
- rejectOnce(reason);
140033
- return void 0;
140034
- },
140035
- name: "reject"
140036
- })
140037
- ]);
140038
- if (isPromiseLike4(result)) {
140039
- Promise.resolve(result).catch((reason) => {
140040
- rejectOnce(reason);
140041
- });
140042
- }
140043
- } catch (error3) {
140044
- if (settlement !== void 0) {
140045
- settlement = { state: "rejected", value: error3 };
140046
- queueMicrotask(complete);
140047
- } else {
140048
- rejectOnce(error3);
139570
+ function predeclareBlockBindings(node, scope) {
139571
+ const names = /* @__PURE__ */ new Set();
139572
+ for (const statement of node.body) {
139573
+ if (statement.type !== "VariableDeclaration" || statement.kind === "var") {
139574
+ continue;
139575
+ }
139576
+ for (const name of getDeclarationBindingNames(statement)) {
139577
+ if (names.has(name) || scope.hasOwnBinding(name)) {
139578
+ throw new Error(`Cannot redeclare binding '${name}' in the same scope.`);
140049
139579
  }
139580
+ names.add(name);
139581
+ scope.predeclare(name, statement.kind);
140050
139582
  }
140051
- }).then((resolved) => budgetIfNeeded(resolved, options.budget));
140052
- }
140053
- function runPromiseReaction(handler, value, state, budget, self) {
140054
- if (!isSandboxClosure(handler)) {
140055
- return state === "fulfilled" ? Promise.resolve(value) : Promise.reject(budgetSandboxValue(value, budget));
140056
- }
140057
- try {
140058
- const result = handler.call([value]);
140059
- return resolveReactionResult(result, budget, self);
140060
- } catch (error3) {
140061
- return Promise.reject(error3);
140062
139583
  }
140063
139584
  }
140064
- function runPromiseFinally(handler, value, state, budget, self) {
140065
- if (!isSandboxClosure(handler)) {
140066
- return runPromiseReaction(void 0, value, state, budget);
139585
+ function getDeclarationBindingNames(node) {
139586
+ return node.declarations.flatMap((declarator) => getPatternBindingNames(declarator.id));
139587
+ }
139588
+ function getPatternBindingNames(pattern) {
139589
+ switch (pattern.type) {
139590
+ case "Identifier":
139591
+ return [pattern.name];
139592
+ case "MemberExpression":
139593
+ return [];
139594
+ case "AssignmentPattern":
139595
+ return getPatternBindingNames(pattern.left);
139596
+ case "ArrayPattern":
139597
+ return pattern.elements.flatMap(
139598
+ (element) => element === null ? [] : getPatternBindingNames(element)
139599
+ );
139600
+ case "ObjectPattern":
139601
+ return pattern.properties.flatMap(
139602
+ (property) => property.type === "RestElement" ? getPatternBindingNames(property) : getPatternBindingNames(property.value)
139603
+ );
139604
+ case "RestElement":
139605
+ return getPatternBindingNames(pattern.argument);
140067
139606
  }
140068
- try {
140069
- const result = handler.call([]);
140070
- return resolveReactionResult(result, budget, self).then(
140071
- () => runPromiseReaction(void 0, value, state, budget)
140072
- );
140073
- } catch (error3) {
140074
- return Promise.reject(error3);
139607
+ }
139608
+ async function bindPattern(pattern, value, context, evaluateNode3) {
139609
+ switch (pattern.type) {
139610
+ case "Identifier":
139611
+ context.scope.declare(pattern.name, "let", value);
139612
+ return { ok: true };
139613
+ case "MemberExpression":
139614
+ throw new TypeError("Catch bindings do not support member expressions.");
139615
+ case "AssignmentPattern":
139616
+ return bindAssignmentPattern(pattern, value, context, evaluateNode3);
139617
+ case "ArrayPattern":
139618
+ return bindArrayPattern(pattern, value, context, evaluateNode3);
139619
+ case "ObjectPattern":
139620
+ return bindObjectPattern(pattern, value, context, evaluateNode3);
139621
+ case "RestElement":
139622
+ return bindPattern(pattern.argument, value, context, evaluateNode3);
140075
139623
  }
140076
139624
  }
140077
- function resolveReactionResult(result, budget, self) {
140078
- return Promise.resolve(result).then((resolved) => {
140079
- if (isSelfResolution(resolved, self)) {
140080
- return Promise.reject({
140081
- message: "Promise cannot resolve to itself.",
140082
- name: "TypeError"
140083
- });
139625
+ async function bindAssignmentPattern(pattern, value, context, evaluateNode3) {
139626
+ let nextValue = value;
139627
+ if (nextValue === void 0) {
139628
+ const defaultValue = await evaluateNode3(pattern.right, context);
139629
+ if (defaultValue.kind !== "normal") {
139630
+ return {
139631
+ ok: false,
139632
+ result: defaultValue
139633
+ };
140084
139634
  }
140085
- return resolveSandboxValue(resolved, { budget });
140086
- });
140087
- }
140088
- function isSelfResolution(result, self) {
140089
- return self !== void 0 && (result === self || isSandboxPromise(result) && result.promise === self.promise);
140090
- }
140091
- function getThenable(value) {
140092
- if (typeof value !== "object" || value === null || isSandboxClosure(value) || isSandboxPromise(value)) {
140093
- return void 0;
139635
+ nextValue = defaultValue.value;
140094
139636
  }
140095
- const then = value.then;
140096
- return isSandboxClosure(then) ? then : void 0;
140097
- }
140098
- function budgetIfNeeded(value, budget) {
140099
- return budget === void 0 ? value : budgetSandboxValue(value, budget);
139637
+ return bindPattern(pattern.left, nextValue, context, evaluateNode3);
140100
139638
  }
140101
- function allocateSandboxValue2(value, budget, seen) {
140102
- if (typeof value === "string") {
140103
- budget.allocateString(value);
140104
- return;
139639
+ async function bindArrayPattern(pattern, value, context, evaluateNode3) {
139640
+ if (!Array.isArray(value)) {
139641
+ throw new TypeError("Array catch bindings require an array value.");
140105
139642
  }
140106
- if (Array.isArray(value)) {
140107
- budget.allocateArrayLength(value.length);
140108
- if (seen.has(value)) {
140109
- return;
139643
+ for (let index = 0; index < pattern.elements.length; index += 1) {
139644
+ const element = pattern.elements[index];
139645
+ if (element === null) {
139646
+ continue;
140110
139647
  }
140111
- seen.add(value);
140112
- for (const entry of value) {
140113
- allocateSandboxValue2(entry, budget, seen);
139648
+ const elementValue = element.type === "RestElement" ? value.slice(index) : value[index];
139649
+ const binding = await bindPattern(element, elementValue, context, evaluateNode3);
139650
+ if (!binding.ok) {
139651
+ return binding;
140114
139652
  }
140115
- return;
140116
- }
140117
- if (typeof value !== "object" || value === null || isSandboxClosure(value) || isSandboxPromise(value)) {
140118
- return;
140119
139653
  }
140120
- if (seen.has(value)) {
140121
- return;
139654
+ return { ok: true };
139655
+ }
139656
+ async function bindObjectPattern(pattern, value, context, evaluateNode3) {
139657
+ if (typeof value !== "object" && !Array.isArray(value) || value === null) {
139658
+ throw new TypeError("Object catch bindings require a non-null object value.");
140122
139659
  }
140123
- seen.add(value);
140124
- for (const entry of Object.values(value)) {
140125
- allocateSandboxValue2(entry, budget, seen);
139660
+ const excludedKeys = /* @__PURE__ */ new Set();
139661
+ for (const property of pattern.properties) {
139662
+ if (property.type === "RestElement") {
139663
+ const restValue = copyObjectRest(value, excludedKeys);
139664
+ const binding2 = await bindPattern(property, restValue, context, evaluateNode3);
139665
+ if (!binding2.ok) {
139666
+ return binding2;
139667
+ }
139668
+ continue;
139669
+ }
139670
+ const key3 = await resolvePatternPropertyKey(property, context, evaluateNode3);
139671
+ if (!key3.ok) {
139672
+ return key3;
139673
+ }
139674
+ excludedKeys.add(String(key3.value));
139675
+ const binding = await bindPattern(
139676
+ property.value,
139677
+ getObjectPatternValue(value, key3.value),
139678
+ context,
139679
+ evaluateNode3
139680
+ );
139681
+ if (!binding.ok) {
139682
+ return binding;
139683
+ }
140126
139684
  }
139685
+ return { ok: true };
140127
139686
  }
140128
- function isPromiseLike4(value) {
140129
- return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function" && !isSandboxClosure(value) && !isSandboxPromise(value);
140130
- }
140131
- var init_promise = __esm({
140132
- "packages/safejs/src/interp/promise.ts"() {
140133
- "use strict";
140134
- init_budget2();
140135
- init_promise_tracker();
140136
- init_values();
139687
+ async function resolvePatternPropertyKey(property, context, evaluateNode3) {
139688
+ if (!property.computed) {
139689
+ return {
139690
+ ok: true,
139691
+ value: getStaticPropertyKey2(property.key)
139692
+ };
140137
139693
  }
140138
- });
140139
-
140140
- // packages/safejs/src/interp/var-hoist.ts
140141
- function hoistVarDeclarations(node, scope) {
140142
- if (node.type === "BlockStatement") {
140143
- for (const statement of node.body) {
140144
- hoistVarStatement(statement, scope);
140145
- }
140146
- return;
140147
- }
140148
- switch (node.type) {
140149
- case "VariableDeclaration":
140150
- case "IfStatement":
140151
- case "ForStatement":
140152
- case "ForInStatement":
140153
- case "ForOfStatement":
140154
- case "WhileStatement":
140155
- case "DoWhileStatement":
140156
- case "TryStatement":
140157
- case "SwitchStatement":
140158
- case "ExportNamedDeclaration":
140159
- hoistVarStatement(node, scope);
140160
- return;
140161
- default:
140162
- return;
140163
- }
140164
- }
140165
- function hoistVarStatement(statement, scope) {
140166
- switch (statement.type) {
140167
- case "VariableDeclaration":
140168
- declareVarBindings(statement, scope);
140169
- return;
140170
- case "BlockStatement":
140171
- hoistVarDeclarations(statement, scope);
140172
- return;
140173
- case "IfStatement":
140174
- hoistVarStatement(statement.consequent, scope);
140175
- if (statement.alternate !== void 0) {
140176
- hoistVarStatement(statement.alternate, scope);
140177
- }
140178
- return;
140179
- case "ForStatement":
140180
- if (statement.init?.type === "VariableDeclaration") {
140181
- declareVarBindings(statement.init, scope);
140182
- }
140183
- hoistVarStatement(statement.body, scope);
140184
- return;
140185
- case "ForInStatement":
140186
- case "ForOfStatement":
140187
- if (statement.left.type === "VariableDeclaration") {
140188
- declareVarBindings(statement.left, scope);
140189
- }
140190
- hoistVarStatement(statement.body, scope);
140191
- return;
140192
- case "WhileStatement":
140193
- case "DoWhileStatement":
140194
- hoistVarStatement(statement.body, scope);
140195
- return;
140196
- case "TryStatement":
140197
- hoistVarDeclarations(statement.block, scope);
140198
- if (statement.handler !== void 0) {
140199
- hoistVarDeclarations(statement.handler.body, scope);
140200
- }
140201
- if (statement.finalizer !== void 0) {
140202
- hoistVarDeclarations(statement.finalizer, scope);
140203
- }
140204
- return;
140205
- case "SwitchStatement":
140206
- for (const switchCase of statement.cases) {
140207
- for (const consequent of switchCase.consequent) {
140208
- hoistVarStatement(consequent, scope);
140209
- }
140210
- }
140211
- return;
140212
- case "ExportNamedDeclaration":
140213
- hoistVarStatement(statement.declaration, scope);
140214
- return;
140215
- case "FunctionDeclaration":
140216
- case "ExportDefaultDeclaration":
140217
- case "ImportDeclaration":
140218
- case "BreakStatement":
140219
- case "ContinueStatement":
140220
- case "EmptyStatement":
140221
- case "ExpressionStatement":
140222
- case "ReturnStatement":
140223
- case "ThrowStatement":
140224
- return;
140225
- }
140226
- }
140227
- function declareVarBindings(declaration, scope) {
140228
- if (declaration.kind !== "var") {
140229
- return;
139694
+ const computedKey = await evaluateNode3(property.key, context);
139695
+ if (computedKey.kind !== "normal") {
139696
+ return {
139697
+ ok: false,
139698
+ result: computedKey
139699
+ };
140230
139700
  }
140231
- for (const declarator of declaration.declarations) {
140232
- for (const name of getPatternBindingNames(declarator.id)) {
140233
- scope.declareVar(name);
140234
- }
139701
+ if (typeof computedKey.value !== "string" && typeof computedKey.value !== "number") {
139702
+ throw new TypeError("Computed catch binding keys must evaluate to a string or number.");
140235
139703
  }
139704
+ return {
139705
+ ok: true,
139706
+ value: computedKey.value
139707
+ };
140236
139708
  }
140237
- function getPatternBindingNames(pattern) {
140238
- switch (pattern.type) {
139709
+ function getStaticPropertyKey2(property) {
139710
+ switch (property.type) {
140239
139711
  case "Identifier":
140240
- return [pattern.name];
140241
- case "ArrayPattern":
140242
- return pattern.elements.flatMap(
140243
- (element) => element === null || element.type === "MemberExpression" ? [] : getNestedPatternBindingNames(element)
140244
- );
140245
- case "ObjectPattern":
140246
- return pattern.properties.flatMap(
140247
- (property) => property.type === "RestElement" ? property.argument.type === "MemberExpression" ? [] : getNestedPatternBindingNames(property.argument) : property.value.type === "MemberExpression" ? [] : getNestedPatternBindingNames(property.value)
140248
- );
139712
+ return property.name;
139713
+ case "StringLiteral":
139714
+ case "NumericLiteral":
139715
+ return property.value;
139716
+ default:
139717
+ throw new TypeError(`Unsupported catch binding property key '${property.type}'.`);
140249
139718
  }
140250
139719
  }
140251
- function getNestedPatternBindingNames(pattern) {
140252
- switch (pattern.type) {
140253
- case "Identifier":
140254
- return [pattern.name];
140255
- case "AssignmentPattern":
140256
- return pattern.left.type === "MemberExpression" ? [] : getNestedPatternBindingNames(pattern.left);
140257
- case "RestElement":
140258
- return pattern.argument.type === "MemberExpression" ? [] : getNestedPatternBindingNames(pattern.argument);
140259
- case "ArrayPattern":
140260
- return pattern.elements.flatMap(
140261
- (element) => element === null || element.type === "MemberExpression" ? [] : getNestedPatternBindingNames(element)
140262
- );
140263
- case "ObjectPattern":
140264
- return pattern.properties.flatMap(
140265
- (property) => property.type === "RestElement" ? property.argument.type === "MemberExpression" ? [] : getNestedPatternBindingNames(property.argument) : property.value.type === "MemberExpression" ? [] : getNestedPatternBindingNames(property.value)
140266
- );
139720
+ function getObjectPatternValue(value, key3) {
139721
+ return value[key3];
139722
+ }
139723
+ function copyObjectRest(value, excludedKeys) {
139724
+ const rest = /* @__PURE__ */ Object.create(null);
139725
+ for (const [key3, entryValue] of Object.entries(value)) {
139726
+ if (excludedKeys.has(key3)) {
139727
+ continue;
139728
+ }
139729
+ rest[key3] = entryValue;
140267
139730
  }
139731
+ return rest;
140268
139732
  }
140269
- var init_var_hoist = __esm({
140270
- "packages/safejs/src/interp/var-hoist.ts"() {
139733
+ var capturedExceptionBrand, sandboxErrorBrand, sandboxErrorNames;
139734
+ var init_exceptions = __esm({
139735
+ "packages/safejs/src/interp/exceptions.ts"() {
140271
139736
  "use strict";
139737
+ init_shape();
139738
+ init_budget2();
139739
+ init_host_call();
139740
+ init_values();
139741
+ capturedExceptionBrand = /* @__PURE__ */ Symbol("CapturedException");
139742
+ sandboxErrorBrand = /* @__PURE__ */ Symbol("SandboxError");
139743
+ sandboxErrorNames = [
139744
+ "Error",
139745
+ "TypeError",
139746
+ "RangeError",
139747
+ "ReferenceError",
139748
+ "SyntaxError",
139749
+ "AbortError",
139750
+ "AggregateError",
139751
+ "HarnessFailure"
139752
+ ];
140272
139753
  }
140273
139754
  });
140274
139755
 
140275
- // packages/safejs/src/interp/async.ts
140276
- function emitResumeBreakpoint(context, breakpoint) {
140277
- context.onYield?.({
140278
- ...breakpoint,
140279
- snapshot: () => context.snapshot?.(context.scope) ?? context.scope.snapshot()
139756
+ // packages/safejs/src/interp/jobs.ts
139757
+ import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
139758
+ function runPromiseJob(task) {
139759
+ const job = activeJob.getStore();
139760
+ return job === void 0 ? Promise.resolve().then(task) : job.queue.run(task);
139761
+ }
139762
+ function runAsyncPrefix(task) {
139763
+ const parent = activeJob.getStore();
139764
+ if (parent === void 0) return task();
139765
+ let owner = parent;
139766
+ while (owner !== void 0 && !owner.ownsExecution) owner = owner.prefixParent;
139767
+ if (owner === void 0) return parent.queue.run(task);
139768
+ const job = { queue: parent.queue, ownsExecution: false, prefixParent: parent };
139769
+ return activeJob.run(job, async () => {
139770
+ try {
139771
+ return await task();
139772
+ } finally {
139773
+ job.queue.release(job);
139774
+ }
140280
139775
  });
140281
139776
  }
140282
- async function evaluateArrowFunctionExpression(node, context, evaluateNode3) {
140283
- return {
140284
- kind: "normal",
140285
- hasValue: true,
140286
- value: createInterpretedClosure(node, context, evaluateNode3)
140287
- };
139777
+ async function suspendJob(pending) {
139778
+ const job = activeJob.getStore();
139779
+ if (job === void 0) return pending;
139780
+ job.queue.release(job);
139781
+ try {
139782
+ return await pending;
139783
+ } finally {
139784
+ await job.queue.acquire(job);
139785
+ }
140288
139786
  }
140289
- async function evaluateFunctionExpression(node, context, evaluateNode3) {
140290
- if (node.id === void 0) {
140291
- return {
140292
- kind: "normal",
140293
- hasValue: true,
140294
- value: createInterpretedClosure(node, context, evaluateNode3)
139787
+ var activeJob, SandboxJobQueue;
139788
+ var init_jobs4 = __esm({
139789
+ "packages/safejs/src/interp/jobs.ts"() {
139790
+ "use strict";
139791
+ activeJob = new AsyncLocalStorage5();
139792
+ SandboxJobQueue = class {
139793
+ running = false;
139794
+ pending = [];
139795
+ idle = [];
139796
+ generation = 0;
139797
+ acquire(job) {
139798
+ return new Promise((resolve17) => {
139799
+ this.pending.push(() => {
139800
+ this.running = true;
139801
+ this.generation += 1;
139802
+ job.ownsExecution = true;
139803
+ resolve17();
139804
+ });
139805
+ this.advance();
139806
+ });
139807
+ }
139808
+ release(job) {
139809
+ job.prefixParent = void 0;
139810
+ if (!job.ownsExecution) return;
139811
+ job.ownsExecution = false;
139812
+ this.running = false;
139813
+ this.advance();
139814
+ }
139815
+ async run(task) {
139816
+ const job = { queue: this, ownsExecution: false };
139817
+ await this.acquire(job);
139818
+ return activeJob.run(job, async () => {
139819
+ try {
139820
+ return await task();
139821
+ } finally {
139822
+ this.release(job);
139823
+ }
139824
+ });
139825
+ }
139826
+ async drain() {
139827
+ let idleTurns = 0;
139828
+ while (idleTurns < 20) {
139829
+ const generation = this.generation;
139830
+ if (this.running) await new Promise((resolve17) => this.idle.push(resolve17));
139831
+ await Promise.resolve();
139832
+ idleTurns = generation === this.generation ? idleTurns + 1 : 0;
139833
+ }
139834
+ }
139835
+ advance() {
139836
+ if (this.running) return;
139837
+ const next = this.pending.shift();
139838
+ if (next !== void 0) {
139839
+ next();
139840
+ } else {
139841
+ for (const resolve17 of this.idle.splice(0)) resolve17();
139842
+ }
139843
+ }
140295
139844
  };
140296
139845
  }
140297
- const wrapperScope = context.scope.child();
140298
- const closure = createInterpretedClosure(node, { ...context, scope: wrapperScope }, evaluateNode3);
140299
- wrapperScope.declare(node.id.name, "const", closure);
139846
+ });
139847
+
139848
+ // packages/safejs/src/interp/promise.ts
139849
+ function createPromiseGlobals(options) {
140300
139850
  return {
140301
- kind: "normal",
140302
- hasValue: true,
140303
- value: closure
140304
- };
140305
- }
140306
- function createInterpretedClosure(node, context, evaluateNode3) {
140307
- if (node.type !== "ArrowFunctionExpression" && node.generator) {
140308
- return createGeneratorClosure(node, context, evaluateNode3);
140309
- }
140310
- const construct = node.type !== "ArrowFunctionExpression" && !(node.type === "FunctionExpression" && node.method === true) && !node.async ? async (args, callContext) => {
140311
- const thisValue = {};
140312
- const result = await executeClosure(
140313
- node,
140314
- args,
140315
- thisValue,
140316
- {
140317
- ...context,
140318
- callStack: [...callContext?.stack ?? context.callStack]
140319
- },
140320
- evaluateNode3
140321
- );
140322
- return isConstructResult(result) ? result : thisValue;
140323
- } : void 0;
140324
- return createSandboxClosure({
140325
- ...node.async ? { async: true } : {},
140326
- ...node.type === "FunctionDeclaration" || node.type === "FunctionExpression" ? node.id === void 0 ? {} : { name: node.id.name } : {},
140327
- ...construct === void 0 ? {} : { construct },
140328
- retainedValues: () => context.scope.retainedValues(),
140329
- call: (args, callContext) => node.async ? createSandboxPromise(
140330
- resolveSandboxValue(
140331
- executeClosure(
140332
- node,
140333
- args,
140334
- callContext?.thisValue,
140335
- {
140336
- ...context,
140337
- callStack: [...callContext?.stack ?? context.callStack]
140338
- },
140339
- evaluateNode3
139851
+ Promise: {
139852
+ all: createSandboxClosure({
139853
+ async: true,
139854
+ call: ([values]) => createSandboxPromise(
139855
+ settleIterable(values, (entries) => Promise.all(entries), options.budget)
140340
139856
  ),
140341
- { budget: context.budget }
140342
- )
140343
- ) : executeClosure(
140344
- node,
140345
- args,
140346
- callContext?.thisValue,
140347
- {
140348
- ...context,
140349
- callStack: [...callContext?.stack ?? context.callStack]
139857
+ name: "all"
139858
+ }),
139859
+ race: createSandboxClosure({
139860
+ async: true,
139861
+ call: ([values]) => createSandboxPromise(
139862
+ settleIterable(values, (entries) => Promise.race(entries), options.budget)
139863
+ ),
139864
+ name: "race"
139865
+ }),
139866
+ allSettled: createSandboxClosure({
139867
+ async: true,
139868
+ call: ([values]) => createSandboxPromise(
139869
+ settleIterable(
139870
+ values,
139871
+ (entries) => Promise.allSettled(entries).then(
139872
+ (results) => budgetSandboxValue(
139873
+ results.map(
139874
+ (result) => result.status === "fulfilled" ? {
139875
+ status: "fulfilled",
139876
+ value: result.value
139877
+ } : {
139878
+ reason: result.reason,
139879
+ status: "rejected"
139880
+ }
139881
+ ),
139882
+ options.budget
139883
+ )
139884
+ ),
139885
+ options.budget
139886
+ )
139887
+ ),
139888
+ name: "allSettled"
139889
+ }),
139890
+ any: createSandboxClosure({
139891
+ async: true,
139892
+ call: ([values]) => createSandboxPromise(
139893
+ settleIterable(
139894
+ values,
139895
+ (entries) => Promise.any(entries).catch((error3) => {
139896
+ const aggregate = createSubsetErrorValue(
139897
+ "AggregateError",
139898
+ "All promises were rejected",
139899
+ [],
139900
+ options.budget
139901
+ );
139902
+ aggregate.errors = Array.isArray(error3.errors) ? error3.errors : [];
139903
+ throw budgetSandboxValue(aggregate, options.budget);
139904
+ }),
139905
+ options.budget
139906
+ )
139907
+ ),
139908
+ name: "any"
139909
+ }),
139910
+ resolve: createSandboxClosure({
139911
+ async: true,
139912
+ call: ([value]) => isSandboxPromise(value) ? value : createSandboxPromise(resolveSandboxValue(value, { budget: options.budget })),
139913
+ name: "resolve"
139914
+ }),
139915
+ reject: createSandboxClosure({
139916
+ async: true,
139917
+ call: ([reason], context) => createRejectedSandboxPromise(reason, options.budget, context?.span),
139918
+ name: "reject"
139919
+ })
139920
+ }
139921
+ };
139922
+ }
139923
+ function getPromiseMember(target, property, budget) {
139924
+ if (property === "then") {
139925
+ return createSandboxClosure({
139926
+ async: true,
139927
+ call: ([onFulfilled, onRejected]) => {
139928
+ observeSandboxPromise(target);
139929
+ const chained = createSandboxPromise(
139930
+ target.promise.then(
139931
+ (value) => runPromiseReaction(onFulfilled, value, "fulfilled", budget, chained),
139932
+ (reason) => runPromiseReaction(onRejected, reason, "rejected", budget, chained)
139933
+ )
139934
+ );
139935
+ return chained;
140350
139936
  },
140351
- evaluateNode3
139937
+ name: "then"
139938
+ });
139939
+ }
139940
+ if (property === "catch") {
139941
+ return createSandboxClosure({
139942
+ async: true,
139943
+ call: ([onRejected]) => {
139944
+ observeSandboxPromise(target);
139945
+ const chained = createSandboxPromise(
139946
+ target.promise.then(
139947
+ (value) => runPromiseReaction(void 0, value, "fulfilled", budget, chained),
139948
+ (reason) => runPromiseReaction(onRejected, reason, "rejected", budget, chained)
139949
+ )
139950
+ );
139951
+ return chained;
139952
+ },
139953
+ name: "catch"
139954
+ });
139955
+ }
139956
+ if (property === "finally") {
139957
+ return createSandboxClosure({
139958
+ async: true,
139959
+ call: ([onFinally]) => {
139960
+ observeSandboxPromise(target);
139961
+ const chained = createSandboxPromise(
139962
+ target.promise.then(
139963
+ (value) => runPromiseFinally(onFinally, value, "fulfilled", budget, chained),
139964
+ (reason) => runPromiseFinally(onFinally, reason, "rejected", budget, chained)
139965
+ )
139966
+ );
139967
+ return chained;
139968
+ },
139969
+ name: "finally"
139970
+ });
139971
+ }
139972
+ return void 0;
139973
+ }
139974
+ function settleIterable(iterable, settle, budget) {
139975
+ return Promise.resolve().then(
139976
+ () => settle(toHostPromiseArray(iterable, budget)).then((value) => budgetSandboxValue(value, budget))
139977
+ );
139978
+ }
139979
+ function toHostPromiseArray(iterable, budget) {
139980
+ const iterator = getPromiseIterator(iterable);
139981
+ if (iterator === void 0) {
139982
+ throw new TypeError("Promise helpers require an iterable.");
139983
+ }
139984
+ const entries = [];
139985
+ while (true) {
139986
+ const next = readIteratorNext(iterator);
139987
+ if (next.done === true) {
139988
+ return entries;
139989
+ }
139990
+ entries.push(resolveSandboxValue(next.value, { budget }));
139991
+ }
139992
+ }
139993
+ function getPromiseIterator(iterable) {
139994
+ if (typeof iterable === "string") {
139995
+ return iterable[Symbol.iterator]();
139996
+ }
139997
+ if (typeof iterable !== "object" && typeof iterable !== "function" || iterable === null) {
139998
+ return void 0;
139999
+ }
140000
+ const iteratorMethod = iterable[Symbol.iterator];
140001
+ if (typeof iteratorMethod !== "function") {
140002
+ return void 0;
140003
+ }
140004
+ const iterator = Reflect.apply(iteratorMethod, iterable, []);
140005
+ if (typeof iterator !== "object" && typeof iterator !== "function" || iterator === null) {
140006
+ throw new TypeError("Promise helper iterable returned a non-object iterator.");
140007
+ }
140008
+ return iterator;
140009
+ }
140010
+ function readIteratorNext(iterator) {
140011
+ const nextMethod = iterator.next;
140012
+ if (typeof nextMethod !== "function") {
140013
+ throw new TypeError("Promise helper iterator requires a next method.");
140014
+ }
140015
+ const next = Reflect.apply(nextMethod, iterator, []);
140016
+ if (typeof next !== "object" || next === null) {
140017
+ throw new TypeError("Iterator result must be an object.");
140018
+ }
140019
+ return next;
140020
+ }
140021
+ function schedulePromise(promise, budget) {
140022
+ return Promise.resolve().then(
140023
+ () => promise.then(
140024
+ (value) => resolveSandboxValue(value, { budget }),
140025
+ (reason) => Promise.reject(budgetSandboxValue(reason, budget))
140352
140026
  )
140353
- });
140027
+ );
140028
+ }
140029
+ function createRejectedSandboxPromise(reason, budget, span) {
140030
+ const promise = schedulePromise(Promise.reject(reason), budget);
140031
+ promise.catch(() => void 0);
140032
+ return createSandboxPromise(promise, { span });
140033
+ }
140034
+ function budgetSandboxValue(value, budget) {
140035
+ allocateSandboxValue2(value, budget, /* @__PURE__ */ new WeakSet());
140036
+ return value;
140037
+ }
140038
+ function resolveSandboxValue(value, options = {}) {
140039
+ return Promise.resolve().then(() => resolveSandboxValueNow(value, options, /* @__PURE__ */ new WeakSet()));
140040
+ }
140041
+ function consumeSettledHostCall(value) {
140042
+ if (value.hostCall?.lifecycle !== "settled") {
140043
+ return;
140044
+ }
140045
+ value.hostCallJournal?.consume(value.hostCall);
140046
+ }
140047
+ function resolveSandboxValueNow(value, options, seenThenables) {
140048
+ if (isPromiseLike3(value)) {
140049
+ return Promise.resolve(value).then(
140050
+ (resolved) => resolveSandboxValueNow(resolved, options, seenThenables),
140051
+ (reason) => Promise.reject(budgetIfNeeded(reason, options.budget))
140052
+ );
140053
+ }
140054
+ if (isSandboxPromise(value)) {
140055
+ observeSandboxPromise(value);
140056
+ return value.promise.then(
140057
+ (resolved) => {
140058
+ consumeSettledHostCall(value);
140059
+ return resolveSandboxValueNow(resolved, options, seenThenables);
140060
+ },
140061
+ (reason) => {
140062
+ consumeSettledHostCall(value);
140063
+ return Promise.reject(budgetIfNeeded(reason, options.budget));
140064
+ }
140065
+ );
140066
+ }
140067
+ const then = getThenable(value);
140068
+ if (then !== void 0) {
140069
+ return resolveThenable(value, then, options, seenThenables);
140070
+ }
140071
+ return Promise.resolve(budgetIfNeeded(value, options.budget));
140072
+ }
140073
+ function resolveThenable(value, then, options, seenThenables) {
140074
+ if (typeof value !== "object" || value === null) {
140075
+ return Promise.resolve(budgetIfNeeded(value, options.budget));
140076
+ }
140077
+ if (seenThenables.has(value)) {
140078
+ return Promise.reject({
140079
+ message: "Promise cannot resolve to itself.",
140080
+ name: "TypeError"
140081
+ });
140082
+ }
140083
+ seenThenables.add(value);
140084
+ return new Promise((resolve17, reject) => {
140085
+ let settlement;
140086
+ let completed = false;
140087
+ let invocationPending = true;
140088
+ const complete = () => {
140089
+ if (completed || invocationPending || settlement === void 0) return;
140090
+ completed = true;
140091
+ try {
140092
+ if (settlement.state === "fulfilled") {
140093
+ resolve17(resolveSandboxValueNow(settlement.value, options, seenThenables));
140094
+ } else {
140095
+ reject(budgetIfNeeded(settlement.value, options.budget));
140096
+ }
140097
+ } catch (error3) {
140098
+ reject(error3);
140099
+ }
140100
+ };
140101
+ const recordSettlement = (state, settledValue) => {
140102
+ if (settlement !== void 0) {
140103
+ return;
140104
+ }
140105
+ settlement = { state, value: settledValue };
140106
+ queueMicrotask(complete);
140107
+ };
140108
+ callInPromiseJob(
140109
+ then,
140110
+ [
140111
+ createSandboxClosure({
140112
+ call: ([resolved]) => {
140113
+ recordSettlement("fulfilled", resolved);
140114
+ return void 0;
140115
+ },
140116
+ name: "resolve"
140117
+ }),
140118
+ createSandboxClosure({
140119
+ call: ([reason]) => {
140120
+ recordSettlement("rejected", reason);
140121
+ return void 0;
140122
+ },
140123
+ name: "reject"
140124
+ })
140125
+ ],
140126
+ value
140127
+ ).then(
140128
+ () => {
140129
+ invocationPending = false;
140130
+ complete();
140131
+ },
140132
+ (error3) => {
140133
+ invocationPending = false;
140134
+ recordSettlement("rejected", error3);
140135
+ complete();
140136
+ }
140137
+ );
140138
+ }).then((resolved) => budgetIfNeeded(resolved, options.budget));
140139
+ }
140140
+ function runPromiseReaction(handler, value, state, budget, self) {
140141
+ if (!isSandboxClosure(handler)) {
140142
+ return state === "fulfilled" ? Promise.resolve(value) : Promise.reject(budgetSandboxValue(value, budget));
140143
+ }
140144
+ return callInPromiseJob(handler, [value]).then(
140145
+ ({ value: result }) => resolveReactionResult(result, budget, self)
140146
+ );
140147
+ }
140148
+ function runPromiseFinally(handler, value, state, budget, self) {
140149
+ if (!isSandboxClosure(handler)) {
140150
+ return runPromiseReaction(void 0, value, state, budget);
140151
+ }
140152
+ return callInPromiseJob(handler, []).then(
140153
+ ({ value: result }) => resolveReactionResult(result, budget, self).then(
140154
+ () => runPromiseReaction(void 0, value, state, budget)
140155
+ )
140156
+ );
140157
+ }
140158
+ function callInPromiseJob(handler, args, thisValue = void 0) {
140159
+ return runPromiseJob(async () => {
140160
+ let result = handler.call(args, { stack: [], thisValue });
140161
+ if (handler.async !== true) result = await result;
140162
+ if (isSandboxPromise(result) && result.synchronousPrefix !== void 0) {
140163
+ await result.synchronousPrefix;
140164
+ }
140165
+ return { value: result };
140166
+ });
140167
+ }
140168
+ function resolveReactionResult(result, budget, self) {
140169
+ return Promise.resolve(result).then((resolved) => {
140170
+ if (isSelfResolution(resolved, self)) {
140171
+ return Promise.reject({
140172
+ message: "Promise cannot resolve to itself.",
140173
+ name: "TypeError"
140174
+ });
140175
+ }
140176
+ return resolveSandboxValue(resolved, { budget });
140177
+ });
140178
+ }
140179
+ function isSelfResolution(result, self) {
140180
+ return self !== void 0 && (result === self || isSandboxPromise(result) && result.promise === self.promise);
140181
+ }
140182
+ function getThenable(value) {
140183
+ if (typeof value !== "object" || value === null || isSandboxPromise(value)) {
140184
+ return void 0;
140185
+ }
140186
+ const then = isSandboxClosure(value) ? value.properties?.then : value.then;
140187
+ return isSandboxClosure(then) ? then : void 0;
140188
+ }
140189
+ function budgetIfNeeded(value, budget) {
140190
+ return budget === void 0 ? value : budgetSandboxValue(value, budget);
140191
+ }
140192
+ function allocateSandboxValue2(value, budget, seen) {
140193
+ if (typeof value === "string") {
140194
+ budget.allocateString(value);
140195
+ return;
140196
+ }
140197
+ if (Array.isArray(value)) {
140198
+ budget.allocateArrayLength(value.length);
140199
+ if (seen.has(value)) {
140200
+ return;
140201
+ }
140202
+ seen.add(value);
140203
+ for (const entry of value) {
140204
+ allocateSandboxValue2(entry, budget, seen);
140205
+ }
140206
+ return;
140207
+ }
140208
+ if (typeof value !== "object" || value === null || isSandboxClosure(value) || isSandboxPromise(value)) {
140209
+ return;
140210
+ }
140211
+ if (seen.has(value)) {
140212
+ return;
140213
+ }
140214
+ seen.add(value);
140215
+ for (const entry of Object.values(value)) {
140216
+ allocateSandboxValue2(entry, budget, seen);
140217
+ }
140218
+ }
140219
+ function isPromiseLike3(value) {
140220
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function" && !isSandboxClosure(value) && !isSandboxPromise(value);
140221
+ }
140222
+ var init_promise = __esm({
140223
+ "packages/safejs/src/interp/promise.ts"() {
140224
+ "use strict";
140225
+ init_exceptions();
140226
+ init_jobs4();
140227
+ init_promise_tracker();
140228
+ init_values();
140229
+ }
140230
+ });
140231
+
140232
+ // packages/safejs/src/interp/cancel.ts
140233
+ function wrapCancelableBindings(bindings, signal) {
140234
+ if (signal === void 0) {
140235
+ return bindings;
140236
+ }
140237
+ return wrapCancelableValue(bindings, signal, /* @__PURE__ */ new WeakMap());
140238
+ }
140239
+ function wrapCancelableValue(value, signal, seen) {
140240
+ if (typeof value !== "object" || value === null) {
140241
+ return value;
140242
+ }
140243
+ const existing = seen.get(value);
140244
+ if (existing !== void 0) {
140245
+ return existing;
140246
+ }
140247
+ if (isSandboxClosure(value)) {
140248
+ const wrapped2 = createSandboxClosure({
140249
+ ...value.async === true ? { async: true } : {},
140250
+ call: (args, context) => {
140251
+ if (signal.aborted) {
140252
+ if (value.async === true) {
140253
+ return createRejectedSandboxPromise2(readAbortReason(signal));
140254
+ }
140255
+ throw readAbortReason(signal);
140256
+ }
140257
+ return wrapCancelableResult(value.call(args, context), signal, seen);
140258
+ },
140259
+ name: value.name
140260
+ });
140261
+ seen.set(value, wrapped2);
140262
+ return wrapped2;
140263
+ }
140264
+ if (isSandboxPromise(value)) {
140265
+ observeSandboxPromise(value);
140266
+ const wrapped2 = createSandboxPromise(wrapCancelablePromise(value.promise, signal, seen), {
140267
+ trackReplay: false,
140268
+ ...value.synchronousPrefix === void 0 ? {} : { synchronousPrefix: value.synchronousPrefix },
140269
+ ...value.hostCall === void 0 ? {} : { hostCall: value.hostCall },
140270
+ ...value.hostCallJournal === void 0 ? {} : { hostCallJournal: value.hostCallJournal },
140271
+ ...value.span === void 0 ? {} : { span: value.span }
140272
+ });
140273
+ seen.set(value, wrapped2);
140274
+ cancellationSignals.set(wrapped2, signal);
140275
+ return wrapped2;
140276
+ }
140277
+ if (Array.isArray(value)) {
140278
+ const wrapped2 = new Array(value.length);
140279
+ seen.set(value, wrapped2);
140280
+ for (let index = 0; index < value.length; index += 1) {
140281
+ wrapped2[index] = wrapCancelableValue(value[index], signal, seen);
140282
+ }
140283
+ return wrapped2;
140284
+ }
140285
+ const wrapped = Object.create(Object.getPrototypeOf(value));
140286
+ seen.set(value, wrapped);
140287
+ for (const [key3, entry] of Object.entries(value)) {
140288
+ wrapped[key3] = wrapCancelableValue(entry, signal, seen);
140289
+ }
140290
+ return wrapped;
140291
+ }
140292
+ function wrapCancelableResult(result, signal, seen) {
140293
+ if (!isPromiseLike4(result)) {
140294
+ return wrapCancelableValue(result, signal, seen);
140295
+ }
140296
+ return wrapCancelablePromise(result, signal, seen);
140297
+ }
140298
+ function wrapCancelablePromise(promise, signal, seen) {
140299
+ return awaitWithSignal(promise, signal).then(
140300
+ (value) => wrapCancelableValue(value, signal, seen),
140301
+ (reason) => {
140302
+ if (signal.aborted && reason === signal.reason) throw reason;
140303
+ throw wrapCancelableUnknown(reason, signal, seen);
140304
+ }
140305
+ );
140306
+ }
140307
+ function awaitSandboxValue(value, signal) {
140308
+ const resolved = resolveSandboxValue(value);
140309
+ return isSandboxPromise(value) && (value.synchronousPrefix !== void 0 || cancellationSignals.get(value) === signal) ? resolved : awaitWithSignal(resolved, signal);
140310
+ }
140311
+ function awaitWithSignal(promise, signal) {
140312
+ if (signal === void 0) return Promise.resolve(promise);
140313
+ if (signal.aborted) {
140314
+ void Promise.resolve(promise).catch(() => void 0);
140315
+ return Promise.reject(readAbortReason(signal));
140316
+ }
140317
+ return new Promise((resolve17, reject) => {
140318
+ let listenerActive = true;
140319
+ let settled = false;
140320
+ const onAbort = () => {
140321
+ cleanup();
140322
+ queueMicrotask(() => {
140323
+ settle(() => reject(readAbortReason(signal)));
140324
+ });
140325
+ };
140326
+ const cleanup = () => {
140327
+ if (!listenerActive) {
140328
+ return;
140329
+ }
140330
+ listenerActive = false;
140331
+ signal.removeEventListener("abort", onAbort);
140332
+ };
140333
+ const settle = (complete) => {
140334
+ if (settled) {
140335
+ return;
140336
+ }
140337
+ settled = true;
140338
+ cleanup();
140339
+ complete();
140340
+ };
140341
+ signal.addEventListener("abort", onAbort, { once: true });
140342
+ Promise.resolve(promise).then(
140343
+ (value) => {
140344
+ settle(() => resolve17(value));
140345
+ },
140346
+ (reason) => {
140347
+ settle(() => reject(reason));
140348
+ }
140349
+ );
140350
+ });
140351
+ }
140352
+ function wrapCancelableUnknown(value, signal, seen) {
140353
+ if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
140354
+ return value;
140355
+ }
140356
+ if (isSandboxClosure(value) || isSandboxPromise(value) || Array.isArray(value) || typeof value === "object" && value !== null) {
140357
+ return wrapCancelableValue(value, signal, seen);
140358
+ }
140359
+ return value;
140360
+ }
140361
+ function readAbortReason(signal) {
140362
+ return signal.reason ?? createAbortError11();
140363
+ }
140364
+ function createAbortError11() {
140365
+ if (typeof DOMException === "function") {
140366
+ const error4 = new DOMException("This operation was aborted", "AbortError");
140367
+ replaceErrorStack(error4);
140368
+ return error4;
140369
+ }
140370
+ const error3 = new Error("This operation was aborted");
140371
+ error3.name = "AbortError";
140372
+ replaceErrorStack(error3);
140373
+ return error3;
140374
+ }
140375
+ function createRejectedSandboxPromise2(reason) {
140376
+ const promise = Promise.reject(reason);
140377
+ promise.catch(() => void 0);
140378
+ return createSandboxPromise(promise);
140379
+ }
140380
+ function isPromiseLike4(value) {
140381
+ return typeof value === "object" && value !== null && "then" in value;
140382
+ }
140383
+ var cancellationSignals;
140384
+ var init_cancel2 = __esm({
140385
+ "packages/safejs/src/interp/cancel.ts"() {
140386
+ "use strict";
140387
+ init_values();
140388
+ init_promise_tracker();
140389
+ init_shape();
140390
+ init_promise();
140391
+ cancellationSignals = /* @__PURE__ */ new WeakMap();
140392
+ }
140393
+ });
140394
+
140395
+ // packages/safejs/src/interp/generator.ts
140396
+ function createGeneratorChannel(body) {
140397
+ let state = "unstarted";
140398
+ let signal = deferred();
140399
+ let resume;
140400
+ const start = deferred();
140401
+ const sent = [];
140402
+ let yieldNodeId;
140403
+ const bodyPromise = start.promise.then(() => body(yieldValue));
140404
+ void bodyPromise.then(
140405
+ (value) => {
140406
+ if (state === "done") {
140407
+ return;
140408
+ }
140409
+ state = "done";
140410
+ signal.resolve({ type: "complete", value });
140411
+ },
140412
+ (error3) => {
140413
+ if (state === "done") {
140414
+ return;
140415
+ }
140416
+ state = "done";
140417
+ signal.resolve({ type: "error", error: error3 });
140418
+ }
140419
+ );
140420
+ void bodyPromise.catch(() => void 0);
140421
+ async function yieldValue(value, nodeId) {
140422
+ resume = deferred();
140423
+ yieldNodeId = nodeId;
140424
+ state = "suspended";
140425
+ signal.resolve({ type: "yield", value });
140426
+ return resume.promise;
140427
+ }
140428
+ async function deliver(completion) {
140429
+ const leaveRunning = enterRunningState(channelIdentity);
140430
+ try {
140431
+ if (state === "done") {
140432
+ if (completion.type === "return") {
140433
+ return { value: completion.value, done: true };
140434
+ }
140435
+ if (completion.type === "throw") {
140436
+ throw completion.value;
140437
+ }
140438
+ return { value: void 0, done: true };
140439
+ }
140440
+ if (state === "unstarted") {
140441
+ if (completion.type === "return") {
140442
+ state = "done";
140443
+ return { value: completion.value, done: true };
140444
+ }
140445
+ if (completion.type === "throw") {
140446
+ state = "done";
140447
+ throw completion.value;
140448
+ }
140449
+ state = "running";
140450
+ sent.push(completion);
140451
+ start.resolve();
140452
+ } else {
140453
+ state = "running";
140454
+ sent.push(completion);
140455
+ signal = deferred();
140456
+ const pendingResume = resume;
140457
+ resume = void 0;
140458
+ pendingResume?.resolve(completion);
140459
+ }
140460
+ const settled = await signal.promise;
140461
+ if (settled.type === "yield") {
140462
+ return { value: settled.value, done: false };
140463
+ }
140464
+ if (settled.type === "error") {
140465
+ throw settled.error;
140466
+ }
140467
+ return { value: settled.value, done: true };
140468
+ } finally {
140469
+ leaveRunning();
140470
+ }
140471
+ }
140472
+ const channelIdentity = {};
140473
+ return {
140474
+ next: (value) => deliver({ type: "normal", value }),
140475
+ return: (value) => deliver({ type: "return", value }),
140476
+ throw: (error3) => deliver({ type: "throw", value: error3 }),
140477
+ snapshot: () => ({
140478
+ ...yieldNodeId === void 0 ? {} : { yieldNodeId },
140479
+ sent: sent.map((completion) => ({ ...completion }))
140480
+ })
140481
+ };
140482
+ }
140483
+ function deferred() {
140484
+ let resolve17;
140485
+ let reject;
140486
+ const promise = new Promise((innerResolve, innerReject) => {
140487
+ resolve17 = innerResolve;
140488
+ reject = innerReject;
140489
+ });
140490
+ return { promise, reject, resolve: resolve17 };
140491
+ }
140492
+ var init_generator = __esm({
140493
+ "packages/safejs/src/interp/generator.ts"() {
140494
+ "use strict";
140495
+ init_running_state();
140496
+ }
140497
+ });
140498
+
140499
+ // packages/safejs/src/interp/patterns.ts
140500
+ async function bindPattern2(pattern, value, target, scope, context) {
140501
+ switch (pattern.type) {
140502
+ case "Identifier":
140503
+ bindIdentifier(pattern, value, target, scope);
140504
+ return { ok: true };
140505
+ case "MemberExpression":
140506
+ if ("kind" in target) {
140507
+ throw new TypeError("Destructuring declarations cannot bind to member expressions.");
140508
+ }
140509
+ return bindMemberExpression(pattern, value, scope, context);
140510
+ case "AssignmentPattern":
140511
+ return bindAssignmentPattern2(pattern, value, target, scope, context);
140512
+ case "ArrayPattern":
140513
+ return bindArrayPattern2(pattern, value, target, scope, context);
140514
+ case "ObjectPattern":
140515
+ return bindObjectPattern2(pattern, value, target, scope, context);
140516
+ case "RestElement":
140517
+ return bindPattern2(pattern.argument, value, target, scope, context);
140518
+ }
140354
140519
  }
140355
- function createGeneratorClosure(node, context, evaluateNode3) {
140356
- return createSandboxClosure({
140357
- ...node.id === void 0 ? {} : { name: node.id.name },
140358
- retainedValues: () => context.scope.retainedValues(),
140359
- call: async (args, callContext) => {
140360
- const closureContext = {
140361
- ...context,
140362
- callStack: [...callContext?.stack ?? context.callStack]
140363
- };
140364
- const scope = await createClosureScope(
140365
- node,
140366
- args,
140367
- callContext?.thisValue,
140368
- closureContext,
140369
- evaluateNode3
140370
- );
140371
- const channel = createGeneratorChannel(async (generatorYield) => {
140372
- const result = await evaluateNode3(node.body, {
140373
- ...closureContext,
140374
- generatorYield: (value, yieldNodeId) => {
140375
- generator.state = "suspended";
140376
- return generatorYield(value, yieldNodeId);
140377
- },
140378
- scope
140379
- });
140380
- if (result.kind === "error") {
140381
- throw result.error;
140382
- }
140383
- if (result.kind === "throw") {
140384
- throw result.value;
140385
- }
140386
- return result.hasValue ? result.value : void 0;
140387
- });
140388
- const generator = createSandboxGenerator(channel);
140389
- return generator;
140520
+ function bindIdentifier(pattern, value, target, scope) {
140521
+ if ("assign" in target || target.kind === "var") {
140522
+ if ("assign" in target) {
140523
+ const binding = scope.lookup(pattern.name);
140524
+ if (!binding.found) {
140525
+ throw new ReferenceError(`Cannot assign to undeclared binding '${pattern.name}'.`);
140526
+ }
140527
+ if (binding.kind === "const") {
140528
+ throw new TypeError(`Cannot assign to const '${pattern.name}'`);
140529
+ }
140390
140530
  }
140391
- });
140531
+ scope.assign(pattern.name, value);
140532
+ return;
140533
+ }
140534
+ scope.declare(pattern.name, target.kind, value);
140392
140535
  }
140393
- function isConstructResult(value) {
140394
- return typeof value === "object" && value !== null;
140536
+ async function bindAssignmentPattern2(pattern, value, target, scope, context) {
140537
+ if (value !== void 0) {
140538
+ return bindPattern2(pattern.left, value, target, scope, context);
140539
+ }
140540
+ const defaultValue = await context.evaluate(pattern.right);
140541
+ if (defaultValue.kind !== "normal") {
140542
+ return { ok: false, result: defaultValue };
140543
+ }
140544
+ return bindPattern2(pattern.left, defaultValue.value, target, scope, context);
140395
140545
  }
140396
- async function evaluateAwaitExpression(node, context, evaluateNode3) {
140397
- const replayState = context.captureReplayState?.();
140398
- const argument = await evaluateNode3(node.argument, context);
140399
- if (argument.kind !== "normal") {
140400
- return argument;
140546
+ async function bindArrayPattern2(pattern, value, target, scope, context) {
140547
+ const values = getArrayPatternValues(value);
140548
+ for (let index = 0; index < pattern.elements.length; index += 1) {
140549
+ const element = pattern.elements[index];
140550
+ if (element === null) {
140551
+ continue;
140552
+ }
140553
+ const elementValue = element.type === "RestElement" ? values.slice(index) : values[index];
140554
+ const binding = await bindPattern2(element, elementValue, target, scope, context);
140555
+ if (!binding.ok) {
140556
+ return binding;
140557
+ }
140401
140558
  }
140402
- emitResumeBreakpoint(context, {
140403
- kind: "await",
140404
- replayState,
140405
- nodeId: node.nodeId,
140406
- ...getBoundOtelSpan(argument.value) === void 0 ? {} : { otelSpan: getBoundOtelSpan(argument.value) },
140407
- span: node.span
140408
- });
140409
- const leaveAwait = context.budget.enterAwait();
140410
- try {
140411
- while (context.microtasks.length > 0) {
140412
- context.microtasks.shift()?.();
140559
+ return { ok: true };
140560
+ }
140561
+ async function bindObjectPattern2(pattern, value, target, scope, context) {
140562
+ if (typeof value !== "object" || value === null) {
140563
+ throw new TypeError("Object destructuring declarations require a non-null object value.");
140564
+ }
140565
+ const excludedKeys = /* @__PURE__ */ new Set();
140566
+ for (const property of pattern.properties) {
140567
+ if (property.type === "RestElement") {
140568
+ const binding2 = await bindPattern2(
140569
+ property,
140570
+ copyObjectRestValue(value, excludedKeys),
140571
+ target,
140572
+ scope,
140573
+ context
140574
+ );
140575
+ if (!binding2.ok) {
140576
+ return binding2;
140577
+ }
140578
+ continue;
140579
+ }
140580
+ const key3 = await evaluatePatternKey(property, context);
140581
+ if (!key3.ok) {
140582
+ return key3;
140583
+ }
140584
+ excludedKeys.add(String(key3.value));
140585
+ const binding = await bindPattern2(
140586
+ property.value,
140587
+ value[key3.value],
140588
+ target,
140589
+ scope,
140590
+ context
140591
+ );
140592
+ if (!binding.ok) {
140593
+ return binding;
140413
140594
  }
140414
- return {
140415
- kind: "normal",
140416
- hasValue: true,
140417
- value: await resolveSandboxValue(argument.value)
140418
- };
140419
- } finally {
140420
- leaveAwait();
140421
140595
  }
140596
+ return { ok: true };
140422
140597
  }
140423
- async function executeClosure(node, args, thisValue, context, evaluateNode3) {
140424
- const scope = await createClosureScope(node, args, thisValue, context, evaluateNode3);
140425
- const result = await evaluateNode3(node.body, {
140426
- ...context,
140427
- scope
140428
- });
140429
- if (result.kind === "error") {
140430
- throw result.error;
140598
+ async function bindMemberExpression(pattern, value, scope, context) {
140599
+ const object = await context.evaluate(pattern.object);
140600
+ if (object.kind !== "normal") {
140601
+ return { ok: false, result: object };
140431
140602
  }
140432
- if (result.kind === "throw") {
140433
- throw result.value;
140603
+ if (object.value === null || object.value === void 0) {
140604
+ throw new TypeError("Cannot assign properties of null or undefined.");
140434
140605
  }
140435
- if (isBlockBody(node.body)) {
140436
- return result.hasValue ? result.value : void 0;
140606
+ if (!isIndexableValue(object.value)) {
140607
+ throw new TypeError("Assignment expressions require a sandbox object property.");
140437
140608
  }
140438
- return result.value;
140609
+ const property = pattern.computed ? await evaluateProperty(pattern.property, context) : { ok: true, value: getStaticPropertyName(pattern.property) };
140610
+ if (!property.ok) {
140611
+ return property;
140612
+ }
140613
+ setProperty(object.value, property.value, value);
140614
+ return { ok: true };
140439
140615
  }
140440
- async function createClosureScope(node, args, thisValue, context, evaluateNode3) {
140441
- const scope = context.scope.child({}, { functionBoundary: true });
140442
- if (node.type !== "ArrowFunctionExpression") {
140443
- scope.declare("this", "const", thisValue);
140444
- context.budget.allocateArrayLength(args.length);
140445
- scope.declare("arguments", "let", createSandboxArguments(args));
140616
+ async function evaluatePatternKey(property, context) {
140617
+ return property.computed ? evaluateProperty(property.key, context) : { ok: true, value: getStaticPropertyName(property.key) };
140618
+ }
140619
+ async function evaluateProperty(property, context) {
140620
+ const result = await context.evaluate(property);
140621
+ if (result.kind !== "normal") {
140622
+ return { ok: false, result };
140446
140623
  }
140447
- await bindParameters(node.params, args, scope, context, evaluateNode3);
140448
- hoistVarDeclarations(node.body, scope);
140449
- return scope;
140624
+ if (typeof result.value !== "string" && typeof result.value !== "number") {
140625
+ throw new TypeError("Computed property access requires a string or number key.");
140626
+ }
140627
+ return { ok: true, value: result.value };
140450
140628
  }
140451
- function isBlockBody(body) {
140452
- return body.type === "BlockStatement";
140629
+ function getStaticPropertyName(property) {
140630
+ if (property.type === "Identifier") {
140631
+ return property.name;
140632
+ }
140633
+ if (property.type === "StringLiteral" || property.type === "NumericLiteral") {
140634
+ return property.value;
140635
+ }
140636
+ throw new TypeError(`Unsupported static property node '${property.type}'.`);
140453
140637
  }
140454
- async function bindParameters(params, args, scope, context, evaluateNode3) {
140455
- for (const param of params) {
140456
- for (const name of getParameterBindingNames(param)) {
140457
- scope.predeclare(name, "let");
140458
- }
140638
+ function getArrayPatternValues(value) {
140639
+ if (Array.isArray(value)) {
140640
+ return value;
140459
140641
  }
140460
- for (let index = 0; index < params.length; index += 1) {
140461
- const param = params[index];
140462
- if (param.type === "RestElement") {
140463
- const rest = args.slice(index);
140464
- context.budget.allocateArrayLength(rest.length);
140465
- const binding2 = await bindPattern(param, rest, { kind: "let" }, scope, {
140466
- evaluate: (defaultNode) => evaluateNode3(defaultNode, { ...context, scope })
140467
- });
140468
- if (!binding2.ok) {
140469
- if (binding2.result.kind === "error") {
140470
- throw binding2.result.error;
140471
- }
140472
- if (binding2.result.kind === "throw") {
140473
- throw binding2.result.value;
140474
- }
140475
- }
140476
- return;
140642
+ if (typeof value === "string") {
140643
+ return Array.from(value);
140644
+ }
140645
+ if (isSandboxMap(value)) {
140646
+ return Array.from(value.entries, ([key3, entry]) => [key3, entry]);
140647
+ }
140648
+ if (isSandboxSet(value)) {
140649
+ return [...value.values];
140650
+ }
140651
+ if (isIterableValue(value)) {
140652
+ throw new TypeError(
140653
+ `Array destructuring declarations support only arrays and strings; received ${describeRuntimeValue(value)}.`
140654
+ );
140655
+ }
140656
+ throw new TypeError("Array destructuring declarations require an array or string iterable.");
140657
+ }
140658
+ function isIterableValue(value) {
140659
+ return typeof value === "object" && value !== null && Symbol.iterator in value && typeof value[Symbol.iterator] === "function";
140660
+ }
140661
+ function describeRuntimeValue(value) {
140662
+ if (value === null) return "null";
140663
+ if (value === void 0) return "undefined";
140664
+ if (typeof value === "object") return value.constructor?.name ?? "Object";
140665
+ return typeof value;
140666
+ }
140667
+ function copyObjectRestValue(value, excludedKeys) {
140668
+ const rest = /* @__PURE__ */ Object.create(null);
140669
+ for (const [key3, entryValue] of Object.entries(value)) {
140670
+ if (!excludedKeys.has(key3)) {
140671
+ defineProperty(rest, key3, entryValue);
140477
140672
  }
140478
- const binding = await bindPattern(param, args[index], { kind: "let" }, scope, {
140479
- evaluate: (defaultNode) => evaluateNode3(defaultNode, { ...context, scope })
140480
- });
140481
- if (!binding.ok) {
140482
- if (binding.result.kind === "error") {
140483
- throw binding.result.error;
140484
- }
140485
- if (binding.result.kind === "throw") {
140486
- throw binding.result.value;
140487
- }
140673
+ }
140674
+ return rest;
140675
+ }
140676
+ function isIndexableValue(value) {
140677
+ return typeof value === "object" && value !== null;
140678
+ }
140679
+ function setProperty(target, property, value) {
140680
+ if (Array.isArray(target)) {
140681
+ const key3 = String(property);
140682
+ if (key3 === "length" || isArrayIndexKey2(key3)) {
140683
+ target[key3] = value;
140684
+ return;
140488
140685
  }
140686
+ defineProperty(target, key3, value);
140687
+ return;
140489
140688
  }
140689
+ defineProperty(target, String(property), value);
140490
140690
  }
140491
- function getParameterBindingNames(pattern) {
140492
- switch (pattern.type) {
140493
- case "Identifier":
140494
- return [pattern.name];
140495
- case "MemberExpression":
140496
- return [];
140497
- case "AssignmentPattern":
140498
- return getParameterBindingNames(pattern.left);
140499
- case "RestElement":
140500
- return getParameterBindingNames(pattern.argument);
140501
- case "ArrayPattern":
140502
- return pattern.elements.flatMap(
140503
- (element) => element === null ? [] : getParameterBindingNames(element)
140504
- );
140505
- case "ObjectPattern":
140506
- return pattern.properties.flatMap(
140507
- (property) => property.type === "RestElement" ? getParameterBindingNames(property) : getParameterBindingNames(property.value)
140508
- );
140691
+ function isArrayIndexKey2(value) {
140692
+ if (value === "") {
140693
+ return false;
140509
140694
  }
140695
+ const index = Number(value);
140696
+ return Number.isInteger(index) && index >= 0 && index < 4294967295 && String(index) === value;
140510
140697
  }
140511
- function normalizeClosureResult(result, budget) {
140512
- if (isSandboxPromise(result)) {
140513
- return result;
140514
- }
140515
- return createSandboxPromise(resolveSandboxValue(result, { budget }));
140698
+ function defineProperty(target, key3, value) {
140699
+ Object.defineProperty(target, key3, {
140700
+ configurable: true,
140701
+ enumerable: true,
140702
+ value,
140703
+ writable: true
140704
+ });
140516
140705
  }
140517
- var init_async = __esm({
140518
- "packages/safejs/src/interp/async.ts"() {
140706
+ var init_patterns = __esm({
140707
+ "packages/safejs/src/interp/patterns.ts"() {
140519
140708
  "use strict";
140520
- init_generator();
140521
- init_otel2();
140522
- init_patterns();
140523
- init_promise();
140524
- init_var_hoist();
140525
140709
  init_values();
140526
140710
  }
140527
140711
  });
140528
140712
 
140529
- // packages/safejs/src/interp/exceptions.ts
140530
- async function evaluateThrowStatement(node, context, evaluateNode3) {
140531
- const argument = await evaluateNode3(node.argument, context);
140532
- if (argument.kind !== "normal") {
140533
- return argument;
140534
- }
140535
- return {
140536
- kind: "throw",
140537
- hasValue: true,
140538
- span: node.span,
140539
- stackFrames: context.callStack,
140540
- value: argument.value
140541
- };
140542
- }
140543
- async function evaluateTryStatement(node, context, evaluateNode3) {
140544
- let fatalBudgetError;
140545
- let tryResult;
140546
- try {
140547
- tryResult = await evaluateBlockCompletion(node.block, context, evaluateNode3);
140548
- } catch (error3) {
140549
- if (!isBudgetExceeded(error3) || node.finalizer === void 0) {
140550
- throw error3;
140713
+ // packages/safejs/src/interp/var-hoist.ts
140714
+ function hoistVarDeclarations(node, scope) {
140715
+ if (node.type === "BlockStatement") {
140716
+ for (const statement of node.body) {
140717
+ hoistVarStatement(statement, scope);
140551
140718
  }
140552
- fatalBudgetError = error3;
140553
- tryResult = {
140554
- kind: "throw",
140555
- hasValue: true,
140556
- value: void 0
140557
- };
140558
- }
140559
- const tryOrCatchResult = fatalBudgetError === void 0 && tryResult.kind === "throw" && node.handler !== void 0 ? await evaluateCatchClause(node.handler, tryResult.value, context, evaluateNode3) : tryResult;
140560
- if (node.finalizer === void 0 || tryOrCatchResult.kind === "error") {
140561
- return tryOrCatchResult;
140562
- }
140563
- const finalizerResult = fatalBudgetError?.budget === "deadline" ? await evaluateWithoutDeadlineChecks(
140564
- context,
140565
- () => evaluateBlockCompletion(node.finalizer, context, evaluateNode3)
140566
- ) : await evaluateBlockCompletion(node.finalizer, context, evaluateNode3);
140567
- if (fatalBudgetError !== void 0) {
140568
- throw fatalBudgetError;
140569
- }
140570
- if (finalizerResult.kind === "normal") {
140571
- return tryOrCatchResult;
140572
- }
140573
- return finalizerResult;
140574
- }
140575
- function createCapturedException(reason, stackFrames) {
140576
- return {
140577
- reason,
140578
- stackFrames,
140579
- [capturedExceptionBrand]: true
140580
- };
140581
- }
140582
- function isCapturedException(value) {
140583
- return typeof value === "object" && value !== null && capturedExceptionBrand in value;
140584
- }
140585
- function coerceThrownValue(reason, budget, stackFrames, span) {
140586
- if (isSubsetErrorValue(reason)) {
140587
- attachErrorSpan(reason, readErrorSpan(reason) ?? span);
140588
- return reason;
140589
- }
140590
- if (reason instanceof Error) {
140591
- return createSubsetErrorValue(reason.name || "Error", reason.message, stackFrames, budget, {
140592
- chargeBudget: false,
140593
- cause: readErrorCause(reason),
140594
- span
140595
- });
140719
+ return;
140596
140720
  }
140597
- if (isErrorLikeValue(reason)) {
140598
- return createSubsetErrorValue(reason.name || "Error", reason.message, stackFrames, budget, {
140599
- chargeBudget: false,
140600
- cause: readErrorCause(reason),
140601
- span
140602
- });
140721
+ switch (node.type) {
140722
+ case "VariableDeclaration":
140723
+ case "IfStatement":
140724
+ case "ForStatement":
140725
+ case "ForInStatement":
140726
+ case "ForOfStatement":
140727
+ case "WhileStatement":
140728
+ case "DoWhileStatement":
140729
+ case "TryStatement":
140730
+ case "SwitchStatement":
140731
+ case "ExportNamedDeclaration":
140732
+ hoistVarStatement(node, scope);
140733
+ return;
140734
+ default:
140735
+ return;
140603
140736
  }
140604
- return deepCopyToSandbox(reason);
140605
140737
  }
140606
- function surfaceThrownValue(reason, budget, stackFrames = [], span) {
140607
- if (reason instanceof HostCallResumabilityError) {
140608
- throw reason;
140609
- }
140610
- if (isSubsetErrorValue(reason)) {
140611
- normalizeSurfacedSubsetError(reason, budget, stackFrames, span);
140612
- return reason;
140613
- }
140614
- if (reason instanceof Error) {
140615
- const error3 = createSubsetErrorValue(
140616
- reason.name || "Error",
140617
- reason.message,
140618
- stackFrames,
140619
- budget,
140620
- {
140621
- cause: reason,
140622
- chargeBudget: false,
140623
- span
140738
+ function hoistVarStatement(statement, scope) {
140739
+ switch (statement.type) {
140740
+ case "VariableDeclaration":
140741
+ declareVarBindings(statement, scope);
140742
+ return;
140743
+ case "BlockStatement":
140744
+ hoistVarDeclarations(statement, scope);
140745
+ return;
140746
+ case "IfStatement":
140747
+ hoistVarStatement(statement.consequent, scope);
140748
+ if (statement.alternate !== void 0) {
140749
+ hoistVarStatement(statement.alternate, scope);
140624
140750
  }
140625
- );
140626
- normalizeSurfacedSubsetError(error3, budget, stackFrames, span);
140627
- return error3;
140628
- }
140629
- if (isErrorLikeValue(reason)) {
140630
- const error3 = createSubsetErrorValue(
140631
- reason.name || "Error",
140632
- reason.message,
140633
- stackFrames,
140634
- budget,
140635
- {
140636
- cause: readErrorCause(reason),
140637
- chargeBudget: false,
140638
- span
140751
+ return;
140752
+ case "ForStatement":
140753
+ if (statement.init?.type === "VariableDeclaration") {
140754
+ declareVarBindings(statement.init, scope);
140639
140755
  }
140640
- );
140641
- normalizeSurfacedSubsetError(error3, budget, stackFrames, span);
140642
- return error3;
140643
- }
140644
- return createSubsetErrorValue("Error", describeThrownValue(reason), stackFrames, budget, {
140645
- chargeBudget: false,
140646
- span
140647
- });
140648
- }
140649
- function createSubsetErrorValue(name, message2, stackFrames, budget, options = {}) {
140650
- const resumeChecks = options.chargeBudget === false ? budget.suspendChecks() : void 0;
140651
- try {
140652
- const errorName = budget.allocateString(name === "" ? "Error" : name);
140653
- const errorMessage9 = budget.allocateString(coerceErrorMessage(message2));
140654
- const header = errorMessage9 === "" ? errorName : `${errorName}: ${errorMessage9}`;
140655
- const stack = budget.allocateString([header, ...[...stackFrames].reverse()].join("\n"));
140656
- const error3 = {
140657
- name: errorName,
140658
- message: errorMessage9,
140659
- stack
140660
- };
140661
- defineSandboxErrorMetadata(error3, errorName);
140662
- attachErrorSpan(error3, options.span);
140663
- attachWrappedErrorCause(error3, options.cause);
140664
- return error3;
140665
- } finally {
140666
- resumeChecks?.();
140756
+ hoistVarStatement(statement.body, scope);
140757
+ return;
140758
+ case "ForInStatement":
140759
+ case "ForOfStatement":
140760
+ if (statement.left.type === "VariableDeclaration") {
140761
+ declareVarBindings(statement.left, scope);
140762
+ }
140763
+ hoistVarStatement(statement.body, scope);
140764
+ return;
140765
+ case "WhileStatement":
140766
+ case "DoWhileStatement":
140767
+ hoistVarStatement(statement.body, scope);
140768
+ return;
140769
+ case "TryStatement":
140770
+ hoistVarDeclarations(statement.block, scope);
140771
+ if (statement.handler !== void 0) {
140772
+ hoistVarDeclarations(statement.handler.body, scope);
140773
+ }
140774
+ if (statement.finalizer !== void 0) {
140775
+ hoistVarDeclarations(statement.finalizer, scope);
140776
+ }
140777
+ return;
140778
+ case "SwitchStatement":
140779
+ for (const switchCase of statement.cases) {
140780
+ for (const consequent of switchCase.consequent) {
140781
+ hoistVarStatement(consequent, scope);
140782
+ }
140783
+ }
140784
+ return;
140785
+ case "ExportNamedDeclaration":
140786
+ hoistVarStatement(statement.declaration, scope);
140787
+ return;
140788
+ case "FunctionDeclaration":
140789
+ case "ExportDefaultDeclaration":
140790
+ case "ImportDeclaration":
140791
+ case "BreakStatement":
140792
+ case "ContinueStatement":
140793
+ case "EmptyStatement":
140794
+ case "ExpressionStatement":
140795
+ case "ReturnStatement":
140796
+ case "ThrowStatement":
140797
+ return;
140667
140798
  }
140668
140799
  }
140669
- function isSandboxErrorConstructorInstance(value, name) {
140670
- return isSandboxErrorObject(value) && value[sandboxErrorBrand].chain.includes(name);
140671
- }
140672
- function defineSandboxErrorMetadata(error3, name) {
140673
- const metadataName = toSandboxErrorName(name);
140674
- Object.defineProperty(error3, sandboxErrorBrand, {
140675
- enumerable: false,
140676
- value: {
140677
- chain: metadataName === "Error" ? ["Error"] : [metadataName, "Error"],
140678
- name: metadataName
140800
+ function declareVarBindings(declaration, scope) {
140801
+ if (declaration.kind !== "var") {
140802
+ return;
140803
+ }
140804
+ for (const declarator of declaration.declarations) {
140805
+ for (const name of getPatternBindingNames2(declarator.id)) {
140806
+ scope.declareVar(name);
140679
140807
  }
140680
- });
140681
- }
140682
- function toSandboxErrorName(name) {
140683
- return isSandboxErrorName(name) ? name : "Error";
140684
- }
140685
- function isSandboxErrorName(name) {
140686
- return sandboxErrorNames.includes(name);
140808
+ }
140687
140809
  }
140688
- function isSandboxErrorObject(value) {
140689
- return typeof value === "object" && value !== null && sandboxErrorBrand in value;
140810
+ function getPatternBindingNames2(pattern) {
140811
+ switch (pattern.type) {
140812
+ case "Identifier":
140813
+ return [pattern.name];
140814
+ case "ArrayPattern":
140815
+ return pattern.elements.flatMap(
140816
+ (element) => element === null || element.type === "MemberExpression" ? [] : getNestedPatternBindingNames(element)
140817
+ );
140818
+ case "ObjectPattern":
140819
+ return pattern.properties.flatMap(
140820
+ (property) => property.type === "RestElement" ? property.argument.type === "MemberExpression" ? [] : getNestedPatternBindingNames(property.argument) : property.value.type === "MemberExpression" ? [] : getNestedPatternBindingNames(property.value)
140821
+ );
140822
+ }
140690
140823
  }
140691
- function isSubsetErrorValue(value) {
140692
- if (typeof value !== "object" || value === null) {
140693
- return false;
140824
+ function getNestedPatternBindingNames(pattern) {
140825
+ switch (pattern.type) {
140826
+ case "Identifier":
140827
+ return [pattern.name];
140828
+ case "AssignmentPattern":
140829
+ return pattern.left.type === "MemberExpression" ? [] : getNestedPatternBindingNames(pattern.left);
140830
+ case "RestElement":
140831
+ return pattern.argument.type === "MemberExpression" ? [] : getNestedPatternBindingNames(pattern.argument);
140832
+ case "ArrayPattern":
140833
+ return pattern.elements.flatMap(
140834
+ (element) => element === null || element.type === "MemberExpression" ? [] : getNestedPatternBindingNames(element)
140835
+ );
140836
+ case "ObjectPattern":
140837
+ return pattern.properties.flatMap(
140838
+ (property) => property.type === "RestElement" ? property.argument.type === "MemberExpression" ? [] : getNestedPatternBindingNames(property.argument) : property.value.type === "MemberExpression" ? [] : getNestedPatternBindingNames(property.value)
140839
+ );
140694
140840
  }
140695
- const prototype = Object.getPrototypeOf(value);
140696
- return (prototype === Object.prototype || prototype === null) && typeof value.name === "string" && typeof value.message === "string" && typeof value.stack === "string";
140697
140841
  }
140698
- function normalizeSurfacedSubsetError(error3, budget, stackFrames, span) {
140699
- const resumeChecks = budget.suspendChecks();
140700
- try {
140701
- const name = budget.allocateString(toSandboxErrorName(readErrorName(error3)));
140702
- const message2 = budget.allocateString(readSurfacedErrorMessage(error3, name));
140703
- const frames = readSandboxStackFrames(error3.stack);
140704
- error3.name = name;
140705
- error3.message = message2;
140706
- error3.stack = budget.allocateString(
140707
- formatErrorStack(name, message2, frames.length > 0 ? frames : [...stackFrames].reverse())
140708
- );
140709
- attachErrorSpan(error3, readErrorSpan(error3) ?? span);
140710
- } finally {
140711
- resumeChecks();
140842
+ var init_var_hoist = __esm({
140843
+ "packages/safejs/src/interp/var-hoist.ts"() {
140844
+ "use strict";
140712
140845
  }
140846
+ });
140847
+
140848
+ // packages/safejs/src/interp/async.ts
140849
+ function emitResumeBreakpoint(context, breakpoint) {
140850
+ context.onYield?.({
140851
+ ...breakpoint,
140852
+ snapshot: () => context.snapshot?.(context.scope) ?? context.scope.snapshot()
140853
+ });
140713
140854
  }
140714
- function readErrorName(error3) {
140715
- return typeof error3.name === "string" && error3.name.length > 0 ? error3.name : "Error";
140855
+ async function evaluateArrowFunctionExpression(node, context, evaluateNode3) {
140856
+ return {
140857
+ kind: "normal",
140858
+ hasValue: true,
140859
+ value: createInterpretedClosure(node, context, evaluateNode3)
140860
+ };
140716
140861
  }
140717
- function readSurfacedErrorMessage(error3, name) {
140718
- const message2 = typeof error3.message === "string" ? error3.message : "";
140719
- if (message2 === "") {
140720
- return `${name} thrown`;
140721
- }
140722
- if (message2 === "[object Object]") {
140723
- return `${name} thrown with non-string message`;
140862
+ async function evaluateFunctionExpression(node, context, evaluateNode3) {
140863
+ if (node.id === void 0) {
140864
+ return {
140865
+ kind: "normal",
140866
+ hasValue: true,
140867
+ value: createInterpretedClosure(node, context, evaluateNode3)
140868
+ };
140724
140869
  }
140725
- return message2;
140870
+ const wrapperScope = context.scope.child();
140871
+ const closure = createInterpretedClosure(node, { ...context, scope: wrapperScope }, evaluateNode3);
140872
+ wrapperScope.declare(node.id.name, "const", closure);
140873
+ return {
140874
+ kind: "normal",
140875
+ hasValue: true,
140876
+ value: closure
140877
+ };
140726
140878
  }
140727
- function readSandboxStackFrames(stack) {
140728
- if (typeof stack !== "string") {
140729
- return [];
140879
+ function createInterpretedClosure(node, context, evaluateNode3) {
140880
+ if (node.type !== "ArrowFunctionExpression" && node.generator) {
140881
+ return createGeneratorClosure(node, context, evaluateNode3);
140730
140882
  }
140731
- const [, ...frames] = stack.split("\n");
140732
- return frames;
140883
+ const construct = node.type !== "ArrowFunctionExpression" && !(node.type === "FunctionExpression" && node.method === true) && !node.async ? async (args, callContext) => {
140884
+ const thisValue = {};
140885
+ const result = await executeClosure(
140886
+ node,
140887
+ args,
140888
+ thisValue,
140889
+ {
140890
+ ...context,
140891
+ callStack: [...callContext?.stack ?? context.callStack]
140892
+ },
140893
+ evaluateNode3
140894
+ );
140895
+ return isConstructResult(result) ? result : thisValue;
140896
+ } : void 0;
140897
+ return createSandboxClosure({
140898
+ ...node.async ? { async: true } : {},
140899
+ ...node.type === "FunctionDeclaration" || node.type === "FunctionExpression" ? node.id === void 0 ? {} : { name: node.id.name } : {},
140900
+ ...construct === void 0 ? {} : { construct },
140901
+ retainedValues: () => context.scope.retainedValues(),
140902
+ call: (args, callContext) => {
140903
+ const invocationContext = {
140904
+ ...context,
140905
+ callStack: [...callContext?.stack ?? context.callStack]
140906
+ };
140907
+ if (!node.async)
140908
+ return executeClosure(node, args, callContext?.thisValue, invocationContext, evaluateNode3);
140909
+ let completePrefix;
140910
+ const synchronousPrefix = new Promise((resolve17) => {
140911
+ completePrefix = resolve17;
140912
+ });
140913
+ const execution = runAsyncPrefix(
140914
+ () => executeClosure(
140915
+ node,
140916
+ args,
140917
+ callContext?.thisValue,
140918
+ { ...invocationContext, onSuspend: completePrefix },
140919
+ evaluateNode3
140920
+ )
140921
+ );
140922
+ execution.then(completePrefix, completePrefix);
140923
+ return createSandboxPromise(
140924
+ resolveSandboxValue(
140925
+ execution.then(
140926
+ (value) => isSandboxPromise(value) || getThenable(value) !== void 0 ? awaitSandboxValue(value, context.signal) : value
140927
+ ),
140928
+ { budget: context.budget }
140929
+ ),
140930
+ { synchronousPrefix }
140931
+ );
140932
+ }
140933
+ });
140733
140934
  }
140734
- function isErrorLikeValue(value) {
140735
- return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.message === "string";
140935
+ function createGeneratorClosure(node, context, evaluateNode3) {
140936
+ return createSandboxClosure({
140937
+ ...node.id === void 0 ? {} : { name: node.id.name },
140938
+ retainedValues: () => context.scope.retainedValues(),
140939
+ call: async (args, callContext) => {
140940
+ const closureContext = {
140941
+ ...context,
140942
+ callStack: [...callContext?.stack ?? context.callStack]
140943
+ };
140944
+ const scope = await createClosureScope(
140945
+ node,
140946
+ args,
140947
+ callContext?.thisValue,
140948
+ closureContext,
140949
+ evaluateNode3
140950
+ );
140951
+ const channel = createGeneratorChannel(async (generatorYield) => {
140952
+ const result = await evaluateNode3(node.body, {
140953
+ ...closureContext,
140954
+ generatorYield: (value, yieldNodeId) => {
140955
+ generator.state = "suspended";
140956
+ return generatorYield(value, yieldNodeId);
140957
+ },
140958
+ scope
140959
+ });
140960
+ if (result.kind === "error") {
140961
+ throw result.error;
140962
+ }
140963
+ if (result.kind === "throw") {
140964
+ throw result.value;
140965
+ }
140966
+ return result.hasValue ? result.value : void 0;
140967
+ });
140968
+ const generator = createSandboxGenerator(channel);
140969
+ return generator;
140970
+ }
140971
+ });
140736
140972
  }
140737
- function coerceErrorMessage(message2) {
140738
- if (message2 === void 0) {
140739
- return "";
140740
- }
140741
- if (Array.isArray(message2)) {
140742
- return message2.map((value) => value === null || value === void 0 ? "" : String(value)).join(",");
140743
- }
140744
- if (typeof message2 === "object" && message2 !== null) {
140745
- return "[object Object]";
140746
- }
140747
- return String(message2);
140973
+ function isConstructResult(value) {
140974
+ return typeof value === "object" && value !== null;
140748
140975
  }
140749
- async function evaluateWithoutDeadlineChecks(context, evaluate) {
140750
- const resumeDeadlineChecks = context.budget.suspendDeadlineChecks();
140976
+ async function evaluateAwaitExpression(node, context, evaluateNode3) {
140977
+ const replayState = context.captureReplayState?.();
140978
+ const argument = await evaluateNode3(node.argument, context);
140979
+ if (argument.kind !== "normal") {
140980
+ return argument;
140981
+ }
140982
+ context.onSuspend?.();
140983
+ emitResumeBreakpoint(context, {
140984
+ kind: "await",
140985
+ replayState,
140986
+ nodeId: node.nodeId,
140987
+ ...getBoundOtelSpan(argument.value) === void 0 ? {} : { otelSpan: getBoundOtelSpan(argument.value) },
140988
+ span: node.span
140989
+ });
140990
+ const leaveAwait = context.budget.enterAwait();
140751
140991
  try {
140752
- return await evaluate();
140992
+ return {
140993
+ kind: "normal",
140994
+ hasValue: true,
140995
+ value: await suspendJob(awaitSandboxValue(argument.value, context.signal))
140996
+ };
140753
140997
  } finally {
140754
- resumeDeadlineChecks();
140998
+ leaveAwait();
140755
140999
  }
140756
141000
  }
140757
- function isBudgetExceeded(error3) {
140758
- return error3 instanceof SandboxError && error3.code === "budgetExceeded";
140759
- }
140760
- async function evaluateCatchClause(node, thrownValue, context, evaluateNode3) {
140761
- const scope = context.scope.child();
140762
- const catchContext = {
141001
+ async function executeClosure(node, args, thisValue, context, evaluateNode3) {
141002
+ const scope = await createClosureScope(node, args, thisValue, context, evaluateNode3);
141003
+ const result = await evaluateNode3(node.body, {
140763
141004
  ...context,
140764
141005
  scope
140765
- };
140766
- if (node.param !== void 0) {
140767
- const binding = await bindPattern2(node.param, thrownValue, catchContext, evaluateNode3);
140768
- if (!binding.ok) {
140769
- return binding.result;
140770
- }
141006
+ });
141007
+ if (result.kind === "error") {
141008
+ throw result.error;
141009
+ }
141010
+ if (result.kind === "throw") {
141011
+ throw result.value;
140771
141012
  }
140772
- return evaluateBlockCompletion(node.body, catchContext, evaluateNode3);
141013
+ if (isBlockBody(node.body)) {
141014
+ return result.hasValue ? result.value : void 0;
141015
+ }
141016
+ return result.value;
140773
141017
  }
140774
- async function evaluateBlockCompletion(node, context, evaluateNode3) {
140775
- const blockContext = {
140776
- ...context,
140777
- scope: context.scope.child()
140778
- };
140779
- predeclareBlockBindings(node, blockContext.scope);
140780
- let result = {
140781
- kind: "normal",
140782
- hasValue: false,
140783
- value: void 0
140784
- };
140785
- for (const statement of node.body) {
140786
- result = await evaluateNode3(statement, blockContext);
140787
- if (result.kind !== "normal") {
140788
- return result;
140789
- }
141018
+ async function createClosureScope(node, args, thisValue, context, evaluateNode3) {
141019
+ const scope = context.scope.child({}, { functionBoundary: true });
141020
+ if (node.type !== "ArrowFunctionExpression") {
141021
+ scope.declare("this", "const", thisValue);
141022
+ context.budget.allocateArrayLength(args.length);
141023
+ scope.declare("arguments", "let", createSandboxArguments(args));
140790
141024
  }
140791
- return result;
141025
+ await bindParameters(node.params, args, scope, context, evaluateNode3);
141026
+ hoistVarDeclarations(node.body, scope);
141027
+ return scope;
140792
141028
  }
140793
- function predeclareBlockBindings(node, scope) {
140794
- const names = /* @__PURE__ */ new Set();
140795
- for (const statement of node.body) {
140796
- if (statement.type !== "VariableDeclaration" || statement.kind === "var") {
140797
- continue;
141029
+ function isBlockBody(body) {
141030
+ return body.type === "BlockStatement";
141031
+ }
141032
+ async function bindParameters(params, args, scope, context, evaluateNode3) {
141033
+ for (const param of params) {
141034
+ for (const name of getParameterBindingNames(param)) {
141035
+ scope.predeclare(name, "let");
140798
141036
  }
140799
- for (const name of getDeclarationBindingNames(statement)) {
140800
- if (names.has(name) || scope.hasOwnBinding(name)) {
140801
- throw new Error(`Cannot redeclare binding '${name}' in the same scope.`);
141037
+ }
141038
+ for (let index = 0; index < params.length; index += 1) {
141039
+ const param = params[index];
141040
+ if (param.type === "RestElement") {
141041
+ const rest = args.slice(index);
141042
+ context.budget.allocateArrayLength(rest.length);
141043
+ const binding2 = await bindPattern2(param, rest, { kind: "let" }, scope, {
141044
+ evaluate: (defaultNode) => evaluateNode3(defaultNode, { ...context, scope })
141045
+ });
141046
+ if (!binding2.ok) {
141047
+ if (binding2.result.kind === "error") {
141048
+ throw binding2.result.error;
141049
+ }
141050
+ if (binding2.result.kind === "throw") {
141051
+ throw binding2.result.value;
141052
+ }
141053
+ }
141054
+ return;
141055
+ }
141056
+ const binding = await bindPattern2(param, args[index], { kind: "let" }, scope, {
141057
+ evaluate: (defaultNode) => evaluateNode3(defaultNode, { ...context, scope })
141058
+ });
141059
+ if (!binding.ok) {
141060
+ if (binding.result.kind === "error") {
141061
+ throw binding.result.error;
141062
+ }
141063
+ if (binding.result.kind === "throw") {
141064
+ throw binding.result.value;
140802
141065
  }
140803
- names.add(name);
140804
- scope.predeclare(name, statement.kind);
140805
141066
  }
140806
141067
  }
140807
141068
  }
140808
- function getDeclarationBindingNames(node) {
140809
- return node.declarations.flatMap((declarator) => getPatternBindingNames2(declarator.id));
140810
- }
140811
- function getPatternBindingNames2(pattern) {
141069
+ function getParameterBindingNames(pattern) {
140812
141070
  switch (pattern.type) {
140813
141071
  case "Identifier":
140814
141072
  return [pattern.name];
140815
141073
  case "MemberExpression":
140816
141074
  return [];
140817
141075
  case "AssignmentPattern":
140818
- return getPatternBindingNames2(pattern.left);
141076
+ return getParameterBindingNames(pattern.left);
141077
+ case "RestElement":
141078
+ return getParameterBindingNames(pattern.argument);
140819
141079
  case "ArrayPattern":
140820
141080
  return pattern.elements.flatMap(
140821
- (element) => element === null ? [] : getPatternBindingNames2(element)
141081
+ (element) => element === null ? [] : getParameterBindingNames(element)
140822
141082
  );
140823
141083
  case "ObjectPattern":
140824
141084
  return pattern.properties.flatMap(
140825
- (property) => property.type === "RestElement" ? getPatternBindingNames2(property) : getPatternBindingNames2(property.value)
141085
+ (property) => property.type === "RestElement" ? getParameterBindingNames(property) : getParameterBindingNames(property.value)
140826
141086
  );
140827
- case "RestElement":
140828
- return getPatternBindingNames2(pattern.argument);
140829
- }
140830
- }
140831
- async function bindPattern2(pattern, value, context, evaluateNode3) {
140832
- switch (pattern.type) {
140833
- case "Identifier":
140834
- context.scope.declare(pattern.name, "let", value);
140835
- return { ok: true };
140836
- case "MemberExpression":
140837
- throw new TypeError("Catch bindings do not support member expressions.");
140838
- case "AssignmentPattern":
140839
- return bindAssignmentPattern2(pattern, value, context, evaluateNode3);
140840
- case "ArrayPattern":
140841
- return bindArrayPattern2(pattern, value, context, evaluateNode3);
140842
- case "ObjectPattern":
140843
- return bindObjectPattern2(pattern, value, context, evaluateNode3);
140844
- case "RestElement":
140845
- return bindPattern2(pattern.argument, value, context, evaluateNode3);
140846
- }
140847
- }
140848
- async function bindAssignmentPattern2(pattern, value, context, evaluateNode3) {
140849
- let nextValue = value;
140850
- if (nextValue === void 0) {
140851
- const defaultValue = await evaluateNode3(pattern.right, context);
140852
- if (defaultValue.kind !== "normal") {
140853
- return {
140854
- ok: false,
140855
- result: defaultValue
140856
- };
140857
- }
140858
- nextValue = defaultValue.value;
140859
- }
140860
- return bindPattern2(pattern.left, nextValue, context, evaluateNode3);
140861
- }
140862
- async function bindArrayPattern2(pattern, value, context, evaluateNode3) {
140863
- if (!Array.isArray(value)) {
140864
- throw new TypeError("Array catch bindings require an array value.");
140865
- }
140866
- for (let index = 0; index < pattern.elements.length; index += 1) {
140867
- const element = pattern.elements[index];
140868
- if (element === null) {
140869
- continue;
140870
- }
140871
- const elementValue = element.type === "RestElement" ? value.slice(index) : value[index];
140872
- const binding = await bindPattern2(element, elementValue, context, evaluateNode3);
140873
- if (!binding.ok) {
140874
- return binding;
140875
- }
140876
- }
140877
- return { ok: true };
140878
- }
140879
- async function bindObjectPattern2(pattern, value, context, evaluateNode3) {
140880
- if (typeof value !== "object" && !Array.isArray(value) || value === null) {
140881
- throw new TypeError("Object catch bindings require a non-null object value.");
140882
- }
140883
- const excludedKeys = /* @__PURE__ */ new Set();
140884
- for (const property of pattern.properties) {
140885
- if (property.type === "RestElement") {
140886
- const restValue = copyObjectRest(value, excludedKeys);
140887
- const binding2 = await bindPattern2(property, restValue, context, evaluateNode3);
140888
- if (!binding2.ok) {
140889
- return binding2;
140890
- }
140891
- continue;
140892
- }
140893
- const key3 = await resolvePatternPropertyKey(property, context, evaluateNode3);
140894
- if (!key3.ok) {
140895
- return key3;
140896
- }
140897
- excludedKeys.add(String(key3.value));
140898
- const binding = await bindPattern2(
140899
- property.value,
140900
- getObjectPatternValue(value, key3.value),
140901
- context,
140902
- evaluateNode3
140903
- );
140904
- if (!binding.ok) {
140905
- return binding;
140906
- }
140907
- }
140908
- return { ok: true };
140909
- }
140910
- async function resolvePatternPropertyKey(property, context, evaluateNode3) {
140911
- if (!property.computed) {
140912
- return {
140913
- ok: true,
140914
- value: getStaticPropertyKey2(property.key)
140915
- };
140916
141087
  }
140917
- const computedKey = await evaluateNode3(property.key, context);
140918
- if (computedKey.kind !== "normal") {
140919
- return {
140920
- ok: false,
140921
- result: computedKey
140922
- };
140923
- }
140924
- if (typeof computedKey.value !== "string" && typeof computedKey.value !== "number") {
140925
- throw new TypeError("Computed catch binding keys must evaluate to a string or number.");
140926
- }
140927
- return {
140928
- ok: true,
140929
- value: computedKey.value
140930
- };
140931
- }
140932
- function getStaticPropertyKey2(property) {
140933
- switch (property.type) {
140934
- case "Identifier":
140935
- return property.name;
140936
- case "StringLiteral":
140937
- case "NumericLiteral":
140938
- return property.value;
140939
- default:
140940
- throw new TypeError(`Unsupported catch binding property key '${property.type}'.`);
140941
- }
140942
- }
140943
- function getObjectPatternValue(value, key3) {
140944
- return value[key3];
140945
141088
  }
140946
- function copyObjectRest(value, excludedKeys) {
140947
- const rest = /* @__PURE__ */ Object.create(null);
140948
- for (const [key3, entryValue] of Object.entries(value)) {
140949
- if (excludedKeys.has(key3)) {
140950
- continue;
140951
- }
140952
- rest[key3] = entryValue;
141089
+ function normalizeClosureResult(result, budget) {
141090
+ if (isSandboxPromise(result)) {
141091
+ return result;
140953
141092
  }
140954
- return rest;
141093
+ return createSandboxPromise(resolveSandboxValue(result, { budget }));
140955
141094
  }
140956
- var capturedExceptionBrand, sandboxErrorBrand, sandboxErrorNames;
140957
- var init_exceptions = __esm({
140958
- "packages/safejs/src/interp/exceptions.ts"() {
141095
+ var init_async = __esm({
141096
+ "packages/safejs/src/interp/async.ts"() {
140959
141097
  "use strict";
140960
- init_shape();
140961
- init_budget2();
140962
- init_host_call();
141098
+ init_generator();
141099
+ init_otel2();
141100
+ init_patterns();
141101
+ init_promise();
141102
+ init_jobs4();
141103
+ init_cancel2();
141104
+ init_var_hoist();
140963
141105
  init_values();
140964
- capturedExceptionBrand = /* @__PURE__ */ Symbol("CapturedException");
140965
- sandboxErrorBrand = /* @__PURE__ */ Symbol("SandboxError");
140966
- sandboxErrorNames = [
140967
- "Error",
140968
- "TypeError",
140969
- "RangeError",
140970
- "ReferenceError",
140971
- "SyntaxError",
140972
- "AbortError",
140973
- "AggregateError",
140974
- "HarnessFailure"
140975
- ];
140976
141106
  }
140977
141107
  });
140978
141108
 
@@ -141832,11 +141962,11 @@ async function stringifyProperty(key3, holder, state, indent = "") {
141832
141962
  if (isStringifyContainer(value)) {
141833
141963
  const toJSON = getOwnDataValue(value, "toJSON");
141834
141964
  if (isSandboxClosure(toJSON)) {
141835
- value = await callStringifyClosure(toJSON, [key3], state);
141965
+ value = await callStringifyClosure(toJSON, [key3], value, state);
141836
141966
  }
141837
141967
  }
141838
141968
  if (state.replacer !== void 0) {
141839
- value = await callStringifyClosure(state.replacer, [key3, toSandboxValue(value)], state);
141969
+ value = await callStringifyClosure(state.replacer, [key3, toSandboxValue(value)], holder, state);
141840
141970
  }
141841
141971
  return stringifyValue3(value, state, indent);
141842
141972
  }
@@ -141856,7 +141986,8 @@ async function stringifyValue3(value, state, indent) {
141856
141986
  if (typeof value === "bigint") {
141857
141987
  throw new TypeError("Do not know how to serialize a BigInt.");
141858
141988
  }
141859
- if (value === void 0 || isSandboxClosure(value) || isSandboxPromise(value)) {
141989
+ if (isSandboxPromise(value)) return "{}";
141990
+ if (value === void 0 || isSandboxClosure(value)) {
141860
141991
  return void 0;
141861
141992
  }
141862
141993
  if (Array.isArray(value)) {
@@ -141914,8 +142045,12 @@ ${indent}}`;
141914
142045
  leaveStringifyObject(value, state);
141915
142046
  }
141916
142047
  }
141917
- async function callStringifyClosure(closure, args, state) {
141918
- return resolveSandboxValue(closure.call(args), { budget: state.budget });
142048
+ async function callStringifyClosure(closure, args, thisValue, state) {
142049
+ const result = await closure.call(args, { stack: [], thisValue });
142050
+ if (isSandboxPromise(result) && result.synchronousPrefix !== void 0) {
142051
+ await result.synchronousPrefix;
142052
+ }
142053
+ return allocateProducedSandboxValue(result, state.budget);
141919
142054
  }
141920
142055
  function enterStringifyObject(value, state) {
141921
142056
  if (state.stack.includes(value)) {
@@ -142011,7 +142146,6 @@ var init_console_json = __esm({
142011
142146
  "packages/safejs/src/interp/globals/console-json.ts"() {
142012
142147
  "use strict";
142013
142148
  init_host_bridge();
142014
- init_promise();
142015
142149
  init_values();
142016
142150
  }
142017
142151
  });
@@ -142505,7 +142639,10 @@ async function arrayFromSandboxValues(args, budget) {
142505
142639
  const mappedValues = [];
142506
142640
  for (const [index, value] of values.entries()) {
142507
142641
  const result = await mapFn.call([value, index]);
142508
- mappedValues.push(isSandboxPromise(result) ? await result.promise : result);
142642
+ if (isSandboxPromise(result) && result.synchronousPrefix !== void 0) {
142643
+ await result.synchronousPrefix;
142644
+ }
142645
+ mappedValues.push(result);
142509
142646
  }
142510
142647
  return budgetSandboxValue2(mappedValues, budget);
142511
142648
  }
@@ -143241,10 +143378,7 @@ async function callMapMethod(target, methodName, args, options, stack = []) {
143241
143378
  const entries = [...target.entries];
143242
143379
  for (let index = 0; index < entries.length; index += 1) {
143243
143380
  const [key3, value] = entries[index];
143244
- const result = await options.callClosure(callback, [value, key3, target], stack);
143245
- if (isSandboxPromise(result)) {
143246
- await result.promise;
143247
- }
143381
+ await options.callClosure(callback, [value, key3, target], stack);
143248
143382
  }
143249
143383
  } finally {
143250
143384
  leaveCallback();
@@ -144014,10 +144148,7 @@ async function callSetMethod(target, methodName, args, options, stack = []) {
144014
144148
  const values = [...target.values];
144015
144149
  for (let index = 0; index < values.length; index += 1) {
144016
144150
  const value = values[index];
144017
- const result = await options.callClosure(callback, [value, value, target], stack);
144018
- if (isSandboxPromise(result)) {
144019
- await result.promise;
144020
- }
144151
+ await options.callClosure(callback, [value, value, target], stack);
144021
144152
  }
144022
144153
  } finally {
144023
144154
  leaveCallback();
@@ -144298,7 +144429,7 @@ async function interpret(node, options = {}) {
144298
144429
  peakDataSize: { enumerable: false, value: 0, writable: true }
144299
144430
  });
144300
144431
  const activeLoopIterations = /* @__PURE__ */ new Map();
144301
- const microtasks = [];
144432
+ const jobs = new SandboxJobQueue();
144302
144433
  hoistVarDeclarations(node, scope);
144303
144434
  const context = {
144304
144435
  budget,
@@ -144307,8 +144438,8 @@ async function interpret(node, options = {}) {
144307
144438
  captureReplayState: options.captureReplayState,
144308
144439
  rootNode: node,
144309
144440
  scope,
144441
+ signal: options.signal,
144310
144442
  stats: stats2,
144311
- microtasks,
144312
144443
  activeLoopIterations,
144313
144444
  restoredLoopIterations: new Map(
144314
144445
  Object.entries(options.snapshot?.loopIterations ?? {}).map(([nodeId, iteration]) => [
@@ -144320,8 +144451,8 @@ async function interpret(node, options = {}) {
144320
144451
  generatorYield: options.generatorYield,
144321
144452
  resumeTarget: { nodeId: options.snapshot?.resumeNodeId }
144322
144453
  };
144323
- const evaluation = await evaluateNode2(node, context);
144324
- await drainMicrotasks(context);
144454
+ const evaluation = await jobs.run(() => evaluateNode2(node, context));
144455
+ await jobs.drain();
144325
144456
  const snapshot2 = scope.snapshot();
144326
144457
  reconcileDataBudget(
144327
144458
  budget,
@@ -144369,24 +144500,9 @@ async function interpret(node, options = {}) {
144369
144500
  stats: stats2
144370
144501
  };
144371
144502
  }
144372
- async function drainMicrotasks(context) {
144373
- let idleTurns = 0;
144374
- while (idleTurns < 20) {
144375
- const task = context.microtasks.shift();
144376
- if (task === void 0) {
144377
- idleTurns += 1;
144378
- await Promise.resolve();
144379
- continue;
144380
- }
144381
- idleTurns = 0;
144382
- context.budget.visitNode();
144383
- task();
144384
- await Promise.resolve();
144385
- }
144386
- }
144387
144503
  async function evaluateNode2(node, context) {
144388
144504
  const replayWait = promiseReplayContext.getStore()?.beforeNode(node.nodeId);
144389
- if (replayWait !== void 0) await replayWait;
144505
+ if (replayWait !== void 0) await suspendJob(replayWait);
144390
144506
  context.budget.visitNode();
144391
144507
  context.stats.nodeVisits += 1;
144392
144508
  if (node.nodeId !== void 0 && context.resumeTarget?.nodeId === node.nodeId) {
@@ -144648,7 +144764,7 @@ async function evaluateAssignmentExpression(node, context) {
144648
144764
  if (right2.kind !== "normal") {
144649
144765
  return right2;
144650
144766
  }
144651
- const binding2 = await bindPattern(node.left, right2.value, { assign: true }, context.scope, {
144767
+ const binding2 = await bindPattern2(node.left, right2.value, { assign: true }, context.scope, {
144652
144768
  evaluate: (patternNode) => evaluateNode2(patternNode, context)
144653
144769
  });
144654
144770
  if (!binding2.ok) {
@@ -144905,7 +145021,7 @@ async function evaluateVariableDeclaration(node, context) {
144905
145021
  if (value.kind !== "normal") {
144906
145022
  return value;
144907
145023
  }
144908
- const binding = await bindPattern(
145024
+ const binding = await bindPattern2(
144909
145025
  declarator.id,
144910
145026
  value.value,
144911
145027
  { kind: node.kind },
@@ -145305,7 +145421,7 @@ function isPlainForInObject(value) {
145305
145421
  }
145306
145422
  async function bindForInLoopVariable(left, key3, scope, context) {
145307
145423
  if (left.type === "Identifier") {
145308
- return bindPattern(left, key3, { assign: true }, scope, {
145424
+ return bindPattern2(left, key3, { assign: true }, scope, {
145309
145425
  evaluate: (patternNode) => evaluateNode2(patternNode, { ...context, scope })
145310
145426
  });
145311
145427
  }
@@ -145313,7 +145429,7 @@ async function bindForInLoopVariable(left, key3, scope, context) {
145313
145429
  if (left.declarations.length !== 1 || declarator?.id.type !== "Identifier") {
145314
145430
  throw new TypeError("for...in keys are strings; destructure inside the body");
145315
145431
  }
145316
- return bindPattern(declarator.id, key3, { kind: left.kind }, scope, {
145432
+ return bindPattern2(declarator.id, key3, { kind: left.kind }, scope, {
145317
145433
  evaluate: (patternNode) => evaluateNode2(patternNode, { ...context, scope })
145318
145434
  });
145319
145435
  }
@@ -145495,7 +145611,7 @@ function hasLoopLabel(labels, target) {
145495
145611
  }
145496
145612
  async function bindForOfLoopVariable(left, value, scope, context) {
145497
145613
  if (left.type === "Identifier") {
145498
- return bindPattern(left, value, { assign: true }, scope, {
145614
+ return bindPattern2(left, value, { assign: true }, scope, {
145499
145615
  evaluate: (patternNode) => evaluateNode2(patternNode, { ...context, scope })
145500
145616
  });
145501
145617
  }
@@ -145506,7 +145622,7 @@ async function bindForOfLoopVariable(left, value, scope, context) {
145506
145622
  if (left.declarations.length !== 1 || declarator === void 0) {
145507
145623
  throw new TypeError("for...of declarations must include exactly one declarator.");
145508
145624
  }
145509
- return bindPattern(declarator.id, value, { kind: left.kind }, scope, {
145625
+ return bindPattern2(declarator.id, value, { kind: left.kind }, scope, {
145510
145626
  evaluate: (patternNode) => evaluateNode2(patternNode, { ...context, scope })
145511
145627
  });
145512
145628
  }
@@ -145837,12 +145953,7 @@ async function evaluateMemberExpression(node, context) {
145837
145953
  return {
145838
145954
  kind: "normal",
145839
145955
  hasValue: true,
145840
- value: getPromiseMember(
145841
- member.object,
145842
- member.property,
145843
- context.budget,
145844
- (task) => enqueueMicrotask(context, task)
145845
- )
145956
+ value: getPromiseMember(member.object, member.property, context.budget)
145846
145957
  };
145847
145958
  }
145848
145959
  if (isSandboxRegex(member.object)) {
@@ -145861,13 +145972,6 @@ async function evaluateMemberExpression(node, context) {
145861
145972
  value: getMemberValue(member.object, member.property, context)
145862
145973
  };
145863
145974
  }
145864
- function enqueueMicrotask(context, task) {
145865
- return new Promise((resolve17, reject) => {
145866
- context.microtasks.push(() => {
145867
- task().then(resolve17, reject);
145868
- });
145869
- });
145870
- }
145871
145975
  async function evaluateCallExpression(node, context) {
145872
145976
  if (node.callee.type === "MemberExpression") {
145873
145977
  context.budget.visitNode();
@@ -146120,12 +146224,7 @@ async function evaluateMemberCallExpression(node, context) {
146120
146224
  if (isSandboxPromise(member.object)) {
146121
146225
  return evaluateResolvedCallExpression(
146122
146226
  node,
146123
- getPromiseMember(
146124
- member.object,
146125
- member.property,
146126
- context.budget,
146127
- (task) => enqueueMicrotask(context, task)
146128
- ),
146227
+ getPromiseMember(member.object, member.property, context.budget),
146129
146228
  context,
146130
146229
  member.object
146131
146230
  );
@@ -146170,15 +146269,7 @@ async function evaluateStringMethodCall(node, target, methodName, context) {
146170
146269
  methodName,
146171
146270
  args.value,
146172
146271
  context.budget,
146173
- async (closure, closureArgs) => {
146174
- const result = await invokeSandboxClosure(
146175
- closure,
146176
- closureArgs,
146177
- context,
146178
- context.callStack
146179
- );
146180
- return isSandboxPromise(result) ? await result.promise : result;
146181
- }
146272
+ (closure, closureArgs) => invokeSandboxClosure(closure, closureArgs, context, context.callStack)
146182
146273
  )
146183
146274
  };
146184
146275
  } catch (error3) {
@@ -146663,6 +146754,9 @@ async function invokeSandboxClosure(callee, args, context, stack, span, thisValu
146663
146754
  ...span === void 0 ? {} : { span }
146664
146755
  }
146665
146756
  ]);
146757
+ if (isSandboxPromise(result) && result.synchronousPrefix !== void 0) {
146758
+ await result.synchronousPrefix;
146759
+ }
146666
146760
  return callee.async === true ? normalizeClosureResult(wrapHostResult(result, stack), context.budget) : await wrapHostResult(result, stack);
146667
146761
  } catch (error3) {
146668
146762
  if (isFatalSandboxError(error3)) {
@@ -146818,6 +146912,7 @@ var init_interpreter = __esm({
146818
146912
  "packages/safejs/src/interp/interpreter.ts"() {
146819
146913
  "use strict";
146820
146914
  init_promise_replay();
146915
+ init_jobs4();
146821
146916
  init_shape();
146822
146917
  init_async();
146823
146918
  init_host_call();
@@ -147634,7 +147729,6 @@ function run(source, options = {}) {
147634
147729
  }),
147635
147730
  ...createRegexGlobals()
147636
147731
  };
147637
- const bindings = wrapCancelableBindings(builtinBindings, options.signal);
147638
147732
  const initialInputs = prepareReplayInputs(
147639
147733
  {
147640
147734
  bindings: callerBindings,
@@ -147688,7 +147782,7 @@ function run(source, options = {}) {
147688
147782
  options.signal
147689
147783
  );
147690
147784
  const scope = new Scope(
147691
- bindings,
147785
+ builtinBindings,
147692
147786
  void 0,
147693
147787
  void 0,
147694
147788
  { chargeData: false },
@@ -147749,6 +147843,7 @@ function run(source, options = {}) {
147749
147843
  dumpController.onYield(createSnapshot);
147750
147844
  },
147751
147845
  scope: executionScope,
147846
+ signal: options.signal,
147752
147847
  snapshot: interpreterSnapshot,
147753
147848
  surfaceUnhandledThrows: true,
147754
147849
  useScopeDirectly: true
@@ -147790,6 +147885,7 @@ function run(source, options = {}) {
147790
147885
  dumpController.onYield(createSnapshot);
147791
147886
  },
147792
147887
  scope: executionScope,
147888
+ signal: options.signal,
147793
147889
  snapshot: interpreterSnapshot
147794
147890
  });
147795
147891
  await throwIfReturnedPromiseRejected(result2);
@@ -147891,6 +147987,7 @@ async function callEntryPoint(input) {
147891
147987
  ...argumentBindings
147892
147988
  });
147893
147989
  return interpret(createEntryPointAwait(input.args.length, input.module.span), {
147990
+ signal: input.signal,
147894
147991
  budget: input.budget,
147895
147992
  captureReplayState: input.captureReplayState,
147896
147993
  onYield: input.onYield,
@@ -147953,6 +148050,7 @@ function createExecutableNode(module) {
147953
148050
  function createRunSnapshot(input) {
147954
148051
  return {
147955
148052
  version: DUMP_FORMAT_VERSION,
148053
+ executionSemantics: EXECUTION_SEMANTICS,
147956
148054
  sourceHash: input.sourceHash,
147957
148055
  bindings: input.bindings,
147958
148056
  clock: input.clock?.snapshot(),
@@ -148219,7 +148317,7 @@ var init_find_exported = __esm({
148219
148317
  });
148220
148318
 
148221
148319
  // packages/safejs/src/modules/agent.ts
148222
- import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
148320
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
148223
148321
  function createSpawnUsageAccumulator() {
148224
148322
  let inputTokens = 0;
148225
148323
  let outputTokens = 0;
@@ -149065,7 +149163,7 @@ var init_agent3 = __esm({
149065
149163
  init_parallel();
149066
149164
  init_types4();
149067
149165
  init_otel2();
149068
- activeUsageAccumulator = new AsyncLocalStorage5();
149166
+ activeUsageAccumulator = new AsyncLocalStorage6();
149069
149167
  oneAttemptRetryOptions = {
149070
149168
  maxAttempts: 1,
149071
149169
  backoffMs: 0,
@@ -154007,7 +154105,7 @@ var init_package2 = __esm({
154007
154105
  "package.json"() {
154008
154106
  package_default2 = {
154009
154107
  name: "poe-code",
154010
- version: "4.0.72",
154108
+ version: "5.0.0",
154011
154109
  description: "CLI tool to configure Poe API for developer workflows.",
154012
154110
  license: "MIT",
154013
154111
  type: "module",