poe-code 14.0.73 → 14.0.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/index.js +1855 -1153
  2. package/dist/index.js.map +4 -4
  3. package/dist/metafile.json +1 -1
  4. package/package.json +1 -1
  5. package/packages/safe-js/dist/chunks/{chunk-I2Z37MKZ.js → chunk-2J6W3YGB.js} +2 -2
  6. package/packages/safe-js/dist/chunks/{chunk-XKCTB5FR.js → chunk-YEZOXLY4.js} +3203 -2543
  7. package/packages/safe-js/dist/chunks/chunk-YEZOXLY4.js.map +7 -0
  8. package/packages/safe-js/dist/cli.js +2 -2
  9. package/packages/safe-js/dist/core.js +1 -1
  10. package/packages/safe-js/dist/graph-depth.js +3 -0
  11. package/packages/safe-js/dist/index.js +2 -2
  12. package/packages/safe-js/dist/interp/cancel.js +3 -0
  13. package/packages/safe-js/dist/interp/globals/misc.js +2 -1
  14. package/packages/safe-js/dist/interp/globals/object.js +3 -0
  15. package/packages/safe-js/dist/interp/globals/regex.js +88 -7
  16. package/packages/safe-js/dist/interp/interpreter.js +14 -7
  17. package/packages/safe-js/dist/interp/iteration.js +6 -1
  18. package/packages/safe-js/dist/interp/methods/regex.d.ts +7 -3
  19. package/packages/safe-js/dist/interp/methods/regex.js +127 -21
  20. package/packages/safe-js/dist/interp/methods/regexp-iterator.d.ts +8 -0
  21. package/packages/safe-js/dist/interp/methods/regexp-iterator.js +49 -0
  22. package/packages/safe-js/dist/interp/methods/string.d.ts +2 -0
  23. package/packages/safe-js/dist/interp/methods/string.js +412 -118
  24. package/packages/safe-js/dist/interp/object-model.d.ts +2 -0
  25. package/packages/safe-js/dist/interp/object-model.js +39 -9
  26. package/packages/safe-js/dist/interp/regexp-iterator.d.ts +14 -0
  27. package/packages/safe-js/dist/interp/regexp-iterator.js +18 -0
  28. package/packages/safe-js/dist/interp/string-coercion.js +11 -7
  29. package/packages/safe-js/dist/interp/values.d.ts +2 -1
  30. package/packages/safe-js/dist/interp/values.js +35 -0
  31. package/packages/safe-js/dist/snapshot/dump-format.js +26 -2
  32. package/packages/safe-js/dist/snapshot/replay-data.d.ts +9 -1
  33. package/packages/safe-js/dist/snapshot/replay-data.js +31 -0
  34. package/packages/safe-js/dist/snapshot/replay-inputs.js +17 -0
  35. package/packages/safe-js/dist/snapshot/restore.js +17 -1
  36. package/packages/safe-js/dist/snapshot/serialize.d.ts +10 -2
  37. package/packages/safe-js/dist/snapshot/serialize.js +26 -10
  38. package/packages/safe-js/dist/snapshot/validation.js +14 -2
  39. package/packages/safe-js/dist/chunks/chunk-XKCTB5FR.js.map +0 -7
  40. /package/packages/safe-js/dist/chunks/{chunk-I2Z37MKZ.js.map → chunk-2J6W3YGB.js.map} +0 -0
package/dist/index.js CHANGED
@@ -12249,7 +12249,7 @@ function matchSubsequence(query, text5) {
12249
12249
  const textCharacters = Array.from(text5);
12250
12250
  let previousStates = [];
12251
12251
  for (let queryIndex = 0; queryIndex < queryCharacters.length; queryIndex += 1) {
12252
- const states2 = [];
12252
+ const states3 = [];
12253
12253
  let offset = 0;
12254
12254
  for (let textIndex = 0; textIndex < textCharacters.length; textIndex += 1) {
12255
12255
  const character2 = textCharacters[textIndex];
@@ -12260,7 +12260,7 @@ function matchSubsequence(query, text5) {
12260
12260
  }
12261
12261
  const positions = character2.length === 2 ? [position, position + 1] : [position];
12262
12262
  if (queryIndex === 0) {
12263
- states2[textIndex] = {
12263
+ states3[textIndex] = {
12264
12264
  score: characterScore(textCharacters, textIndex, void 0) + Math.max(0, EARLY_MATCH_BONUS - position),
12265
12265
  positions
12266
12266
  };
@@ -12275,12 +12275,12 @@ function matchSubsequence(query, text5) {
12275
12275
  score: previous.score + characterScore(textCharacters, textIndex, previousIndex),
12276
12276
  positions: [...previous.positions, ...positions]
12277
12277
  };
12278
- if (isBetterMatch(next, states2[textIndex])) {
12279
- states2[textIndex] = next;
12278
+ if (isBetterMatch(next, states3[textIndex])) {
12279
+ states3[textIndex] = next;
12280
12280
  }
12281
12281
  }
12282
12282
  }
12283
- previousStates = states2;
12283
+ previousStates = states3;
12284
12284
  if (!previousStates.some((state) => state !== void 0)) {
12285
12285
  return void 0;
12286
12286
  }
@@ -21524,14 +21524,14 @@ function validateMachine(machine) {
21524
21524
  if (!hasOwnRecordField(machine, "states") || !isStateList(machine.states)) {
21525
21525
  throw new TypeError("State machine states must be a string array.");
21526
21526
  }
21527
- const states2 = new Set(machine.states);
21527
+ const states3 = new Set(machine.states);
21528
21528
  if (machine.states.some((state) => !hasVisibleName(state))) {
21529
21529
  throw new Error("State names must not be empty.");
21530
21530
  }
21531
21531
  if (!hasOwnRecordField(machine, "initial") || typeof machine.initial !== "string") {
21532
21532
  throw new TypeError("State machine initial must be a string.");
21533
21533
  }
21534
- if (!states2.has(machine.initial)) {
21534
+ if (!states3.has(machine.initial)) {
21535
21535
  throw new Error(`Initial state "${machine.initial}" is not declared.`);
21536
21536
  }
21537
21537
  if (!hasOwnRecordField(machine, "events") || !isRecord9(machine.events)) {
@@ -21550,12 +21550,12 @@ function validateMachine(machine) {
21550
21550
  if (!hasOwnRecordField(event, "to") || typeof event.to !== "string") {
21551
21551
  throw new TypeError(`Event "${eventName}" target state must be a string.`);
21552
21552
  }
21553
- if (!states2.has(event.to)) {
21553
+ if (!states3.has(event.to)) {
21554
21554
  throw new Error(`Event "${eventName}" references unknown target state "${event.to}".`);
21555
21555
  }
21556
21556
  if (event.from !== "*") {
21557
21557
  for (const fromState of event.from) {
21558
- if (!states2.has(fromState)) {
21558
+ if (!states3.has(fromState)) {
21559
21559
  throw new Error(`Event "${eventName}" references unknown source state "${fromState}".`);
21560
21560
  }
21561
21561
  }
@@ -23953,13 +23953,13 @@ async function ghIssuesBackend(deps) {
23953
23953
  }
23954
23954
  function createProjectSession(project, field, labelPrefix) {
23955
23955
  const statusOptions = new Map(field.options.map((option) => [option.name, option.id]));
23956
- const states2 = field.options.map((option) => option.name);
23956
+ const states3 = field.options.map((option) => option.name);
23957
23957
  const events = Object.fromEntries(
23958
- states2.map((state) => [state, Object.freeze({ from: "*", to: state })])
23958
+ states3.map((state) => [state, Object.freeze({ from: "*", to: state })])
23959
23959
  );
23960
23960
  const stateMachine = Object.freeze({
23961
- states: Object.freeze([...states2]),
23962
- initial: states2[0],
23961
+ states: Object.freeze([...states3]),
23962
+ initial: states3[0],
23963
23963
  events: Object.freeze(events)
23964
23964
  });
23965
23965
  return Object.freeze({
@@ -80210,8 +80210,8 @@ function hasEmptyStringValue(value) {
80210
80210
  }
80211
80211
  return Object.values(value).some((entry) => hasEmptyStringValue(entry));
80212
80212
  }
80213
- function hasOwnState(states2, state) {
80214
- return Object.prototype.hasOwnProperty.call(states2, state);
80213
+ function hasOwnState(states3, state) {
80214
+ return Object.prototype.hasOwnProperty.call(states3, state);
80215
80215
  }
80216
80216
  function getOwnEntry29(record2, key3) {
80217
80217
  return Object.prototype.hasOwnProperty.call(record2, key3) ? record2[key3] : void 0;
@@ -80245,7 +80245,7 @@ import path98 from "node:path";
80245
80245
  function resolveConfig2(raw, cwd) {
80246
80246
  const rawConfig = isRecord31(raw) ? raw : {};
80247
80247
  const scoped = resolveScope(maestroConfigScope, rawConfig, process.env);
80248
- const { states: states2, stateOrder } = parseStates(getOwnEntry30(rawConfig, "states"));
80248
+ const { states: states3, stateOrder } = parseStates(getOwnEntry30(rawConfig, "states"));
80249
80249
  const polling = scoped.polling;
80250
80250
  const workspace = scoped.workspace;
80251
80251
  const agent3 = scoped.agent;
@@ -80254,9 +80254,9 @@ function resolveConfig2(raw, cwd) {
80254
80254
  }
80255
80255
  return {
80256
80256
  tasks: resolveTasks(getOwnEntry30(rawConfig, "tasks"), cwd),
80257
- states: states2,
80258
- activeStateNames: stateOrder.filter((name) => states2[name]?.prompt !== void 0),
80259
- terminalStateNames: stateOrder.filter((name) => states2[name]?.terminal === true),
80257
+ states: states3,
80258
+ activeStateNames: stateOrder.filter((name) => states3[name]?.prompt !== void 0),
80259
+ terminalStateNames: stateOrder.filter((name) => states3[name]?.terminal === true),
80260
80260
  stateOrder,
80261
80261
  polling: {
80262
80262
  intervalMs: readPositiveInteger(
@@ -80289,13 +80289,13 @@ function resolveConfig2(raw, cwd) {
80289
80289
  }
80290
80290
  function parseStates(value) {
80291
80291
  validateStateDefinitions(value);
80292
- const states2 = /* @__PURE__ */ Object.create(null);
80292
+ const states3 = /* @__PURE__ */ Object.create(null);
80293
80293
  const stateOrder = [];
80294
80294
  const entries = value instanceof Map ? value.entries() : Object.entries(value);
80295
80295
  for (const [name, rawDefinition] of entries) {
80296
80296
  const stateName = String(name);
80297
80297
  const definition = rawDefinition;
80298
- Object.defineProperty(states2, stateName, {
80298
+ Object.defineProperty(states3, stateName, {
80299
80299
  configurable: true,
80300
80300
  enumerable: true,
80301
80301
  value: parseStateDefinition(definition),
@@ -80303,7 +80303,7 @@ function parseStates(value) {
80303
80303
  });
80304
80304
  stateOrder.push(stateName);
80305
80305
  }
80306
- return { states: states2, stateOrder };
80306
+ return { states: states3, stateOrder };
80307
80307
  }
80308
80308
  function parseStateDefinition(definition) {
80309
80309
  const state = {};
@@ -81573,8 +81573,8 @@ var init_phases = __esm({
81573
81573
  function isRunningPhase(phase) {
81574
81574
  return phase === "running-step";
81575
81575
  }
81576
- function hasOwnState2(states2, state) {
81577
- return Object.prototype.hasOwnProperty.call(states2, state);
81576
+ function hasOwnState2(states3, state) {
81577
+ return Object.prototype.hasOwnProperty.call(states3, state);
81578
81578
  }
81579
81579
  function isAbortError5(error3) {
81580
81580
  return error3 instanceof Error && error3.name === "AbortError";
@@ -82697,7 +82697,7 @@ function createStateStore(stateDir, fs31 = nodeFs7) {
82697
82697
  }
82698
82698
  throw error3;
82699
82699
  }
82700
- const states2 = [];
82700
+ const states3 = [];
82701
82701
  for (const entry of [...entries].sort()) {
82702
82702
  if (entry.startsWith(REMOVED_STATE_PREFIX)) {
82703
82703
  continue;
@@ -82716,10 +82716,10 @@ function createStateStore(stateDir, fs31 = nodeFs7) {
82716
82716
  }
82717
82717
  const state = await read(entry);
82718
82718
  if (state !== null) {
82719
- states2.push(state);
82719
+ states3.push(state);
82720
82720
  }
82721
82721
  }
82722
- return states2;
82722
+ return states3;
82723
82723
  }
82724
82724
  async function remove2(id) {
82725
82725
  const processDir = resolveProcessDir(stateDir, id);
@@ -102105,13 +102105,13 @@ function markApprovalsBuiltIn(group) {
102105
102105
  function isApprovalsBuiltIn(node) {
102106
102106
  return node.kind === "group" && node[approvalsGroupSymbol] === true;
102107
102107
  }
102108
- async function loadApprovals(tasks, states2 = []) {
102109
- if (states2.length === 0) {
102108
+ async function loadApprovals(tasks, states3 = []) {
102109
+ if (states3.length === 0) {
102110
102110
  return tasks.all();
102111
102111
  }
102112
102112
  const seenIds = /* @__PURE__ */ new Set();
102113
102113
  const approvals = [];
102114
- for (const state of states2) {
102114
+ for (const state of states3) {
102115
102115
  const matching = await tasks.all({
102116
102116
  state
102117
102117
  });
@@ -126223,6 +126223,29 @@ var init_collection_iterator = __esm({
126223
126223
  }
126224
126224
  });
126225
126225
 
126226
+ // packages/safe-js/src/interp/regexp-iterator.ts
126227
+ function isSandboxRegExpIterator(value) {
126228
+ return typeof value === "object" && value !== null && states2.has(value);
126229
+ }
126230
+ function restoreSandboxRegExpIterator(state, target = /* @__PURE__ */ Object.create(null)) {
126231
+ if (!state.exhausted && (state.matcher === void 0 || state.input === void 0))
126232
+ throw new TypeError("A live RegExp iterator requires its matcher and input.");
126233
+ states2.set(target, state.exhausted ? { matcher: void 0, input: void 0, exhausted: true } : { ...state });
126234
+ return target;
126235
+ }
126236
+ function regexpIteratorState(value) {
126237
+ const state = states2.get(value);
126238
+ if (state === void 0) throw new TypeError("Expected a RegExp string iterator.");
126239
+ return state;
126240
+ }
126241
+ var states2;
126242
+ var init_regexp_iterator = __esm({
126243
+ "packages/safe-js/src/interp/regexp-iterator.ts"() {
126244
+ "use strict";
126245
+ states2 = /* @__PURE__ */ new WeakMap();
126246
+ }
126247
+ });
126248
+
126226
126249
  // packages/safe-js/src/interp/date.ts
126227
126250
  import { types } from "node:util";
126228
126251
  function isSandboxDate(value) {
@@ -127475,6 +127498,7 @@ function graphEntries(value) {
127475
127498
  }
127476
127499
  const entries = [];
127477
127500
  if (isSandboxCollectionIterator(value)) entries.push([".<collection>", collectionIteratorState(value).collection]);
127501
+ if (isSandboxRegExpIterator(value)) entries.push([".<matcher>", regexpIteratorState(value).matcher]);
127478
127502
  for (const key3 of Object.keys(value)) {
127479
127503
  const descriptor = Object.getOwnPropertyDescriptor(value, key3);
127480
127504
  if (descriptor !== void 0 && "value" in descriptor)
@@ -127490,6 +127514,7 @@ var init_graph_depth = __esm({
127490
127514
  init_budget2();
127491
127515
  init_arguments();
127492
127516
  init_collection_iterator();
127517
+ init_regexp_iterator();
127493
127518
  init_collection_brands();
127494
127519
  init_boxed();
127495
127520
  init_regexp_properties();
@@ -127571,6 +127596,21 @@ function installBoxedPrototype(budget, prototype, constructor, kind = typeof box
127571
127596
  function getBoxedPrototype(value, budget) {
127572
127597
  return boxedPrototypes.get(budget)?.get(typeof value);
127573
127598
  }
127599
+ function installRegexPrototype(budget, prototype, constructor) {
127600
+ regexPrototypes.set(budget, prototype);
127601
+ initialRegexDescriptors.set(budget, Object.getOwnPropertyDescriptors(prototype));
127602
+ registerIntrinsicPrototype(budget, prototype, constructor);
127603
+ }
127604
+ function hasRegexPropertyOverride(value, keys, budget) {
127605
+ const initial = initialRegexDescriptors.get(budget);
127606
+ const prototype = regexPrototypes.get(budget);
127607
+ const defaultPrototype = isSandboxRegex(value) && prototype !== void 0 && getSandboxPrototype(value, budget) === prototype;
127608
+ return keys.some((key3) => {
127609
+ const current = defaultPrototype ? Object.getOwnPropertyDescriptor(getRegexProperties(value), key3) ?? Object.getOwnPropertyDescriptor(prototype, key3) : getSandboxPropertyDescriptor(value, key3, budget);
127610
+ const expected = initial?.[key3];
127611
+ return expected === void 0 ? current !== void 0 : current === void 0 || current.value !== expected.value || current.get !== expected.get || current.set !== expected.set;
127612
+ });
127613
+ }
127574
127614
  function isDefaultBoxedMethod(value, key3, budget) {
127575
127615
  const prototype = getBoxedPrototype(value, budget);
127576
127616
  return prototype !== void 0 && initialBoxedMethods.get(prototype)?.has(key3) === true && Object.getOwnPropertyDescriptor(prototype, key3)?.value === initialBoxedMethods.get(prototype)?.get(key3);
@@ -127582,30 +127622,32 @@ function registerIntrinsicPrototype(budget, prototype, constructor) {
127582
127622
  let roots = intrinsicPrototypeRoots.get(budget);
127583
127623
  if (roots === void 0) intrinsicPrototypeRoots.set(budget, roots = /* @__PURE__ */ new Set());
127584
127624
  roots.add(prototype);
127585
- const records = [prototype, constructor].map((target) => ({
127625
+ const methods = Reflect.ownKeys(prototype).map((key3) => Object.getOwnPropertyDescriptor(prototype, key3)?.value).filter(isGuestClosure);
127626
+ const records = [.../* @__PURE__ */ new Set([prototype, constructor, ...methods])].map((target) => ({
127586
127627
  target,
127587
127628
  value: isGuestClosure(target) ? materializeFunctionProperties(target) : target,
127588
127629
  prototype: getSandboxPrototype(target),
127589
127630
  explicit: hasExplicitSandboxPrototype(target)
127590
127631
  })).map((record2) => ({
127591
127632
  ...record2,
127592
- descriptors: new Map(Object.entries(Object.getOwnPropertyDescriptors(record2.value)))
127633
+ descriptors: new Map(Reflect.ownKeys(record2.value).map((key3) => [key3, Object.getOwnPropertyDescriptor(record2.value, key3)]))
127593
127634
  }));
127594
127635
  const unchanged = (before, after) => before !== void 0 && after !== void 0 && Object.is(before.value, after.value) && before.get === after.get && before.set === after.set && before.writable === after.writable && before.configurable === after.configurable && before.enumerable === after.enumerable;
127595
127636
  intrinsicConstructors.set(
127596
127637
  constructor,
127597
127638
  () => records.every(({ target, value, descriptors, prototype: parent, explicit }) => {
127598
127639
  const current = Object.getOwnPropertyDescriptors(value);
127599
- return getSandboxPrototype(target) === parent && hasExplicitSandboxPrototype(target) === explicit && Object.keys(current).length === descriptors.size && Object.keys(current).every((key3) => unchanged(descriptors.get(key3), current[key3]));
127640
+ return getSandboxPrototype(target) === parent && hasExplicitSandboxPrototype(target) === explicit && Reflect.ownKeys(current).length === descriptors.size && Reflect.ownKeys(value).every((key3) => unchanged(descriptors.get(key3), Object.getOwnPropertyDescriptor(value, key3)));
127600
127641
  })
127601
127642
  );
127602
127643
  budget.setRetainedValues(
127603
127644
  prototype,
127604
127645
  () => records.flatMap(({ target, value, descriptors, prototype: parent }) => [
127605
127646
  ...getSandboxPrototype(target) === parent ? [] : [getSandboxPrototype(target)],
127606
- ...Object.entries(Object.getOwnPropertyDescriptors(value)).flatMap(
127607
- ([key3, descriptor]) => unchanged(descriptors.get(key3), descriptor) ? [] : [key3, descriptor.value, ...retainedAccessorClosures(descriptor)]
127608
- )
127647
+ ...Reflect.ownKeys(value).flatMap((key3) => {
127648
+ const descriptor = Object.getOwnPropertyDescriptor(value, key3);
127649
+ return unchanged(descriptors.get(key3), descriptor) ? [] : [key3, descriptor.value, ...retainedAccessorClosures(descriptor)];
127650
+ })
127609
127651
  ])
127610
127652
  );
127611
127653
  }
@@ -127613,10 +127655,13 @@ function releaseObjectPrototype(budget) {
127613
127655
  for (const prototype of intrinsicPrototypeRoots.get(budget) ?? []) budget.setRetainedValues(prototype, void 0);
127614
127656
  intrinsicPrototypeRoots.delete(budget);
127615
127657
  boxedPrototypes.delete(budget);
127658
+ regexPrototypes.delete(budget);
127659
+ initialRegexDescriptors.delete(budget);
127616
127660
  intrinsicPrototypes.delete(budget);
127617
127661
  }
127618
127662
  function getSandboxPrototype(value, budget) {
127619
127663
  if (prototypes.has(value)) return prototypes.get(value) ?? null;
127664
+ if (budget !== void 0 && isSandboxRegex(value)) return regexPrototypes.get(budget) ?? null;
127620
127665
  if (budget !== void 0 && isSandboxBox(value)) {
127621
127666
  const prototype = getBoxedPrototype(boxedValue(value), budget);
127622
127667
  if (prototype !== void 0 && prototype !== value) return prototype;
@@ -127672,13 +127717,13 @@ function setSandboxPrototype(value, prototype, budget) {
127672
127717
  if (budget !== void 0 && intrinsicPrototypes.get(budget) === value && prototype !== null) {
127673
127718
  throw new TypeError("Object.prototype has an immutable null prototype.");
127674
127719
  }
127675
- if (!Array.isArray(value) && !isPrototypeRecord(value) || prototype !== null && !Array.isArray(prototype) && !isPrototypeRecord(prototype)) {
127720
+ if (!Array.isArray(value) && !isSandboxRegex(value) && !isPrototypeRecord(value) || prototype !== null && !Array.isArray(prototype) && !isPrototypeRecord(prototype)) {
127676
127721
  throw new TypeError(
127677
127722
  "Prototype links require ordinary sandbox objects, arrays, or guest functions."
127678
127723
  );
127679
127724
  }
127680
127725
  if (prototypes.has(value) && getSandboxPrototype(value, budget) === prototype) return;
127681
- if (!Object.isExtensible(isGuestClosure(value) ? materializeFunctionProperties(value) : value)) {
127726
+ if (!Object.isExtensible(isGuestClosure(value) ? materializeFunctionProperties(value) : isSandboxRegex(value) ? getRegexProperties(value) : value)) {
127682
127727
  throw new TypeError("Cannot change the prototype of a non-extensible object.");
127683
127728
  }
127684
127729
  let depth = 0;
@@ -127713,7 +127758,7 @@ function hasGuestObjectState(value) {
127713
127758
  (descriptor) => !descriptor.enumerable || !descriptor.configurable || !descriptor.writable
127714
127759
  );
127715
127760
  }
127716
- var guestClosures, functionProperties, prototypes, intrinsicPrototypes, boxedPrototypes, intrinsicPrototypeRoots, intrinsicConstructors, initialBoxedMethods, descriptorObjects;
127761
+ var guestClosures, functionProperties, prototypes, intrinsicPrototypes, boxedPrototypes, regexPrototypes, initialRegexDescriptors, intrinsicPrototypeRoots, intrinsicConstructors, initialBoxedMethods, descriptorObjects;
127717
127762
  var init_object_model = __esm({
127718
127763
  "packages/safe-js/src/interp/object-model.ts"() {
127719
127764
  "use strict";
@@ -127728,6 +127773,8 @@ var init_object_model = __esm({
127728
127773
  prototypes = /* @__PURE__ */ new WeakMap();
127729
127774
  intrinsicPrototypes = /* @__PURE__ */ new WeakMap();
127730
127775
  boxedPrototypes = /* @__PURE__ */ new WeakMap();
127776
+ regexPrototypes = /* @__PURE__ */ new WeakMap();
127777
+ initialRegexDescriptors = /* @__PURE__ */ new WeakMap();
127731
127778
  intrinsicPrototypeRoots = /* @__PURE__ */ new WeakMap();
127732
127779
  intrinsicConstructors = /* @__PURE__ */ new WeakMap();
127733
127780
  initialBoxedMethods = /* @__PURE__ */ new WeakMap();
@@ -128014,6 +128061,16 @@ function encodeReplayData(value, options = {}) {
128014
128061
  };
128015
128062
  }
128016
128063
  nodes[id] = { ...storage2, properties, extensible: Object.isExtensible(entry) };
128064
+ } else if (isSandboxRegExpIterator(entry)) {
128065
+ const snapshot2 = regexpIteratorState(entry);
128066
+ const properties = /* @__PURE__ */ Object.create(null);
128067
+ for (const [key3, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(entry))) {
128068
+ if (!("value" in descriptor)) throw new TypeError(`Cannot record replay data accessor '${key3}'.`);
128069
+ properties[key3] = { value: child(descriptor.value, JSON.stringify(["property", key3])), configurable: descriptor.configurable === true, enumerable: descriptor.enumerable === true, writable: descriptor.writable === true };
128070
+ }
128071
+ let symbolIndex = 0;
128072
+ const symbolEntries = serializeSymbolProperties(entry, (value2) => encode(value2, depth + 1, [...path193, { symbol: Math.floor(symbolIndex++ / 2) }]));
128073
+ nodes[id] = { kind: "regexp-iterator", matcher: child(snapshot2.matcher, "<matcher>"), input: child(snapshot2.input, "<input>"), exhausted: snapshot2.exhausted, properties, extensible: Object.isExtensible(entry), symbolEntries };
128017
128074
  } else if (isSandboxCollectionIterator(entry)) {
128018
128075
  const snapshot2 = snapshotCollectionIterator(entry);
128019
128076
  const properties = /* @__PURE__ */ Object.create(null);
@@ -128204,6 +128261,20 @@ function decodeReplayData(input, options = {}, parent) {
128204
128261
  if (!node.extensible) Object.preventExtensions(result3);
128205
128262
  return result3;
128206
128263
  }
128264
+ if (kind === "regexp-iterator") {
128265
+ const exhausted = own(node, "exhausted");
128266
+ if (typeof exhausted !== "boolean" || typeof node.extensible !== "boolean") throw new TypeError("Invalid replay RegExp iterator.");
128267
+ const result3 = restoreSandboxRegExpIterator({ matcher: void 0, input: void 0, exhausted: true });
128268
+ restored.set(id, result3);
128269
+ const matcher = child(own(node, "matcher"));
128270
+ const input2 = child(own(node, "input"));
128271
+ if (matcher !== void 0 && !isSandboxRegex(matcher)) throw new TypeError("Invalid replay RegExp iterator matcher.");
128272
+ if (input2 !== void 0 && typeof input2 !== "string") throw new TypeError("Invalid replay RegExp iterator input.");
128273
+ restoreSandboxRegExpIterator({ matcher, input: input2, exhausted }, result3);
128274
+ defineProperties(result3, record(own(node, "properties")), child, node.symbolEntries);
128275
+ if (!node.extensible) Object.preventExtensions(result3);
128276
+ return result3;
128277
+ }
128207
128278
  if (kind === "collection-iterator") {
128208
128279
  const collectionKind = own(node, "collectionKind");
128209
128280
  const method = own(node, "method");
@@ -128338,6 +128409,7 @@ var init_replay_data = __esm({
128338
128409
  init_symbols2();
128339
128410
  init_symbols3();
128340
128411
  init_collection_iterator();
128412
+ init_regexp_iterator();
128341
128413
  init_object_model();
128342
128414
  init_compile_guard();
128343
128415
  init_float32();
@@ -129271,6 +129343,242 @@ var init_resources = __esm({
129271
129343
  }
129272
129344
  });
129273
129345
 
129346
+ // packages/safe-js/src/interp/regex/engine.ts
129347
+ function matchRegex(pattern, input, lastIndex = 0) {
129348
+ const startIndex = pattern.flags.global ? normalizeLastIndex(lastIndex) : 0;
129349
+ return matchRegexFrom(pattern, input, startIndex);
129350
+ }
129351
+ function matchRegexFrom(pattern, input, startIndex) {
129352
+ if (startIndex > input.length) {
129353
+ return null;
129354
+ }
129355
+ for (let attempt = startIndex; attempt <= input.length; attempt += 1) {
129356
+ const context = { input, flags: pattern.flags, steps: 0 };
129357
+ charge(context);
129358
+ const initialState = {
129359
+ position: attempt,
129360
+ captures: new Array(pattern.captureCount)
129361
+ };
129362
+ const result = matchNode(pattern.body, initialState, context).next();
129363
+ if (!result.done) {
129364
+ return toRegexMatch(input, attempt, result.value);
129365
+ }
129366
+ }
129367
+ return null;
129368
+ }
129369
+ function* matchNode(node, state, context) {
129370
+ charge(context);
129371
+ switch (node.type) {
129372
+ case "empty":
129373
+ yield state;
129374
+ return;
129375
+ case "literal":
129376
+ if (charactersEqual(context.input[state.position], node.value, context.flags.ignoreCase)) {
129377
+ yield { ...state, position: state.position + 1 };
129378
+ }
129379
+ return;
129380
+ case "dot":
129381
+ if (state.position < context.input.length && (context.flags.dotAll || !isLineTerminator(context.input[state.position]))) {
129382
+ yield { ...state, position: state.position + 1 };
129383
+ }
129384
+ return;
129385
+ case "anchor":
129386
+ if (matchesAnchor(node.kind, state.position, context)) {
129387
+ yield state;
129388
+ }
129389
+ return;
129390
+ case "wordBoundary": {
129391
+ const previousWord = state.position > 0 && isWordCharacter(context.input[state.position - 1]);
129392
+ const nextWord = state.position < context.input.length && isWordCharacter(context.input[state.position]);
129393
+ if (previousWord !== nextWord !== node.negated) {
129394
+ yield state;
129395
+ }
129396
+ return;
129397
+ }
129398
+ case "characterClass": {
129399
+ const character2 = context.input[state.position];
129400
+ if (character2 !== void 0 && matchesCharacterClass(character2, node.items, node.negated, context.flags.ignoreCase)) {
129401
+ yield { ...state, position: state.position + 1 };
129402
+ }
129403
+ return;
129404
+ }
129405
+ case "sequence":
129406
+ yield* matchSequence(node.elements, 0, state, context);
129407
+ return;
129408
+ case "alternation":
129409
+ for (const alternative of node.alternatives) {
129410
+ yield* matchNode(alternative, cloneState(state), context);
129411
+ }
129412
+ return;
129413
+ case "group":
129414
+ for (const result of matchNode(node.body, cloneState(state), context)) {
129415
+ if (!node.capturing || node.index === void 0) {
129416
+ yield result;
129417
+ continue;
129418
+ }
129419
+ const captures = result.captures.slice();
129420
+ captures[node.index - 1] = { start: state.position, end: result.position };
129421
+ yield { position: result.position, captures };
129422
+ }
129423
+ return;
129424
+ case "quantifier":
129425
+ yield* matchQuantifier(node, state, context, 0);
129426
+ }
129427
+ }
129428
+ function* matchSequence(elements, index, state, context) {
129429
+ charge(context);
129430
+ if (index === elements.length) {
129431
+ yield state;
129432
+ return;
129433
+ }
129434
+ for (const result of matchNode(elements[index], state, context)) {
129435
+ yield* matchSequence(elements, index + 1, result, context);
129436
+ }
129437
+ }
129438
+ function* matchQuantifier(node, state, context, count) {
129439
+ charge(context);
129440
+ const canRepeat = node.max === void 0 || count < node.max;
129441
+ if (!node.greedy && count >= node.min) {
129442
+ yield state;
129443
+ }
129444
+ if (canRepeat) {
129445
+ for (const result of matchNode(node.body, clearCaptures(node.body, state), context)) {
129446
+ if (result.position === state.position) {
129447
+ if (count >= node.min) {
129448
+ continue;
129449
+ }
129450
+ if (count + 1 >= node.min) {
129451
+ yield result;
129452
+ } else {
129453
+ yield* matchQuantifier(node, result, context, count + 1);
129454
+ }
129455
+ continue;
129456
+ }
129457
+ yield* matchQuantifier(node, result, context, count + 1);
129458
+ }
129459
+ }
129460
+ if (node.greedy && count >= node.min) {
129461
+ yield state;
129462
+ }
129463
+ }
129464
+ function matchesAnchor(kind, position, context) {
129465
+ if (kind === "start") {
129466
+ return position === 0 || context.flags.multiline && position > 0 && isLineTerminator(context.input[position - 1]);
129467
+ }
129468
+ return position === context.input.length || context.flags.multiline && position < context.input.length && isLineTerminator(context.input[position]);
129469
+ }
129470
+ function matchesCharacterClass(character2, items, negated, ignoreCase) {
129471
+ const matched = items.some((item) => matchesCharacterClassItem(character2, item, ignoreCase));
129472
+ return negated ? !matched : matched;
129473
+ }
129474
+ function matchesCharacterClassItem(character2, item, ignoreCase) {
129475
+ if (item.type === "character") {
129476
+ return charactersEqual(character2, item.value, ignoreCase);
129477
+ }
129478
+ if (item.type === "range") {
129479
+ const candidate = character2.charCodeAt(0);
129480
+ const from = item.from.charCodeAt(0);
129481
+ const to = item.to.charCodeAt(0);
129482
+ if (candidate >= from && candidate <= to) {
129483
+ return true;
129484
+ }
129485
+ if (!ignoreCase) {
129486
+ return false;
129487
+ }
129488
+ const foldedCandidate = foldCharacter(character2, true).charCodeAt(0);
129489
+ const foldedFrom = foldCharacter(item.from, true).charCodeAt(0);
129490
+ const foldedTo = foldCharacter(item.to, true).charCodeAt(0);
129491
+ return foldedCandidate >= foldedFrom && foldedCandidate <= foldedTo;
129492
+ }
129493
+ const matched = item.kind === "digit" ? isDigit5(character2) : item.kind === "word" ? isWordCharacter(character2) : isSpaceCharacter(character2);
129494
+ return item.negated ? !matched : matched;
129495
+ }
129496
+ function toRegexMatch(input, start, state) {
129497
+ return {
129498
+ index: start,
129499
+ text: input.slice(start, state.position),
129500
+ captures: state.captures.map(
129501
+ (capture) => capture === void 0 ? void 0 : input.slice(capture.start, capture.end)
129502
+ )
129503
+ };
129504
+ }
129505
+ function cloneState(state) {
129506
+ return { position: state.position, captures: state.captures.slice() };
129507
+ }
129508
+ function clearCaptures(node, state) {
129509
+ const captures = state.captures.slice();
129510
+ clearNodeCaptures(node, captures);
129511
+ return { position: state.position, captures };
129512
+ }
129513
+ function clearNodeCaptures(node, captures) {
129514
+ if (node.type === "group") {
129515
+ if (node.capturing && node.index !== void 0) {
129516
+ captures[node.index - 1] = void 0;
129517
+ }
129518
+ clearNodeCaptures(node.body, captures);
129519
+ return;
129520
+ }
129521
+ if (node.type === "sequence") {
129522
+ for (const element of node.elements) {
129523
+ clearNodeCaptures(element, captures);
129524
+ }
129525
+ return;
129526
+ }
129527
+ if (node.type === "alternation") {
129528
+ for (const alternative of node.alternatives) {
129529
+ clearNodeCaptures(alternative, captures);
129530
+ }
129531
+ return;
129532
+ }
129533
+ if (node.type === "quantifier") {
129534
+ clearNodeCaptures(node.body, captures);
129535
+ }
129536
+ }
129537
+ function charge(context) {
129538
+ context.steps += 1;
129539
+ allocateRegexSteps(context.steps);
129540
+ }
129541
+ function normalizeLastIndex(lastIndex) {
129542
+ if (Number.isNaN(lastIndex) || lastIndex <= 0) {
129543
+ return 0;
129544
+ }
129545
+ return Math.min(Math.floor(lastIndex), Number.MAX_SAFE_INTEGER);
129546
+ }
129547
+ function charactersEqual(left, right, ignoreCase) {
129548
+ return left !== void 0 && foldCharacter(left, ignoreCase) === foldCharacter(right, ignoreCase);
129549
+ }
129550
+ function foldCharacter(character2, ignoreCase) {
129551
+ if (!ignoreCase) {
129552
+ return character2;
129553
+ }
129554
+ const folded = character2.toUpperCase();
129555
+ if (folded.length !== 1) {
129556
+ return character2;
129557
+ }
129558
+ if (character2.charCodeAt(0) >= 128 && folded.charCodeAt(0) < 128) {
129559
+ return character2;
129560
+ }
129561
+ return folded;
129562
+ }
129563
+ function isDigit5(character2) {
129564
+ return character2 >= "0" && character2 <= "9";
129565
+ }
129566
+ function isWordCharacter(character2) {
129567
+ return isDigit5(character2) || character2 >= "A" && character2 <= "Z" || character2 >= "a" && character2 <= "z" || character2 === "_";
129568
+ }
129569
+ function isSpaceCharacter(character2) {
129570
+ return character2 === " " || character2 === "\f" || character2 === "\n" || character2 === "\r" || character2 === " " || character2 === "\v" || character2 === "\xA0" || character2 === "\u1680" || character2 >= "\u2000" && character2 <= "\u200A" || character2 === "\u2028" || character2 === "\u2029" || character2 === "\u202F" || character2 === "\u205F" || character2 === "\u3000" || character2 === "\uFEFF";
129571
+ }
129572
+ function isLineTerminator(character2) {
129573
+ return character2 === "\n" || character2 === "\r" || character2 === "\u2028" || character2 === "\u2029";
129574
+ }
129575
+ var init_engine2 = __esm({
129576
+ "packages/safe-js/src/interp/regex/engine.ts"() {
129577
+ "use strict";
129578
+ init_budget2();
129579
+ }
129580
+ });
129581
+
129274
129582
  // packages/safe-js/src/interp/jobs.ts
129275
129583
  import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
129276
129584
  function runPromiseJob(task) {
@@ -129369,616 +129677,6 @@ var init_jobs4 = __esm({
129369
129677
  }
129370
129678
  });
129371
129679
 
129372
- // packages/safe-js/src/interp/iteration.ts
129373
- async function acquireSandboxIterator(value, budget, context, asyncProtocol = false, signal) {
129374
- const key3 = asyncProtocol ? Symbol.asyncIterator : Symbol.iterator;
129375
- if (context.getProperty === void 0 || isGuestHostObject(value))
129376
- return asyncProtocol ? getSandboxAsyncIterator(value, budget, context, signal) : getSandboxIterator(value, budget, context);
129377
- if (getSandboxPropertyDescriptor(value, key3, budget) === void 0) {
129378
- if (!asyncProtocol) return getSandboxIterator(value, budget, context);
129379
- if (isSandboxGenerator(value) && value.async)
129380
- return getSandboxAsyncIterator(value, budget, context, signal);
129381
- const iterator2 = await acquireSandboxIterator(value, budget, context);
129382
- return iterator2 === void 0 ? void 0 : asyncFromSyncIterator(iterator2, budget, signal);
129383
- }
129384
- const factory = await context.getProperty(value, key3);
129385
- if (factory === null || factory === void 0) {
129386
- if (!asyncProtocol) return void 0;
129387
- const iterator2 = await acquireSandboxIterator(value, budget, context);
129388
- return iterator2 === void 0 ? void 0 : asyncFromSyncIterator(iterator2, budget, signal);
129389
- }
129390
- if (!isSandboxClosure(factory)) {
129391
- if (typeof factory !== "function") throw new TypeError("Iterator method must be callable.");
129392
- if (asyncProtocol) return nativeAsyncIterator(value, factory, signal);
129393
- const iterator2 = Reflect.apply(factory, value, []);
129394
- if (typeof iterator2 !== "object" && typeof iterator2 !== "function" || iterator2 === null)
129395
- throw new TypeError("Iterator must be an object.");
129396
- return syncIterator(iterator2);
129397
- }
129398
- const iterator = await invokeBuiltinClosure(factory, [], budget, context, value);
129399
- if (typeof iterator !== "object" && typeof iterator !== "function" || iterator === null)
129400
- throw new TypeError("Iterator must be an object.");
129401
- const next = await context.getProperty(iterator, "next");
129402
- const invoke2 = async (operation, args) => {
129403
- if (!isSandboxClosure(operation)) throw new TypeError("Iterator operation must be callable.");
129404
- const returned = await invokeBuiltinClosure(operation, args, budget, context, iterator);
129405
- const result = asyncProtocol ? await awaitSandboxValue(returned, signal, budget) : returned;
129406
- if (typeof result !== "object" && typeof result !== "function" || result === null)
129407
- throw new TypeError("Iterator result must be an object.");
129408
- return result;
129409
- };
129410
- return {
129411
- ...asyncProtocol ? { asyncProtocol: true } : {},
129412
- asynchronous: true,
129413
- retainedValue: [value, iterator, next],
129414
- next: (...args) => invoke2(next, args),
129415
- getOperation: async (method) => {
129416
- const operation = method === "next" ? next : await context.getProperty(iterator, method);
129417
- return method !== "next" && (operation === void 0 || operation === null) ? void 0 : (...args) => invoke2(operation, args);
129418
- },
129419
- readResultProperty: async (result, property) => ({
129420
- value: await context.getProperty(result, property)
129421
- })
129422
- };
129423
- }
129424
- async function readIteratorResult(iterator, result, property) {
129425
- return iterator.readResultProperty === void 0 ? { value: result[property] } : iterator.readResultProperty(result, property);
129426
- }
129427
- function getSandboxAsyncIterator(value, budget, context, signal) {
129428
- if (isSandboxGenerator(value) && value.async) {
129429
- return { ...generatorIterator(value, budget), asyncProtocol: true };
129430
- }
129431
- if (value !== null && (typeof value === "object" || typeof value === "function") && !isGuestHostObject(value)) {
129432
- const method = value[Symbol.asyncIterator];
129433
- if (method !== void 0 && method !== null) {
129434
- return nativeAsyncIterator(value, method, signal);
129435
- }
129436
- }
129437
- const iterator = getSandboxIterator(value, budget, context);
129438
- return iterator === void 0 ? void 0 : asyncFromSyncIterator(iterator, budget, signal);
129439
- }
129440
- function nativeAsyncIterator(value, method, signal) {
129441
- if (typeof method !== "function") throw new TypeError("Async iterator method must be callable.");
129442
- const iterator = Reflect.apply(method, value, []);
129443
- if (typeof iterator !== "object" && typeof iterator !== "function" || iterator === null) {
129444
- throw new TypeError("Async iterator must be an object.");
129445
- }
129446
- const next = iterator.next;
129447
- const invoke2 = async (operation, args) => {
129448
- if (typeof operation !== "function")
129449
- throw new TypeError("Async iterator operation must be callable.");
129450
- const pending = Promise.resolve(Reflect.apply(operation, iterator, args)).then((result2) => ({
129451
- result: result2
129452
- }));
129453
- const { result } = await awaitWithSignal(pending, signal);
129454
- if (typeof result !== "object" && typeof result !== "function" || result === null) {
129455
- throw new TypeError("Iterator result must be an object.");
129456
- }
129457
- return {
129458
- get done() {
129459
- return result.done;
129460
- },
129461
- get value() {
129462
- return result.value;
129463
- }
129464
- };
129465
- };
129466
- return {
129467
- asyncProtocol: true,
129468
- retainedValue: value,
129469
- next: (...args) => invoke2(next, args),
129470
- get return() {
129471
- const operation = iterator.return;
129472
- return operation === void 0 || operation === null ? void 0 : (...args) => invoke2(operation, args);
129473
- },
129474
- get throw() {
129475
- const operation = iterator.throw;
129476
- return operation === void 0 || operation === null ? void 0 : (...args) => invoke2(operation, args);
129477
- }
129478
- };
129479
- }
129480
- function asyncFromSyncIterator(iterator, budget, signal) {
129481
- const invoke2 = async (method, args) => {
129482
- const operation = iterator.getOperation === void 0 ? iterator[method] : await iterator.getOperation(method);
129483
- if (operation === void 0) {
129484
- if (method === "throw") {
129485
- await closeIterator(iterator);
129486
- throw new TypeError("Delegated iterator does not provide a throw method.");
129487
- }
129488
- return { done: true, value: args[0] };
129489
- }
129490
- const returned = operation(...args);
129491
- const result = iterator.generator || iterator.asynchronous ? await returned : returned;
129492
- if (typeof result !== "object" && typeof result !== "function" || result === null) {
129493
- throw new TypeError("Iterator result must be an object.");
129494
- }
129495
- const done = Boolean((await readIteratorResult(iterator, result, "done")).value);
129496
- const resultValue = (await readIteratorResult(iterator, result, "value")).value;
129497
- try {
129498
- return { done, value: await awaitSandboxValue(resultValue, signal, budget) };
129499
- } catch (error3) {
129500
- if (isFatalSandboxError(error3) || error3 instanceof HostCallResumabilityError) throw error3;
129501
- if (!done && method !== "return") await closeIterator(iterator, true);
129502
- throw error3;
129503
- }
129504
- };
129505
- return {
129506
- asyncProtocol: true,
129507
- snapshotIndex: iterator.snapshotIndex,
129508
- get retainedValue() {
129509
- return iterator.retainedValue;
129510
- },
129511
- next: (...args) => invoke2("next", args),
129512
- return: (...args) => invoke2("return", args),
129513
- throw: (...args) => invoke2("throw", args)
129514
- };
129515
- }
129516
- async function closeIterator(iterator, preserveThrow = false) {
129517
- try {
129518
- const close = iterator.getOperation === void 0 ? iterator.return : await iterator.getOperation("return");
129519
- if (close === void 0) return;
129520
- const returned = close();
129521
- const result = iterator.asyncProtocol ? await suspendJob(Promise.resolve(returned)) : iterator.generator || iterator.asynchronous ? await returned : returned;
129522
- if (typeof result !== "object" && typeof result !== "function" || result === null) {
129523
- throw new TypeError("Iterator return result must be an object.");
129524
- }
129525
- } catch (error3) {
129526
- if (!preserveThrow || isFatalSandboxError(error3) || error3 instanceof HostCallResumabilityError)
129527
- throw error3;
129528
- }
129529
- }
129530
- function getSandboxIterator(value, budget, context) {
129531
- if (isSandboxBox(value) && typeof boxedValue(value) === "string") {
129532
- const primitive = boxedValue(value);
129533
- let text5;
129534
- let iterator2;
129535
- let initialized;
129536
- return {
129537
- asynchronous: true,
129538
- get retainedValue() {
129539
- return text5 === primitive ? void 0 : text5;
129540
- },
129541
- next: async () => {
129542
- initialized ??= Promise.resolve(sandboxString(value, budget ?? new Budget(), context)).then(
129543
- (converted) => {
129544
- text5 = converted;
129545
- iterator2 = syncIterator(converted[Symbol.iterator]());
129546
- }
129547
- );
129548
- await initialized;
129549
- return iterator2.next();
129550
- }
129551
- };
129552
- }
129553
- if (isSandboxCollectionIterator(value))
129554
- return { next: () => nextCollectionIterator(value, budget), snapshotIndex: () => 0 };
129555
- if (isGuestHostObject(value)) return getHostObjectIterator(value);
129556
- if (isFloat32Array(value)) {
129557
- return syncIterator(Float32Array.prototype.values.call(value));
129558
- }
129559
- if (isSandboxGenerator(value)) {
129560
- return value.async ? void 0 : generatorIterator(value);
129561
- }
129562
- if (typeof value === "string") {
129563
- return syncIterator(value[Symbol.iterator]());
129564
- }
129565
- if (isSandboxMap(value)) {
129566
- return collectionIterator(value.entries);
129567
- }
129568
- if (isSandboxSet(value)) {
129569
- return collectionIterator(value.values);
129570
- }
129571
- if (Array.isArray(value) && hasExplicitSandboxPrototype(value)) return void 0;
129572
- if (Array.isArray(value) && context?.getProperty !== void 0) {
129573
- let index = 0;
129574
- return {
129575
- asynchronous: true,
129576
- snapshotIndex: () => index,
129577
- next: async () => {
129578
- if (index >= value.length) return { done: true, value: void 0 };
129579
- budget?.visitNode();
129580
- return { done: false, value: await context.getProperty(value, index++) };
129581
- }
129582
- };
129583
- }
129584
- if (typeof value !== "object" && typeof value !== "function" || value === null) {
129585
- return void 0;
129586
- }
129587
- const iteratorMethod = value[Symbol.iterator];
129588
- if (iteratorMethod === void 0 || iteratorMethod === null) return void 0;
129589
- if (typeof iteratorMethod !== "function") {
129590
- throw new TypeError("Iterator method must be callable.");
129591
- }
129592
- const iterator = Reflect.apply(iteratorMethod, value, []);
129593
- if (typeof iterator !== "object" && typeof iterator !== "function" || iterator === null) {
129594
- throw new TypeError("Iterator must be an object.");
129595
- }
129596
- return syncIterator(iterator);
129597
- }
129598
- function collectionIterator(collection) {
129599
- let iterator = collection[Symbol.iterator]();
129600
- let exhausted = false;
129601
- return {
129602
- ...syncIterator({
129603
- next: () => {
129604
- if (exhausted) return { done: true, value: void 0 };
129605
- const result = iterator.next();
129606
- exhausted = result.done === true;
129607
- return result;
129608
- }
129609
- }),
129610
- snapshotIndex: () => {
129611
- if (exhausted) return collection.size;
129612
- let remaining = 0;
129613
- while (!iterator.next().done) remaining += 1;
129614
- const index = collection.size - remaining;
129615
- iterator = collection[Symbol.iterator]();
129616
- for (let skipped = 0; skipped < index; skipped += 1) iterator.next();
129617
- return index;
129618
- }
129619
- };
129620
- }
129621
- function generatorIterator(generator, budget) {
129622
- const invoke2 = async (method, value) => {
129623
- const leaveRunning = enterRunningState(generator);
129624
- const initialState = generator.state;
129625
- generator.state = "running";
129626
- try {
129627
- if (generator.async && method === "return" && (initialState === "start" || initialState === "done")) {
129628
- if (initialState === "start") await generator.channel.return();
129629
- value = await awaitSandboxValue(value, void 0, budget);
129630
- }
129631
- const result = await generator.channel[method](value);
129632
- generator.state = result.done ? "done" : "suspended";
129633
- return result;
129634
- } catch (error3) {
129635
- generator.state = "done";
129636
- throw error3;
129637
- } finally {
129638
- leaveRunning();
129639
- }
129640
- };
129641
- const request = (method, value) => {
129642
- if (!generator.async) return invoke2(method, value);
129643
- const previous = asyncGeneratorRequests.get(generator) ?? Promise.resolve();
129644
- const result = previous.then(() => invoke2(method, value));
129645
- asyncGeneratorRequests.set(
129646
- generator,
129647
- result.catch(() => void 0)
129648
- );
129649
- return result;
129650
- };
129651
- return {
129652
- generator: true,
129653
- next: (value) => request("next", value),
129654
- return: (value) => request("return", value),
129655
- throw: (error3) => request("throw", error3)
129656
- };
129657
- }
129658
- function syncIterator(iterator) {
129659
- const next = iterator.next;
129660
- const invoke2 = (method, args) => {
129661
- const leaveRunning = enterRunningState(iterator);
129662
- try {
129663
- return Reflect.apply(method, iterator, args);
129664
- } finally {
129665
- leaveRunning();
129666
- }
129667
- };
129668
- return {
129669
- next: (...args) => invoke2(next, args),
129670
- get return() {
129671
- const method = iterator.return;
129672
- if (method === void 0 || method === null) return void 0;
129673
- if (typeof method !== "function") throw new TypeError("Iterator return must be callable.");
129674
- return (...args) => invoke2(method, args);
129675
- },
129676
- get throw() {
129677
- const method = iterator.throw;
129678
- if (method === void 0 || method === null) return void 0;
129679
- if (typeof method !== "function") throw new TypeError("Iterator throw must be callable.");
129680
- return (...args) => invoke2(method, args);
129681
- }
129682
- };
129683
- }
129684
- var asyncGeneratorRequests;
129685
- var init_iteration = __esm({
129686
- "packages/safe-js/src/interp/iteration.ts"() {
129687
- "use strict";
129688
- init_values();
129689
- init_running_state();
129690
- init_float32();
129691
- init_boxed();
129692
- init_host_capabilities();
129693
- init_collection_iterator();
129694
- init_budget2();
129695
- init_string_coercion();
129696
- init_cancel2();
129697
- init_host_call();
129698
- init_jobs4();
129699
- init_builtin_call();
129700
- init_object_model();
129701
- asyncGeneratorRequests = /* @__PURE__ */ new WeakMap();
129702
- }
129703
- });
129704
-
129705
- // packages/safe-js/src/interp/patterns.ts
129706
- async function bindPattern(pattern, value, target, scope, context, reference) {
129707
- switch (pattern.type) {
129708
- case "Identifier":
129709
- bindIdentifier(pattern, value, target, scope);
129710
- return { ok: true };
129711
- case "MemberExpression":
129712
- if ("kind" in target) {
129713
- throw new TypeError("Destructuring declarations cannot bind to member expressions.");
129714
- }
129715
- return bindMemberExpression(pattern, value, context, reference);
129716
- case "AssignmentPattern":
129717
- return bindAssignmentPattern(pattern, value, target, scope, context, reference);
129718
- case "ArrayPattern":
129719
- return bindArrayPattern(pattern, value, target, scope, context);
129720
- case "ObjectPattern":
129721
- return bindObjectPattern(pattern, value, target, scope, context);
129722
- case "RestElement":
129723
- return bindPattern(pattern.argument, value, target, scope, context, reference);
129724
- }
129725
- }
129726
- function bindIdentifier(pattern, value, target, scope) {
129727
- if ("assign" in target || target.kind === "var" && target.initialize !== true) {
129728
- if ("assign" in target) {
129729
- const binding = scope.lookup(pattern.name);
129730
- if (!binding.found) {
129731
- throw new ReferenceError(`Cannot assign to undeclared binding '${pattern.name}'.`);
129732
- }
129733
- if (binding.kind === "const") {
129734
- throw new TypeError(`Cannot assign to const '${pattern.name}'`);
129735
- }
129736
- }
129737
- scope.assign(pattern.name, value);
129738
- return;
129739
- }
129740
- scope.declare(pattern.name, target.kind, value);
129741
- }
129742
- async function bindAssignmentPattern(pattern, value, target, scope, context, reference) {
129743
- if (value !== void 0) {
129744
- return bindPattern(pattern.left, value, target, scope, context, reference);
129745
- }
129746
- const defaultValue = await context.evaluate(
129747
- pattern.right,
129748
- pattern.left.type === "Identifier" ? pattern.left.name : void 0
129749
- );
129750
- if (defaultValue.kind !== "normal") {
129751
- return { ok: false, result: defaultValue };
129752
- }
129753
- return bindPattern(pattern.left, defaultValue.value, target, scope, context, reference);
129754
- }
129755
- async function bindPatternValue(pattern, readValue, target, scope, context) {
129756
- let member = pattern;
129757
- while (member.type === "AssignmentPattern" || member.type === "RestElement")
129758
- member = member.type === "AssignmentPattern" ? member.left : member.argument;
129759
- let reference;
129760
- if ("assign" in target && member.type === "MemberExpression") {
129761
- const prepared = await prepareMemberReference(member, context);
129762
- if (!prepared.ok) return prepared;
129763
- reference = prepared.reference;
129764
- }
129765
- let value;
129766
- const release2 = context.budget === void 0 ? () => void 0 : retainValues(context.budget, () => [reference?.object, reference?.key, value]);
129767
- try {
129768
- value = (await readValue()).value;
129769
- return await bindPattern(pattern, value, target, scope, context, reference);
129770
- } finally {
129771
- release2();
129772
- }
129773
- }
129774
- async function bindArrayPattern(pattern, value, target, scope, context) {
129775
- const budget = context.budget ?? new Budget();
129776
- const iterator = await acquireSandboxIterator(
129777
- value,
129778
- budget,
129779
- context.callContext ?? {
129780
- stack: [],
129781
- thisValue: void 0,
129782
- getProperty: context.getProperty
129783
- }
129784
- );
129785
- if (iterator === void 0) throw new TypeError("Array destructuring requires an iterable.");
129786
- let done = false;
129787
- const next = async (readValue = true) => {
129788
- if (done) return { value: void 0 };
129789
- try {
129790
- const result = await iterator.next();
129791
- if (typeof result !== "object" && typeof result !== "function" || result === null)
129792
- throw new TypeError("Iterator result must be an object.");
129793
- done = Boolean((await readIteratorResult(iterator, result, "done")).value);
129794
- return done || !readValue ? { value: void 0 } : await readIteratorResult(iterator, result, "value");
129795
- } catch (error3) {
129796
- done = true;
129797
- throw error3;
129798
- }
129799
- };
129800
- let retained;
129801
- const release2 = retainValues(budget, () => [value, iterator.retainedValue, retained]);
129802
- try {
129803
- for (let index = 0; index < pattern.elements.length; index += 1) {
129804
- const element = pattern.elements[index];
129805
- if (element === null) {
129806
- await next(false);
129807
- continue;
129808
- }
129809
- const binding = await bindPatternValue(
129810
- element,
129811
- async () => {
129812
- if (element.type !== "RestElement") return next();
129813
- const rest = [];
129814
- retained = rest;
129815
- for (let entry = await next(); !done; entry = await next()) {
129816
- budget.allocateArrayLength(rest.length + 1);
129817
- rest.push(entry.value);
129818
- }
129819
- return { value: rest };
129820
- },
129821
- target,
129822
- scope,
129823
- context
129824
- );
129825
- if (!binding.ok) {
129826
- if (!done) {
129827
- done = true;
129828
- await closeIterator(iterator, binding.result.kind === "throw");
129829
- }
129830
- return binding;
129831
- }
129832
- }
129833
- if (!done) {
129834
- done = true;
129835
- await closeIterator(iterator);
129836
- }
129837
- return { ok: true };
129838
- } catch (error3) {
129839
- if (!done && !isFatalSandboxError(error3)) await closeIterator(iterator, true);
129840
- throw error3;
129841
- } finally {
129842
- release2();
129843
- }
129844
- }
129845
- async function bindObjectPattern(pattern, value, target, scope, context) {
129846
- if (value === void 0 || value === null) {
129847
- throw new TypeError("Object destructuring requires a non-nullish value.");
129848
- }
129849
- const excludedKeys = /* @__PURE__ */ new Set();
129850
- for (const property of pattern.properties) {
129851
- if (property.type === "RestElement") {
129852
- const binding2 = await bindPatternValue(
129853
- property,
129854
- async () => ({ value: await copyObjectRestValue(value, excludedKeys, context) }),
129855
- target,
129856
- scope,
129857
- context
129858
- );
129859
- if (!binding2.ok) {
129860
- return binding2;
129861
- }
129862
- continue;
129863
- }
129864
- const key3 = await evaluatePatternKey(property, context);
129865
- if (!key3.ok) {
129866
- return key3;
129867
- }
129868
- excludedKeys.add(typeof key3.value === "symbol" ? key3.value : String(key3.value));
129869
- const binding = await bindPatternValue(
129870
- property.value,
129871
- async () => ({ value: await context.getProperty(value, key3.value) }),
129872
- target,
129873
- scope,
129874
- context
129875
- );
129876
- if (!binding.ok) {
129877
- return binding;
129878
- }
129879
- }
129880
- return { ok: true };
129881
- }
129882
- async function bindMemberExpression(pattern, value, context, reference) {
129883
- if (reference === void 0) {
129884
- const prepared = await prepareMemberReference(pattern, context);
129885
- if (!prepared.ok) return prepared;
129886
- reference = prepared.reference;
129887
- }
129888
- if (reference.object === null || reference.object === void 0) {
129889
- throw new TypeError("Cannot assign properties of null or undefined.");
129890
- }
129891
- if (!isIndexableValue(reference.object)) {
129892
- throw new TypeError("Assignment expressions require a sandbox object property.");
129893
- }
129894
- await context.setProperty(reference.object, reference.key, value);
129895
- return { ok: true };
129896
- }
129897
- async function prepareMemberReference(pattern, context) {
129898
- const object = await context.evaluate(pattern.object);
129899
- if (object.kind !== "normal") {
129900
- return { ok: false, result: object };
129901
- }
129902
- const property = pattern.computed ? await context.evaluate(pattern.property) : { kind: "normal", value: getStaticPropertyName(pattern.property) };
129903
- if (property.kind !== "normal") {
129904
- return { ok: false, result: property };
129905
- }
129906
- return {
129907
- ok: true,
129908
- reference: { object: object.value, key: await context.toPropertyKey(property.value) }
129909
- };
129910
- }
129911
- async function evaluatePatternKey(property, context) {
129912
- return property.computed ? evaluateProperty(property.key, context) : { ok: true, value: getStaticPropertyName(property.key) };
129913
- }
129914
- async function evaluateProperty(property, context) {
129915
- const result = await context.evaluate(property);
129916
- if (result.kind !== "normal") {
129917
- return { ok: false, result };
129918
- }
129919
- return { ok: true, value: await context.toPropertyKey(result.value) };
129920
- }
129921
- function getStaticPropertyName(property) {
129922
- if (property.type === "Identifier") {
129923
- return property.name;
129924
- }
129925
- if (property.type === "StringLiteral" || property.type === "NumericLiteral") {
129926
- return property.value;
129927
- }
129928
- throw new TypeError(`Unsupported static property node '${property.type}'.`);
129929
- }
129930
- async function copyObjectRestValue(value, excludedKeys, context) {
129931
- const rest = /* @__PURE__ */ Object.create(null);
129932
- const release2 = context.budget === void 0 ? () => void 0 : retainValues(context.budget, () => [value, rest]);
129933
- try {
129934
- for (const key3 of ownEnumerableSandboxKeys(value, true)) {
129935
- if (excludedKeys.has(key3) || !hasOwnSandboxProperty(value, key3, true)) continue;
129936
- defineProperty(rest, key3, await context.getProperty(value, key3));
129937
- }
129938
- return rest;
129939
- } finally {
129940
- release2();
129941
- }
129942
- }
129943
- function isIndexableValue(value) {
129944
- return typeof value === "object" && value !== null;
129945
- }
129946
- function defineProperty(target, key3, value) {
129947
- Object.defineProperty(target, key3, {
129948
- configurable: true,
129949
- enumerable: true,
129950
- value,
129951
- writable: true
129952
- });
129953
- }
129954
- var init_patterns = __esm({
129955
- "packages/safe-js/src/interp/patterns.ts"() {
129956
- "use strict";
129957
- init_budget2();
129958
- init_resources();
129959
- init_object2();
129960
- init_iteration();
129961
- init_values();
129962
- }
129963
- });
129964
-
129965
- // packages/safe-js/src/interp/var-hoist.ts
129966
- function hoistVarDeclarations(node, scope) {
129967
- for (const declaration of hoistedVarDeclarations([node])) {
129968
- for (const declarator of declaration.declarations) {
129969
- for (const identifier of boundIdentifiers(declarator.id)) {
129970
- scope.declareVar(identifier.name);
129971
- }
129972
- }
129973
- }
129974
- }
129975
- var init_var_hoist = __esm({
129976
- "packages/safe-js/src/interp/var-hoist.ts"() {
129977
- "use strict";
129978
- init_bindings();
129979
- }
129980
- });
129981
-
129982
129680
  // packages/safe-js/src/interp/data-checkpoint.ts
129983
129681
  function createDataCheckpoint(budget, context) {
129984
129682
  let estimatedDataSize = 0;
@@ -130109,360 +129807,6 @@ var init_number = __esm({
130109
129807
  }
130110
129808
  });
130111
129809
 
130112
- // packages/safe-js/src/interp/regex/engine.ts
130113
- function matchRegex(pattern, input, lastIndex = 0) {
130114
- const startIndex = pattern.flags.global ? normalizeLastIndex(lastIndex) : 0;
130115
- return matchRegexFrom(pattern, input, startIndex);
130116
- }
130117
- function matchRegexFrom(pattern, input, startIndex) {
130118
- if (startIndex > input.length) {
130119
- return null;
130120
- }
130121
- for (let attempt = startIndex; attempt <= input.length; attempt += 1) {
130122
- const context = { input, flags: pattern.flags, steps: 0 };
130123
- charge(context);
130124
- const initialState = {
130125
- position: attempt,
130126
- captures: new Array(pattern.captureCount)
130127
- };
130128
- const result = matchNode(pattern.body, initialState, context).next();
130129
- if (!result.done) {
130130
- return toRegexMatch(input, attempt, result.value);
130131
- }
130132
- }
130133
- return null;
130134
- }
130135
- function* matchNode(node, state, context) {
130136
- charge(context);
130137
- switch (node.type) {
130138
- case "empty":
130139
- yield state;
130140
- return;
130141
- case "literal":
130142
- if (charactersEqual(context.input[state.position], node.value, context.flags.ignoreCase)) {
130143
- yield { ...state, position: state.position + 1 };
130144
- }
130145
- return;
130146
- case "dot":
130147
- if (state.position < context.input.length && (context.flags.dotAll || !isLineTerminator(context.input[state.position]))) {
130148
- yield { ...state, position: state.position + 1 };
130149
- }
130150
- return;
130151
- case "anchor":
130152
- if (matchesAnchor(node.kind, state.position, context)) {
130153
- yield state;
130154
- }
130155
- return;
130156
- case "wordBoundary": {
130157
- const previousWord = state.position > 0 && isWordCharacter(context.input[state.position - 1]);
130158
- const nextWord = state.position < context.input.length && isWordCharacter(context.input[state.position]);
130159
- if (previousWord !== nextWord !== node.negated) {
130160
- yield state;
130161
- }
130162
- return;
130163
- }
130164
- case "characterClass": {
130165
- const character2 = context.input[state.position];
130166
- if (character2 !== void 0 && matchesCharacterClass(character2, node.items, node.negated, context.flags.ignoreCase)) {
130167
- yield { ...state, position: state.position + 1 };
130168
- }
130169
- return;
130170
- }
130171
- case "sequence":
130172
- yield* matchSequence(node.elements, 0, state, context);
130173
- return;
130174
- case "alternation":
130175
- for (const alternative of node.alternatives) {
130176
- yield* matchNode(alternative, cloneState(state), context);
130177
- }
130178
- return;
130179
- case "group":
130180
- for (const result of matchNode(node.body, cloneState(state), context)) {
130181
- if (!node.capturing || node.index === void 0) {
130182
- yield result;
130183
- continue;
130184
- }
130185
- const captures = result.captures.slice();
130186
- captures[node.index - 1] = { start: state.position, end: result.position };
130187
- yield { position: result.position, captures };
130188
- }
130189
- return;
130190
- case "quantifier":
130191
- yield* matchQuantifier(node, state, context, 0);
130192
- }
130193
- }
130194
- function* matchSequence(elements, index, state, context) {
130195
- charge(context);
130196
- if (index === elements.length) {
130197
- yield state;
130198
- return;
130199
- }
130200
- for (const result of matchNode(elements[index], state, context)) {
130201
- yield* matchSequence(elements, index + 1, result, context);
130202
- }
130203
- }
130204
- function* matchQuantifier(node, state, context, count) {
130205
- charge(context);
130206
- const canRepeat = node.max === void 0 || count < node.max;
130207
- if (!node.greedy && count >= node.min) {
130208
- yield state;
130209
- }
130210
- if (canRepeat) {
130211
- for (const result of matchNode(node.body, clearCaptures(node.body, state), context)) {
130212
- if (result.position === state.position) {
130213
- if (count >= node.min) {
130214
- continue;
130215
- }
130216
- if (count + 1 >= node.min) {
130217
- yield result;
130218
- } else {
130219
- yield* matchQuantifier(node, result, context, count + 1);
130220
- }
130221
- continue;
130222
- }
130223
- yield* matchQuantifier(node, result, context, count + 1);
130224
- }
130225
- }
130226
- if (node.greedy && count >= node.min) {
130227
- yield state;
130228
- }
130229
- }
130230
- function matchesAnchor(kind, position, context) {
130231
- if (kind === "start") {
130232
- return position === 0 || context.flags.multiline && position > 0 && isLineTerminator(context.input[position - 1]);
130233
- }
130234
- return position === context.input.length || context.flags.multiline && position < context.input.length && isLineTerminator(context.input[position]);
130235
- }
130236
- function matchesCharacterClass(character2, items, negated, ignoreCase) {
130237
- const matched = items.some((item) => matchesCharacterClassItem(character2, item, ignoreCase));
130238
- return negated ? !matched : matched;
130239
- }
130240
- function matchesCharacterClassItem(character2, item, ignoreCase) {
130241
- if (item.type === "character") {
130242
- return charactersEqual(character2, item.value, ignoreCase);
130243
- }
130244
- if (item.type === "range") {
130245
- const candidate = character2.charCodeAt(0);
130246
- const from = item.from.charCodeAt(0);
130247
- const to = item.to.charCodeAt(0);
130248
- if (candidate >= from && candidate <= to) {
130249
- return true;
130250
- }
130251
- if (!ignoreCase) {
130252
- return false;
130253
- }
130254
- const foldedCandidate = foldCharacter(character2, true).charCodeAt(0);
130255
- const foldedFrom = foldCharacter(item.from, true).charCodeAt(0);
130256
- const foldedTo = foldCharacter(item.to, true).charCodeAt(0);
130257
- return foldedCandidate >= foldedFrom && foldedCandidate <= foldedTo;
130258
- }
130259
- const matched = item.kind === "digit" ? isDigit5(character2) : item.kind === "word" ? isWordCharacter(character2) : isSpaceCharacter(character2);
130260
- return item.negated ? !matched : matched;
130261
- }
130262
- function toRegexMatch(input, start, state) {
130263
- return {
130264
- index: start,
130265
- text: input.slice(start, state.position),
130266
- captures: state.captures.map(
130267
- (capture) => capture === void 0 ? void 0 : input.slice(capture.start, capture.end)
130268
- )
130269
- };
130270
- }
130271
- function cloneState(state) {
130272
- return { position: state.position, captures: state.captures.slice() };
130273
- }
130274
- function clearCaptures(node, state) {
130275
- const captures = state.captures.slice();
130276
- clearNodeCaptures(node, captures);
130277
- return { position: state.position, captures };
130278
- }
130279
- function clearNodeCaptures(node, captures) {
130280
- if (node.type === "group") {
130281
- if (node.capturing && node.index !== void 0) {
130282
- captures[node.index - 1] = void 0;
130283
- }
130284
- clearNodeCaptures(node.body, captures);
130285
- return;
130286
- }
130287
- if (node.type === "sequence") {
130288
- for (const element of node.elements) {
130289
- clearNodeCaptures(element, captures);
130290
- }
130291
- return;
130292
- }
130293
- if (node.type === "alternation") {
130294
- for (const alternative of node.alternatives) {
130295
- clearNodeCaptures(alternative, captures);
130296
- }
130297
- return;
130298
- }
130299
- if (node.type === "quantifier") {
130300
- clearNodeCaptures(node.body, captures);
130301
- }
130302
- }
130303
- function charge(context) {
130304
- context.steps += 1;
130305
- allocateRegexSteps(context.steps);
130306
- }
130307
- function normalizeLastIndex(lastIndex) {
130308
- if (Number.isNaN(lastIndex) || lastIndex <= 0) {
130309
- return 0;
130310
- }
130311
- return Math.min(Math.floor(lastIndex), Number.MAX_SAFE_INTEGER);
130312
- }
130313
- function charactersEqual(left, right, ignoreCase) {
130314
- return left !== void 0 && foldCharacter(left, ignoreCase) === foldCharacter(right, ignoreCase);
130315
- }
130316
- function foldCharacter(character2, ignoreCase) {
130317
- if (!ignoreCase) {
130318
- return character2;
130319
- }
130320
- const folded = character2.toUpperCase();
130321
- if (folded.length !== 1) {
130322
- return character2;
130323
- }
130324
- if (character2.charCodeAt(0) >= 128 && folded.charCodeAt(0) < 128) {
130325
- return character2;
130326
- }
130327
- return folded;
130328
- }
130329
- function isDigit5(character2) {
130330
- return character2 >= "0" && character2 <= "9";
130331
- }
130332
- function isWordCharacter(character2) {
130333
- return isDigit5(character2) || character2 >= "A" && character2 <= "Z" || character2 >= "a" && character2 <= "z" || character2 === "_";
130334
- }
130335
- function isSpaceCharacter(character2) {
130336
- return character2 === " " || character2 === "\f" || character2 === "\n" || character2 === "\r" || character2 === " " || character2 === "\v" || character2 === "\xA0" || character2 === "\u1680" || character2 >= "\u2000" && character2 <= "\u200A" || character2 === "\u2028" || character2 === "\u2029" || character2 === "\u202F" || character2 === "\u205F" || character2 === "\u3000" || character2 === "\uFEFF";
130337
- }
130338
- function isLineTerminator(character2) {
130339
- return character2 === "\n" || character2 === "\r" || character2 === "\u2028" || character2 === "\u2029";
130340
- }
130341
- var init_engine2 = __esm({
130342
- "packages/safe-js/src/interp/regex/engine.ts"() {
130343
- "use strict";
130344
- init_budget2();
130345
- }
130346
- });
130347
-
130348
- // packages/safe-js/src/interp/methods/regex.ts
130349
- function isRegexMethodName(property) {
130350
- return typeof property === "string" && regexMethodNames.has(property);
130351
- }
130352
- function getRegexMember(target, property, budget) {
130353
- if (property === "source") return escapeRegexSource(target.source, budget);
130354
- if (property === "flags") {
130355
- const flags = [..."gims"].filter((flag) => target.flags.includes(flag)).join("");
130356
- return budget === void 0 ? flags : budget.allocateString(flags);
130357
- }
130358
- if (property === "lastIndex") return target.lastIndex;
130359
- if (Object.hasOwn(regexFlagProperties, property)) return target.flags.includes(regexFlagProperties[property]);
130360
- if (!isRegexMethodName(property)) {
130361
- return void 0;
130362
- }
130363
- return createSandboxClosure({
130364
- sandbox: true,
130365
- name: `RegExp#${property}`,
130366
- call: (args, context) => callRegexMethod(context?.thisValue, property, args, budget, context)
130367
- });
130368
- }
130369
- function escapeRegexSource(source, budget) {
130370
- let text5 = "";
130371
- let escaped = false;
130372
- let inClass = false;
130373
- for (const character2 of source) {
130374
- budget?.visitNode();
130375
- if (character2 === "\n" || character2 === "\r" || character2 === "\u2028" || character2 === "\u2029") {
130376
- if (escaped) text5 = text5.slice(0, -1);
130377
- text5 += character2 === "\n" ? "\\n" : character2 === "\r" ? "\\r" : character2 === "\u2028" ? "\\u2028" : "\\u2029";
130378
- escaped = false;
130379
- } else {
130380
- if (!escaped && character2 === "[") inClass = true;
130381
- if (!escaped && character2 === "]") inClass = false;
130382
- text5 += character2 === "/" && !escaped && !inClass ? "\\/" : character2;
130383
- escaped = character2 === "\\" && !escaped;
130384
- }
130385
- budget?.allocateString(text5);
130386
- }
130387
- text5 = text5 === "" ? "(?:)" : text5;
130388
- return budget === void 0 ? text5 : budget.allocateString(text5);
130389
- }
130390
- function setRegexMember(target, property, value) {
130391
- const properties = getRegexProperties(target);
130392
- if (!Object.hasOwn(properties, property) && (property === "source" || property === "flags" || Object.hasOwn(regexFlagProperties, property))) {
130393
- throw new TypeError(`RegExp#${String(property)} is not writable.`);
130394
- }
130395
- if (!Reflect.set(properties, property, value)) throw new TypeError(`RegExp#${String(property)} is not writable.`);
130396
- }
130397
- async function callRegexMethod(target, methodName, args, budget, context) {
130398
- if (target === null || typeof target !== "object" || methodName === "exec" && !isSandboxRegex(target)) {
130399
- throw new TypeError(`RegExp#${methodName} requires ${methodName === "exec" ? "a regex" : "an object"} receiver.`);
130400
- }
130401
- const retained = {};
130402
- let cursor2;
130403
- let convertedInput;
130404
- budget.setRetainedValues(retained, () => [target, ...args, cursor2, convertedInput]);
130405
- try {
130406
- const input = await sandboxString(args[0], budget, context);
130407
- if (methodName === "test") {
130408
- const exec2 = context?.getProperty === void 0 ? getSandboxDataProperty(target, "exec", budget) : await context.getProperty(target, "exec");
130409
- if (isSandboxClosure(exec2)) {
130410
- const result = await invokeBuiltinClosure(exec2, [input], budget, context, target);
130411
- if (result !== null && typeof result !== "object") {
130412
- throw new TypeError("RegExp#test exec must return an object or null.");
130413
- }
130414
- return result !== null;
130415
- }
130416
- }
130417
- if (!isSandboxRegex(target)) throw new TypeError("RegExp execution requires a regex receiver.");
130418
- if (typeof args[0] !== "string") convertedInput = input;
130419
- cursor2 = target.lastIndex;
130420
- const lastIndex = await sandboxNumber(cursor2, budget, context);
130421
- const match = executeRegex(target, input, lastIndex);
130422
- return methodName === "test" ? match !== null : toMatchArray(match, input);
130423
- } finally {
130424
- budget.setRetainedValues(retained, void 0);
130425
- }
130426
- }
130427
- function executeRegex(target, input, lastIndex) {
130428
- const pattern = getSandboxRegexPattern(target);
130429
- const match = matchRegex(pattern, input, lastIndex);
130430
- if (pattern.flags.global) {
130431
- target.lastIndex = match === null ? 0 : match.index + match.text.length;
130432
- }
130433
- return match;
130434
- }
130435
- function toMatchArray(match, input) {
130436
- if (match === null) {
130437
- return null;
130438
- }
130439
- const result = [match.text, ...match.captures];
130440
- Object.assign(result, { index: match.index, input, groups: void 0 });
130441
- return result;
130442
- }
130443
- var regexMethodNames, regexFlagProperties;
130444
- var init_regex = __esm({
130445
- "packages/safe-js/src/interp/methods/regex.ts"() {
130446
- "use strict";
130447
- init_values();
130448
- init_engine2();
130449
- init_builtin_call();
130450
- init_object_model();
130451
- init_string_coercion();
130452
- regexMethodNames = /* @__PURE__ */ new Set(["exec", "test"]);
130453
- regexFlagProperties = {
130454
- hasIndices: "d",
130455
- global: "g",
130456
- ignoreCase: "i",
130457
- multiline: "m",
130458
- dotAll: "s",
130459
- unicode: "u",
130460
- unicodeSets: "v",
130461
- sticky: "y"
130462
- };
130463
- }
130464
- });
130465
-
130466
129810
  // packages/safe-js/src/interp/methods/string.ts
130467
129811
  import { types as types5 } from "node:util";
130468
129812
  function getStringMember(value, property, budget) {
@@ -130519,19 +129863,31 @@ function validateStringMethodArguments(_methodName, _args) {
130519
129863
  function callStringMethod(value, methodName, args, budget, callClosure = async (closure, closureArgs) => await closure.call(closureArgs), parent, context) {
130520
129864
  if (value === null || value === void 0)
130521
129865
  throw new TypeError(`String#${methodName} requires a non-null receiver.`);
130522
- const fallback = () => typeof value === "string" ? callStringMethodBody(value, methodName, args, budget, callClosure, parent, context) : Promise.resolve(sandboxString(value, budget, context)).then((string) => callStringMethodBody(string, methodName, args, budget, callClosure, parent, context));
129866
+ const fallback = (coercePattern = false) => {
129867
+ const apply = (string) => {
129868
+ if (coercePattern && (methodName === "match" || methodName === "matchAll" || methodName === "search"))
129869
+ return callStringPattern(string, methodName, args[0], budget, parent, context);
129870
+ const useRegex = isSandboxRegex(args[0]) && !coercePattern;
129871
+ if (methodName === "replace" || methodName === "replaceAll")
129872
+ return callReplaceLikeMethod(string, methodName, args, budget, callClosure, useRegex, context);
129873
+ if (methodName === "split") return callSplit(string, args, budget, useRegex, parent, context);
129874
+ return callStringMethodBody(string, methodName, args, budget, parent, context);
129875
+ };
129876
+ return typeof value === "string" ? apply(value) : Promise.resolve(sandboxString(value, budget, context)).then(apply);
129877
+ };
130523
129878
  const symbol2 = methodName === "match" ? Symbol.match : methodName === "search" ? Symbol.search : methodName === "matchAll" ? Symbol.matchAll : methodName === "replace" || methodName === "replaceAll" ? Symbol.replace : methodName === "split" ? Symbol.split : void 0;
130524
129879
  const pattern = args[0];
130525
129880
  if (symbol2 !== void 0 && types5.isRegExp(pattern))
130526
129881
  throw new TypeError(`String#${methodName} does not accept unbranded host RegExp values.`);
130527
129882
  if (symbol2 === void 0 || pattern === null || pattern === void 0) return fallback();
130528
- const applyHook = (hook) => {
130529
- if (hook === null || hook === void 0) return fallback();
130530
- if (!isSandboxClosure(hook)) throw new TypeError(`String#${methodName} symbol hook must be callable.`);
130531
- return invokeBuiltinClosure(hook, symbol2 === Symbol.split || symbol2 === Symbol.replace ? [value, args[1]] : [value], budget, context, pattern);
130532
- };
130533
- const readProperty = (key3) => context?.getProperty !== void 0 ? context.getProperty(pattern, key3) : key3 === "flags" && isSandboxRegex(pattern) && getSandboxPropertyDescriptor(pattern, key3, budget) === void 0 ? pattern.flags : getSandboxDataProperty(pattern, key3, budget);
129883
+ const readProperty = (key3) => context?.getProperty !== void 0 ? context.getProperty(pattern, key3) : key3 === "flags" && isSandboxRegex(pattern) && getSandboxPropertyDescriptor(pattern, key3, budget) === void 0 ? getRegexMember(pattern, key3, budget, context) : getSandboxDataProperty(pattern, key3, budget);
130534
129884
  const dispatch = () => {
129885
+ const overriddenRegex = isSandboxRegex(pattern) && getSandboxPropertyDescriptor(pattern, symbol2, budget) !== void 0;
129886
+ const applyHook = (hook2) => {
129887
+ if (hook2 === null || hook2 === void 0) return fallback(overriddenRegex);
129888
+ if (!isSandboxClosure(hook2)) throw new TypeError(`String#${methodName} symbol hook must be callable.`);
129889
+ return invokeBuiltinClosure(hook2, symbol2 === Symbol.split || symbol2 === Symbol.replace ? [value, args[1]] : [value], budget, context, pattern);
129890
+ };
130535
129891
  const hook = readProperty(symbol2);
130536
129892
  return hook instanceof Promise ? hook.then(applyHook) : applyHook(hook);
130537
129893
  };
@@ -130554,7 +129910,7 @@ function callStringMethod(value, methodName, args, budget, callClosure = async (
130554
129910
  }
130555
129911
  return dispatch();
130556
129912
  }
130557
- function callStringMethodBody(value, methodName, args, budget, callClosure = async (closure, closureArgs) => await closure.call(closureArgs), parent, context) {
129913
+ function callStringMethodBody(value, methodName, args, budget, parent, context) {
130558
129914
  if (methodName === "concat" && args.some((argument) => argument !== null && typeof argument === "object")) {
130559
129915
  return callConcat(value, args, budget, context);
130560
129916
  }
@@ -130593,11 +129949,12 @@ function callStringMethodBody(value, methodName, args, budget, callClosure = asy
130593
129949
  }
130594
129950
  return budget.allocateString(result + value.slice(spanStart));
130595
129951
  }
130596
- if (methodName === "replace" || methodName === "replaceAll") {
130597
- return callReplaceLikeMethod(value, methodName, args, budget, callClosure, context);
130598
- }
130599
129952
  const regex = args[0];
130600
- if (isSandboxRegex(regex) && regex.lastIndex !== null && typeof regex.lastIndex === "object" && (methodName === "match" && !regex.flags.includes("g") || methodName === "matchAll")) {
129953
+ if (methodName === "search" && isSandboxRegex(regex) && hasRegexPropertyOverride(regex, ["exec"], budget))
129954
+ return regexSearch(regex, value, budget, context);
129955
+ if (methodName === "match" && isSandboxRegex(regex) && hasRegexPropertyOverride(regex, ["exec", "flags", ...Object.keys(regexFlagProperties)], budget))
129956
+ return regexMatch(value, regex, budget, context);
129957
+ if (isSandboxRegex(regex) && (methodName === "matchAll" || methodName === "match" && !regex.flags.includes("g") && regex.lastIndex !== null && typeof regex.lastIndex === "object")) {
130601
129958
  return callStringRegexCursor(value, methodName, regex, budget, parent, context);
130602
129959
  }
130603
129960
  if ((methodName === "match" || methodName === "matchAll" || methodName === "search") && !isSandboxRegex(args[0])) {
@@ -130606,9 +129963,6 @@ function callStringMethodBody(value, methodName, args, budget, callClosure = asy
130606
129963
  const operation = budget.acquireCompileOwner(false, parent?.owner);
130607
129964
  const compilation = new CompileScope(operation.owner);
130608
129965
  try {
130609
- if (methodName === "split") {
130610
- return callSplit(value, args, budget, compilation);
130611
- }
130612
129966
  if (methodName === "match" || methodName === "matchAll" || methodName === "search") {
130613
129967
  return callMatchLikeMethod(value, methodName, args, compilation);
130614
129968
  }
@@ -130726,19 +130080,19 @@ async function callConcat(value, args, budget, context) {
130726
130080
  release2();
130727
130081
  }
130728
130082
  }
130729
- function callReplaceLikeMethod(value, methodName, args, budget, callClosure, context) {
130083
+ function callReplaceLikeMethod(value, methodName, args, budget, callClosure, useRegex, context) {
130730
130084
  const search = args[0];
130731
130085
  const replacement = args[1];
130732
- const useRegex = isSandboxRegex(search) && getSandboxPropertyDescriptor(search, Symbol.replace, budget) === void 0;
130733
- if (!useRegex && typeof search !== "string" || typeof replacement !== "string" && !isSandboxClosure(replacement)) {
130086
+ const regexSearch2 = useRegex && isSandboxRegex(search);
130087
+ if (!regexSearch2 && typeof search !== "string" || typeof replacement !== "string" && !isSandboxClosure(replacement)) {
130734
130088
  return (async () => {
130735
130089
  let normalizedSearch;
130736
130090
  let normalizedReplacement;
130737
130091
  const release2 = retainValues(budget, () => [normalizedSearch, normalizedReplacement]);
130738
130092
  try {
130739
- normalizedSearch = useRegex ? search : await sandboxString(search, budget, context);
130093
+ normalizedSearch = regexSearch2 ? search : await sandboxString(search, budget, context);
130740
130094
  normalizedReplacement = isSandboxClosure(replacement) ? replacement : await sandboxString(replacement, budget, context);
130741
- return await callReplaceLikeMethod(value, methodName, [normalizedSearch, normalizedReplacement], budget, callClosure, context);
130095
+ return await callReplaceLikeMethod(value, methodName, [normalizedSearch, normalizedReplacement], budget, callClosure, useRegex, context);
130742
130096
  } finally {
130743
130097
  release2();
130744
130098
  }
@@ -130765,23 +130119,28 @@ function callReplaceLikeMethod(value, methodName, args, budget, callClosure, con
130765
130119
  replacement,
130766
130120
  methodName === "replaceAll",
130767
130121
  budget,
130768
- callClosure
130122
+ callClosure,
130123
+ context
130769
130124
  );
130770
130125
  }
130771
130126
  async function replaceRegex(value, regex, replacement, budget, callClosure, context) {
130127
+ if (hasRegexPropertyOverride(regex, ["exec", "flags", ...Object.keys(regexFlagProperties)], budget))
130128
+ return regexReplace(value, regex, replacement, budget, callClosure, context);
130772
130129
  if (regex.flags.includes("g")) regex.lastIndex = 0;
130773
130130
  const cursor2 = regex.lastIndex;
130131
+ let result = "";
130774
130132
  const retained = {};
130775
- budget.setRetainedValues(retained, () => [value, regex, cursor2, replacement]);
130133
+ budget.setRetainedValues(retained, () => [value, regex, cursor2, replacement, result]);
130776
130134
  try {
130777
130135
  const lastIndex = await sandboxNumber(cursor2, budget, context);
130778
130136
  const matches = collectRegexMatches(regex, value, regex.flags.includes("g"), void 0, lastIndex);
130779
- let result = "";
130780
130137
  let copiedThrough = 0;
130781
130138
  for (const match of matches) {
130782
130139
  result += value.slice(copiedThrough, match.index);
130783
- result += typeof replacement === "string" ? expandReplacement(replacement, match.text, match.captures, value, match.index) : String(
130784
- await callClosure(replacement, [match.text, ...match.captures, match.index, value])
130140
+ result += typeof replacement === "string" ? await expandReplacement(replacement, match.text, match.captures, value, match.index, budget, context) : await sandboxString(
130141
+ await callClosure(replacement, [match.text, ...match.captures, match.index, value]),
130142
+ budget,
130143
+ context
130785
130144
  );
130786
130145
  copiedThrough = match.index + match.text.length;
130787
130146
  }
@@ -130791,57 +130150,182 @@ async function replaceRegex(value, regex, replacement, budget, callClosure, cont
130791
130150
  budget.setRetainedValues(retained, void 0);
130792
130151
  }
130793
130152
  }
130794
- function expandReplacement(replacement, match, captures, input, matchIndex) {
130153
+ function readReplacementProperty(target, key3, budget, context) {
130154
+ if (context?.getProperty !== void 0) return context.getProperty(target, key3);
130155
+ const descriptor = getSandboxPropertyDescriptor(target, key3, budget);
130156
+ if (descriptor !== void 0) return readPropertyDescriptor(descriptor, target, context);
130157
+ return isSandboxRegex(target) ? getRegexMember(target, key3, budget, context) : void 0;
130158
+ }
130159
+ async function regexReplace(input, regex, replacementInput, budget, callClosure, context) {
130160
+ if (regex === null || typeof regex !== "object") throw new TypeError("RegExp replace requires an object receiver.");
130161
+ let value;
130162
+ let replacement;
130163
+ const matches = [];
130164
+ let current;
130165
+ let field;
130166
+ let groups;
130167
+ let matched;
130168
+ let captures = [];
130795
130169
  let result = "";
130796
- for (let index = 0; index < replacement.length; index += 1) {
130797
- const character2 = replacement.charAt(index);
130798
- if (character2 !== "$") {
130799
- result += character2;
130800
- continue;
130801
- }
130802
- const token = replacement.charAt(index + 1);
130803
- if (token === "$") {
130804
- result += "$";
130805
- } else if (token === "&") {
130806
- result += match;
130807
- } else if (token === "`") {
130808
- result += input.slice(0, matchIndex);
130809
- } else if (token === "'") {
130810
- result += input.slice(matchIndex + match.length);
130811
- } else if (token >= "0" && token <= "9") {
130812
- let captureIndex = Number(token);
130813
- const nextDigit = replacement.charAt(index + 2);
130814
- if (nextDigit >= "0" && nextDigit <= "9") {
130815
- const twoDigitIndex = Number(token + nextDigit);
130816
- if (twoDigitIndex > 0 && twoDigitIndex <= captures.length) {
130817
- captureIndex = twoDigitIndex;
130818
- index += 1;
130819
- }
130170
+ let flags;
130171
+ const release2 = retainValues(budget, () => [input, value, regex, replacementInput, replacement, matches, current, field, groups, matched, captures, result, flags]);
130172
+ try {
130173
+ value = await sandboxString(input, budget, context);
130174
+ input = void 0;
130175
+ replacement = isSandboxClosure(replacementInput) ? replacementInput : await sandboxString(replacementInput, budget, context);
130176
+ replacementInput = void 0;
130177
+ if (isSandboxRegex(regex) && !hasRegexPropertyOverride(regex, ["exec", "flags", ...Object.keys(regexFlagProperties)], budget)) {
130178
+ release2();
130179
+ return await replaceRegex(value, regex, replacement, budget, callClosure, context);
130180
+ }
130181
+ field = await readReplacementProperty(regex, "flags", budget, context);
130182
+ flags = await sandboxString(field, budget, context);
130183
+ field = void 0;
130184
+ const global2 = flags.includes("g");
130185
+ const fullUnicode = flags.includes("u") || flags.includes("v");
130186
+ flags = void 0;
130187
+ if (global2) await setSandboxProperty(regex, "lastIndex", 0, budget, true, context);
130188
+ while (true) {
130189
+ budget.visitNode();
130190
+ current = await regexExec(regex, value, budget, context);
130191
+ if (current === null) break;
130192
+ budget.allocateArrayLength(matches.length + 1);
130193
+ matches.push(current);
130194
+ if (!global2) break;
130195
+ field = await readReplacementProperty(current, "0", budget, context);
130196
+ matched = await sandboxString(field, budget, context);
130197
+ field = void 0;
130198
+ if (matched.length === 0) {
130199
+ field = await readReplacementProperty(regex, "lastIndex", budget, context);
130200
+ const index = normalizeLastIndex(await sandboxNumber(field, budget, context));
130201
+ const point = fullUnicode ? value.codePointAt(index) : void 0;
130202
+ await setSandboxProperty(regex, "lastIndex", index + (point !== void 0 && point > 65535 ? 2 : 1), budget, true, context);
130203
+ field = void 0;
130204
+ }
130205
+ matched = void 0;
130206
+ current = void 0;
130207
+ }
130208
+ let copiedThrough = 0;
130209
+ for (current of matches) {
130210
+ field = await readReplacementProperty(current, "length", budget, context);
130211
+ const count = Math.max(normalizeLastIndex(await sandboxNumber(field, budget, context)) - 1, 0);
130212
+ field = await readReplacementProperty(current, "0", budget, context);
130213
+ matched = await sandboxString(field, budget, context);
130214
+ field = await readReplacementProperty(current, "index", budget, context);
130215
+ const number = await sandboxNumber(field, budget, context);
130216
+ const position = Math.min(Math.max(Number.isNaN(number) ? 0 : Math.trunc(number), 0), value.length);
130217
+ field = void 0;
130218
+ captures = [];
130219
+ budget.allocateArrayLength(count);
130220
+ for (let index = 1; index <= count; index++) {
130221
+ budget.visitNode();
130222
+ field = await readReplacementProperty(current, String(index), budget, context);
130223
+ captures.push(field === void 0 ? void 0 : await sandboxString(field, budget, context));
130224
+ field = void 0;
130225
+ }
130226
+ groups = await readReplacementProperty(current, "groups", budget, context);
130227
+ let text5;
130228
+ if (typeof replacement === "string") {
130229
+ if (groups === null) throw new TypeError("Replacement groups cannot be null.");
130230
+ if (groups !== void 0 && typeof groups !== "object") {
130231
+ groups = createSandboxBox(groups);
130232
+ budget.chargeDataUsage(measureSandboxData([groups]));
130233
+ }
130234
+ text5 = await expandReplacement(replacement, matched, captures, value, position, budget, context, groups);
130235
+ } else {
130236
+ const args = [matched, ...captures, position, value];
130237
+ if (groups !== void 0) args.push(groups);
130238
+ budget.allocateArrayLength(args.length);
130239
+ field = await callClosure(replacement, args);
130240
+ text5 = await sandboxString(field, budget, context);
130241
+ field = void 0;
130242
+ }
130243
+ if (position >= copiedThrough) {
130244
+ result = budget.allocateString(result + value.slice(copiedThrough, position) + text5);
130245
+ copiedThrough = position + matched.length;
130246
+ }
130247
+ matched = void 0;
130248
+ captures = [];
130249
+ groups = void 0;
130250
+ }
130251
+ return budget.allocateString(result + value.slice(copiedThrough));
130252
+ } finally {
130253
+ release2();
130254
+ }
130255
+ }
130256
+ async function expandReplacement(replacement, match, captures, input, matchIndex, budget, context, groups) {
130257
+ let result = "";
130258
+ const release2 = retainValues(budget, () => [replacement, match, captures, input, groups, result]);
130259
+ try {
130260
+ for (let index = 0; index < replacement.length; index += 1) {
130261
+ budget.visitNode();
130262
+ budget.allocateString(result);
130263
+ const character2 = replacement.charAt(index);
130264
+ if (character2 !== "$") {
130265
+ result += character2;
130266
+ continue;
130820
130267
  }
130821
- if (captureIndex === 0 || captureIndex > captures.length) {
130268
+ const token = replacement.charAt(index + 1);
130269
+ if (token === "$") {
130270
+ result += "$";
130271
+ } else if (token === "&") {
130272
+ result += match;
130273
+ } else if (token === "`") {
130274
+ result += input.slice(0, matchIndex);
130275
+ } else if (token === "'") {
130276
+ result += input.slice(matchIndex + match.length);
130277
+ } else if (token === "<" && groups !== void 0) {
130278
+ const end = replacement.indexOf(">", index + 2);
130279
+ if (end === -1) {
130280
+ result += "$";
130281
+ continue;
130282
+ }
130283
+ const capture = await readReplacementProperty(groups, replacement.slice(index + 2, end), budget, context);
130284
+ if (capture !== void 0) result += await sandboxString(capture, budget, context);
130285
+ index = end;
130286
+ continue;
130287
+ } else if (token >= "0" && token <= "9") {
130288
+ let captureIndex = Number(token);
130289
+ const nextDigit = replacement.charAt(index + 2);
130290
+ if (nextDigit >= "0" && nextDigit <= "9") {
130291
+ const twoDigitIndex = Number(token + nextDigit);
130292
+ if (twoDigitIndex > 0 && twoDigitIndex <= captures.length) {
130293
+ captureIndex = twoDigitIndex;
130294
+ index += 1;
130295
+ }
130296
+ }
130297
+ if (captureIndex === 0 || captureIndex > captures.length) {
130298
+ result += "$";
130299
+ continue;
130300
+ }
130301
+ result += captures[captureIndex - 1] ?? "";
130302
+ } else {
130822
130303
  result += "$";
130823
130304
  continue;
130824
130305
  }
130825
- result += captures[captureIndex - 1] ?? "";
130826
- } else {
130827
- result += "$";
130828
- continue;
130306
+ index += 1;
130829
130307
  }
130830
- index += 1;
130308
+ return budget.allocateString(result);
130309
+ } finally {
130310
+ release2();
130831
130311
  }
130832
- return result;
130833
130312
  }
130834
- async function replaceWithClosure(value, searchValue, replacer, replaceAll2, budget, callClosure) {
130313
+ async function replaceWithClosure(value, searchValue, replacer, replaceAll2, budget, callClosure, context) {
130835
130314
  const offsets = findReplacementOffsets(value, searchValue, replaceAll2);
130836
130315
  let result = "";
130837
130316
  let copiedThrough = 0;
130838
- for (const offset of offsets) {
130839
- result += value.slice(copiedThrough, offset);
130840
- result += String(await callClosure(replacer, [searchValue, offset, value]));
130841
- copiedThrough = offset + searchValue.length;
130317
+ const release2 = retainValues(budget, () => [value, searchValue, replacer, result]);
130318
+ try {
130319
+ for (const offset of offsets) {
130320
+ result += value.slice(copiedThrough, offset);
130321
+ result += await sandboxString(await callClosure(replacer, [searchValue, offset, value]), budget, context);
130322
+ copiedThrough = offset + searchValue.length;
130323
+ }
130324
+ result += value.slice(copiedThrough);
130325
+ return budget.allocateString(result);
130326
+ } finally {
130327
+ release2();
130842
130328
  }
130843
- result += value.slice(copiedThrough);
130844
- return budget.allocateString(result);
130845
130329
  }
130846
130330
  function findReplacementOffsets(value, searchValue, replaceAll2) {
130847
130331
  const firstOffset = value.indexOf(searchValue);
@@ -130862,42 +130346,73 @@ function findReplacementOffsets(value, searchValue, replaceAll2) {
130862
130346
  }
130863
130347
  return offsets;
130864
130348
  }
130865
- function callSplit(value, args, budget, compilation) {
130866
- if (args.some(isSandboxClosure))
130867
- throw new TypeError("String#split does not support function arguments.");
130868
- if (isSandboxRegex(args[0])) {
130869
- const regex = args[0];
130870
- const splitter = createSandboxRegex(
130871
- regex.source,
130872
- regex.flags.includes("g") ? regex.flags : `${regex.flags}g`,
130873
- 0,
130874
- compilation
130875
- );
130876
- const limit2 = asNumberOrUndefined(args[1]) ?? 2 ** 32 - 1;
130877
- const result2 = [];
130878
- let copiedThrough = 0;
130879
- let endedWithZeroWidthMatch = false;
130880
- for (const match of collectRegexMatches(splitter, value, true)) {
130881
- endedWithZeroWidthMatch = match.text.length === 0 && match.index === value.length;
130882
- if (match.text.length === 0 && (match.index === copiedThrough || match.index === value.length))
130883
- continue;
130884
- if (result2.length >= limit2) break;
130885
- result2.push(budget.allocateString(value.slice(copiedThrough, match.index)));
130886
- for (const capture of match.captures) {
130887
- if (result2.length >= limit2) break;
130888
- result2.push(capture === void 0 ? void 0 : budget.allocateString(capture));
130349
+ function callSplit(value, args, budget, useRegex, parent, context) {
130350
+ const pattern = args[0];
130351
+ let separator;
130352
+ const release2 = retainValues(budget, () => [value, ...args, separator]);
130353
+ const withLimit = (number) => {
130354
+ const limit = number >>> 0;
130355
+ const converted = useRegex || pattern === void 0 ? pattern : sandboxString(pattern, budget, context);
130356
+ const split = (converted2) => {
130357
+ separator = converted2;
130358
+ return splitNormalized(value, converted2, limit, budget, parent);
130359
+ };
130360
+ return converted instanceof Promise ? converted.then(split) : split(converted);
130361
+ };
130362
+ try {
130363
+ const limit = args[1] === void 0 ? 2 ** 32 - 1 : sandboxNumber(args[1], budget, context);
130364
+ const result = limit instanceof Promise ? limit.then(withLimit) : withLimit(limit);
130365
+ if (result instanceof Promise) return result.finally(release2);
130366
+ release2();
130367
+ return result;
130368
+ } catch (error3) {
130369
+ release2();
130370
+ throw error3;
130371
+ }
130372
+ }
130373
+ function splitNormalized(value, separator, limit, budget, parent) {
130374
+ if (limit === 0) return [];
130375
+ if (isSandboxRegex(separator)) {
130376
+ const regex = separator;
130377
+ const operation = budget.acquireCompileOwner(false, parent?.owner);
130378
+ const compilation = new CompileScope(operation.owner);
130379
+ try {
130380
+ const splitter = createSandboxRegex(
130381
+ regex.source,
130382
+ regex.flags.includes("g") ? regex.flags : `${regex.flags}g`,
130383
+ 0,
130384
+ compilation
130385
+ );
130386
+ const result2 = [];
130387
+ let copiedThrough = 0;
130388
+ let endedWithZeroWidthMatch = false;
130389
+ while (result2.length < limit) {
130390
+ const match = executeRegex(splitter, value, Number(splitter.lastIndex));
130391
+ if (match === null) break;
130392
+ if (match.text.length === 0) splitter.lastIndex = match.index + 1;
130393
+ endedWithZeroWidthMatch = match.text.length === 0 && match.index === value.length;
130394
+ if (match.text.length === 0 && (match.index === copiedThrough || match.index === value.length))
130395
+ continue;
130396
+ budget.allocateArrayLength(result2.length + 1);
130397
+ result2.push(budget.allocateString(value.slice(copiedThrough, match.index)));
130398
+ for (const capture of match.captures) {
130399
+ if (result2.length >= limit) break;
130400
+ budget.allocateArrayLength(result2.length + 1);
130401
+ result2.push(capture === void 0 ? void 0 : budget.allocateString(capture));
130402
+ }
130403
+ copiedThrough = match.index + match.text.length;
130889
130404
  }
130890
- copiedThrough = match.index + match.text.length;
130405
+ if (result2.length < limit && (value.length > 0 || !endedWithZeroWidthMatch)) {
130406
+ budget.allocateArrayLength(result2.length + 1);
130407
+ result2.push(budget.allocateString(value.slice(copiedThrough)));
130408
+ }
130409
+ return result2;
130410
+ } finally {
130411
+ compilation.dispose();
130412
+ operation.release();
130891
130413
  }
130892
- if (result2.length < limit2 && (value.length > 0 || !endedWithZeroWidthMatch))
130893
- result2.push(budget.allocateString(value.slice(copiedThrough)));
130894
- budget.allocateArrayLength(result2.length);
130895
- return result2;
130896
130414
  }
130897
- if (args[0] !== void 0 && typeof args[0] !== "string")
130898
- throw new TypeError(SPLIT_STRING_MESSAGE);
130899
- const limit = asNumberOrUndefined(args[1]);
130900
- const result = splitString(value, args[0], limit).map((part) => budget.allocateString(part));
130415
+ const result = splitString(value, separator, limit).map((part) => budget.allocateString(part));
130901
130416
  budget.allocateArrayLength(result.length);
130902
130417
  return result;
130903
130418
  }
@@ -130916,19 +130431,109 @@ async function callStringPattern(value, methodName, pattern, budget, parent, con
130916
130431
  operation.release();
130917
130432
  }
130918
130433
  }
130919
- async function callStringRegexCursor(value, methodName, regex, budget, parent, context) {
130434
+ async function regexMatch(input, regex, budget, context) {
130435
+ if (regex === null || typeof regex !== "object") throw new TypeError("RegExp match requires an object receiver.");
130436
+ let value;
130437
+ const matches = [];
130438
+ let result;
130439
+ let matched;
130440
+ let cursor2;
130441
+ let flagsValue;
130442
+ let flags;
130443
+ const release2 = retainValues(budget, () => [input, value, regex, matches, result, matched, cursor2, flagsValue, flags]);
130444
+ const read = (target, key3) => {
130445
+ if (context?.getProperty !== void 0) return context.getProperty(target, key3);
130446
+ const descriptor = getSandboxPropertyDescriptor(target, key3, budget);
130447
+ return descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, target, context);
130448
+ };
130449
+ try {
130450
+ value = await sandboxString(input, budget, context);
130451
+ input = void 0;
130452
+ if (isSandboxRegex(regex) && !hasRegexPropertyOverride(regex, ["exec", "flags", ...Object.keys(regexFlagProperties)], budget)) {
130453
+ release2();
130454
+ return await callStringMethodBody(value, "match", [regex], budget, context?.compilation, context);
130455
+ }
130456
+ flagsValue = await read(regex, "flags");
130457
+ flags = await sandboxString(flagsValue, budget, context);
130458
+ flagsValue = void 0;
130459
+ if (!flags.includes("g")) return await regexExec(regex, value, budget, context);
130460
+ const fullUnicode = flags.includes("u") || flags.includes("v");
130461
+ flags = void 0;
130462
+ await setSandboxProperty(regex, "lastIndex", 0, budget, true, context);
130463
+ while (true) {
130464
+ budget.visitNode();
130465
+ result = await regexExec(regex, value, budget, context);
130466
+ if (result === null) return matches.length === 0 ? null : matches;
130467
+ const descriptor = context?.getProperty === void 0 ? getSandboxPropertyDescriptor(result, "0", budget) : void 0;
130468
+ matched = await (context?.getProperty !== void 0 ? context.getProperty(result, "0") : descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, result, context));
130469
+ const text5 = await sandboxString(matched, budget, context);
130470
+ matched = void 0;
130471
+ budget.allocateArrayLength(matches.length + 1);
130472
+ matches.push(text5);
130473
+ if (text5.length === 0) {
130474
+ cursor2 = await read(regex, "lastIndex");
130475
+ const index = normalizeLastIndex(await sandboxNumber(cursor2, budget, context));
130476
+ const point = fullUnicode ? value.codePointAt(index) : void 0;
130477
+ await setSandboxProperty(regex, "lastIndex", index + (point !== void 0 && point > 65535 ? 2 : 1), budget, true, context);
130478
+ cursor2 = void 0;
130479
+ }
130480
+ result = void 0;
130481
+ }
130482
+ } finally {
130483
+ release2();
130484
+ }
130485
+ }
130486
+ function callStringRegexCursor(value, methodName, regex, budget, parent, context) {
130920
130487
  const operation = budget.acquireCompileOwner(false, parent?.owner);
130921
130488
  const compilation = new CompileScope(operation.owner);
130922
- const cursor2 = regex.lastIndex;
130489
+ let cursor2;
130490
+ let flagsValue;
130491
+ let flags;
130492
+ let matcher;
130923
130493
  const retained = {};
130924
- budget.setRetainedValues(retained, () => [value, regex, cursor2]);
130925
- try {
130926
- const lastIndex = await sandboxNumber(cursor2, budget, context);
130927
- return callMatchLikeMethod(value, methodName, [regex], compilation, lastIndex);
130928
- } finally {
130494
+ budget.setRetainedValues(retained, () => [value, regex, cursor2, flagsValue, flags, matcher]);
130495
+ const release2 = () => {
130929
130496
  budget.setRetainedValues(retained, void 0);
130930
130497
  compilation.dispose();
130931
130498
  operation.release();
130499
+ };
130500
+ const readCursor = () => {
130501
+ cursor2 = regex.lastIndex;
130502
+ const finish = (lastIndex2) => {
130503
+ if (matcher !== void 0) {
130504
+ matcher.lastIndex = normalizeLastIndex(lastIndex2);
130505
+ return restoreSandboxRegExpIterator({ matcher, input: value, exhausted: false });
130506
+ }
130507
+ return callMatchLikeMethod(value, methodName, [regex], compilation, lastIndex2);
130508
+ };
130509
+ const lastIndex = sandboxNumber(cursor2, budget, context);
130510
+ return lastIndex instanceof Promise ? lastIndex.then(finish) : finish(lastIndex);
130511
+ };
130512
+ const clone = (text5) => {
130513
+ flags = text5;
130514
+ flagsValue = void 0;
130515
+ matcher = createSandboxRegex(regex.source, flags, 0, compilation);
130516
+ flags = void 0;
130517
+ return readCursor();
130518
+ };
130519
+ const convertFlags = (value2) => {
130520
+ flagsValue = value2;
130521
+ const text5 = sandboxString(value2, budget, context);
130522
+ return text5 instanceof Promise ? text5.then(clone) : clone(text5);
130523
+ };
130524
+ try {
130525
+ let result;
130526
+ if (methodName === "matchAll") {
130527
+ const descriptor = context?.getProperty === void 0 ? getSandboxPropertyDescriptor(regex, "flags", budget) : void 0;
130528
+ const value2 = context?.getProperty !== void 0 ? context.getProperty(regex, "flags") : descriptor !== void 0 ? readPropertyDescriptor(descriptor, regex, context) : getRegexMember(regex, "flags", budget, context);
130529
+ result = value2 instanceof Promise ? value2.then(convertFlags) : convertFlags(value2);
130530
+ } else result = readCursor();
130531
+ if (result instanceof Promise) return result.finally(release2);
130532
+ release2();
130533
+ return result;
130534
+ } catch (error3) {
130535
+ release2();
130536
+ throw error3;
130932
130537
  }
130933
130538
  }
130934
130539
  function callMatchLikeMethod(value, methodName, args, compilation, lastIndex) {
@@ -130946,9 +130551,10 @@ function callMatchLikeMethod(value, methodName, args, compilation, lastIndex) {
130946
130551
  return toMatchArray(executeRegex(regex, value, lastIndex ?? Number(regex.lastIndex)), value);
130947
130552
  if (methodName === "match") regex.lastIndex = 0;
130948
130553
  const matcher = methodName === "matchAll" ? createSandboxRegex(regex.source, regex.flags, normalizeLastIndex(lastIndex ?? Number(regex.lastIndex)), compilation) : regex;
130554
+ if (methodName === "matchAll")
130555
+ return restoreSandboxRegExpIterator({ matcher, input: value, exhausted: false });
130949
130556
  const matches = collectRegexMatches(matcher, value, matcher.flags.includes("g"), compilation.owner?.budget, Number(matcher.lastIndex));
130950
- if (methodName === "match" && matches.length === 0) return null;
130951
- return methodName === "match" ? matches.map((match) => match.text) : matches.map((match) => toMatchArray(match, value));
130557
+ return matches.length === 0 ? null : matches.map((match) => match.text);
130952
130558
  }
130953
130559
  function collectRegexMatches(regex, value, all, budget, lastIndex = 0) {
130954
130560
  const matches = [];
@@ -130975,7 +130581,7 @@ function asNumberOrUndefined(value) {
130975
130581
  function asStringOrUndefined(value) {
130976
130582
  return value === void 0 ? void 0 : String(value);
130977
130583
  }
130978
- var SPLIT_STRING_MESSAGE, stringMethodNames;
130584
+ var stringMethodNames;
130979
130585
  var init_string = __esm({
130980
130586
  "packages/safe-js/src/interp/methods/string.ts"() {
130981
130587
  "use strict";
@@ -130985,9 +130591,12 @@ var init_string = __esm({
130985
130591
  init_string_coercion();
130986
130592
  init_resources();
130987
130593
  init_object_model();
130594
+ init_accessors();
130595
+ init_boxed();
130596
+ init_interpreter();
130988
130597
  init_values();
130989
130598
  init_regex();
130990
- SPLIT_STRING_MESSAGE = "String#split only supports string separator values.";
130599
+ init_regexp_iterator();
130991
130600
  stringMethodNames = /* @__PURE__ */ new Set([
130992
130601
  "at",
130993
130602
  "charAt",
@@ -131834,6 +131443,23 @@ var init_object_array = __esm({
131834
131443
  }
131835
131444
  });
131836
131445
 
131446
+ // packages/safe-js/src/interp/var-hoist.ts
131447
+ function hoistVarDeclarations(node, scope) {
131448
+ for (const declaration of hoistedVarDeclarations([node])) {
131449
+ for (const declarator of declaration.declarations) {
131450
+ for (const identifier of boundIdentifiers(declarator.id)) {
131451
+ scope.declareVar(identifier.name);
131452
+ }
131453
+ }
131454
+ }
131455
+ }
131456
+ var init_var_hoist = __esm({
131457
+ "packages/safe-js/src/interp/var-hoist.ts"() {
131458
+ "use strict";
131459
+ init_bindings();
131460
+ }
131461
+ });
131462
+
131837
131463
  // packages/safe-js/src/interp/classes.ts
131838
131464
  async function evaluateClass(node, context, evaluateNode3, callContext) {
131839
131465
  const scope = context.scope.child();
@@ -134993,6 +134619,7 @@ function isRestorableBindingValue(value, seen = /* @__PURE__ */ new WeakSet()) {
134993
134619
  }
134994
134620
  if (seen.has(value)) return true;
134995
134621
  seen.add(value);
134622
+ if (isSandboxRegExpIterator(value)) return isRestorableBindingValue(regexpIteratorState(value).matcher, seen);
134996
134623
  if (isSandboxCollectionIterator(value)) {
134997
134624
  return isRestorableBindingValue(collectionIteratorState(value).collection, seen);
134998
134625
  }
@@ -135247,7 +134874,7 @@ async function evaluateForOfStatement(node, context) {
135247
134874
  const restored = context.scope.consumeRestoredBinding(restoredIteration.values[0]);
135248
134875
  if (restored.found && Array.isArray(restored.value)) {
135249
134876
  restoredEntry = { done: false, value: restored.value[1] };
135250
- if (Array.isArray(restored.value[0]) || isSandboxMap(restored.value[0]) || isSandboxSet(restored.value[0]) || isSandboxCollectionIterator(restored.value[0])) {
134877
+ if (Array.isArray(restored.value[0]) || isSandboxMap(restored.value[0]) || isSandboxSet(restored.value[0]) || isSandboxCollectionIterator(restored.value[0]) || isSandboxRegExpIterator(restored.value[0])) {
135251
134878
  return evaluateForOfIterator(node, restored.value[0], context, restoredEntry);
135252
134879
  }
135253
134880
  }
@@ -135619,7 +135246,7 @@ function createLoopIterationContext(context, scope) {
135619
135246
  if (context.activeLoopIterations.size === 0) return snapshot2;
135620
135247
  snapshot2.loopIterations = {};
135621
135248
  for (const [nodeId, iteration] of context.activeLoopIterations) {
135622
- if (typeof iteration !== "number" && (Array.isArray(iteration.values[0]) || isSandboxMap(iteration.values[0]) || isSandboxSet(iteration.values[0]) || isSandboxCollectionIterator(iteration.values[0]))) {
135249
+ if (typeof iteration !== "number" && (Array.isArray(iteration.values[0]) || isSandboxMap(iteration.values[0]) || isSandboxSet(iteration.values[0]) || isSandboxCollectionIterator(iteration.values[0]) || isSandboxRegExpIterator(iteration.values[0]))) {
135623
135250
  const bindingName = `#for-of:${nodeId}`;
135624
135251
  snapshot2.bindings[bindingName] = iteration.values;
135625
135252
  snapshot2.loopIterations[nodeId] = { index: iteration.index, values: [bindingName] };
@@ -135967,6 +135594,7 @@ function getPropertyValue(target, property, context, receiver = target) {
135967
135594
  const descriptor = getSandboxPropertyDescriptor(target, property, context.budget);
135968
135595
  if (descriptor !== void 0)
135969
135596
  return readPropertyDescriptor(descriptor, receiver, createCoercionContext(context), true);
135597
+ if (isSandboxRegExpIterator(target)) return getRegExpIteratorMember(property, context.budget);
135970
135598
  if (typeof target === "symbol") {
135971
135599
  const prototype = getBoxedPrototype(target, context.budget);
135972
135600
  return prototype === void 0 ? void 0 : getPropertyValue(prototype, property, context, receiver);
@@ -135993,7 +135621,7 @@ function getPropertyValue(target, property, context, receiver = target) {
135993
135621
  if (isSandboxGenerator(target)) return getGeneratorMember(target, property, context.budget);
135994
135622
  if (isSandboxClosure(target)) return getClosureMemberValue(target, property, context);
135995
135623
  if (isSandboxPromise(target)) return getPromiseMember(property, context.budget);
135996
- if (isSandboxRegex(target)) return getRegexMember(target, property, context.budget);
135624
+ if (isSandboxRegex(target)) return hasExplicitSandboxPrototype(target) || getSandboxPrototype(target, context.budget) !== null ? void 0 : getRegexMember(target, property, context.budget, createCoercionContext(context));
135997
135625
  if (!isIndexableSandboxValue(target)) {
135998
135626
  throw new TypeError("Attempted to read a property from a non-object value.");
135999
135627
  }
@@ -136112,7 +135740,7 @@ async function evaluateMemberAccess(node, context, consume) {
136112
135740
  let property;
136113
135741
  const release2 = retainValues(context.budget, () => [object.value, property]);
136114
135742
  try {
136115
- const result = node.computed ? await evaluateNode2(node.property, context) : { kind: "normal", value: getStaticPropertyName2(node.property) };
135743
+ const result = node.computed ? await evaluateNode2(node.property, context) : { kind: "normal", value: getStaticPropertyName(node.property) };
136116
135744
  if (result.kind !== "normal") return result;
136117
135745
  property = result.value;
136118
135746
  return await consume({
@@ -136142,12 +135770,12 @@ async function evaluateObjectPropertyKey(node, context) {
136142
135770
  if (!node.computed) {
136143
135771
  return {
136144
135772
  ok: true,
136145
- value: getStaticPropertyName2(node.key)
135773
+ value: getStaticPropertyName(node.key)
136146
135774
  };
136147
135775
  }
136148
135776
  return evaluateMemberProperty(node.key, context);
136149
135777
  }
136150
- function getStaticPropertyName2(node) {
135778
+ function getStaticPropertyName(node) {
136151
135779
  if (node.type === "Identifier") {
136152
135780
  return node.name;
136153
135781
  }
@@ -136549,7 +136177,7 @@ function hasSandboxProperty(value, key3, context) {
136549
136177
  while (typeof current === "object" && current !== null) {
136550
136178
  if (isGuestHostObject(current)) return typeof key3 === "symbol" ? false : hasHostObjectMember(current, String(key3));
136551
136179
  if (hasOwnSandboxProperty(current, key3, false)) return true;
136552
- if (!((isGuestClosure(current) || Array.isArray(current)) && hasExplicitSandboxPrototype(current)) && (Array.isArray(current) || !isPlainSandboxObject(current) || isSandboxDate(current) || isFloat32Array(current) || isSandboxGenerator(current) || isSandboxCollectionIterator(current))) {
136180
+ if (!isSandboxRegex(current) && !((isGuestClosure(current) || Array.isArray(current)) && hasExplicitSandboxPrototype(current)) && (Array.isArray(current) || !isPlainSandboxObject(current) || isSandboxDate(current) || isFloat32Array(current) || isSandboxGenerator(current) || isSandboxCollectionIterator(current) || isSandboxRegExpIterator(current))) {
136553
136181
  return getPropertyValue(current, key3, context) !== void 0;
136554
136182
  }
136555
136183
  current = getSandboxPrototype(current, context.budget);
@@ -136749,7 +136377,7 @@ function getMemberValue(target, property, context) {
136749
136377
  while (typeof current === "object" && current !== null) {
136750
136378
  if (isSandboxClosure(current)) return getClosureMemberValue(current, property, context);
136751
136379
  if (Array.isArray(current)) return getArrayMemberValue(current, property, context);
136752
- if (!isPlainSandboxObject(current) || isSandboxGenerator(current) || isSandboxCollectionIterator(current) || isFloat32Array(current)) {
136380
+ if (!isPlainSandboxObject(current) || isSandboxGenerator(current) || isSandboxCollectionIterator(current) || isSandboxRegExpIterator(current) || isFloat32Array(current)) {
136753
136381
  return getPropertyValue(current, property, context);
136754
136382
  }
136755
136383
  if (Object.hasOwn(current, String(property))) return current[String(property)];
@@ -136787,7 +136415,7 @@ function setSandboxProperty(target, property, value, budget, checkInherited = tr
136787
136415
  return;
136788
136416
  }
136789
136417
  if (isSandboxRegex(target)) {
136790
- setRegexMember(target, property, value);
136418
+ setRegexMember(target, property, value, budget);
136791
136419
  return;
136792
136420
  }
136793
136421
  if (!isIndexableSandboxValue(target)) {
@@ -137155,6 +136783,8 @@ var init_interpreter = __esm({
137155
136783
  init_collections();
137156
136784
  init_collection_iterator();
137157
136785
  init_collection_iterator2();
136786
+ init_regexp_iterator();
136787
+ init_regexp_iterator2();
137158
136788
  init_float32array2();
137159
136789
  init_float32();
137160
136790
  init_date();
@@ -137223,6 +136853,859 @@ var init_interpreter = __esm({
137223
136853
  }
137224
136854
  });
137225
136855
 
136856
+ // packages/safe-js/src/interp/methods/regex.ts
136857
+ async function regexSearch(target, input, budget, context) {
136858
+ if (target === null || typeof target !== "object") throw new TypeError("RegExp search requires an object receiver.");
136859
+ let string;
136860
+ let previous;
136861
+ let result;
136862
+ const release2 = retainValues(budget, () => [target, input, string, previous, result]);
136863
+ const read = (value, key3) => {
136864
+ if (context?.getProperty !== void 0) return context.getProperty(value, key3);
136865
+ const descriptor = getSandboxPropertyDescriptor(value, key3, budget);
136866
+ return descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, value, context);
136867
+ };
136868
+ try {
136869
+ string = await sandboxString(input, budget, context);
136870
+ input = void 0;
136871
+ previous = await read(target, "lastIndex");
136872
+ if (!Object.is(previous, 0)) await setSandboxProperty(target, "lastIndex", 0, budget, true, context);
136873
+ result = await regexExec(target, string, budget, context);
136874
+ if (!Object.is(await read(target, "lastIndex"), previous))
136875
+ await setSandboxProperty(target, "lastIndex", previous, budget, true, context);
136876
+ return result === null ? -1 : await read(result, "index");
136877
+ } finally {
136878
+ release2();
136879
+ }
136880
+ }
136881
+ function isRegexMethodName(property) {
136882
+ return typeof property === "string" && regexMethodNames.has(property);
136883
+ }
136884
+ function getRegexMember(target, property, budget, context) {
136885
+ if (property === "source") return escapeRegexSource(target.source, budget);
136886
+ if (property === "flags") {
136887
+ let flags = "";
136888
+ const entries = Object.entries(regexFlagProperties);
136889
+ const release2 = retainValues(budget, () => [target, flags]);
136890
+ const read = (index) => {
136891
+ if (index === entries.length) return budget.allocateString(flags);
136892
+ budget.visitNode();
136893
+ const [key3, flag] = entries[index];
136894
+ const descriptor = context?.getProperty === void 0 ? getSandboxPropertyDescriptor(target, key3, budget) : void 0;
136895
+ const value = context?.getProperty !== void 0 ? context.getProperty(target, key3) : descriptor !== void 0 ? readPropertyDescriptor(descriptor, target, context) : target.flags.includes(flag);
136896
+ const append = (value2) => {
136897
+ if (value2) flags += flag;
136898
+ return read(index + 1);
136899
+ };
136900
+ return value instanceof Promise ? value.then(append) : append(value);
136901
+ };
136902
+ try {
136903
+ const result = read(0);
136904
+ if (result instanceof Promise) return result.finally(release2);
136905
+ release2();
136906
+ return result;
136907
+ } catch (error3) {
136908
+ release2();
136909
+ throw error3;
136910
+ }
136911
+ }
136912
+ if (property === "lastIndex") return target.lastIndex;
136913
+ if (Object.hasOwn(regexFlagProperties, property)) return target.flags.includes(regexFlagProperties[property]);
136914
+ if (!isRegexMethodName(property)) {
136915
+ return void 0;
136916
+ }
136917
+ return createSandboxClosure({
136918
+ sandbox: true,
136919
+ name: property === "toString" ? "toString" : `RegExp#${property}`,
136920
+ call: (args, context2) => callRegexMethod(context2?.thisValue, property, args, budget, context2)
136921
+ });
136922
+ }
136923
+ function escapeRegexSource(source, budget) {
136924
+ let text5 = "";
136925
+ let escaped = false;
136926
+ let inClass = false;
136927
+ for (const character2 of source) {
136928
+ budget?.visitNode();
136929
+ if (character2 === "\n" || character2 === "\r" || character2 === "\u2028" || character2 === "\u2029") {
136930
+ if (escaped) text5 = text5.slice(0, -1);
136931
+ text5 += character2 === "\n" ? "\\n" : character2 === "\r" ? "\\r" : character2 === "\u2028" ? "\\u2028" : "\\u2029";
136932
+ escaped = false;
136933
+ } else {
136934
+ if (!escaped && character2 === "[") inClass = true;
136935
+ if (!escaped && character2 === "]") inClass = false;
136936
+ text5 += character2 === "/" && !escaped && !inClass ? "\\/" : character2;
136937
+ escaped = character2 === "\\" && !escaped;
136938
+ }
136939
+ budget?.allocateString(text5);
136940
+ }
136941
+ text5 = text5 === "" ? "(?:)" : text5;
136942
+ return budget === void 0 ? text5 : budget.allocateString(text5);
136943
+ }
136944
+ function setRegexMember(target, property, value, budget) {
136945
+ const properties = getRegexProperties(target);
136946
+ if (!hasExplicitSandboxPrototype(target) && getSandboxPrototype(target, budget) === null && !Object.hasOwn(properties, property) && (property === "source" || property === "flags" || Object.hasOwn(regexFlagProperties, property))) {
136947
+ throw new TypeError(`RegExp#${String(property)} is not writable.`);
136948
+ }
136949
+ if (!Reflect.set(properties, property, value)) throw new TypeError(`RegExp#${String(property)} is not writable.`);
136950
+ }
136951
+ async function callRegexMethod(target, methodName, args, budget, context) {
136952
+ if (methodName === "toString") return regexToString(target, budget, context);
136953
+ if (target === null || typeof target !== "object" || methodName === "exec" && !isSandboxRegex(target)) {
136954
+ throw new TypeError(`RegExp#${methodName} requires ${methodName === "exec" ? "a regex" : "an object"} receiver.`);
136955
+ }
136956
+ const retained = {};
136957
+ let cursor2;
136958
+ let convertedInput;
136959
+ budget.setRetainedValues(retained, () => [target, ...args, cursor2, convertedInput]);
136960
+ try {
136961
+ const input = await sandboxString(args[0], budget, context);
136962
+ if (methodName === "test") {
136963
+ budget.setRetainedValues(retained, void 0);
136964
+ return await regexExec(target, input, budget, context) !== null;
136965
+ }
136966
+ if (typeof args[0] !== "string") convertedInput = input;
136967
+ if (!isSandboxRegex(target)) throw new TypeError("RegExp execution requires a regex receiver.");
136968
+ cursor2 = target.lastIndex;
136969
+ const lastIndex = await sandboxNumber(cursor2, budget, context);
136970
+ const match = executeRegex(target, input, lastIndex);
136971
+ return toMatchArray(match, input);
136972
+ } finally {
136973
+ budget.setRetainedValues(retained, void 0);
136974
+ }
136975
+ }
136976
+ async function regexExec(target, input, budget, context) {
136977
+ let exec2;
136978
+ const release2 = retainValues(budget, () => [target, input, exec2]);
136979
+ try {
136980
+ const descriptor = context?.getProperty === void 0 ? getSandboxPropertyDescriptor(target, "exec", budget) : void 0;
136981
+ exec2 = await (context?.getProperty !== void 0 ? context.getProperty(target, "exec") : descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, target, context));
136982
+ if (isSandboxClosure(exec2)) {
136983
+ const result = await invokeBuiltinClosure(exec2, [input], budget, context, target);
136984
+ if (result !== null && typeof result !== "object")
136985
+ throw new TypeError("RegExp exec must return an object or null.");
136986
+ return result;
136987
+ }
136988
+ return await callRegexMethod(target, "exec", [input], budget, context);
136989
+ } finally {
136990
+ release2();
136991
+ }
136992
+ }
136993
+ async function regexToString(target, budget, context) {
136994
+ if (target === null || typeof target !== "object")
136995
+ throw new TypeError("RegExp#toString requires an object receiver.");
136996
+ const read = (key3) => {
136997
+ if (context?.getProperty !== void 0) return context.getProperty(target, key3);
136998
+ const descriptor = getSandboxPropertyDescriptor(target, key3, budget);
136999
+ if (descriptor !== void 0) return readPropertyDescriptor(descriptor, target, context);
137000
+ return isSandboxRegex(target) ? getRegexMember(target, key3, budget, context) : void 0;
137001
+ };
137002
+ let sourceValue;
137003
+ let flagsValue;
137004
+ let source;
137005
+ let flags;
137006
+ const release2 = retainValues(budget, () => [target, sourceValue, flagsValue, source, flags]);
137007
+ try {
137008
+ sourceValue = await read("source");
137009
+ source = await sandboxString(sourceValue, budget, context);
137010
+ sourceValue = void 0;
137011
+ flagsValue = await read("flags");
137012
+ flags = await sandboxString(flagsValue, budget, context);
137013
+ flagsValue = void 0;
137014
+ return budget.allocateString(`/${source}/${flags}`);
137015
+ } finally {
137016
+ release2();
137017
+ }
137018
+ }
137019
+ function executeRegex(target, input, lastIndex) {
137020
+ const pattern = getSandboxRegexPattern(target);
137021
+ const match = matchRegex(pattern, input, lastIndex);
137022
+ if (pattern.flags.global) {
137023
+ target.lastIndex = match === null ? 0 : match.index + match.text.length;
137024
+ }
137025
+ return match;
137026
+ }
137027
+ function toMatchArray(match, input) {
137028
+ if (match === null) {
137029
+ return null;
137030
+ }
137031
+ const result = [match.text, ...match.captures];
137032
+ Object.assign(result, { index: match.index, input, groups: void 0 });
137033
+ return result;
137034
+ }
137035
+ var regexMethodNames, regexFlagProperties;
137036
+ var init_regex = __esm({
137037
+ "packages/safe-js/src/interp/methods/regex.ts"() {
137038
+ "use strict";
137039
+ init_values();
137040
+ init_engine2();
137041
+ init_builtin_call();
137042
+ init_object_model();
137043
+ init_accessors();
137044
+ init_resources();
137045
+ init_string_coercion();
137046
+ init_interpreter();
137047
+ regexMethodNames = /* @__PURE__ */ new Set(["exec", "test", "toString"]);
137048
+ regexFlagProperties = {
137049
+ hasIndices: "d",
137050
+ global: "g",
137051
+ ignoreCase: "i",
137052
+ multiline: "m",
137053
+ dotAll: "s",
137054
+ unicode: "u",
137055
+ unicodeSets: "v",
137056
+ sticky: "y"
137057
+ };
137058
+ }
137059
+ });
137060
+
137061
+ // packages/safe-js/src/interp/methods/regexp-iterator.ts
137062
+ function nextRegExpIterator(iterator, budget) {
137063
+ const state = regexpIteratorState(iterator);
137064
+ budget?.visitNode();
137065
+ if (state.exhausted) return { value: void 0, done: true };
137066
+ const matcher = state.matcher;
137067
+ const input = state.input;
137068
+ const match = executeRegex(matcher, input, Number(matcher.lastIndex));
137069
+ if (match === null || !matcher.flags.includes("g")) {
137070
+ state.exhausted = true;
137071
+ state.matcher = void 0;
137072
+ state.input = void 0;
137073
+ }
137074
+ if (match === null) return { value: void 0, done: true };
137075
+ if (!state.exhausted && match.text.length === 0) {
137076
+ const index = Number(matcher.lastIndex);
137077
+ const unicode = matcher.flags.includes("u") || matcher.flags.includes("v");
137078
+ const codePoint = input.codePointAt(index);
137079
+ matcher.lastIndex = index + (unicode && codePoint !== void 0 && codePoint > 65535 ? 2 : 1);
137080
+ }
137081
+ budget?.allocateArrayLength(match.captures.length + 1);
137082
+ return { value: toMatchArray(match, input), done: false };
137083
+ }
137084
+ function getRegExpIteratorMember(property, budget) {
137085
+ if (property === Symbol.toStringTag) return "RegExp String Iterator";
137086
+ if (property === Symbol.iterator) return createSandboxClosure({
137087
+ sandbox: true,
137088
+ name: "[Symbol.iterator]",
137089
+ call: (_args, context) => context?.thisValue
137090
+ });
137091
+ if (property !== "next") return void 0;
137092
+ return createSandboxClosure({
137093
+ sandbox: true,
137094
+ name: "next",
137095
+ call: (_args, context) => {
137096
+ const receiver = context?.thisValue;
137097
+ if (!isSandboxRegExpIterator(receiver))
137098
+ throw new TypeError("RegExp string iterator next requires a matching receiver.");
137099
+ return nextRegExpIterator(receiver, budget);
137100
+ }
137101
+ });
137102
+ }
137103
+ var init_regexp_iterator2 = __esm({
137104
+ "packages/safe-js/src/interp/methods/regexp-iterator.ts"() {
137105
+ "use strict";
137106
+ init_regexp_iterator();
137107
+ init_values();
137108
+ init_regex();
137109
+ }
137110
+ });
137111
+
137112
+ // packages/safe-js/src/interp/iteration.ts
137113
+ async function acquireSandboxIterator(value, budget, context, asyncProtocol = false, signal) {
137114
+ const key3 = asyncProtocol ? Symbol.asyncIterator : Symbol.iterator;
137115
+ if (context.getProperty === void 0 || isGuestHostObject(value))
137116
+ return asyncProtocol ? getSandboxAsyncIterator(value, budget, context, signal) : getSandboxIterator(value, budget, context);
137117
+ if (getSandboxPropertyDescriptor(value, key3, budget) === void 0 && !(isSandboxRegExpIterator(value) && !asyncProtocol && getSandboxPropertyDescriptor(value, "next", budget) !== void 0)) {
137118
+ if (!asyncProtocol) return getSandboxIterator(value, budget, context);
137119
+ if (isSandboxGenerator(value) && value.async)
137120
+ return getSandboxAsyncIterator(value, budget, context, signal);
137121
+ const iterator2 = await acquireSandboxIterator(value, budget, context);
137122
+ return iterator2 === void 0 ? void 0 : asyncFromSyncIterator(iterator2, budget, signal);
137123
+ }
137124
+ const factory = await context.getProperty(value, key3);
137125
+ if (factory === null || factory === void 0) {
137126
+ if (!asyncProtocol) return void 0;
137127
+ const iterator2 = await acquireSandboxIterator(value, budget, context);
137128
+ return iterator2 === void 0 ? void 0 : asyncFromSyncIterator(iterator2, budget, signal);
137129
+ }
137130
+ if (!isSandboxClosure(factory)) {
137131
+ if (typeof factory !== "function") throw new TypeError("Iterator method must be callable.");
137132
+ if (asyncProtocol) return nativeAsyncIterator(value, factory, signal);
137133
+ const iterator2 = Reflect.apply(factory, value, []);
137134
+ if (typeof iterator2 !== "object" && typeof iterator2 !== "function" || iterator2 === null)
137135
+ throw new TypeError("Iterator must be an object.");
137136
+ return syncIterator(iterator2);
137137
+ }
137138
+ const iterator = await invokeBuiltinClosure(factory, [], budget, context, value);
137139
+ if (typeof iterator !== "object" && typeof iterator !== "function" || iterator === null)
137140
+ throw new TypeError("Iterator must be an object.");
137141
+ const next = await context.getProperty(iterator, "next");
137142
+ const invoke2 = async (operation, args) => {
137143
+ if (!isSandboxClosure(operation)) throw new TypeError("Iterator operation must be callable.");
137144
+ const returned = await invokeBuiltinClosure(operation, args, budget, context, iterator);
137145
+ const result = asyncProtocol ? await awaitSandboxValue(returned, signal, budget) : returned;
137146
+ if (typeof result !== "object" && typeof result !== "function" || result === null)
137147
+ throw new TypeError("Iterator result must be an object.");
137148
+ return result;
137149
+ };
137150
+ return {
137151
+ ...asyncProtocol ? { asyncProtocol: true } : {},
137152
+ asynchronous: true,
137153
+ retainedValue: [value, iterator, next],
137154
+ next: (...args) => invoke2(next, args),
137155
+ getOperation: async (method) => {
137156
+ const operation = method === "next" ? next : await context.getProperty(iterator, method);
137157
+ return method !== "next" && (operation === void 0 || operation === null) ? void 0 : (...args) => invoke2(operation, args);
137158
+ },
137159
+ readResultProperty: async (result, property) => ({
137160
+ value: await context.getProperty(result, property)
137161
+ })
137162
+ };
137163
+ }
137164
+ async function readIteratorResult(iterator, result, property) {
137165
+ return iterator.readResultProperty === void 0 ? { value: result[property] } : iterator.readResultProperty(result, property);
137166
+ }
137167
+ function getSandboxAsyncIterator(value, budget, context, signal) {
137168
+ if (isSandboxGenerator(value) && value.async) {
137169
+ return { ...generatorIterator(value, budget), asyncProtocol: true };
137170
+ }
137171
+ if (value !== null && (typeof value === "object" || typeof value === "function") && !isGuestHostObject(value)) {
137172
+ const method = value[Symbol.asyncIterator];
137173
+ if (method !== void 0 && method !== null) {
137174
+ return nativeAsyncIterator(value, method, signal);
137175
+ }
137176
+ }
137177
+ const iterator = getSandboxIterator(value, budget, context);
137178
+ return iterator === void 0 ? void 0 : asyncFromSyncIterator(iterator, budget, signal);
137179
+ }
137180
+ function nativeAsyncIterator(value, method, signal) {
137181
+ if (typeof method !== "function") throw new TypeError("Async iterator method must be callable.");
137182
+ const iterator = Reflect.apply(method, value, []);
137183
+ if (typeof iterator !== "object" && typeof iterator !== "function" || iterator === null) {
137184
+ throw new TypeError("Async iterator must be an object.");
137185
+ }
137186
+ const next = iterator.next;
137187
+ const invoke2 = async (operation, args) => {
137188
+ if (typeof operation !== "function")
137189
+ throw new TypeError("Async iterator operation must be callable.");
137190
+ const pending = Promise.resolve(Reflect.apply(operation, iterator, args)).then((result2) => ({
137191
+ result: result2
137192
+ }));
137193
+ const { result } = await awaitWithSignal(pending, signal);
137194
+ if (typeof result !== "object" && typeof result !== "function" || result === null) {
137195
+ throw new TypeError("Iterator result must be an object.");
137196
+ }
137197
+ return {
137198
+ get done() {
137199
+ return result.done;
137200
+ },
137201
+ get value() {
137202
+ return result.value;
137203
+ }
137204
+ };
137205
+ };
137206
+ return {
137207
+ asyncProtocol: true,
137208
+ retainedValue: value,
137209
+ next: (...args) => invoke2(next, args),
137210
+ get return() {
137211
+ const operation = iterator.return;
137212
+ return operation === void 0 || operation === null ? void 0 : (...args) => invoke2(operation, args);
137213
+ },
137214
+ get throw() {
137215
+ const operation = iterator.throw;
137216
+ return operation === void 0 || operation === null ? void 0 : (...args) => invoke2(operation, args);
137217
+ }
137218
+ };
137219
+ }
137220
+ function asyncFromSyncIterator(iterator, budget, signal) {
137221
+ const invoke2 = async (method, args) => {
137222
+ const operation = iterator.getOperation === void 0 ? iterator[method] : await iterator.getOperation(method);
137223
+ if (operation === void 0) {
137224
+ if (method === "throw") {
137225
+ await closeIterator(iterator);
137226
+ throw new TypeError("Delegated iterator does not provide a throw method.");
137227
+ }
137228
+ return { done: true, value: args[0] };
137229
+ }
137230
+ const returned = operation(...args);
137231
+ const result = iterator.generator || iterator.asynchronous ? await returned : returned;
137232
+ if (typeof result !== "object" && typeof result !== "function" || result === null) {
137233
+ throw new TypeError("Iterator result must be an object.");
137234
+ }
137235
+ const done = Boolean((await readIteratorResult(iterator, result, "done")).value);
137236
+ const resultValue = (await readIteratorResult(iterator, result, "value")).value;
137237
+ try {
137238
+ return { done, value: await awaitSandboxValue(resultValue, signal, budget) };
137239
+ } catch (error3) {
137240
+ if (isFatalSandboxError(error3) || error3 instanceof HostCallResumabilityError) throw error3;
137241
+ if (!done && method !== "return") await closeIterator(iterator, true);
137242
+ throw error3;
137243
+ }
137244
+ };
137245
+ return {
137246
+ asyncProtocol: true,
137247
+ snapshotIndex: iterator.snapshotIndex,
137248
+ get retainedValue() {
137249
+ return iterator.retainedValue;
137250
+ },
137251
+ next: (...args) => invoke2("next", args),
137252
+ return: (...args) => invoke2("return", args),
137253
+ throw: (...args) => invoke2("throw", args)
137254
+ };
137255
+ }
137256
+ async function closeIterator(iterator, preserveThrow = false) {
137257
+ try {
137258
+ const close = iterator.getOperation === void 0 ? iterator.return : await iterator.getOperation("return");
137259
+ if (close === void 0) return;
137260
+ const returned = close();
137261
+ const result = iterator.asyncProtocol ? await suspendJob(Promise.resolve(returned)) : iterator.generator || iterator.asynchronous ? await returned : returned;
137262
+ if (typeof result !== "object" && typeof result !== "function" || result === null) {
137263
+ throw new TypeError("Iterator return result must be an object.");
137264
+ }
137265
+ } catch (error3) {
137266
+ if (!preserveThrow || isFatalSandboxError(error3) || error3 instanceof HostCallResumabilityError)
137267
+ throw error3;
137268
+ }
137269
+ }
137270
+ function getSandboxIterator(value, budget, context) {
137271
+ if (isSandboxBox(value) && typeof boxedValue(value) === "string") {
137272
+ const primitive = boxedValue(value);
137273
+ let text5;
137274
+ let iterator2;
137275
+ let initialized;
137276
+ return {
137277
+ asynchronous: true,
137278
+ get retainedValue() {
137279
+ return text5 === primitive ? void 0 : text5;
137280
+ },
137281
+ next: async () => {
137282
+ initialized ??= Promise.resolve(sandboxString(value, budget ?? new Budget(), context)).then(
137283
+ (converted) => {
137284
+ text5 = converted;
137285
+ iterator2 = syncIterator(converted[Symbol.iterator]());
137286
+ }
137287
+ );
137288
+ await initialized;
137289
+ return iterator2.next();
137290
+ }
137291
+ };
137292
+ }
137293
+ if (isSandboxCollectionIterator(value))
137294
+ return { next: () => nextCollectionIterator(value, budget), snapshotIndex: () => 0 };
137295
+ if (isSandboxRegExpIterator(value))
137296
+ return { next: () => nextRegExpIterator(value, budget), snapshotIndex: () => 0 };
137297
+ if (isGuestHostObject(value)) return getHostObjectIterator(value);
137298
+ if (isFloat32Array(value)) {
137299
+ return syncIterator(Float32Array.prototype.values.call(value));
137300
+ }
137301
+ if (isSandboxGenerator(value)) {
137302
+ return value.async ? void 0 : generatorIterator(value);
137303
+ }
137304
+ if (typeof value === "string") {
137305
+ return syncIterator(value[Symbol.iterator]());
137306
+ }
137307
+ if (isSandboxMap(value)) {
137308
+ return collectionIterator(value.entries);
137309
+ }
137310
+ if (isSandboxSet(value)) {
137311
+ return collectionIterator(value.values);
137312
+ }
137313
+ if (Array.isArray(value) && hasExplicitSandboxPrototype(value)) return void 0;
137314
+ if (Array.isArray(value) && context?.getProperty !== void 0) {
137315
+ let index = 0;
137316
+ return {
137317
+ asynchronous: true,
137318
+ snapshotIndex: () => index,
137319
+ next: async () => {
137320
+ if (index >= value.length) return { done: true, value: void 0 };
137321
+ budget?.visitNode();
137322
+ return { done: false, value: await context.getProperty(value, index++) };
137323
+ }
137324
+ };
137325
+ }
137326
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
137327
+ return void 0;
137328
+ }
137329
+ const iteratorMethod = value[Symbol.iterator];
137330
+ if (iteratorMethod === void 0 || iteratorMethod === null) return void 0;
137331
+ if (typeof iteratorMethod !== "function") {
137332
+ throw new TypeError("Iterator method must be callable.");
137333
+ }
137334
+ const iterator = Reflect.apply(iteratorMethod, value, []);
137335
+ if (typeof iterator !== "object" && typeof iterator !== "function" || iterator === null) {
137336
+ throw new TypeError("Iterator must be an object.");
137337
+ }
137338
+ return syncIterator(iterator);
137339
+ }
137340
+ function collectionIterator(collection) {
137341
+ let iterator = collection[Symbol.iterator]();
137342
+ let exhausted = false;
137343
+ return {
137344
+ ...syncIterator({
137345
+ next: () => {
137346
+ if (exhausted) return { done: true, value: void 0 };
137347
+ const result = iterator.next();
137348
+ exhausted = result.done === true;
137349
+ return result;
137350
+ }
137351
+ }),
137352
+ snapshotIndex: () => {
137353
+ if (exhausted) return collection.size;
137354
+ let remaining = 0;
137355
+ while (!iterator.next().done) remaining += 1;
137356
+ const index = collection.size - remaining;
137357
+ iterator = collection[Symbol.iterator]();
137358
+ for (let skipped = 0; skipped < index; skipped += 1) iterator.next();
137359
+ return index;
137360
+ }
137361
+ };
137362
+ }
137363
+ function generatorIterator(generator, budget) {
137364
+ const invoke2 = async (method, value) => {
137365
+ const leaveRunning = enterRunningState(generator);
137366
+ const initialState = generator.state;
137367
+ generator.state = "running";
137368
+ try {
137369
+ if (generator.async && method === "return" && (initialState === "start" || initialState === "done")) {
137370
+ if (initialState === "start") await generator.channel.return();
137371
+ value = await awaitSandboxValue(value, void 0, budget);
137372
+ }
137373
+ const result = await generator.channel[method](value);
137374
+ generator.state = result.done ? "done" : "suspended";
137375
+ return result;
137376
+ } catch (error3) {
137377
+ generator.state = "done";
137378
+ throw error3;
137379
+ } finally {
137380
+ leaveRunning();
137381
+ }
137382
+ };
137383
+ const request = (method, value) => {
137384
+ if (!generator.async) return invoke2(method, value);
137385
+ const previous = asyncGeneratorRequests.get(generator) ?? Promise.resolve();
137386
+ const result = previous.then(() => invoke2(method, value));
137387
+ asyncGeneratorRequests.set(
137388
+ generator,
137389
+ result.catch(() => void 0)
137390
+ );
137391
+ return result;
137392
+ };
137393
+ return {
137394
+ generator: true,
137395
+ next: (value) => request("next", value),
137396
+ return: (value) => request("return", value),
137397
+ throw: (error3) => request("throw", error3)
137398
+ };
137399
+ }
137400
+ function syncIterator(iterator) {
137401
+ const next = iterator.next;
137402
+ const invoke2 = (method, args) => {
137403
+ const leaveRunning = enterRunningState(iterator);
137404
+ try {
137405
+ return Reflect.apply(method, iterator, args);
137406
+ } finally {
137407
+ leaveRunning();
137408
+ }
137409
+ };
137410
+ return {
137411
+ next: (...args) => invoke2(next, args),
137412
+ get return() {
137413
+ const method = iterator.return;
137414
+ if (method === void 0 || method === null) return void 0;
137415
+ if (typeof method !== "function") throw new TypeError("Iterator return must be callable.");
137416
+ return (...args) => invoke2(method, args);
137417
+ },
137418
+ get throw() {
137419
+ const method = iterator.throw;
137420
+ if (method === void 0 || method === null) return void 0;
137421
+ if (typeof method !== "function") throw new TypeError("Iterator throw must be callable.");
137422
+ return (...args) => invoke2(method, args);
137423
+ }
137424
+ };
137425
+ }
137426
+ var asyncGeneratorRequests;
137427
+ var init_iteration = __esm({
137428
+ "packages/safe-js/src/interp/iteration.ts"() {
137429
+ "use strict";
137430
+ init_values();
137431
+ init_running_state();
137432
+ init_float32();
137433
+ init_boxed();
137434
+ init_host_capabilities();
137435
+ init_collection_iterator();
137436
+ init_regexp_iterator();
137437
+ init_regexp_iterator2();
137438
+ init_budget2();
137439
+ init_string_coercion();
137440
+ init_cancel2();
137441
+ init_host_call();
137442
+ init_jobs4();
137443
+ init_builtin_call();
137444
+ init_object_model();
137445
+ asyncGeneratorRequests = /* @__PURE__ */ new WeakMap();
137446
+ }
137447
+ });
137448
+
137449
+ // packages/safe-js/src/interp/patterns.ts
137450
+ async function bindPattern(pattern, value, target, scope, context, reference) {
137451
+ switch (pattern.type) {
137452
+ case "Identifier":
137453
+ bindIdentifier(pattern, value, target, scope);
137454
+ return { ok: true };
137455
+ case "MemberExpression":
137456
+ if ("kind" in target) {
137457
+ throw new TypeError("Destructuring declarations cannot bind to member expressions.");
137458
+ }
137459
+ return bindMemberExpression(pattern, value, context, reference);
137460
+ case "AssignmentPattern":
137461
+ return bindAssignmentPattern(pattern, value, target, scope, context, reference);
137462
+ case "ArrayPattern":
137463
+ return bindArrayPattern(pattern, value, target, scope, context);
137464
+ case "ObjectPattern":
137465
+ return bindObjectPattern(pattern, value, target, scope, context);
137466
+ case "RestElement":
137467
+ return bindPattern(pattern.argument, value, target, scope, context, reference);
137468
+ }
137469
+ }
137470
+ function bindIdentifier(pattern, value, target, scope) {
137471
+ if ("assign" in target || target.kind === "var" && target.initialize !== true) {
137472
+ if ("assign" in target) {
137473
+ const binding = scope.lookup(pattern.name);
137474
+ if (!binding.found) {
137475
+ throw new ReferenceError(`Cannot assign to undeclared binding '${pattern.name}'.`);
137476
+ }
137477
+ if (binding.kind === "const") {
137478
+ throw new TypeError(`Cannot assign to const '${pattern.name}'`);
137479
+ }
137480
+ }
137481
+ scope.assign(pattern.name, value);
137482
+ return;
137483
+ }
137484
+ scope.declare(pattern.name, target.kind, value);
137485
+ }
137486
+ async function bindAssignmentPattern(pattern, value, target, scope, context, reference) {
137487
+ if (value !== void 0) {
137488
+ return bindPattern(pattern.left, value, target, scope, context, reference);
137489
+ }
137490
+ const defaultValue = await context.evaluate(
137491
+ pattern.right,
137492
+ pattern.left.type === "Identifier" ? pattern.left.name : void 0
137493
+ );
137494
+ if (defaultValue.kind !== "normal") {
137495
+ return { ok: false, result: defaultValue };
137496
+ }
137497
+ return bindPattern(pattern.left, defaultValue.value, target, scope, context, reference);
137498
+ }
137499
+ async function bindPatternValue(pattern, readValue, target, scope, context) {
137500
+ let member = pattern;
137501
+ while (member.type === "AssignmentPattern" || member.type === "RestElement")
137502
+ member = member.type === "AssignmentPattern" ? member.left : member.argument;
137503
+ let reference;
137504
+ if ("assign" in target && member.type === "MemberExpression") {
137505
+ const prepared = await prepareMemberReference(member, context);
137506
+ if (!prepared.ok) return prepared;
137507
+ reference = prepared.reference;
137508
+ }
137509
+ let value;
137510
+ const release2 = context.budget === void 0 ? () => void 0 : retainValues(context.budget, () => [reference?.object, reference?.key, value]);
137511
+ try {
137512
+ value = (await readValue()).value;
137513
+ return await bindPattern(pattern, value, target, scope, context, reference);
137514
+ } finally {
137515
+ release2();
137516
+ }
137517
+ }
137518
+ async function bindArrayPattern(pattern, value, target, scope, context) {
137519
+ const budget = context.budget ?? new Budget();
137520
+ const iterator = await acquireSandboxIterator(
137521
+ value,
137522
+ budget,
137523
+ context.callContext ?? {
137524
+ stack: [],
137525
+ thisValue: void 0,
137526
+ getProperty: context.getProperty
137527
+ }
137528
+ );
137529
+ if (iterator === void 0) throw new TypeError("Array destructuring requires an iterable.");
137530
+ let done = false;
137531
+ const next = async (readValue = true) => {
137532
+ if (done) return { value: void 0 };
137533
+ try {
137534
+ const result = await iterator.next();
137535
+ if (typeof result !== "object" && typeof result !== "function" || result === null)
137536
+ throw new TypeError("Iterator result must be an object.");
137537
+ done = Boolean((await readIteratorResult(iterator, result, "done")).value);
137538
+ return done || !readValue ? { value: void 0 } : await readIteratorResult(iterator, result, "value");
137539
+ } catch (error3) {
137540
+ done = true;
137541
+ throw error3;
137542
+ }
137543
+ };
137544
+ let retained;
137545
+ const release2 = retainValues(budget, () => [value, iterator.retainedValue, retained]);
137546
+ try {
137547
+ for (let index = 0; index < pattern.elements.length; index += 1) {
137548
+ const element = pattern.elements[index];
137549
+ if (element === null) {
137550
+ await next(false);
137551
+ continue;
137552
+ }
137553
+ const binding = await bindPatternValue(
137554
+ element,
137555
+ async () => {
137556
+ if (element.type !== "RestElement") return next();
137557
+ const rest = [];
137558
+ retained = rest;
137559
+ for (let entry = await next(); !done; entry = await next()) {
137560
+ budget.allocateArrayLength(rest.length + 1);
137561
+ rest.push(entry.value);
137562
+ }
137563
+ return { value: rest };
137564
+ },
137565
+ target,
137566
+ scope,
137567
+ context
137568
+ );
137569
+ if (!binding.ok) {
137570
+ if (!done) {
137571
+ done = true;
137572
+ await closeIterator(iterator, binding.result.kind === "throw");
137573
+ }
137574
+ return binding;
137575
+ }
137576
+ }
137577
+ if (!done) {
137578
+ done = true;
137579
+ await closeIterator(iterator);
137580
+ }
137581
+ return { ok: true };
137582
+ } catch (error3) {
137583
+ if (!done && !isFatalSandboxError(error3)) await closeIterator(iterator, true);
137584
+ throw error3;
137585
+ } finally {
137586
+ release2();
137587
+ }
137588
+ }
137589
+ async function bindObjectPattern(pattern, value, target, scope, context) {
137590
+ if (value === void 0 || value === null) {
137591
+ throw new TypeError("Object destructuring requires a non-nullish value.");
137592
+ }
137593
+ const excludedKeys = /* @__PURE__ */ new Set();
137594
+ for (const property of pattern.properties) {
137595
+ if (property.type === "RestElement") {
137596
+ const binding2 = await bindPatternValue(
137597
+ property,
137598
+ async () => ({ value: await copyObjectRestValue(value, excludedKeys, context) }),
137599
+ target,
137600
+ scope,
137601
+ context
137602
+ );
137603
+ if (!binding2.ok) {
137604
+ return binding2;
137605
+ }
137606
+ continue;
137607
+ }
137608
+ const key3 = await evaluatePatternKey(property, context);
137609
+ if (!key3.ok) {
137610
+ return key3;
137611
+ }
137612
+ excludedKeys.add(typeof key3.value === "symbol" ? key3.value : String(key3.value));
137613
+ const binding = await bindPatternValue(
137614
+ property.value,
137615
+ async () => ({ value: await context.getProperty(value, key3.value) }),
137616
+ target,
137617
+ scope,
137618
+ context
137619
+ );
137620
+ if (!binding.ok) {
137621
+ return binding;
137622
+ }
137623
+ }
137624
+ return { ok: true };
137625
+ }
137626
+ async function bindMemberExpression(pattern, value, context, reference) {
137627
+ if (reference === void 0) {
137628
+ const prepared = await prepareMemberReference(pattern, context);
137629
+ if (!prepared.ok) return prepared;
137630
+ reference = prepared.reference;
137631
+ }
137632
+ if (reference.object === null || reference.object === void 0) {
137633
+ throw new TypeError("Cannot assign properties of null or undefined.");
137634
+ }
137635
+ if (!isIndexableValue(reference.object)) {
137636
+ throw new TypeError("Assignment expressions require a sandbox object property.");
137637
+ }
137638
+ await context.setProperty(reference.object, reference.key, value);
137639
+ return { ok: true };
137640
+ }
137641
+ async function prepareMemberReference(pattern, context) {
137642
+ const object = await context.evaluate(pattern.object);
137643
+ if (object.kind !== "normal") {
137644
+ return { ok: false, result: object };
137645
+ }
137646
+ const property = pattern.computed ? await context.evaluate(pattern.property) : { kind: "normal", value: getStaticPropertyName2(pattern.property) };
137647
+ if (property.kind !== "normal") {
137648
+ return { ok: false, result: property };
137649
+ }
137650
+ return {
137651
+ ok: true,
137652
+ reference: { object: object.value, key: await context.toPropertyKey(property.value) }
137653
+ };
137654
+ }
137655
+ async function evaluatePatternKey(property, context) {
137656
+ return property.computed ? evaluateProperty(property.key, context) : { ok: true, value: getStaticPropertyName2(property.key) };
137657
+ }
137658
+ async function evaluateProperty(property, context) {
137659
+ const result = await context.evaluate(property);
137660
+ if (result.kind !== "normal") {
137661
+ return { ok: false, result };
137662
+ }
137663
+ return { ok: true, value: await context.toPropertyKey(result.value) };
137664
+ }
137665
+ function getStaticPropertyName2(property) {
137666
+ if (property.type === "Identifier") {
137667
+ return property.name;
137668
+ }
137669
+ if (property.type === "StringLiteral" || property.type === "NumericLiteral") {
137670
+ return property.value;
137671
+ }
137672
+ throw new TypeError(`Unsupported static property node '${property.type}'.`);
137673
+ }
137674
+ async function copyObjectRestValue(value, excludedKeys, context) {
137675
+ const rest = /* @__PURE__ */ Object.create(null);
137676
+ const release2 = context.budget === void 0 ? () => void 0 : retainValues(context.budget, () => [value, rest]);
137677
+ try {
137678
+ for (const key3 of ownEnumerableSandboxKeys(value, true)) {
137679
+ if (excludedKeys.has(key3) || !hasOwnSandboxProperty(value, key3, true)) continue;
137680
+ defineProperty(rest, key3, await context.getProperty(value, key3));
137681
+ }
137682
+ return rest;
137683
+ } finally {
137684
+ release2();
137685
+ }
137686
+ }
137687
+ function isIndexableValue(value) {
137688
+ return typeof value === "object" && value !== null;
137689
+ }
137690
+ function defineProperty(target, key3, value) {
137691
+ Object.defineProperty(target, key3, {
137692
+ configurable: true,
137693
+ enumerable: true,
137694
+ value,
137695
+ writable: true
137696
+ });
137697
+ }
137698
+ var init_patterns = __esm({
137699
+ "packages/safe-js/src/interp/patterns.ts"() {
137700
+ "use strict";
137701
+ init_budget2();
137702
+ init_resources();
137703
+ init_object2();
137704
+ init_iteration();
137705
+ init_values();
137706
+ }
137707
+ });
137708
+
137226
137709
  // packages/safe-js/src/interp/async.ts
137227
137710
  function emitResumeBreakpoint(context, breakpoint) {
137228
137711
  context.onYield?.({
@@ -138781,11 +139264,11 @@ async function objectToPrimitive(value, budget, context, joining, hint, ordinary
138781
139264
  }
138782
139265
  }
138783
139266
  function conversionHook(value, name, budget, context) {
138784
- const implicitBuiltin = !hasExplicitSandboxPrototype(value) && (Array.isArray(value) || isSandboxDate(value) || isFloat32Array(value) || sandboxErrorTypes.has(value) || isSandboxClosure(value) || isSandboxMap(value) || isSandboxSet(value) || isSandboxCollectionIterator(value) || isSandboxPromise(value) || isSandboxRegex(value) || isSandboxGenerator(value) || isGuestHostObject(value));
139267
+ const implicitBuiltin = !hasExplicitSandboxPrototype(value) && (Array.isArray(value) || isSandboxDate(value) || isFloat32Array(value) || sandboxErrorTypes.has(value) || isSandboxClosure(value) || isSandboxMap(value) || isSandboxSet(value) || isSandboxCollectionIterator(value) || isSandboxRegExpIterator(value) || isSandboxPromise(value) || isSandboxRegex(value) && getSandboxPrototype(value, budget) === null || isSandboxGenerator(value) || isGuestHostObject(value));
138785
139268
  let current = value;
138786
139269
  let depth = 0;
138787
139270
  while (current !== null) {
138788
- const properties = isGuestClosure(current) ? getGuestFunctionProperties(current) : current;
139271
+ const properties = isGuestClosure(current) ? getGuestFunctionProperties(current) : isSandboxRegex(current) ? getRegexProperties(current) : current;
138789
139272
  const descriptor = properties === void 0 ? void 0 : Object.getOwnPropertyDescriptor(properties, name);
138790
139273
  if (descriptor !== void 0) {
138791
139274
  return readPropertyDescriptor(descriptor, value, context);
@@ -138810,14 +139293,11 @@ async function defaultToString(value, budget, context, joining) {
138810
139293
  if (isSandboxClosure(value)) return budget.allocateString(functionString(value));
138811
139294
  if (isSandboxMap(value)) return "[object Map]";
138812
139295
  if (isSandboxSet(value)) return "[object Set]";
139296
+ if (isSandboxRegExpIterator(value)) return "[object RegExp String Iterator]";
138813
139297
  if (isSandboxCollectionIterator(value))
138814
139298
  return collectionIteratorState(value).collectionKind === "map" ? "[object Map Iterator]" : "[object Set Iterator]";
138815
139299
  if (isSandboxGenerator(value)) return "[object Generator]";
138816
- if (isSandboxRegex(value)) {
138817
- return budget.allocateString(
138818
- `/${String(getRegexMember(value, "source", budget))}/${String(getRegexMember(value, "flags", budget))}`
138819
- );
138820
- }
139300
+ if (isSandboxRegex(value)) return regexToString(value, budget, context);
138821
139301
  if (isSandboxDate(value)) return budget.allocateString(dateString(value));
138822
139302
  if (Array.isArray(value) || isFloat32Array(value)) {
138823
139303
  if (Object.hasOwn(value, "join")) {
@@ -138861,6 +139341,7 @@ var init_string_coercion = __esm({
138861
139341
  init_graph_depth();
138862
139342
  init_host_capabilities();
138863
139343
  init_collection_iterator();
139344
+ init_regexp_iterator();
138864
139345
  init_object_model();
138865
139346
  init_regex();
138866
139347
  init_resources();
@@ -139044,6 +139525,7 @@ function typeTag(value, builtinOnly = false) {
139044
139525
  if (builtinOnly) return "Object";
139045
139526
  if (isSandboxMap(value)) return "Map";
139046
139527
  if (isSandboxSet(value)) return "Set";
139528
+ if (isSandboxRegExpIterator(value)) return "RegExp String Iterator";
139047
139529
  if (isSandboxCollectionIterator(value)) return collectionIteratorState(value).collectionKind === "map" ? "Map Iterator" : "Set Iterator";
139048
139530
  if (isSandboxPromise(value)) return "Promise";
139049
139531
  if (isSandboxGenerator(value)) return "Generator";
@@ -139062,6 +139544,7 @@ var init_object2 = __esm({
139062
139544
  init_float32();
139063
139545
  init_host_capabilities();
139064
139546
  init_collection_iterator();
139547
+ init_regexp_iterator();
139065
139548
  init_object_model();
139066
139549
  init_property_key();
139067
139550
  init_values();
@@ -140443,6 +140926,7 @@ function registerCancelablePromises(value, signal) {
140443
140926
  for (const entry of current.values) pending.push(entry);
140444
140927
  } else {
140445
140928
  if (isSandboxCollectionIterator(current)) pending.push(collectionIteratorState(current).collection);
140929
+ if (isSandboxRegExpIterator(current)) pending.push(regexpIteratorState(current).matcher);
140446
140930
  for (const descriptor of Object.values(Object.getOwnPropertyDescriptors(current))) {
140447
140931
  if ("value" in descriptor) pending.push(descriptor.value);
140448
140932
  }
@@ -140545,6 +141029,7 @@ var init_cancel2 = __esm({
140545
141029
  "packages/safe-js/src/interp/cancel.ts"() {
140546
141030
  "use strict";
140547
141031
  init_collection_iterator();
141032
+ init_regexp_iterator();
140548
141033
  init_object_model();
140549
141034
  init_values();
140550
141035
  init_promise_tracker();
@@ -140889,6 +141374,16 @@ function measureSandboxData(values, options = {}) {
140889
141374
  }
140890
141375
  return;
140891
141376
  }
141377
+ if (isSandboxRegExpIterator(value)) {
141378
+ const state = regexpIteratorState(value);
141379
+ visit(state.matcher, depth + 1);
141380
+ visit(state.input, depth + 1);
141381
+ for (const [key3, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
141382
+ usage += key3.length + 1;
141383
+ if ("value" in descriptor) visit(descriptor.value, depth + 1);
141384
+ }
141385
+ return;
141386
+ }
140892
141387
  if (isSandboxCollectionIterator(value)) {
140893
141388
  visit(collectionIteratorState(value).collection, depth + 1);
140894
141389
  for (const [key3, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
@@ -141046,6 +141541,22 @@ function copyToSandbox(value, state, path193 = "<root>", cloneSandboxCollections
141046
141541
  if (isSandboxClosure(value) || isSandboxGenerator(value) || isSandboxPromise(value)) {
141047
141542
  return value;
141048
141543
  }
141544
+ if (isSandboxRegExpIterator(value)) {
141545
+ if (hasGuestObjectState(value)) throw new TypeError("Guest prototype links and custom descriptors cannot be copied as data.");
141546
+ if (!cloneSandboxCollections) return value;
141547
+ const existing = state.seen.get(value);
141548
+ if (existing !== void 0) return existing;
141549
+ const snapshot2 = regexpIteratorState(value);
141550
+ const copy = restoreSandboxRegExpIterator({ matcher: void 0, input: void 0, exhausted: true });
141551
+ state.seen.set(value, copy);
141552
+ const matcher = copyToSandbox(snapshot2.matcher, state, `${path193}.<matcher>`, true, depth + 1);
141553
+ if (matcher !== void 0 && !isSandboxRegex(matcher)) throw new TypeError("Invalid RegExp iterator matcher.");
141554
+ restoreSandboxRegExpIterator({ ...snapshot2, matcher }, copy);
141555
+ for (const entry of getEnumerableObjectEntries(value, path193)) {
141556
+ defineOwnDataProperty(copy, entry.key, copyToSandbox(entry.value, state, joinPath2(path193, entry.key), true, depth + 1));
141557
+ }
141558
+ return copy;
141559
+ }
141049
141560
  if (isSandboxCollectionIterator(value)) {
141050
141561
  if (hasGuestObjectState(value)) throw new TypeError("Guest prototype links and custom descriptors cannot be copied as data.");
141051
141562
  if (!cloneSandboxCollections) return value;
@@ -141372,6 +141883,9 @@ function copyFromSandbox(value, state, path193 = "<root>", options, depth = 0) {
141372
141883
  if (isSandboxCollectionIterator(value)) {
141373
141884
  throw new TypeError("Sandbox collection iterators cannot cross into host values.");
141374
141885
  }
141886
+ if (isSandboxRegExpIterator(value)) {
141887
+ throw new TypeError("Sandbox RegExp iterators cannot cross into host values.");
141888
+ }
141375
141889
  if (isSandboxRegex(value)) {
141376
141890
  throw new TypeError("Invalid sandbox RegExp brand.");
141377
141891
  }
@@ -141625,6 +142139,7 @@ var init_values = __esm({
141625
142139
  init_accessors();
141626
142140
  init_collection_brands();
141627
142141
  init_collection_iterator();
142142
+ init_regexp_iterator();
141628
142143
  init_date();
141629
142144
  init_boxed();
141630
142145
  init_host_capabilities();
@@ -141830,7 +142345,7 @@ function serializeDumpValue(value, path193, state) {
141830
142345
  if (hasGuestObjectState(value)) {
141831
142346
  throw new TypeError("Guest function properties and prototype links cannot be serialized.");
141832
142347
  }
141833
- if (isSandboxRegex(value) && hasCustomRegexProperties(value) || isSandboxBox(value) || isSandboxDate(value) || isFloat32Array(value)) return serializeHeapReference(value, path193, state);
142348
+ if (isSandboxRegExpIterator(value) || isSandboxRegex(value) && hasCustomRegexProperties(value) || isSandboxBox(value) || isSandboxDate(value) || isFloat32Array(value)) return serializeHeapReference(value, path193, state);
141834
142349
  if (Array.isArray(value)) {
141835
142350
  const reference2 = serializeHeapReference(value, path193, state);
141836
142351
  if (reference2 !== void 0) {
@@ -141854,7 +142369,28 @@ function serializeHeapReference(value, path193, state) {
141854
142369
  }
141855
142370
  if (!state.serializedHeapIds.has(id)) {
141856
142371
  state.serializedHeapIds.add(id);
141857
- if (isSandboxRegex(value) && hasCustomRegexProperties(value)) {
142372
+ if (isSandboxRegExpIterator(value)) {
142373
+ const snapshot2 = regexpIteratorState(value);
142374
+ const matcher = snapshot2.matcher;
142375
+ const entries = /* @__PURE__ */ Object.create(null);
142376
+ state.heap[String(id)] = {
142377
+ kind: "regexp-iterator",
142378
+ exhausted: snapshot2.exhausted,
142379
+ matcher: matcher === void 0 ? { kind: "undefined" } : { kind: "regex", source: matcher.source, flags: matcher.flags, lastIndex: Number(matcher.lastIndex) },
142380
+ input: snapshot2.input ?? { kind: "undefined" },
142381
+ entries,
142382
+ symbolEntries: serializeSymbolProperties(value, (entry) => {
142383
+ const serialized = serializeDumpValue(entry, `${path193}.[symbol]`, state);
142384
+ if (serialized === SKIP_VALUE) throw new TypeError("Unsupported RegExp iterator symbol property in public dump.");
142385
+ return serialized;
142386
+ })
142387
+ };
142388
+ for (const [key3, entry] of getEnumerableDataEntries(value)) {
142389
+ const serialized = serializeDumpValue(entry, `${path193}.${key3}`, state);
142390
+ if (serialized === SKIP_VALUE) throw new TypeError("Unsupported RegExp iterator property in public dump.");
142391
+ entries[key3] = serialized;
142392
+ }
142393
+ } else if (isSandboxRegex(value) && hasCustomRegexProperties(value)) {
141858
142394
  const encode = (entry) => {
141859
142395
  const serialized = serializeDumpValue(entry, `${path193}.<regex-property>`, state);
141860
142396
  if (serialized === SKIP_VALUE) throw new TypeError("Unsupported RegExp property in public dump.");
@@ -141946,7 +142482,7 @@ function indexHeapContainers(snapshot2) {
141946
142482
  const heapIds = /* @__PURE__ */ new Map();
141947
142483
  let nextId = 1;
141948
142484
  for (const [value, stat35] of stats2.entries()) {
141949
- if (stat35.count > 1 || stat35.cyclic || ownSerializableSymbolKeys(value).length > 0 || isSandboxBox(value) || isSandboxRegex(value) && hasCustomRegexProperties(value) || isSandboxDate(value) || isFloat32Array(value) || Array.isArray(value) && requiresArrayEntries(value) || isSandboxArguments(value) || sandboxErrorTypes.has(value)) {
142485
+ if (stat35.count > 1 || stat35.cyclic || ownSerializableSymbolKeys(value).length > 0 || isSandboxBox(value) || isSandboxRegExpIterator(value) || isSandboxRegex(value) && hasCustomRegexProperties(value) || isSandboxDate(value) || isFloat32Array(value) || Array.isArray(value) && requiresArrayEntries(value) || isSandboxArguments(value) || sandboxErrorTypes.has(value)) {
141950
142486
  heapIds.set(value, nextId);
141951
142487
  nextId += 1;
141952
142488
  }
@@ -142029,6 +142565,7 @@ var init_dump_format = __esm({
142029
142565
  "packages/safe-js/src/snapshot/dump-format.ts"() {
142030
142566
  "use strict";
142031
142567
  init_values();
142568
+ init_regexp_iterator();
142032
142569
  init_regexp_properties2();
142033
142570
  init_graph_depth();
142034
142571
  init_object_model();
@@ -142097,6 +142634,10 @@ function validateDumpHeap(root, state) {
142097
142634
  const entry = requireRecord3(value, path193);
142098
142635
  validateErrorType(entry, path193);
142099
142636
  validateSymbolEntries(entry, path193, state, heap);
142637
+ if (entry.kind === "regexp-iterator") {
142638
+ validateHeapValue(entry, path193, state, heap);
142639
+ continue;
142640
+ }
142100
142641
  if (entry.kind === "regex-object") {
142101
142642
  validateTaggedValue(entry, path193, state);
142102
142643
  continue;
@@ -142201,6 +142742,9 @@ function validatePosition(value, path193) {
142201
142742
  requireSafeInteger(position.column, `${path193}.column`, 0);
142202
142743
  return requireSafeInteger(position.offset, `${path193}.offset`, 0);
142203
142744
  }
142745
+ function validateValue(value, path193, depth, state) {
142746
+ validateGenericValue(value, path193, depth, state);
142747
+ }
142204
142748
  function validateTaggedValue(record2, path193, state) {
142205
142749
  switch (record2.kind) {
142206
142750
  case "undefined":
@@ -142244,6 +142788,7 @@ function validateTaggedValue(record2, path193, state) {
142244
142788
  case "map":
142245
142789
  case "set":
142246
142790
  case "collection-iterator":
142791
+ case "regexp-iterator":
142247
142792
  return;
142248
142793
  }
142249
142794
  }
@@ -142284,9 +142829,47 @@ function validateGeneratorShape(record2, path193, state) {
142284
142829
  }
142285
142830
  });
142286
142831
  }
142832
+ function validateHeapValue(value, path193, state, heap) {
142833
+ const record2 = requireRecord3(value, path193);
142834
+ validateErrorType(record2, path193);
142835
+ if (!["symbol", "arguments", "array", "object", "map", "set", "float32array", "date", "boxed", "collection-iterator", "regexp-iterator", "regex-object"].includes(String(record2.kind)))
142836
+ fail2("unknownTag", `${path193}.kind`, "unknown heap tag");
142837
+ validateValue(record2, path193, 1, state);
142838
+ if (record2.kind === "symbol") validateSymbolRecord(record2, path193, state);
142839
+ if (record2.kind === "arguments") validateArgumentsProperties(record2, path193);
142840
+ if (record2.kind === "array") validateArrayHeap(record2, path193, state);
142841
+ if (record2.kind === "object") requireRecord3(record2.entries, `${path193}.entries`);
142842
+ if (record2.kind === "boxed") validateBoxedRecord(record2, path193, heap);
142843
+ if (record2.kind === "date") validateDateRecord(record2, path193);
142844
+ if (record2.kind === "float32array") {
142845
+ validateFloat32Storage(record2);
142846
+ requireRecord3(record2.entries, `${path193}.entries`);
142847
+ }
142848
+ if (record2.kind === "map") {
142849
+ const entries = requireArray(record2.entries, `${path193}.entries`, state);
142850
+ entries.forEach((entry, index) => {
142851
+ if (!Array.isArray(entry) || entry.length !== 2)
142852
+ fail2("invalidValue", `${path193}.entries[${index}]`, "map entry must contain two values");
142853
+ });
142854
+ }
142855
+ if (record2.kind === "set") requireArray(record2.values, `${path193}.values`, state);
142856
+ if (record2.kind === "regexp-iterator") {
142857
+ if (typeof record2.exhausted !== "boolean") fail2("invalidValue", `${path193}.exhausted`, "invalid iterator exhaustion");
142858
+ if (!Object.hasOwn(record2, "matcher") || !Object.hasOwn(record2, "input")) fail2("invalidValue", path193, "missing RegExp iterator state");
142859
+ requireRecord3(record2.entries, `${path193}.entries`);
142860
+ }
142861
+ if (record2.kind === "collection-iterator") {
142862
+ if (record2.collectionKind !== "map" && record2.collectionKind !== "set") fail2("invalidValue", `${path193}.collectionKind`, "invalid iterator brand");
142863
+ if (record2.method !== "keys" && record2.method !== "values" && record2.method !== "entries") fail2("invalidValue", `${path193}.method`, "invalid iteration method");
142864
+ if (typeof record2.exhausted !== "boolean") fail2("invalidValue", `${path193}.exhausted`, "invalid iterator exhaustion");
142865
+ requireSafeInteger(record2.index, `${path193}.index`, 0);
142866
+ if (!Object.hasOwn(record2, "collection")) fail2("invalidValue", `${path193}.collection`, "missing iterator source");
142867
+ requireRecord3(record2.entries, `${path193}.entries`);
142868
+ }
142869
+ }
142287
142870
  function validateSymbolEntries(record2, path193, state, heap) {
142288
142871
  if (record2.symbolEntries === void 0) return;
142289
- if (record2.kind !== "object" && record2.kind !== "array" && record2.kind !== "date" && record2.kind !== "boxed" && record2.kind !== "regex-object")
142872
+ if (record2.kind !== "object" && record2.kind !== "array" && record2.kind !== "date" && record2.kind !== "boxed" && record2.kind !== "regex-object" && record2.kind !== "regexp-iterator")
142290
142873
  fail2("invalidValue", `${path193}.symbolEntries`, "symbol properties are unsupported for this heap kind");
142291
142874
  const entries = requireArray(record2.symbolEntries, `${path193}.symbolEntries`, state);
142292
142875
  const keys = /* @__PURE__ */ new Set();
@@ -154506,22 +155089,49 @@ function createRegexGlobals(options) {
154506
155089
  const operation = options.budget.acquireCompileOwner(false, selected);
154507
155090
  const compilation = context?.compilation?.owner === operation.owner ? context.compilation : new CompileScope(operation.owner);
154508
155091
  let source = "";
155092
+ let retainedSource;
155093
+ let retainedFlags;
155094
+ let retainedPrototype;
154509
155095
  const retained = {};
154510
- options.budget.setRetainedValues(retained, () => [...args, source]);
155096
+ options.budget.setRetainedValues(retained, () => [...args, source, retainedSource, retainedFlags, retainedPrototype]);
154511
155097
  try {
154512
155098
  const pattern = args[0];
154513
155099
  const flags = args[1];
154514
- if (!construct && isSandboxRegex(pattern) && flags === void 0) return pattern;
154515
- const sourceValue = isSandboxRegex(pattern) ? pattern.source : pattern;
154516
- const flagsValue = isSandboxRegex(pattern) && flags === void 0 ? pattern.flags : flags;
155100
+ const read = (key3) => {
155101
+ const descriptor = getSandboxPropertyDescriptor(pattern, key3, options.budget);
155102
+ if (context?.getProperty !== void 0) return context.getProperty(pattern, key3);
155103
+ return descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, pattern, context);
155104
+ };
155105
+ let regexLike = false;
155106
+ if (pattern !== null && typeof pattern === "object") {
155107
+ const match = await read(Symbol.match);
155108
+ regexLike = match === void 0 ? isSandboxRegex(pattern) : Boolean(match);
155109
+ }
155110
+ if (!construct && regexLike && flags === void 0 && await read("constructor") === constructor) return pattern;
155111
+ let sourceValue = pattern;
155112
+ let flagsValue = flags;
155113
+ if (isSandboxRegex(pattern)) {
155114
+ sourceValue = pattern.source;
155115
+ if (flags === void 0) flagsValue = pattern.flags;
155116
+ } else if (regexLike) {
155117
+ sourceValue = retainedSource = await read("source");
155118
+ if (flags === void 0) flagsValue = retainedFlags = await read("flags");
155119
+ }
155120
+ if (construct && context?.newTarget !== void 0 && context.newTarget !== constructor) {
155121
+ retainedPrototype = context.getProperty !== void 0 ? await context.getProperty(context.newTarget, "prototype") : await readPropertyDescriptor(getSandboxPropertyDescriptor(context.newTarget, "prototype", options.budget) ?? { value: void 0 }, context.newTarget, context);
155122
+ }
154517
155123
  source = sourceValue === void 0 ? "" : await sandboxString(sourceValue, options.budget, context);
155124
+ retainedSource = void 0;
154518
155125
  const flagText = flagsValue === void 0 ? "" : await sandboxString(flagsValue, options.budget, context);
155126
+ retainedFlags = void 0;
154519
155127
  const regex = createSandboxRegex(
154520
155128
  source,
154521
155129
  flagText,
154522
155130
  0,
154523
155131
  compilation
154524
155132
  );
155133
+ if (typeof retainedPrototype === "object" && retainedPrototype !== null)
155134
+ setSandboxPrototype(regex, retainedPrototype, options.budget);
154525
155135
  if (compilation !== context?.compilation) {
154526
155136
  reconcileCompiledValues(options.budget, [regex], compilation);
154527
155137
  }
@@ -154532,9 +155142,82 @@ function createRegexGlobals(options) {
154532
155142
  operation.release();
154533
155143
  }
154534
155144
  };
154535
- return {
154536
- RegExp: createSandboxClosure({ sandbox: true, name: "RegExp", call: invoke2(false), construct: invoke2(true) })
154537
- };
155145
+ const constructor = createSandboxClosure({ guest: true, sandbox: true, name: "RegExp", length: 2, call: invoke2(false), construct: invoke2(true) });
155146
+ const prototype = /* @__PURE__ */ Object.create(null);
155147
+ Object.defineProperty(materializeFunctionProperties(constructor), "prototype", { value: prototype, writable: false });
155148
+ Object.defineProperty(prototype, "constructor", { value: constructor, writable: true, configurable: true });
155149
+ Object.defineProperty(prototype, Symbol.search, {
155150
+ value: createSandboxClosure({
155151
+ guest: true,
155152
+ sandbox: true,
155153
+ name: "[Symbol.search]",
155154
+ length: 1,
155155
+ call: (args, context) => regexSearch(context?.thisValue, args[0], options.budget, context)
155156
+ }),
155157
+ writable: true,
155158
+ configurable: true
155159
+ });
155160
+ Object.defineProperty(prototype, Symbol.match, {
155161
+ value: createSandboxClosure({
155162
+ guest: true,
155163
+ sandbox: true,
155164
+ name: "[Symbol.match]",
155165
+ length: 1,
155166
+ call: (args, context) => regexMatch(args[0], context?.thisValue, options.budget, context)
155167
+ }),
155168
+ writable: true,
155169
+ configurable: true
155170
+ });
155171
+ Object.defineProperty(prototype, Symbol.replace, {
155172
+ value: createSandboxClosure({
155173
+ guest: true,
155174
+ sandbox: true,
155175
+ name: "[Symbol.replace]",
155176
+ length: 2,
155177
+ call: (args, context) => regexReplace(
155178
+ args[0],
155179
+ context?.thisValue,
155180
+ args[1],
155181
+ options.budget,
155182
+ (closure, values) => invokeBuiltinClosure(closure, values, options.budget, context, void 0),
155183
+ context
155184
+ )
155185
+ }),
155186
+ writable: true,
155187
+ configurable: true
155188
+ });
155189
+ for (const name of ["exec", "test", "toString"]) {
155190
+ Object.defineProperty(prototype, name, {
155191
+ value: createSandboxClosure({
155192
+ sandbox: true,
155193
+ name,
155194
+ length: name === "toString" ? 0 : 1,
155195
+ call: (args, context) => callRegexMethod(context?.thisValue, name, args, options.budget, context)
155196
+ }),
155197
+ writable: true,
155198
+ configurable: true
155199
+ });
155200
+ }
155201
+ for (const name of ["source", "flags", ...Object.keys(regexFlagProperties)]) {
155202
+ const getter = createSandboxClosure({
155203
+ sandbox: true,
155204
+ name: `get ${name}`,
155205
+ length: 0,
155206
+ call: (_args, context) => {
155207
+ const receiver = context?.thisValue;
155208
+ if (name === "flags") {
155209
+ if (receiver === null || typeof receiver !== "object") throw new TypeError("RegExp flags requires an object receiver.");
155210
+ return getRegexMember(receiver, name, options.budget, context);
155211
+ }
155212
+ if (receiver === prototype) return name === "source" ? "(?:)" : void 0;
155213
+ if (!isSandboxRegex(receiver)) throw new TypeError("RegExp accessor requires a regex receiver.");
155214
+ return getRegexMember(receiver, name, options.budget, context);
155215
+ }
155216
+ });
155217
+ Object.defineProperty(prototype, name, { get: accessorAdapter(getter, "get"), configurable: true });
155218
+ }
155219
+ installRegexPrototype(options.budget, prototype, constructor);
155220
+ return { RegExp: constructor };
154538
155221
  }
154539
155222
  var init_regex2 = __esm({
154540
155223
  "packages/safe-js/src/interp/globals/regex.ts"() {
@@ -154543,6 +155226,11 @@ var init_regex2 = __esm({
154543
155226
  init_compile_guard();
154544
155227
  init_budget2();
154545
155228
  init_string_coercion();
155229
+ init_object_model();
155230
+ init_accessors();
155231
+ init_regex();
155232
+ init_string();
155233
+ init_builtin_call();
154546
155234
  }
154547
155235
  });
154548
155236
 
@@ -154589,7 +155277,7 @@ function structuredCloneSandboxValue(value, budget, parent) {
154589
155277
  }
154590
155278
  }
154591
155279
  function assertStructuredCloneable(value, seen) {
154592
- if (isSandboxClosure(value) || isSandboxPromise(value) || isSandboxCollectionIterator(value)) {
155280
+ if (isSandboxClosure(value) || isSandboxPromise(value) || isSandboxCollectionIterator(value) || isSandboxRegExpIterator(value)) {
154593
155281
  throw new TypeError("structuredClone() cannot clone closures, promises, or collection iterators.");
154594
155282
  }
154595
155283
  if (typeof value !== "object" || value === null || seen.has(value)) {
@@ -154617,6 +155305,7 @@ var init_misc = __esm({
154617
155305
  "packages/safe-js/src/interp/globals/misc.ts"() {
154618
155306
  "use strict";
154619
155307
  init_collection_iterator();
155308
+ init_regexp_iterator();
154620
155309
  init_graph_depth();
154621
155310
  init_compile_guard();
154622
155311
  init_numeric_parsers();
@@ -156190,6 +156879,7 @@ var init_serialize = __esm({
156190
156879
  init_regexp_properties2();
156191
156880
  init_symbols3();
156192
156881
  init_collection_iterator();
156882
+ init_regexp_iterator();
156193
156883
  init_object_model();
156194
156884
  init_shape();
156195
156885
  init_graph_depth();
@@ -156266,6 +156956,17 @@ function prepareReplayInputs(current, saved, preparePromise, onCapabilityRestore
156266
156956
  value = descriptor2.value;
156267
156957
  continue;
156268
156958
  }
156959
+ if (isSandboxRegExpIterator(value)) {
156960
+ if (key3 === "<matcher>") value = regexpIteratorState(value).matcher;
156961
+ else if (key3 === "<input>") value = regexpIteratorState(value).input;
156962
+ else {
156963
+ const property = JSON.parse(key3);
156964
+ if (!Array.isArray(property) || property.length !== 2 || property[0] !== "property" || typeof property[1] !== "string") throw new TypeError("Invalid replay input iterator capability path.");
156965
+ const descriptor2 = Object.getOwnPropertyDescriptor(value, property[1]);
156966
+ value = descriptor2 !== void 0 && "value" in descriptor2 ? descriptor2.value : void 0;
156967
+ }
156968
+ continue;
156969
+ }
156269
156970
  if (isSandboxCollectionIterator(value)) {
156270
156971
  if (key3 === "<collection>") value = collectionIteratorState(value).collection;
156271
156972
  else {
@@ -156336,11 +157037,11 @@ function prepareReplayInputs(current, saved, preparePromise, onCapabilityRestore
156336
157037
  return { values: restored, snapshot: structuredClone(saved) };
156337
157038
  }
156338
157039
  function assertReplayInputShape(restored) {
156339
- if (restored === null || typeof restored !== "object" || Array.isArray(restored) || isSandboxClosure(restored) || isSandboxPromise(restored) || isSandboxCollectionIterator(restored) || isSandboxMap(restored) || isSandboxSet(restored))
157040
+ if (restored === null || typeof restored !== "object" || Array.isArray(restored) || isSandboxClosure(restored) || isSandboxPromise(restored) || isSandboxCollectionIterator(restored) || isSandboxRegExpIterator(restored) || isSandboxMap(restored) || isSandboxSet(restored))
156340
157041
  throw new TypeError("Invalid replay inputs.");
156341
157042
  const values = restored;
156342
157043
  for (const key3 of ["bindings", "imports"]) {
156343
- if (values[key3] === null || typeof values[key3] !== "object" || Array.isArray(values[key3]) || isSandboxClosure(values[key3]) || isSandboxPromise(values[key3]) || isSandboxCollectionIterator(values[key3]) || isSandboxMap(values[key3]) || isSandboxSet(values[key3]))
157044
+ if (values[key3] === null || typeof values[key3] !== "object" || Array.isArray(values[key3]) || isSandboxClosure(values[key3]) || isSandboxPromise(values[key3]) || isSandboxCollectionIterator(values[key3]) || isSandboxRegExpIterator(values[key3]) || isSandboxMap(values[key3]) || isSandboxSet(values[key3]))
156344
157045
  throw new TypeError(`Invalid replay input ${key3}.`);
156345
157046
  }
156346
157047
  if (values.entryPointArgs !== void 0 && !Array.isArray(values.entryPointArgs))
@@ -156351,6 +157052,7 @@ var init_replay_inputs = __esm({
156351
157052
  "packages/safe-js/src/snapshot/replay-inputs.ts"() {
156352
157053
  "use strict";
156353
157054
  init_collection_iterator();
157055
+ init_regexp_iterator();
156354
157056
  init_values();
156355
157057
  init_replay_data();
156356
157058
  init_compile_guard();
@@ -162381,11 +163083,11 @@ async function resolveWorkflowTasksOptions(options) {
162381
163083
  };
162382
163084
  }
162383
163085
  function readGateStates(frontmatter) {
162384
- const states2 = asRecord6(frontmatter.states);
162385
- if (states2 === void 0) {
163086
+ const states3 = asRecord6(frontmatter.states);
163087
+ if (states3 === void 0) {
162386
163088
  return [];
162387
163089
  }
162388
- return Object.entries(states2).filter(([, definition]) => asRecord6(definition)?.gate === true).map(([name]) => name);
163090
+ return Object.entries(states3).filter(([, definition]) => asRecord6(definition)?.gate === true).map(([name]) => name);
162389
163091
  }
162390
163092
  async function readWorkflowFrontmatter(workflowPath) {
162391
163093
  const workflowContent = await readWorkflow(workflowPath);
@@ -162416,11 +163118,11 @@ function readTaskListOptions(frontmatter, workflowPath) {
162416
163118
  }
162417
163119
  return resolved;
162418
163120
  }
162419
- function createAnyToAnyStateMachine(states2) {
163121
+ function createAnyToAnyStateMachine(states3) {
162420
163122
  return {
162421
- initial: states2[0],
162422
- states: states2,
162423
- events: Object.fromEntries(states2.map((state) => [state, { from: "*", to: state }]))
163123
+ initial: states3[0],
163124
+ states: states3,
163125
+ events: Object.fromEntries(states3.map((state) => [state, { from: "*", to: state }]))
162424
163126
  };
162425
163127
  }
162426
163128
  function parseProject(value) {
@@ -162441,9 +163143,9 @@ function parseProject(value) {
162441
163143
  }
162442
163144
  function resolveRequiredStates(statesOption, frontmatter) {
162443
163145
  if (statesOption !== void 0) {
162444
- const states2 = parseStatesCsv(statesOption);
162445
- if (states2.length > 0) {
162446
- return states2;
163146
+ const states3 = parseStatesCsv(statesOption);
163147
+ if (states3.length > 0) {
163148
+ return states3;
162447
163149
  }
162448
163150
  throw new TasksOptionsError(
162449
163151
  "missing_required_states",
@@ -162493,8 +163195,8 @@ function readLegacyTopLevelStates(frontmatter) {
162493
163195
  ]);
162494
163196
  }
162495
163197
  function readDeclaredStates(value) {
162496
- const states2 = asRecord6(value);
162497
- return states2 === void 0 ? [] : Object.keys(states2);
163198
+ const states3 = asRecord6(value);
163199
+ return states3 === void 0 ? [] : Object.keys(states3);
162498
163200
  }
162499
163201
  function readTasksRepo(frontmatter) {
162500
163202
  const tasks = asRecord6(getOwnEntry37(frontmatter, "tasks"));