poe-code 14.0.5 → 14.0.7

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 (54) hide show
  1. package/dist/index.js +1604 -255
  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-B7H4ZL65.js → chunk-BWVASPJX.js} +2099 -783
  6. package/packages/safe-js/dist/chunks/chunk-BWVASPJX.js.map +7 -0
  7. package/packages/safe-js/dist/chunks/{chunk-7B7BKWVF.js → chunk-ETKM3KPA.js} +2 -2
  8. package/packages/safe-js/dist/cli.js +2 -2
  9. package/packages/safe-js/dist/core.d.ts +3 -0
  10. package/packages/safe-js/dist/core.js +5 -1
  11. package/packages/safe-js/dist/extensions.d.ts +44 -0
  12. package/packages/safe-js/dist/extensions.js +83 -0
  13. package/packages/safe-js/dist/index.d.ts +4 -1
  14. package/packages/safe-js/dist/index.js +6 -2
  15. package/packages/safe-js/dist/index.js.map +2 -2
  16. package/packages/safe-js/dist/interp/async.d.ts +1 -0
  17. package/packages/safe-js/dist/interp/date.d.ts +19 -0
  18. package/packages/safe-js/dist/interp/date.js +129 -0
  19. package/packages/safe-js/dist/interp/globals/console-json.js +5 -1
  20. package/packages/safe-js/dist/interp/globals/date.d.ts +10 -0
  21. package/packages/safe-js/dist/interp/globals/date.js +95 -0
  22. package/packages/safe-js/dist/interp/globals/object-array.d.ts +2 -1
  23. package/packages/safe-js/dist/interp/globals/object-array.js +15 -1
  24. package/packages/safe-js/dist/interp/globals.d.ts +34 -0
  25. package/packages/safe-js/dist/interp/globals.js +24 -0
  26. package/packages/safe-js/dist/interp/host-bridge.d.ts +18 -1
  27. package/packages/safe-js/dist/interp/host-bridge.js +39 -5
  28. package/packages/safe-js/dist/interp/host-call.js +4 -0
  29. package/packages/safe-js/dist/interp/host-capabilities.d.ts +50 -0
  30. package/packages/safe-js/dist/interp/host-capabilities.js +151 -0
  31. package/packages/safe-js/dist/interp/interpreter.d.ts +4 -0
  32. package/packages/safe-js/dist/interp/interpreter.js +41 -6
  33. package/packages/safe-js/dist/interp/object-model.js +7 -0
  34. package/packages/safe-js/dist/interp/string-coercion.js +3 -0
  35. package/packages/safe-js/dist/interp/values.d.ts +2 -1
  36. package/packages/safe-js/dist/interp/values.js +36 -0
  37. package/packages/safe-js/dist/lint/rules/known-globals.d.ts +1 -1
  38. package/packages/safe-js/dist/lint/rules/known-globals.js +1 -0
  39. package/packages/safe-js/dist/modules/registry.d.ts +3 -1
  40. package/packages/safe-js/dist/modules/registry.js +2 -1
  41. package/packages/safe-js/dist/parse/parser.js +4 -2
  42. package/packages/safe-js/dist/realm.d.ts +46 -0
  43. package/packages/safe-js/dist/realm.js +779 -0
  44. package/packages/safe-js/dist/run.d.ts +7 -1
  45. package/packages/safe-js/dist/run.js +6 -35
  46. package/packages/safe-js/dist/snapshot/dump-format.js +8 -3
  47. package/packages/safe-js/dist/snapshot/replay-data.d.ts +4 -1
  48. package/packages/safe-js/dist/snapshot/replay-data.js +11 -0
  49. package/packages/safe-js/dist/snapshot/restore.js +6 -0
  50. package/packages/safe-js/dist/snapshot/serialize.d.ts +5 -2
  51. package/packages/safe-js/dist/snapshot/serialize.js +8 -2
  52. package/packages/safe-js/dist/snapshot/validation.js +18 -1
  53. package/packages/safe-js/dist/chunks/chunk-B7H4ZL65.js.map +0 -7
  54. /package/packages/safe-js/dist/chunks/{chunk-7B7BKWVF.js.map → chunk-ETKM3KPA.js.map} +0 -0
package/dist/index.js CHANGED
@@ -7179,24 +7179,24 @@ function renderReferencedFootnotes(context) {
7179
7179
  return items.length === 0 ? "" : `<section class="footnotes"><ol>${items}</ol></section>`;
7180
7180
  }
7181
7181
  function createFootnoteState(children2) {
7182
- const definitions = /* @__PURE__ */ new Map();
7182
+ const definitions2 = /* @__PURE__ */ new Map();
7183
7183
  for (const child of children2) {
7184
- collectFootnoteDefinitions(child, definitions);
7184
+ collectFootnoteDefinitions(child, definitions2);
7185
7185
  }
7186
7186
  return {
7187
- definitions,
7187
+ definitions: definitions2,
7188
7188
  labelsInOrder: [],
7189
7189
  numbers: /* @__PURE__ */ new Map()
7190
7190
  };
7191
7191
  }
7192
- function collectFootnoteDefinitions(node, definitions) {
7192
+ function collectFootnoteDefinitions(node, definitions2) {
7193
7193
  if (node.type === "footnoteDefinition") {
7194
- definitions.set(node.label, node);
7194
+ definitions2.set(node.label, node);
7195
7195
  return;
7196
7196
  }
7197
7197
  if ("children" in node) {
7198
7198
  for (const child of node.children) {
7199
- collectFootnoteDefinitions(child, definitions);
7199
+ collectFootnoteDefinitions(child, definitions2);
7200
7200
  }
7201
7201
  }
7202
7202
  }
@@ -12159,19 +12159,19 @@ function selectedRows(state, fallback) {
12159
12159
  return source.filter((row) => state.selected.has(row.id));
12160
12160
  }
12161
12161
  function runtimePanes(state) {
12162
- const definitions = state.paneDefinitions;
12162
+ const definitions2 = state.paneDefinitions;
12163
12163
  return [
12164
12164
  {
12165
- id: definitions[0]?.id ?? "list",
12166
- title: definitions[0]?.title ?? state.title,
12165
+ id: definitions2[0]?.id ?? "list",
12166
+ title: definitions2[0]?.title ?? state.title,
12167
12167
  rows: state.rows,
12168
12168
  cursor: state.cursor,
12169
12169
  selected: state.selected,
12170
12170
  filter: state.filter
12171
12171
  },
12172
12172
  {
12173
- id: definitions[1]?.id ?? "detail",
12174
- title: definitions[1]?.title ?? "Preview",
12173
+ id: definitions2[1]?.id ?? "detail",
12174
+ title: definitions2[1]?.title ?? "Preview",
12175
12175
  rows: (state.detail.items ?? []).map((item) => ({
12176
12176
  id: item.id,
12177
12177
  title: item.title ?? item.id,
@@ -49222,9 +49222,9 @@ function buildSkillGuidance(activeDefinitions, activeTools) {
49222
49222
  ];
49223
49223
  return lines.join("\n");
49224
49224
  }
49225
- function normalizeDefinitions(definitions) {
49225
+ function normalizeDefinitions(definitions2) {
49226
49226
  const normalized = /* @__PURE__ */ new Map();
49227
- for (const [rawName, rawDefinition] of Object.entries(definitions)) {
49227
+ for (const [rawName, rawDefinition] of Object.entries(definitions2)) {
49228
49228
  const name = rawName.trim();
49229
49229
  if (name.length === 0 || normalized.has(name)) {
49230
49230
  continue;
@@ -49259,14 +49259,14 @@ var init_poe_agent_plugin_skills = __esm({
49259
49259
  "packages/poe-agent/src/plugins/poe-agent-plugin-skills.ts"() {
49260
49260
  "use strict";
49261
49261
  skills = (options) => {
49262
- const definitions = normalizeDefinitions(options.definitions);
49262
+ const definitions2 = normalizeDefinitions(options.definitions);
49263
49263
  return {
49264
49264
  name: "skills",
49265
49265
  prompt(ctx) {
49266
49266
  const activeSkills = normalizeStringList(
49267
49267
  typeof options.skills === "function" ? options.skills() : options.skills
49268
49268
  );
49269
- const activeDefinitions = activeSkills.map((skillName) => definitions.get(skillName)).filter((definition) => definition !== void 0);
49269
+ const activeDefinitions = activeSkills.map((skillName) => definitions2.get(skillName)).filter((definition) => definition !== void 0);
49270
49270
  const activeTools = options.toolRegistry?.getActiveTools(activeSkills).map((tool) => tool.name) ?? [];
49271
49271
  const guidance = buildSkillGuidance(activeDefinitions, activeTools);
49272
49272
  return {
@@ -50271,8 +50271,8 @@ function assertNonNegativeInteger3(value, keyword) {
50271
50271
  }
50272
50272
  function validateSchemaObject(schema, dialect) {
50273
50273
  if (schema.type !== void 0) {
50274
- const types2 = Array.isArray(schema.type) ? schema.type : [schema.type];
50275
- if (types2.length === 0 || !types2.every((type) => typeof type === "string" && draftTypeSet.has(type)) || new Set(types2).size !== types2.length) {
50274
+ const types5 = Array.isArray(schema.type) ? schema.type : [schema.type];
50275
+ if (types5.length === 0 || !types5.every((type) => typeof type === "string" && draftTypeSet.has(type)) || new Set(types5).size !== types5.length) {
50276
50276
  throw new Error("type must be a JSON Schema type or a unique array of JSON Schema types.");
50277
50277
  }
50278
50278
  }
@@ -50991,9 +50991,9 @@ function evaluateValidationKeywords(node, schema, value, path193) {
50991
50991
  if (schema.nullable === true && value === null) {
50992
50992
  return results;
50993
50993
  }
50994
- const types2 = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];
50995
- if (types2.length > 0 && !types2.some((type) => typeof type === "string" && typeMatches(type, value))) {
50996
- results.push(invalidResult(issue(path193, types2.join(","), value, `must be ${types2.join(",")}`)));
50994
+ const types5 = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];
50995
+ if (types5.length > 0 && !types5.some((type) => typeof type === "string" && typeMatches(type, value))) {
50996
+ results.push(invalidResult(issue(path193, types5.join(","), value, `must be ${types5.join(",")}`)));
50997
50997
  return results;
50998
50998
  }
50999
50999
  if (schema.const !== void 0 && !deepEqual(schema.const, value)) {
@@ -124460,8 +124460,9 @@ var init_parser3 = __esm({
124460
124460
  }
124461
124461
  break;
124462
124462
  }
124463
- this.expectPunctuator("(");
124464
- const args = this.parseArguments();
124463
+ const optional = this.consumePunctuator("?.");
124464
+ if (optional !== void 0) throw new DisallowedSyntaxError("new optional chain", optional.start);
124465
+ const args = this.consumePunctuator("(") === void 0 ? [] : this.parseArguments();
124465
124466
  const end = this.previousToken();
124466
124467
  return {
124467
124468
  node: {
@@ -125538,6 +125539,204 @@ var init_graph_depth = __esm({
125538
125539
  }
125539
125540
  });
125540
125541
 
125542
+ // packages/safe-js/src/extensions.ts
125543
+ import { types } from "node:util";
125544
+ function readDataRecord(value, label) {
125545
+ if (typeof value !== "object" || value === null || types.isProxy(value)) {
125546
+ throw new TypeError(`${label} must be a plain data record.`);
125547
+ }
125548
+ const prototype = Object.getPrototypeOf(value);
125549
+ if (prototype !== null && prototype !== Object.prototype) {
125550
+ throw new TypeError(`${label} must be a plain data record.`);
125551
+ }
125552
+ const keys = Reflect.ownKeys(value);
125553
+ if (keys.length > 4096) throw new RangeError(`${label} has too many fields.`);
125554
+ const result = /* @__PURE__ */ Object.create(null);
125555
+ for (const key3 of keys) {
125556
+ const descriptor = Object.getOwnPropertyDescriptor(value, key3);
125557
+ if (typeof key3 !== "string" || !("value" in descriptor)) {
125558
+ throw new TypeError(`${label} requires string-keyed data properties, not accessors.`);
125559
+ }
125560
+ result[key3] = descriptor.value;
125561
+ }
125562
+ return result;
125563
+ }
125564
+ function readStringList(value, label) {
125565
+ if (!Array.isArray(value) || types.isProxy(value) || value.length > 4096) {
125566
+ throw new TypeError(`${label} must be a bounded string array.`);
125567
+ }
125568
+ const result = [];
125569
+ for (let index = 0; index < value.length; index++) {
125570
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
125571
+ if (descriptor === void 0 || !("value" in descriptor) || typeof descriptor.value !== "string" || descriptor.value.length === 0) {
125572
+ throw new TypeError(`${label} requires nonempty string data properties.`);
125573
+ }
125574
+ if (result.includes(descriptor.value))
125575
+ throw new TypeError(`${label} contains a duplicate name.`);
125576
+ result.push(descriptor.value);
125577
+ }
125578
+ if (Reflect.ownKeys(value).length !== result.length + 1)
125579
+ throw new TypeError(`${label} has unexpected fields.`);
125580
+ return Object.freeze(result);
125581
+ }
125582
+ function getExtensionSetup(extension) {
125583
+ const setup = definitions.get(extension);
125584
+ if (setup === void 0) throw new TypeError("Extensions must be created by defineExtension.");
125585
+ return setup;
125586
+ }
125587
+ var definitions;
125588
+ var init_extensions = __esm({
125589
+ "packages/safe-js/src/extensions.ts"() {
125590
+ "use strict";
125591
+ definitions = /* @__PURE__ */ new WeakMap();
125592
+ }
125593
+ });
125594
+
125595
+ // packages/safe-js/src/interp/host-capabilities.ts
125596
+ function createGuestReference(root, owner, assertActive) {
125597
+ const reference = Object.freeze(/* @__PURE__ */ Object.create(null));
125598
+ guestReferences.set(reference, { root, owner, assertActive });
125599
+ return reference;
125600
+ }
125601
+ function readGuestReference(reference, owner) {
125602
+ const state = typeof reference === "object" && reference !== null ? guestReferences.get(reference) : void 0;
125603
+ if (state === void 0 || state.owner !== owner)
125604
+ throw new TypeError("Foreign or invalid guest reference.");
125605
+ state.assertActive();
125606
+ if (state.root === void 0) throw new TypeError("Guest reference is revoked.");
125607
+ return state.root[0];
125608
+ }
125609
+ function revokeGuestReference(reference, owner) {
125610
+ const state = guestReferences.get(reference);
125611
+ if (state === void 0 || state.owner !== owner) throw new TypeError("Foreign guest reference.");
125612
+ state.root = void 0;
125613
+ }
125614
+ function createLiveHostObject(definition, controller) {
125615
+ const input = readDataRecord(definition, "Host object definition");
125616
+ if (Object.keys(input).some((key3) => key3 !== "properties" && key3 !== "methods"))
125617
+ throw new TypeError("Unknown host object definition field.");
125618
+ const properties = /* @__PURE__ */ new Map();
125619
+ for (const [name, inputProperty] of Object.entries(
125620
+ readDataRecord(input.properties ?? {}, "Host properties")
125621
+ )) {
125622
+ const property = readDataRecord(inputProperty, `Host property '${name}'`);
125623
+ if (Object.keys(property).some((key3) => key3 !== "get" && key3 !== "set"))
125624
+ throw new TypeError("Unknown host property field.");
125625
+ if (property.get !== void 0 && typeof property.get !== "function" || property.set !== void 0 && typeof property.set !== "function")
125626
+ throw new TypeError("Host property operations must be functions.");
125627
+ properties.set(name, property);
125628
+ }
125629
+ const operations = readDataRecord(input.methods ?? {}, "Host methods");
125630
+ for (const [name, operation] of Object.entries(operations)) {
125631
+ if (typeof operation !== "function") throw new TypeError("Host methods must be functions.");
125632
+ if (properties.has(name)) throw new TypeError(`Conflicting host member '${name}'.`);
125633
+ }
125634
+ for (const name of [...properties.keys(), ...Object.keys(operations)]) {
125635
+ if (["constructor", "prototype", "__proto__"].includes(name))
125636
+ throw new TypeError(`Reserved host member '${name}'.`);
125637
+ }
125638
+ controller.assertActive();
125639
+ controller.chargeWork(properties.size + Object.keys(operations).length + 1);
125640
+ const host = Object.freeze(/* @__PURE__ */ Object.create(null));
125641
+ const guest = Object.freeze(/* @__PURE__ */ Object.create(null));
125642
+ const methods = new Map(
125643
+ Object.entries(operations).map(([name, operation]) => [
125644
+ name,
125645
+ controller.method(operation)
125646
+ ])
125647
+ );
125648
+ const state = { host, guest, controller, properties, methods };
125649
+ hostObjects.set(host, state);
125650
+ guestObjects.set(guest, state);
125651
+ return host;
125652
+ }
125653
+ function isGuestHostObject(value) {
125654
+ return typeof value === "object" && value !== null && guestObjects.has(value);
125655
+ }
125656
+ function isLiveCapability(value) {
125657
+ return (typeof value === "object" && value !== null || typeof value === "function") && (hostObjects.has(value) || guestObjects.has(value) || guestCallbacks.has(value) || guestReferences.has(value));
125658
+ }
125659
+ function importHostCapability(value, owner) {
125660
+ if (guestReferences.has(value)) return readGuestReference(value, owner);
125661
+ const object = hostObjects.get(value);
125662
+ if (object !== void 0) {
125663
+ if (object.controller.owner !== owner) throw new TypeError("Foreign realm host capability.");
125664
+ object.controller.assertActive();
125665
+ return object.guest;
125666
+ }
125667
+ const callback = guestCallbacks.get(value);
125668
+ if (callback !== void 0) {
125669
+ if (callback.owner !== owner) throw new TypeError("Foreign realm guest callback.");
125670
+ callback.assertActive();
125671
+ if (callback.closure === void 0) throw new TypeError("Guest callback is revoked.");
125672
+ return callback.closure;
125673
+ }
125674
+ throw new TypeError("Unsupported live capability conversion.");
125675
+ }
125676
+ function exportHostCapability(value, owner) {
125677
+ const state = guestObjects.get(value);
125678
+ if (state === void 0 || state.controller.owner !== owner)
125679
+ throw new TypeError("Foreign realm host capability.");
125680
+ state.controller.assertActive();
125681
+ return state.host;
125682
+ }
125683
+ function registerGuestCallback(callback, state) {
125684
+ guestCallbacks.set(callback, state);
125685
+ }
125686
+ function readGuestCallback(callback, owner) {
125687
+ const state = typeof callback === "function" ? guestCallbacks.get(callback) : void 0;
125688
+ if (state === void 0 || state.owner !== owner)
125689
+ throw new TypeError("Foreign or invalid guest callback.");
125690
+ state.assertActive();
125691
+ if (state.closure === void 0) throw new TypeError("Guest callback is revoked.");
125692
+ return state.closure;
125693
+ }
125694
+ function revokeGuestCallback(callback, owner) {
125695
+ const state = guestCallbacks.get(callback);
125696
+ if (state === void 0 || state.owner !== owner) throw new TypeError("Foreign guest callback.");
125697
+ state.closure = void 0;
125698
+ }
125699
+ function revokeHostObject(value, owner) {
125700
+ const state = hostObjects.get(value);
125701
+ if (state === void 0 || state.controller.owner !== owner)
125702
+ throw new TypeError("Foreign host object.");
125703
+ state.properties.clear();
125704
+ state.methods.clear();
125705
+ }
125706
+ function getHostObjectMember(value, key3) {
125707
+ const state = guestObjects.get(value);
125708
+ state.controller.assertActive();
125709
+ state.controller.chargeWork();
125710
+ const property = state.properties.get(key3);
125711
+ if (property !== void 0)
125712
+ return property.get === void 0 ? void 0 : state.controller.read(property.get);
125713
+ return state.methods.get(key3);
125714
+ }
125715
+ function setHostObjectMember(value, key3, entry) {
125716
+ const state = guestObjects.get(value);
125717
+ state.controller.assertActive();
125718
+ state.controller.chargeWork();
125719
+ const property = state.properties.get(key3);
125720
+ if (property?.set === void 0) throw new TypeError(`Host property '${key3}' is not writable.`);
125721
+ state.controller.write(property.set, entry);
125722
+ }
125723
+ function getHostObjectKeys(value) {
125724
+ const state = guestObjects.get(value);
125725
+ state.controller.assertActive();
125726
+ return [...state.properties.keys(), ...state.methods.keys()];
125727
+ }
125728
+ var hostObjects, guestObjects, guestCallbacks, guestReferences;
125729
+ var init_host_capabilities = __esm({
125730
+ "packages/safe-js/src/interp/host-capabilities.ts"() {
125731
+ "use strict";
125732
+ init_extensions();
125733
+ hostObjects = /* @__PURE__ */ new WeakMap();
125734
+ guestObjects = /* @__PURE__ */ new WeakMap();
125735
+ guestCallbacks = /* @__PURE__ */ new WeakMap();
125736
+ guestReferences = /* @__PURE__ */ new WeakMap();
125737
+ }
125738
+ });
125739
+
125541
125740
  // packages/safe-js/src/observability/otel.ts
125542
125741
  function bindOtelSpan(value, span) {
125543
125742
  spanByAsyncValue.set(value, span);
@@ -125631,6 +125830,134 @@ var init_otel2 = __esm({
125631
125830
  }
125632
125831
  });
125633
125832
 
125833
+ // packages/safe-js/src/interp/date.ts
125834
+ import { types as types2 } from "node:util";
125835
+ function isSandboxDate(value) {
125836
+ return typeof value === "object" && value !== null && dates.has(value);
125837
+ }
125838
+ function createSandboxDate(time) {
125839
+ const value = new NativeDate(time);
125840
+ dates.add(value);
125841
+ return Object.freeze(value);
125842
+ }
125843
+ function dateTime(value) {
125844
+ return Reflect.apply(readTime, value, []);
125845
+ }
125846
+ function copyNativeDate(value) {
125847
+ if (!types2.isDate(value)) return void 0;
125848
+ if (Object.getPrototypeOf(value) !== NativeDate.prototype || Reflect.ownKeys(value).length > 0)
125849
+ throw new TypeError("Date subclasses and own properties are not supported.");
125850
+ return createSandboxDate(dateTime(value));
125851
+ }
125852
+ function exportDate(value) {
125853
+ return new NativeDate(dateTime(value));
125854
+ }
125855
+ function dateNumber(value) {
125856
+ if (isSandboxDate(value)) return dateTime(value);
125857
+ if (typeof value === "object" && value !== null || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint")
125858
+ throw new TypeError("Date arguments require primitive values; custom coercion is unsupported.");
125859
+ return Number(value);
125860
+ }
125861
+ function parseDate2(value, budget) {
125862
+ if (typeof value === "object" && value !== null || typeof value === "function")
125863
+ throw new TypeError("Date parsing requires a primitive value.");
125864
+ const text5 = String(value);
125865
+ if (text5.length > 4096) throw new RangeError("Date input exceeds the 4096 character limit.");
125866
+ budget.allocateString(text5);
125867
+ for (let index = 0; index < text5.length; index++) budget.visitNode();
125868
+ return NativeDate.parse(text5);
125869
+ }
125870
+ function dateFromParts(args, utc) {
125871
+ const parts = args.slice(0, 7).map(dateNumber);
125872
+ return utc ? Reflect.apply(NativeDate.UTC, NativeDate, parts) : dateTime(Reflect.construct(NativeDate, parts));
125873
+ }
125874
+ function dateString(value) {
125875
+ return dateMethods.get("toString").invoke(value, []);
125876
+ }
125877
+ function restoreDateTime(value) {
125878
+ if (value !== null && (typeof value !== "number" || !Number.isInteger(value) || Math.abs(value) > 864e13 || Object.is(value, -0)))
125879
+ throw new TypeError("Invalid serialized Date epoch.");
125880
+ const date = createSandboxDate(0);
125881
+ Reflect.apply(writeTime, date, [value === null ? NaN : value]);
125882
+ return date;
125883
+ }
125884
+ function serializedDateTime(value) {
125885
+ const time = dateTime(value);
125886
+ return Number.isNaN(time) ? null : time;
125887
+ }
125888
+ var NativeDate, readTime, writeTime, dates, methodNames, dateMethods;
125889
+ var init_date = __esm({
125890
+ "packages/safe-js/src/interp/date.ts"() {
125891
+ "use strict";
125892
+ NativeDate = Date;
125893
+ readTime = NativeDate.prototype.getTime;
125894
+ writeTime = NativeDate.prototype.setTime;
125895
+ dates = /* @__PURE__ */ new WeakSet();
125896
+ methodNames = [
125897
+ "getTime",
125898
+ "valueOf",
125899
+ "getDate",
125900
+ "getDay",
125901
+ "getFullYear",
125902
+ "getHours",
125903
+ "getMilliseconds",
125904
+ "getMinutes",
125905
+ "getMonth",
125906
+ "getSeconds",
125907
+ "getTimezoneOffset",
125908
+ "getUTCDate",
125909
+ "getUTCDay",
125910
+ "getUTCFullYear",
125911
+ "getUTCHours",
125912
+ "getUTCMilliseconds",
125913
+ "getUTCMinutes",
125914
+ "getUTCMonth",
125915
+ "getUTCSeconds",
125916
+ "setTime",
125917
+ "setDate",
125918
+ "setFullYear",
125919
+ "setHours",
125920
+ "setMilliseconds",
125921
+ "setMinutes",
125922
+ "setMonth",
125923
+ "setSeconds",
125924
+ "setUTCDate",
125925
+ "setUTCFullYear",
125926
+ "setUTCHours",
125927
+ "setUTCMilliseconds",
125928
+ "setUTCMinutes",
125929
+ "setUTCMonth",
125930
+ "setUTCSeconds",
125931
+ "toDateString",
125932
+ "toISOString",
125933
+ "toString",
125934
+ "toTimeString",
125935
+ "toUTCString",
125936
+ "toJSON"
125937
+ ];
125938
+ dateMethods = new Map(
125939
+ methodNames.map((name) => {
125940
+ const native = NativeDate.prototype[name];
125941
+ return [
125942
+ name,
125943
+ {
125944
+ length: native.length,
125945
+ invoke: (date, args) => {
125946
+ if (name === "toJSON")
125947
+ return Number.isNaN(dateTime(date)) ? null : Reflect.apply(NativeDate.prototype.toISOString, date, []);
125948
+ return Reflect.apply(
125949
+ native,
125950
+ date,
125951
+ name.startsWith("set") ? args.slice(0, native.length).map(dateNumber) : []
125952
+ );
125953
+ }
125954
+ }
125955
+ ];
125956
+ })
125957
+ );
125958
+ }
125959
+ });
125960
+
125634
125961
  // packages/safe-js/src/interp/float32.ts
125635
125962
  function isFloat32Array(value) {
125636
125963
  return ArrayBuffer.isView(value) && Object.getPrototypeOf(value) === Float32Array.prototype && Reflect.apply(readTag, value, []) === "Float32Array";
@@ -126301,6 +126628,8 @@ function encodeReplayData(value, options = {}) {
126301
126628
  id: capabilityId,
126302
126629
  properties: child(entry.properties, "properties")
126303
126630
  };
126631
+ } else if (isSandboxDate(entry)) {
126632
+ nodes[id] = { kind: "date", time: serializedDateTime(entry) };
126304
126633
  } else if (isFloat32Array(entry)) {
126305
126634
  const storage2 = encodeFloat32Storage(entry, id, float32Buffers, (id2) => ({
126306
126635
  tag: "ref",
@@ -126451,6 +126780,12 @@ function decodeReplayData(input, options = {}, parent) {
126451
126780
  options.onCapabilityRestored?.(capability, copy);
126452
126781
  return copy;
126453
126782
  }
126783
+ if (kind === "date") {
126784
+ if (Object.keys(node).length !== 2) throw new TypeError("Invalid serialized Date fields.");
126785
+ const result3 = restoreDateTime(own(node, "time"));
126786
+ restored.set(id, result3);
126787
+ return result3;
126788
+ }
126454
126789
  if (kind === "float32array") {
126455
126790
  if (typeof node.extensible !== "boolean")
126456
126791
  throw new TypeError("Invalid Float32Array extensibility.");
@@ -126562,6 +126897,7 @@ var init_replay_data = __esm({
126562
126897
  init_compile_guard();
126563
126898
  init_float32();
126564
126899
  init_float32array();
126900
+ init_date();
126565
126901
  init_shape();
126566
126902
  init_values();
126567
126903
  init_arguments2();
@@ -126791,6 +127127,8 @@ function normalize2(value, seen) {
126791
127127
  if (seen.has(value)) throw new TypeError("Host call arguments cannot contain cycles.");
126792
127128
  seen.add(value);
126793
127129
  try {
127130
+ const date = copyNativeDate(value);
127131
+ if (date !== void 0) return Object.assign(/* @__PURE__ */ Object.create(null), { $type: "date", time: serializedDateTime(date) });
126794
127132
  if (isFloat32Array(value)) {
126795
127133
  const storage2 = float32Storage(value);
126796
127134
  const properties = /* @__PURE__ */ Object.create(null);
@@ -126839,6 +127177,7 @@ var init_host_call = __esm({
126839
127177
  "packages/safe-js/src/interp/host-call.ts"() {
126840
127178
  "use strict";
126841
127179
  init_float32();
127180
+ init_date();
126842
127181
  init_values();
126843
127182
  init_compile_guard();
126844
127183
  init_replay_data();
@@ -128921,6 +129260,7 @@ function createSandboxClosure(input) {
128921
129260
  return Object.freeze(closure);
128922
129261
  }
128923
129262
  function ownEnumerableSandboxEntries(value) {
129263
+ if (isGuestHostObject(value)) return getHostObjectKeys(value).map((key3) => [key3, getHostObjectMember(value, key3)]);
128924
129264
  if (value === null || value === void 0) throw new TypeError("Cannot convert undefined or null to object.");
128925
129265
  if (isGuestClosure(value)) return Object.entries(value.properties ?? {});
128926
129266
  if (isSandboxClosure(value) || isSandboxGenerator(value) || isSandboxMap(value) || isSandboxSet(value) || isSandboxPromise(value) || isSandboxRegex(value)) return [];
@@ -129073,6 +129413,14 @@ function measureSandboxData(values, options = {}) {
129073
129413
  assertSandboxDataDepth(depth);
129074
129414
  seen.add(value);
129075
129415
  usage += 1;
129416
+ if (isSandboxDate(value)) {
129417
+ usage += 8;
129418
+ return;
129419
+ }
129420
+ if (isGuestHostObject(value)) {
129421
+ for (const key3 of getHostObjectKeys(value)) usage += key3.length + 1;
129422
+ return;
129423
+ }
129076
129424
  const prototype = getSandboxPrototype(value);
129077
129425
  if (prototype !== null) visit(prototype, depth + 1);
129078
129426
  if (isFloat32Array(value)) {
@@ -129215,6 +129563,7 @@ function copyToSandbox(value, state, path193 = "<root>", cloneSandboxCollections
129215
129563
  if (isSandboxPrimitive(value)) {
129216
129564
  return value;
129217
129565
  }
129566
+ if (isLiveCapability(value)) throw new TypeError("Live capabilities require their owning realm bridge.");
129218
129567
  if (isSandboxClosure(value) || isSandboxGenerator(value) || isSandboxRegex(value) || isSandboxPromise(value)) {
129219
129568
  return value;
129220
129569
  }
@@ -129262,6 +129611,13 @@ function copyToSandbox(value, state, path193 = "<root>", cloneSandboxCollections
129262
129611
  }
129263
129612
  return sandboxPromise;
129264
129613
  }
129614
+ if (nodeTypes.isDate(value)) {
129615
+ const existing = state.seen.get(value);
129616
+ if (existing !== void 0) return existing;
129617
+ const copy = copyNativeDate(value);
129618
+ state.seen.set(value, copy);
129619
+ return copy;
129620
+ }
129265
129621
  if (isFloat32Array(value)) {
129266
129622
  const existing = state.seen.get(value);
129267
129623
  if (existing !== void 0) return existing;
@@ -129378,6 +129734,10 @@ function copyFromSandbox(value, state, path193 = "<root>", options, depth = 0) {
129378
129734
  if (isSandboxPrimitive(value)) {
129379
129735
  return value;
129380
129736
  }
129737
+ if (isGuestHostObject(value)) {
129738
+ if (options.unwrapHostObject === void 0) throw new TypeError("Live capabilities require their owning realm bridge.");
129739
+ return options.unwrapHostObject(value);
129740
+ }
129381
129741
  if (nodeTypes.isProxy(value)) throw new TypeError("Unsupported proxy sandbox value.");
129382
129742
  if (!isSandboxClosure(value) && hasGuestObjectState(value)) {
129383
129743
  throw new TypeError("Guest prototype links and custom descriptors cannot be copied as data.");
@@ -129417,6 +129777,13 @@ function copyFromSandbox(value, state, path193 = "<root>", options, depth = 0) {
129417
129777
  if (!Object.isExtensible(value)) Object.preventExtensions(copy);
129418
129778
  return copy;
129419
129779
  }
129780
+ if (isSandboxDate(value)) {
129781
+ const existing = state.seen.get(value);
129782
+ if (existing !== void 0) return existing;
129783
+ const copy = exportDate(value);
129784
+ state.seen.set(value, copy);
129785
+ return copy;
129786
+ }
129420
129787
  if (isSandboxClosure(value)) {
129421
129788
  if (options.wrapClosure === void 0) {
129422
129789
  throw new TypeError(
@@ -129685,6 +130052,8 @@ var init_values = __esm({
129685
130052
  "packages/safe-js/src/interp/values.ts"() {
129686
130053
  "use strict";
129687
130054
  init_otel2();
130055
+ init_date();
130056
+ init_host_capabilities();
129688
130057
  init_compile_guard();
129689
130058
  init_float32();
129690
130059
  init_budget2();
@@ -129775,6 +130144,7 @@ function setSandboxPrototype(value, prototype, budget) {
129775
130144
  else prototypes.set(value, prototype);
129776
130145
  }
129777
130146
  function isPrototypeRecord(value) {
130147
+ if (isGuestHostObject(value)) return false;
129778
130148
  if (isSandboxClosure(value) || isSandboxGenerator(value) || isSandboxMap(value) || isSandboxPromise(value) || isSandboxRegex(value) || isSandboxSet(value))
129779
130149
  return false;
129780
130150
  const prototype = Object.getPrototypeOf(value);
@@ -129787,6 +130157,7 @@ function hasManagedDescriptors(value) {
129787
130157
  return descriptorObjects.has(value);
129788
130158
  }
129789
130159
  function hasGuestObjectState(value) {
130160
+ if (isLiveCapability(value)) return true;
129790
130161
  if (functionProperties.has(value) || prototypes.has(value)) return true;
129791
130162
  return descriptorObjects.has(value) && Object.values(Object.getOwnPropertyDescriptors(value)).some(
129792
130163
  (descriptor) => !descriptor.enumerable || !descriptor.configurable || !descriptor.writable
@@ -129797,6 +130168,7 @@ var init_object_model = __esm({
129797
130168
  "packages/safe-js/src/interp/object-model.ts"() {
129798
130169
  "use strict";
129799
130170
  init_graph_depth();
130171
+ init_host_capabilities();
129800
130172
  init_values();
129801
130173
  guestClosures = /* @__PURE__ */ new WeakSet();
129802
130174
  functionProperties = /* @__PURE__ */ new WeakMap();
@@ -129897,7 +130269,7 @@ function serializeDumpValue(value, path193, state) {
129897
130269
  if (hasGuestObjectState(value)) {
129898
130270
  throw new TypeError("Guest function properties and prototype links cannot be serialized.");
129899
130271
  }
129900
- if (isFloat32Array(value)) return serializeHeapReference(value, path193, state);
130272
+ if (isSandboxDate(value) || isFloat32Array(value)) return serializeHeapReference(value, path193, state);
129901
130273
  if (Array.isArray(value)) {
129902
130274
  const reference2 = serializeHeapReference(value, path193, state);
129903
130275
  if (reference2 !== void 0) {
@@ -129921,7 +130293,9 @@ function serializeHeapReference(value, path193, state) {
129921
130293
  }
129922
130294
  if (!state.serializedHeapIds.has(id)) {
129923
130295
  state.serializedHeapIds.add(id);
129924
- if (isFloat32Array(value)) {
130296
+ if (isSandboxDate(value)) {
130297
+ state.heap[String(id)] = { kind: "date", time: serializedDateTime(value) };
130298
+ } else if (isFloat32Array(value)) {
129925
130299
  const storage2 = encodeFloat32Storage(value, id, state.float32Buffers, (id2) => ({
129926
130300
  kind: "ref",
129927
130301
  id: id2
@@ -129978,7 +130352,7 @@ function indexHeapContainers(snapshot2) {
129978
130352
  const heapIds = /* @__PURE__ */ new WeakMap();
129979
130353
  let nextId = 1;
129980
130354
  for (const [value, stat35] of stats2.entries()) {
129981
- if (stat35.count > 1 || stat35.cyclic || isFloat32Array(value) || Array.isArray(value) && requiresArrayEntries(value) || isSandboxArguments(value) || sandboxErrorTypes.has(value)) {
130355
+ if (stat35.count > 1 || stat35.cyclic || isSandboxDate(value) || isFloat32Array(value) || Array.isArray(value) && requiresArrayEntries(value) || isSandboxArguments(value) || sandboxErrorTypes.has(value)) {
129982
130356
  heapIds.set(value, nextId);
129983
130357
  nextId += 1;
129984
130358
  }
@@ -129989,7 +130363,7 @@ function collectContainerStats(value, stats2, ancestors) {
129989
130363
  if (value === null || typeof value !== "object") {
129990
130364
  return;
129991
130365
  }
129992
- if (!Array.isArray(value) && !isPlainObject10(value) && !isFloat32Array(value)) {
130366
+ if (!Array.isArray(value) && !isPlainObject10(value) && !isFloat32Array(value) && !isSandboxDate(value)) {
129993
130367
  return;
129994
130368
  }
129995
130369
  let stat35 = stats2.get(value);
@@ -130060,6 +130434,7 @@ var init_dump_format = __esm({
130060
130434
  init_arrays();
130061
130435
  init_float32();
130062
130436
  init_float32array();
130437
+ init_date();
130063
130438
  DUMP_FORMAT_VERSION = 1;
130064
130439
  EXECUTION_SEMANTICS = "jobs-v7";
130065
130440
  SKIP_VALUE = /* @__PURE__ */ Symbol("SafeJS.skip-dump-value");
@@ -130067,7 +130442,7 @@ var init_dump_format = __esm({
130067
130442
  });
130068
130443
 
130069
130444
  // packages/safe-js/src/snapshot/validation.ts
130070
- import { types } from "node:util";
130445
+ import { types as types3 } from "node:util";
130071
130446
  function validateSnapshotData(value) {
130072
130447
  validateGenericValue(value, "$", 0, {
130073
130448
  allowFunctions: false,
@@ -130113,6 +130488,10 @@ function validateDumpHeap(root, state) {
130113
130488
  addUnique2(heapIds, id, path193);
130114
130489
  const entry = requireRecord3(value, path193);
130115
130490
  validateErrorType(entry, path193);
130491
+ if (entry.kind === "date") {
130492
+ validateDateRecord(entry, path193);
130493
+ continue;
130494
+ }
130116
130495
  if (entry.kind === "float32array") {
130117
130496
  validateFloat32Storage(entry);
130118
130497
  requireRecord3(entry.entries, `${path193}.entries`);
@@ -130270,6 +130649,14 @@ function validateGeneratorShape(record2, path193, state) {
130270
130649
  }
130271
130650
  });
130272
130651
  }
130652
+ function validateDateRecord(record2, path193) {
130653
+ if (Object.keys(record2).length !== 2) fail2("invalidValue", path193, "invalid Date fields");
130654
+ try {
130655
+ restoreDateTime(record2.time);
130656
+ } catch {
130657
+ fail2("invalidValue", `${path193}.time`, "invalid Date epoch");
130658
+ }
130659
+ }
130273
130660
  function validateArrayHeap(record2, path193, state) {
130274
130661
  if (Object.hasOwn(record2, "items")) {
130275
130662
  requireArray(record2.items, `${path193}.items`, state);
@@ -130353,7 +130740,7 @@ function validateGenericValue(value, path193, depth, state) {
130353
130740
  if (typeof value === "object" && value !== null && hasGuestObjectState(value)) {
130354
130741
  fail2("invalidState", path193, "guest function properties, prototype links and custom descriptors cannot be restored");
130355
130742
  }
130356
- if (state.dataPropertiesOnly && types.isProxy(value)) {
130743
+ if (state.dataPropertiesOnly && types3.isProxy(value)) {
130357
130744
  fail2("invalidType", path193, "proxy objects are not snapshot data");
130358
130745
  }
130359
130746
  if (depth > state.limits.maxDepth)
@@ -130487,6 +130874,7 @@ var init_validation = __esm({
130487
130874
  init_dump_format();
130488
130875
  init_graph_depth();
130489
130876
  init_float32array();
130877
+ init_date();
130490
130878
  init_object_model();
130491
130879
  DEFAULT_MAX_DEPTH = MAX_DATA_DEPTH;
130492
130880
  DEFAULT_MAX_ENTRIES = 1e5;
@@ -131385,6 +131773,7 @@ var init_known_globals = __esm({
131385
131773
  "AggregateError",
131386
131774
  "Array",
131387
131775
  "Boolean",
131776
+ "Date",
131388
131777
  "Error",
131389
131778
  "Infinity",
131390
131779
  "isFinite",
@@ -136648,9 +137037,9 @@ var init_AS_floating_promise = __esm({
136648
137037
  isPromiseFactoryCall(node) {
136649
137038
  return this.isPromiseStaticMethodCall(node, PROMISE_FACTORIES);
136650
137039
  }
136651
- isPromiseStaticMethodCall(node, methodNames) {
137040
+ isPromiseStaticMethodCall(node, methodNames2) {
136652
137041
  const member = node.callee.type === "MemberExpression" ? node.callee : void 0;
136653
- return member !== void 0 && !member.computed && member.object.type === "Identifier" && member.object.name === "Promise" && member.property.type === "Identifier" && methodNames.has(member.property.name);
137042
+ return member !== void 0 && !member.computed && member.object.type === "Identifier" && member.object.name === "Promise" && member.property.type === "Identifier" && methodNames2.has(member.property.name);
136654
137043
  }
136655
137044
  isPromiseChainCall(node) {
136656
137045
  const member = node.callee.type === "MemberExpression" ? node.callee : void 0;
@@ -142064,180 +142453,6 @@ var init_lint4 = __esm({
142064
142453
  }
142065
142454
  });
142066
142455
 
142067
- // packages/safe-js/src/interp/resources.ts
142068
- import { AsyncLocalStorage as AsyncLocalStorage8 } from "node:async_hooks";
142069
- async function withRunResources(signal, execute2) {
142070
- const controller = new AbortController();
142071
- const cancel2 = () => controller.abort(signal?.reason);
142072
- const cleanups = /* @__PURE__ */ new Set();
142073
- const resources = {
142074
- signal: controller.signal,
142075
- add(close) {
142076
- cleanups.add(close);
142077
- }
142078
- };
142079
- signal?.addEventListener("abort", cancel2, { once: true });
142080
- if (signal?.aborted) cancel2();
142081
- let result;
142082
- let failure;
142083
- let errors2 = [];
142084
- try {
142085
- result = await runResources.run(resources, execute2);
142086
- } catch (error3) {
142087
- failure = { reason: error3 };
142088
- } finally {
142089
- signal?.removeEventListener("abort", cancel2);
142090
- controller.abort(new Error("SafeJS run finished."));
142091
- const outcomes = await Promise.allSettled(
142092
- [...cleanups].map((close) => Promise.resolve().then(close))
142093
- );
142094
- errors2 = outcomes.flatMap((outcome) => outcome.status === "rejected" ? [outcome.reason] : []);
142095
- }
142096
- if (failure !== void 0) throw failure.reason;
142097
- if (errors2.length > 0) throw new AggregateError(errors2, "SafeJS resource cleanup failed.");
142098
- return result;
142099
- }
142100
- var runResources;
142101
- var init_resources = __esm({
142102
- "packages/safe-js/src/interp/resources.ts"() {
142103
- "use strict";
142104
- runResources = new AsyncLocalStorage8();
142105
- }
142106
- });
142107
-
142108
- // packages/safe-js/src/interp/globals/math.ts
142109
- function f16round(value) {
142110
- const number = +value;
142111
- if (!Number.isFinite(number) || number === 0) {
142112
- return number;
142113
- }
142114
- const magnitude = Math.abs(number);
142115
- if (magnitude >= 65520) {
142116
- return number < 0 ? -Infinity : Infinity;
142117
- }
142118
- let quantum = 2 ** -24;
142119
- let boundary = 2 ** -13;
142120
- for (let exponent = -13; exponent <= 15 && magnitude >= boundary; exponent += 1) {
142121
- quantum *= 2;
142122
- boundary *= 2;
142123
- }
142124
- const scaled = magnitude / quantum;
142125
- const lower = Math.floor(scaled);
142126
- const remainder = scaled - lower;
142127
- const rounded = (remainder > 0.5 || remainder === 0.5 && lower % 2 !== 0 ? lower + 1 : lower) * quantum;
142128
- return number < 0 ? -rounded : rounded;
142129
- }
142130
- function createMathGlobals(options = {}) {
142131
- const random = options.random ?? Math.random;
142132
- const mathObject = {
142133
- E: Math.E,
142134
- LN2: Math.LN2,
142135
- LN10: Math.LN10,
142136
- LOG2E: Math.LOG2E,
142137
- LOG10E: Math.LOG10E,
142138
- PI: Math.PI,
142139
- SQRT1_2: Math.SQRT1_2,
142140
- SQRT2: Math.SQRT2,
142141
- random: createSandboxClosure({ sandbox: true, call: () => random(), name: "random" })
142142
- };
142143
- for (const [name, method] of Object.entries(mathMethods)) {
142144
- mathObject[name] = createSandboxClosure({
142145
- sandbox: true,
142146
- call: (args) => Reflect.apply(method, Math, args),
142147
- name
142148
- });
142149
- }
142150
- return {
142151
- Infinity: Infinity,
142152
- Math: mathObject,
142153
- NaN: Number.NaN
142154
- };
142155
- }
142156
- function createSeededRandom(seed) {
142157
- let state = normalizeSeed(seed);
142158
- return {
142159
- next: () => {
142160
- state = Math.imul(state, 1664525) + 1013904223 >>> 0;
142161
- return state / 4294967296;
142162
- },
142163
- snapshot: () => state,
142164
- restore: (nextState) => {
142165
- state = normalizeSeed(nextState);
142166
- }
142167
- };
142168
- }
142169
- function normalizeSeed(seed) {
142170
- if (!Number.isFinite(seed)) {
142171
- throw new TypeError("Seeded random requires a finite numeric seed.");
142172
- }
142173
- return Math.trunc(seed) >>> 0;
142174
- }
142175
- var mathMethods;
142176
- var init_math = __esm({
142177
- "packages/safe-js/src/interp/globals/math.ts"() {
142178
- "use strict";
142179
- init_values();
142180
- mathMethods = {
142181
- abs: Math.abs,
142182
- acos: Math.acos,
142183
- acosh: Math.acosh,
142184
- asin: Math.asin,
142185
- asinh: Math.asinh,
142186
- atan: Math.atan,
142187
- atan2: Math.atan2,
142188
- atanh: Math.atanh,
142189
- ceil: Math.ceil,
142190
- cbrt: Math.cbrt,
142191
- clz32: Math.clz32,
142192
- cos: Math.cos,
142193
- cosh: Math.cosh,
142194
- exp: Math.exp,
142195
- expm1: Math.expm1,
142196
- floor: Math.floor,
142197
- f16round,
142198
- fround: Math.fround,
142199
- hypot: Math.hypot,
142200
- imul: Math.imul,
142201
- log: Math.log,
142202
- log1p: Math.log1p,
142203
- log10: Math.log10,
142204
- log2: Math.log2,
142205
- max: Math.max,
142206
- min: Math.min,
142207
- pow: Math.pow,
142208
- round: Math.round,
142209
- sign: Math.sign,
142210
- sin: Math.sin,
142211
- sinh: Math.sinh,
142212
- sqrt: Math.sqrt,
142213
- tan: Math.tan,
142214
- tanh: Math.tanh,
142215
- trunc: Math.trunc
142216
- };
142217
- }
142218
- });
142219
-
142220
- // packages/safe-js/src/random.ts
142221
- import { randomInt } from "node:crypto";
142222
- function createReplayableRandom(options = {}) {
142223
- const snapshot2 = options.snapshot;
142224
- const saved = snapshot2?.random;
142225
- let initialState = options.seed;
142226
- if (saved !== void 0) {
142227
- const hasLoopState = typeof snapshot2?.loopIterations === "object" && snapshot2.loopIterations !== null && Object.keys(snapshot2.loopIterations).length > 0;
142228
- const replaysFromStart = snapshot2?.replay !== void 0 || Array.isArray(snapshot2?.pendingAwaits) && snapshot2.pendingAwaits.length > 0 && !hasLoopState;
142229
- initialState = replaysFromStart ? saved.initialState ?? saved.seed : saved.resumeState ?? saved.state;
142230
- }
142231
- const generator = createSeededRandom(initialState ?? randomInt(4294967296));
142232
- return { seed: saved?.seed ?? generator.snapshot(), ...generator };
142233
- }
142234
- var init_random = __esm({
142235
- "packages/safe-js/src/random.ts"() {
142236
- "use strict";
142237
- init_math();
142238
- }
142239
- });
142240
-
142241
142456
  // packages/safe-js/src/interp/generator.ts
142242
142457
  function createGeneratorChannel(body) {
142243
142458
  let state = "unstarted";
@@ -144706,6 +144921,110 @@ var init_float32array2 = __esm({
144706
144921
  }
144707
144922
  });
144708
144923
 
144924
+ // packages/safe-js/src/interp/globals/date.ts
144925
+ function createDateGlobal(options) {
144926
+ const validateClockTime = (value) => {
144927
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || Math.abs(value) > 864e13)
144928
+ throw new TypeError("Date clock must return a finite integer epoch within the Date range.");
144929
+ return value;
144930
+ };
144931
+ const readNow = declareHostOperation(
144932
+ () => {
144933
+ options.budget.visitNode();
144934
+ const value = options.clock?.now === void 0 ? Date.now() : options.clock.now();
144935
+ return validateClockTime(value);
144936
+ },
144937
+ "re-issue",
144938
+ {
144939
+ onReplay: (_args, outcome) => {
144940
+ if (outcome.status === "fulfilled") {
144941
+ const time = validateClockTime(outcome.value);
144942
+ options.clock?.restore?.({ next: time + 1 });
144943
+ }
144944
+ }
144945
+ }
144946
+ );
144947
+ const now = wrapCallerInjectedBindings({ now: readNow }, { ...options, moduleId: "<Date>" }).now;
144948
+ const prototype = createSandboxDate(NaN);
144949
+ const constructor = createSandboxClosure({
144950
+ sandbox: true,
144951
+ name: "Date",
144952
+ length: 7,
144953
+ call: async (_args, context) => options.budget.allocateString(
144954
+ dateString(createSandboxDate(Number(await now.call([], context))))
144955
+ ),
144956
+ construct: async (args, context) => {
144957
+ let time;
144958
+ if (args.length === 0) time = Number(await now.call([], context));
144959
+ else if (args.length > 1) time = dateFromParts(args, false);
144960
+ else if (isSandboxDate(args[0])) time = dateTime(args[0]);
144961
+ else if (typeof args[0] === "string") time = parseDate2(args[0], options.budget);
144962
+ else time = dateNumber(args[0]);
144963
+ options.budget.chargeDataUsage(9);
144964
+ return createSandboxDate(time);
144965
+ },
144966
+ properties: {
144967
+ now,
144968
+ prototype,
144969
+ parse: createSandboxClosure({
144970
+ sandbox: true,
144971
+ name: "parse",
144972
+ length: 1,
144973
+ call: ([value]) => parseDate2(value, options.budget)
144974
+ }),
144975
+ UTC: createSandboxClosure({
144976
+ sandbox: true,
144977
+ name: "UTC",
144978
+ length: 7,
144979
+ call: (args) => dateFromParts(args, true)
144980
+ })
144981
+ }
144982
+ });
144983
+ const methods = /* @__PURE__ */ new Map();
144984
+ for (const [name, method] of dateMethods)
144985
+ methods.set(
144986
+ name,
144987
+ createSandboxClosure({
144988
+ sandbox: true,
144989
+ name,
144990
+ length: method.length,
144991
+ call: (args, context) => {
144992
+ const receiver = context?.thisValue;
144993
+ if (!isSandboxDate(receiver))
144994
+ throw new TypeError(`Date#${name} requires a Date receiver.`);
144995
+ options.budget.visitNode();
144996
+ const value = method.invoke(receiver, args);
144997
+ return typeof value === "string" ? options.budget.allocateString(value) : value;
144998
+ }
144999
+ })
145000
+ );
145001
+ constructors2.add(constructor);
145002
+ intrinsics.set(options.compileOwner ?? options.budget, { constructor, prototype, methods });
145003
+ return constructor;
145004
+ }
145005
+ function isDateConstructor(value) {
145006
+ return typeof value === "object" && value !== null && constructors2.has(value);
145007
+ }
145008
+ function getDateMember(property, budget, owner) {
145009
+ const state = intrinsics.get(owner ?? budget);
145010
+ return property === "constructor" ? state?.constructor : state?.methods.get(String(property));
145011
+ }
145012
+ function getDatePrototype(value, budget, owner) {
145013
+ const prototype = intrinsics.get(owner ?? budget)?.prototype;
145014
+ return prototype === value ? null : prototype ?? null;
145015
+ }
145016
+ var intrinsics, constructors2;
145017
+ var init_date2 = __esm({
145018
+ "packages/safe-js/src/interp/globals/date.ts"() {
145019
+ "use strict";
145020
+ init_date();
145021
+ init_host_bridge();
145022
+ init_values();
145023
+ intrinsics = /* @__PURE__ */ new WeakMap();
145024
+ constructors2 = /* @__PURE__ */ new WeakSet();
145025
+ }
145026
+ });
145027
+
144709
145028
  // packages/safe-js/src/interp/scope.ts
144710
145029
  function defineSnapshotBinding(target, name, value) {
144711
145030
  Object.defineProperty(target, name, {
@@ -144957,9 +145276,10 @@ async function interpret(node, options = {}) {
144957
145276
  peakDataSize: { enumerable: false, value: 0, writable: true }
144958
145277
  });
144959
145278
  const activeLoopIterations = /* @__PURE__ */ new Map();
144960
- const jobs = new SandboxJobQueue();
145279
+ const jobs = options.jobs ?? new SandboxJobQueue();
144961
145280
  hoistVarDeclarations(node, scope);
144962
145281
  const context = {
145282
+ assertActive: options.assertActive,
144963
145283
  compilation,
144964
145284
  budget,
144965
145285
  callStack: [],
@@ -144982,9 +145302,9 @@ async function interpret(node, options = {}) {
144982
145302
  };
144983
145303
  const evaluation = await withCancellationSignal(
144984
145304
  options.signal,
144985
- () => jobs.run(() => evaluateNode2(node, context))
145305
+ () => options.nested ? runAsyncPrefix(() => evaluateNode2(node, context)) : jobs.run(() => evaluateNode2(node, context))
144986
145306
  );
144987
- await jobs.drain();
145307
+ if (!options.nested) await jobs.drain();
144988
145308
  const snapshot2 = scope.snapshot();
144989
145309
  reconcileDataBudget(
144990
145310
  budget,
@@ -145039,6 +145359,7 @@ async function interpret(node, options = {}) {
145039
145359
  }
145040
145360
  }
145041
145361
  async function evaluateNode2(node, context) {
145362
+ context.assertActive?.();
145042
145363
  const replayWait = promiseReplayContext.getStore()?.beforeNode(node.nodeId);
145043
145364
  if (replayWait !== void 0) await suspendJob(replayWait);
145044
145365
  assertPromiseExecutionAllowed();
@@ -146010,6 +146331,7 @@ function forInObject(value) {
146010
146331
  return void 0;
146011
146332
  }
146012
146333
  function forInKeys(object, budget) {
146334
+ if (isGuestHostObject(object)) return getHostObjectKeys(object);
146013
146335
  const keys = [];
146014
146336
  const seen = /* @__PURE__ */ new Set();
146015
146337
  let depth = 0;
@@ -146027,6 +146349,7 @@ function forInKeys(object, budget) {
146027
146349
  return keys;
146028
146350
  }
146029
146351
  function hasForInProperty(object, key3, budget) {
146352
+ if (isGuestHostObject(object)) return getHostObjectKeys(object).includes(key3);
146030
146353
  let depth = 0;
146031
146354
  for (let current = object; current !== null; current = getSandboxPrototype(current)) {
146032
146355
  if (depth > 0) budget.visitNode();
@@ -146518,10 +146841,12 @@ async function evaluateMemberExpression(node, context) {
146518
146841
  };
146519
146842
  }
146520
146843
  function getPropertyValue(target, property, context) {
146844
+ if (isGuestHostObject(target)) return getHostObjectMember(target, String(property));
146521
146845
  if (typeof target === "string") return getStringMember(target, property, context.budget);
146522
146846
  if (typeof target === "number") return getNumberMember(target, property, context.budget);
146523
146847
  if (typeof target === "boolean") return void 0;
146524
146848
  if (isFloat32Array(target)) return getFloat32Member(target, property, context.budget);
146849
+ if (isSandboxDate(target)) return getDateMember(property, context.budget, context.compilation?.owner);
146525
146850
  if (isSandboxMap(target)) return getMapMember(target, property, createMapMethodOptions(context));
146526
146851
  if (isSandboxSet(target)) return getSetMember(target, property, createSetMethodOptions(context));
146527
146852
  if (isSandboxGenerator(target)) return getGeneratorMember(target, property, context.budget);
@@ -146758,6 +147083,9 @@ async function evaluateMemberCallExpression(node, context) {
146758
147083
  context
146759
147084
  );
146760
147085
  }
147086
+ if (isSandboxDate(member.object)) {
147087
+ return evaluateResolvedCallExpression(node, getDateMember(member.property, context.budget, context.compilation?.owner), context, member.object);
147088
+ }
146761
147089
  if (isFloat32Array(member.object)) {
146762
147090
  return evaluateResolvedCallExpression(
146763
147091
  node,
@@ -147010,6 +147338,7 @@ function applyBinaryOperator(node, left, right, context) {
147010
147338
  return true;
147011
147339
  }
147012
147340
  if (isFloat32ArrayConstructor(right)) return isFloat32Array(left);
147341
+ if (isDateConstructor(right)) return isSandboxDate(left) && getDatePrototype(left, context.budget, context.compilation?.owner) !== null;
147013
147342
  if (isSandboxSetConstructor(right) && isSandboxSet(left)) {
147014
147343
  return true;
147015
147344
  }
@@ -147073,8 +147402,8 @@ function applyAdditionOperator(left, right, context) {
147073
147402
  return toNumber(leftPrimitive) + toNumber(rightPrimitive);
147074
147403
  }
147075
147404
  function compareRelational(left, right, operator) {
147076
- const leftPrimitive = toPrimitive(left);
147077
- const rightPrimitive = toPrimitive(right);
147405
+ const leftPrimitive = isSandboxDate(left) ? dateTime(left) : toPrimitive(left);
147406
+ const rightPrimitive = isSandboxDate(right) ? dateTime(right) : toPrimitive(right);
147078
147407
  if (typeof leftPrimitive === "string" && typeof rightPrimitive === "string") {
147079
147408
  switch (operator) {
147080
147409
  case "<":
@@ -147157,6 +147486,7 @@ function toPrimitive(value) {
147157
147486
  return toString(value);
147158
147487
  }
147159
147488
  async function toNumericPrimitive(value, context) {
147489
+ if (isSandboxDate(value)) return dateTime(value);
147160
147490
  if (isPrimitiveCoercionType(getCoercionType(value))) {
147161
147491
  return value;
147162
147492
  }
@@ -147186,6 +147516,7 @@ async function toNumericPrimitive(value, context) {
147186
147516
  return toString(value);
147187
147517
  }
147188
147518
  function toNumber(value) {
147519
+ if (isSandboxDate(value)) return dateTime(value);
147189
147520
  if (typeof value === "number") {
147190
147521
  return value;
147191
147522
  }
@@ -147204,6 +147535,7 @@ function toNumber(value) {
147204
147535
  return toNumber(toPrimitive(value));
147205
147536
  }
147206
147537
  function toString(value) {
147538
+ if (isSandboxDate(value)) return dateString(value);
147207
147539
  if (Array.isArray(value)) {
147208
147540
  return value.map((entry) => entry === null || entry === void 0 ? "" : toString(entry)).join(",");
147209
147541
  }
@@ -147224,6 +147556,7 @@ function isPlainSandboxObject(value) {
147224
147556
  return typeof value === "object" && value !== null && !Array.isArray(value) && !isSandboxClosure(value) && !isSandboxMap(value) && !isSandboxSet(value) && !isSandboxPromise(value) && !isSandboxRegex(value);
147225
147557
  }
147226
147558
  function getMemberValue(target, property, context) {
147559
+ if (isGuestHostObject(target)) return getHostObjectMember(target, String(property));
147227
147560
  let current = target;
147228
147561
  let depth = 0;
147229
147562
  while (typeof current === "object" && current !== null) {
@@ -147248,6 +147581,11 @@ function getArrayMemberValue(target, property, context) {
147248
147581
  return getArrayMember(target, property, createArrayMethodOptions(context));
147249
147582
  }
147250
147583
  function setSandboxProperty(target, property, value, budget) {
147584
+ if (isSandboxDate(target)) throw new TypeError("Date own properties are not supported.");
147585
+ if (isGuestHostObject(target)) {
147586
+ setHostObjectMember(target, String(property), value);
147587
+ return;
147588
+ }
147251
147589
  const prototypeOwner = target;
147252
147590
  if (isGuestClosure(target)) target = materializeFunctionProperties(target);
147253
147591
  if (isFloat32Array(target)) {
@@ -147292,6 +147630,7 @@ function setSandboxProperty(target, property, value, budget) {
147292
147630
  }
147293
147631
  }
147294
147632
  function deleteSandboxProperty(target, property) {
147633
+ if (isGuestHostObject(target)) throw new TypeError("Live host properties cannot be deleted.");
147295
147634
  if (isGuestClosure(target)) target = materializeFunctionProperties(target);
147296
147635
  if (Array.isArray(target)) {
147297
147636
  assertCollectionMutable(target);
@@ -147546,6 +147885,7 @@ var init_interpreter = __esm({
147546
147885
  "packages/safe-js/src/interp/interpreter.ts"() {
147547
147886
  "use strict";
147548
147887
  init_promise_replay();
147888
+ init_host_capabilities();
147549
147889
  init_promise_tracker();
147550
147890
  init_jobs4();
147551
147891
  init_cancel2();
@@ -147573,6 +147913,8 @@ var init_interpreter = __esm({
147573
147913
  init_collections();
147574
147914
  init_float32array2();
147575
147915
  init_float32();
147916
+ init_date();
147917
+ init_date2();
147576
147918
  init_values();
147577
147919
  init_scope();
147578
147920
  init_var_hoist();
@@ -147951,7 +148293,7 @@ function wrapCallerInjectedBindings(bindings, options) {
147951
148293
  const copied = Object.fromEntries(
147952
148294
  Object.entries(bindings).map(([name, value]) => [
147953
148295
  name,
147954
- typeof value === "function" ? wrapCallerInjectedFunction(name, value, { ...options, capabilityPath: [name] }, state) : copyHostValueToSandbox(
148296
+ typeof value === "function" && !isLiveCapability(value) ? wrapCallerInjectedFunction(name, value, { ...options, capabilityPath: [name] }, state) : copyHostValueToSandbox(
147955
148297
  value,
147956
148298
  [],
147957
148299
  { ...options, operation: name, capabilityPath: [name] },
@@ -147972,9 +148314,10 @@ function wrapCallerInjectedFunction(name, value, options, state) {
147972
148314
  const bindingName = name === "default" && value.name.length > 0 ? value.name : name;
147973
148315
  const callable = value;
147974
148316
  return createSandboxClosure({
147975
- ...isAsyncFunction(callable) ? { async: true } : {},
148317
+ ...isAsyncFunction(callable) && !options.realm?.awaitResult(callable) ? { async: true } : {},
147976
148318
  cancellationSignal: options.signal,
147977
148319
  call: (args, context) => {
148320
+ options.realm?.assertActive();
147978
148321
  const operationLease = options.budget.acquireCompileOwner(false, options.compileOwner);
147979
148322
  const compilation = new CompileScope(operationLease.owner);
147980
148323
  try {
@@ -147990,9 +148333,10 @@ function wrapCallerInjectedFunction(name, value, options, state) {
147990
148333
  seen: /* @__PURE__ */ new WeakMap(),
147991
148334
  restored: []
147992
148335
  };
147993
- const hostArgs = deepCopyFromSandbox([...args], {
148336
+ const copyArguments = (values) => deepCopyFromSandbox([...values], {
147994
148337
  compilation,
147995
- wrapClosure: (closure) => wrapSandboxClosureForHost(
148338
+ unwrapHostObject: options.realm === void 0 ? void 0 : (object) => exportHostCapability(object, options.realm.owner),
148339
+ wrapClosure: (closure) => options.realm?.wrapCallback(closure) ?? wrapSandboxClosureForHost(
147996
148340
  closure,
147997
148341
  stackFrames,
147998
148342
  options.budget,
@@ -148000,11 +148344,26 @@ function wrapCallerInjectedFunction(name, value, options, state) {
148000
148344
  callbacks
148001
148345
  )
148002
148346
  });
148347
+ const captured = options.realm?.captureArguments(callable, args, copyArguments);
148348
+ const hostArgs = captured?.args ?? copyArguments(args);
148003
148349
  const hostCalls = options.hostCalls;
148004
148350
  const operation = options.operation ?? bindingName;
148005
148351
  const moduleId = options.moduleId ?? "<bindings>";
148006
148352
  const policy = readHostOperationPolicy(value) ?? readRegisteredPendingHostCallPolicy(moduleId, operation) ?? "re-issue";
148007
148353
  if (hostCalls === void 0) {
148354
+ if (options.realm !== void 0) {
148355
+ let result;
148356
+ try {
148357
+ result = options.realm.invoke(callable, () => Reflect.apply(callable, void 0, hostArgs));
148358
+ } catch (error3) {
148359
+ captured.rollback();
148360
+ throw error3;
148361
+ }
148362
+ if (options.realm.awaitResult(callable)) {
148363
+ return Promise.resolve(result).then((value2) => copyHostResultToSandbox(value2, stackFrames, options));
148364
+ }
148365
+ return copyHostResultToSandbox(result, stackFrames, options);
148366
+ }
148008
148367
  return copyHostResultToSandbox(
148009
148368
  invokeHostCallback(() => Reflect.apply(callable, void 0, hostArgs), options),
148010
148369
  stackFrames,
@@ -148542,6 +148901,10 @@ function wrapHostPromiseWithSignal(promise, signal) {
148542
148901
  }
148543
148902
  function copyHostValueToSandbox(value, stackFrames, options, state, path193) {
148544
148903
  const { budget } = options;
148904
+ if (isLiveCapability(value)) {
148905
+ if (options.realm === void 0 || options.errorData || options.hostCalls !== void 0) throw new TypeError("Live capabilities are not portable replay or error data.");
148906
+ return importHostCapability(value, options.realm.owner);
148907
+ }
148545
148908
  if (value === null || value === void 0 || typeof value === "number" || typeof value === "boolean") {
148546
148909
  return value;
148547
148910
  }
@@ -148583,6 +148946,14 @@ function copyHostValueToSandbox(value, stackFrames, options, state, path193) {
148583
148946
  state
148584
148947
  );
148585
148948
  }
148949
+ const date = copyNativeDate(value);
148950
+ if (date !== void 0) {
148951
+ const existing = state.seen.get(value);
148952
+ if (existing !== void 0) return existing;
148953
+ budget.chargeDataUsage(9);
148954
+ state.seen.set(value, date);
148955
+ return date;
148956
+ }
148586
148957
  if (isFloat32Array(value)) {
148587
148958
  const existing = state.seen.get(value);
148588
148959
  if (existing !== void 0) return existing;
@@ -148864,6 +149235,8 @@ var init_host_bridge = __esm({
148864
149235
  "packages/safe-js/src/interp/host-bridge.ts"() {
148865
149236
  "use strict";
148866
149237
  init_async();
149238
+ init_date();
149239
+ init_host_capabilities();
148867
149240
  init_shape();
148868
149241
  init_budget2();
148869
149242
  init_compile_guard();
@@ -149002,7 +149375,9 @@ function toJsonParseText(input) {
149002
149375
  }
149003
149376
  async function stringifyProperty(key3, holder, state, indent = "") {
149004
149377
  let value = getOwnDataValue(holder, key3);
149005
- if (isStringifyContainer(value)) {
149378
+ if (isSandboxDate(value)) {
149379
+ value = dateMethods.get("toJSON").invoke(value, []);
149380
+ } else if (isStringifyContainer(value)) {
149006
149381
  const toJSON = getOwnDataValue(value, "toJSON");
149007
149382
  if (isSandboxClosure(toJSON)) {
149008
149383
  value = await callStringifyClosure(toJSON, [key3], value, state);
@@ -149188,12 +149563,125 @@ function defineDataProperty8(target, key3, value) {
149188
149563
  var init_console_json = __esm({
149189
149564
  "packages/safe-js/src/interp/globals/console-json.ts"() {
149190
149565
  "use strict";
149566
+ init_date();
149191
149567
  init_compile_guard();
149192
149568
  init_host_bridge();
149193
149569
  init_values();
149194
149570
  }
149195
149571
  });
149196
149572
 
149573
+ // packages/safe-js/src/interp/globals/math.ts
149574
+ function f16round(value) {
149575
+ const number = +value;
149576
+ if (!Number.isFinite(number) || number === 0) {
149577
+ return number;
149578
+ }
149579
+ const magnitude = Math.abs(number);
149580
+ if (magnitude >= 65520) {
149581
+ return number < 0 ? -Infinity : Infinity;
149582
+ }
149583
+ let quantum = 2 ** -24;
149584
+ let boundary = 2 ** -13;
149585
+ for (let exponent = -13; exponent <= 15 && magnitude >= boundary; exponent += 1) {
149586
+ quantum *= 2;
149587
+ boundary *= 2;
149588
+ }
149589
+ const scaled = magnitude / quantum;
149590
+ const lower = Math.floor(scaled);
149591
+ const remainder = scaled - lower;
149592
+ const rounded = (remainder > 0.5 || remainder === 0.5 && lower % 2 !== 0 ? lower + 1 : lower) * quantum;
149593
+ return number < 0 ? -rounded : rounded;
149594
+ }
149595
+ function createMathGlobals(options = {}) {
149596
+ const random = options.random ?? Math.random;
149597
+ const mathObject = {
149598
+ E: Math.E,
149599
+ LN2: Math.LN2,
149600
+ LN10: Math.LN10,
149601
+ LOG2E: Math.LOG2E,
149602
+ LOG10E: Math.LOG10E,
149603
+ PI: Math.PI,
149604
+ SQRT1_2: Math.SQRT1_2,
149605
+ SQRT2: Math.SQRT2,
149606
+ random: createSandboxClosure({ sandbox: true, call: () => random(), name: "random" })
149607
+ };
149608
+ for (const [name, method] of Object.entries(mathMethods)) {
149609
+ mathObject[name] = createSandboxClosure({
149610
+ sandbox: true,
149611
+ call: (args) => Reflect.apply(method, Math, args),
149612
+ name
149613
+ });
149614
+ }
149615
+ return {
149616
+ Infinity: Infinity,
149617
+ Math: mathObject,
149618
+ NaN: Number.NaN
149619
+ };
149620
+ }
149621
+ function createSeededRandom(seed) {
149622
+ let state = normalizeSeed(seed);
149623
+ return {
149624
+ next: () => {
149625
+ state = Math.imul(state, 1664525) + 1013904223 >>> 0;
149626
+ return state / 4294967296;
149627
+ },
149628
+ snapshot: () => state,
149629
+ restore: (nextState) => {
149630
+ state = normalizeSeed(nextState);
149631
+ }
149632
+ };
149633
+ }
149634
+ function normalizeSeed(seed) {
149635
+ if (!Number.isFinite(seed)) {
149636
+ throw new TypeError("Seeded random requires a finite numeric seed.");
149637
+ }
149638
+ return Math.trunc(seed) >>> 0;
149639
+ }
149640
+ var mathMethods;
149641
+ var init_math = __esm({
149642
+ "packages/safe-js/src/interp/globals/math.ts"() {
149643
+ "use strict";
149644
+ init_values();
149645
+ mathMethods = {
149646
+ abs: Math.abs,
149647
+ acos: Math.acos,
149648
+ acosh: Math.acosh,
149649
+ asin: Math.asin,
149650
+ asinh: Math.asinh,
149651
+ atan: Math.atan,
149652
+ atan2: Math.atan2,
149653
+ atanh: Math.atanh,
149654
+ ceil: Math.ceil,
149655
+ cbrt: Math.cbrt,
149656
+ clz32: Math.clz32,
149657
+ cos: Math.cos,
149658
+ cosh: Math.cosh,
149659
+ exp: Math.exp,
149660
+ expm1: Math.expm1,
149661
+ floor: Math.floor,
149662
+ f16round,
149663
+ fround: Math.fround,
149664
+ hypot: Math.hypot,
149665
+ imul: Math.imul,
149666
+ log: Math.log,
149667
+ log1p: Math.log1p,
149668
+ log10: Math.log10,
149669
+ log2: Math.log2,
149670
+ max: Math.max,
149671
+ min: Math.min,
149672
+ pow: Math.pow,
149673
+ round: Math.round,
149674
+ sign: Math.sign,
149675
+ sin: Math.sin,
149676
+ sinh: Math.sinh,
149677
+ sqrt: Math.sqrt,
149678
+ tan: Math.tan,
149679
+ tanh: Math.tanh,
149680
+ trunc: Math.trunc
149681
+ };
149682
+ }
149683
+ });
149684
+
149197
149685
  // packages/safe-js/src/interp/globals/regex.ts
149198
149686
  function createRegexGlobals(owner) {
149199
149687
  const construct = (args, context) => {
@@ -149337,6 +149825,7 @@ async function stringifyObject2(value, budget, context, joining) {
149337
149825
  }
149338
149826
  }
149339
149827
  async function defaultToString(value, budget, context, joining) {
149828
+ if (isSandboxDate(value)) return budget.allocateString(dateString(value));
149340
149829
  if (Array.isArray(value) || isFloat32Array(value)) {
149341
149830
  if (Object.hasOwn(value, "join")) {
149342
149831
  const join21 = ownDataValue(value, "join");
@@ -149383,6 +149872,7 @@ var init_string_coercion = __esm({
149383
149872
  "packages/safe-js/src/interp/string-coercion.ts"() {
149384
149873
  "use strict";
149385
149874
  init_shape();
149875
+ init_date();
149386
149876
  init_float32();
149387
149877
  init_values();
149388
149878
  }
@@ -149448,6 +149938,7 @@ function createObjectArrayGlobals(options) {
149448
149938
  getPrototypeOf: createSandboxClosure({
149449
149939
  sandbox: true,
149450
149940
  call: ([value]) => {
149941
+ if (isSandboxDate(value)) return getDatePrototype(value, options.budget, options.compileOwner);
149451
149942
  objectProperties(value);
149452
149943
  return getSandboxPrototype(value);
149453
149944
  },
@@ -149572,7 +150063,7 @@ function createObjectArrayGlobals(options) {
149572
150063
  }),
149573
150064
  Number: createSandboxClosure({
149574
150065
  sandbox: true,
149575
- call: ([value]) => Number(value),
150066
+ call: ([value]) => isSandboxDate(value) ? dateTime(value) : Number(value),
149576
150067
  name: "Number",
149577
150068
  properties: {
149578
150069
  isFinite: createSandboxClosure({
@@ -149672,6 +150163,11 @@ function assignSandboxValues(target, sources, budget) {
149672
150163
  return target;
149673
150164
  }
149674
150165
  function objectProperties(value, mutable = false) {
150166
+ if (isSandboxDate(value)) {
150167
+ if (mutable) throw new TypeError("Date own properties and prototypes are not supported.");
150168
+ return value;
150169
+ }
150170
+ if (isGuestHostObject(value)) throw new TypeError("Live host object descriptors are not supported.");
149675
150171
  if (isGuestClosure(value)) return materializeFunctionProperties(value);
149676
150172
  if (isSandboxClosure(value)) {
149677
150173
  if (mutable) throw new TypeError("Host function properties are read only.");
@@ -149756,6 +150252,7 @@ async function collectIteratorValues(iterator) {
149756
150252
  }
149757
150253
  }
149758
150254
  function getOwnEnumerableKeys(value) {
150255
+ if (isGuestHostObject(value)) return getHostObjectKeys(value);
149759
150256
  return ownEnumerableSandboxEntries(value).map(([key3]) => key3);
149760
150257
  }
149761
150258
  function getOwnEnumerableValues(value) {
@@ -149787,6 +150284,9 @@ function getTemplateRawParts(template2) {
149787
150284
  var init_object_array = __esm({
149788
150285
  "packages/safe-js/src/interp/globals/object-array.ts"() {
149789
150286
  "use strict";
150287
+ init_date();
150288
+ init_date2();
150289
+ init_host_capabilities();
149790
150290
  init_float32();
149791
150291
  init_interpreter();
149792
150292
  init_iteration();
@@ -149796,6 +150296,78 @@ var init_object_array = __esm({
149796
150296
  }
149797
150297
  });
149798
150298
 
150299
+ // packages/safe-js/src/interp/globals.ts
150300
+ function createBuiltinBindings(options) {
150301
+ return {
150302
+ ...createConsoleJsonGlobals(options),
150303
+ ...createCollectionGlobals(options),
150304
+ Float32Array: createFloat32ArrayGlobal(options.budget),
150305
+ Date: createDateGlobal(options),
150306
+ ...createErrorGlobals(options),
150307
+ ...createMathGlobals({ random: options.random }),
150308
+ ...createObjectArrayGlobals(options),
150309
+ ...createMiscGlobals(options),
150310
+ ...createPromiseGlobals(options),
150311
+ ...createRegexGlobals(options.compileOwner)
150312
+ };
150313
+ }
150314
+ var init_globals = __esm({
150315
+ "packages/safe-js/src/interp/globals.ts"() {
150316
+ "use strict";
150317
+ init_console_json();
150318
+ init_collections();
150319
+ init_float32array2();
150320
+ init_error();
150321
+ init_math();
150322
+ init_regex2();
150323
+ init_misc();
150324
+ init_object_array();
150325
+ init_promise();
150326
+ init_date2();
150327
+ }
150328
+ });
150329
+
150330
+ // packages/safe-js/src/interp/resources.ts
150331
+ import { AsyncLocalStorage as AsyncLocalStorage8 } from "node:async_hooks";
150332
+ async function withRunResources(signal, execute2) {
150333
+ const controller = new AbortController();
150334
+ const cancel2 = () => controller.abort(signal?.reason);
150335
+ const cleanups = /* @__PURE__ */ new Set();
150336
+ const resources = {
150337
+ signal: controller.signal,
150338
+ add(close) {
150339
+ cleanups.add(close);
150340
+ }
150341
+ };
150342
+ signal?.addEventListener("abort", cancel2, { once: true });
150343
+ if (signal?.aborted) cancel2();
150344
+ let result;
150345
+ let failure;
150346
+ let errors2 = [];
150347
+ try {
150348
+ result = await runResources.run(resources, execute2);
150349
+ } catch (error3) {
150350
+ failure = { reason: error3 };
150351
+ } finally {
150352
+ signal?.removeEventListener("abort", cancel2);
150353
+ controller.abort(new Error("SafeJS run finished."));
150354
+ const outcomes = await Promise.allSettled(
150355
+ [...cleanups].map((close) => Promise.resolve().then(close))
150356
+ );
150357
+ errors2 = outcomes.flatMap((outcome) => outcome.status === "rejected" ? [outcome.reason] : []);
150358
+ }
150359
+ if (failure !== void 0) throw failure.reason;
150360
+ if (errors2.length > 0) throw new AggregateError(errors2, "SafeJS resource cleanup failed.");
150361
+ return result;
150362
+ }
150363
+ var runResources;
150364
+ var init_resources = __esm({
150365
+ "packages/safe-js/src/interp/resources.ts"() {
150366
+ "use strict";
150367
+ runResources = new AsyncLocalStorage8();
150368
+ }
150369
+ });
150370
+
149799
150371
  // packages/safe-js/src/modules/registry.ts
149800
150372
  function createUnknownModuleMessage2(moduleName, moduleNames) {
149801
150373
  if (moduleNames.length === 0) {
@@ -149812,7 +150384,7 @@ function createUnknownExportMessage2(moduleName, exportName, availableExports) {
149812
150384
  function resolveModuleImports(module, modules, options) {
149813
150385
  const registry = normalizeModuleRegistry(modules);
149814
150386
  const bindings = createBindingRecord();
149815
- const wrappedModules = /* @__PURE__ */ new Map();
150387
+ const wrappedModules = options.wrappedModules ?? /* @__PURE__ */ new Map();
149816
150388
  for (const statement of module.body) {
149817
150389
  if (statement.type !== "ImportDeclaration") {
149818
150390
  continue;
@@ -149834,6 +150406,7 @@ function bindImportDeclaration(declaration, registry, wrappedModules, bindings,
149834
150406
  const wrappedExports = wrappedModules.get(moduleName) ?? createBindingRecord(
149835
150407
  wrapCancelableBindings(
149836
150408
  wrapCallerInjectedBindings(Object.fromEntries(moduleExports), {
150409
+ realm: options.realm,
149837
150410
  budget: options.budget,
149838
150411
  compileOwner: options.compileOwner,
149839
150412
  hostCalls: options.hostCalls,
@@ -149923,6 +150496,809 @@ var init_registry7 = __esm({
149923
150496
  }
149924
150497
  });
149925
150498
 
150499
+ // packages/safe-js/src/random.ts
150500
+ import { randomInt } from "node:crypto";
150501
+ function createReplayableRandom(options = {}) {
150502
+ const snapshot2 = options.snapshot;
150503
+ const saved = snapshot2?.random;
150504
+ let initialState = options.seed;
150505
+ if (saved !== void 0) {
150506
+ const hasLoopState = typeof snapshot2?.loopIterations === "object" && snapshot2.loopIterations !== null && Object.keys(snapshot2.loopIterations).length > 0;
150507
+ const replaysFromStart = snapshot2?.replay !== void 0 || Array.isArray(snapshot2?.pendingAwaits) && snapshot2.pendingAwaits.length > 0 && !hasLoopState;
150508
+ initialState = replaysFromStart ? saved.initialState ?? saved.seed : saved.resumeState ?? saved.state;
150509
+ }
150510
+ const generator = createSeededRandom(initialState ?? randomInt(4294967296));
150511
+ return { seed: saved?.seed ?? generator.snapshot(), ...generator };
150512
+ }
150513
+ var init_random = __esm({
150514
+ "packages/safe-js/src/random.ts"() {
150515
+ "use strict";
150516
+ init_math();
150517
+ }
150518
+ });
150519
+
150520
+ // packages/safe-js/src/realm.ts
150521
+ import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
150522
+ import { types as types4 } from "node:util";
150523
+ function readModules(input) {
150524
+ const entries = (value, label) => {
150525
+ if (types4.isMap(value) && !types4.isProxy(value)) {
150526
+ const result = [...Map.prototype.entries.call(value)];
150527
+ if (result.length > 4096 || result.some(([key3]) => typeof key3 !== "string" || key3.length === 0))
150528
+ throw new TypeError(`${label} requires bounded string keys.`);
150529
+ return result;
150530
+ }
150531
+ return Object.entries(readDataRecord(value, label));
150532
+ };
150533
+ const modules = /* @__PURE__ */ Object.create(null);
150534
+ for (const [name, exports] of entries(input ?? {}, "Module registry")) {
150535
+ const exported = /* @__PURE__ */ Object.create(null);
150536
+ for (const [key3, value] of entries(exports, "Module exports"))
150537
+ exported[key3] = value;
150538
+ modules[name] = exported;
150539
+ }
150540
+ return modules;
150541
+ }
150542
+ function assertNames(actual, expected, label) {
150543
+ if (actual.length !== expected.length || actual.some((name) => !expected.includes(name)))
150544
+ throw new TypeError(`Extension ${label} names do not match its manifest.`);
150545
+ }
150546
+ async function runWithExtensions(source, options) {
150547
+ if (options.snapshot !== void 0 || options.snapshotBackend !== void 0 || options.snapshotPath !== void 0 || options.entryPointArgs !== void 0)
150548
+ throw new TypeError(
150549
+ "Live extension runs do not support snapshots or entryPointArgs; use a persistent realm."
150550
+ );
150551
+ const state = new RealmState(readRealmOptions(options, true));
150552
+ try {
150553
+ const result = await state.perform(() => state.evaluateRaw(source, options.filename));
150554
+ if (result.ok) encodeReplayData(result.returnValue);
150555
+ return {
150556
+ ...result,
150557
+ snapshot: {
150558
+ version: 1,
150559
+ sourceHash: hashSource(source),
150560
+ bindings: {},
150561
+ replayError: "Live realm state cannot be serialized or replayed."
150562
+ }
150563
+ };
150564
+ } catch (error3) {
150565
+ if (state.disposal === void 0) {
150566
+ try {
150567
+ await state.close();
150568
+ } catch (cleanupError) {
150569
+ throw new AggregateError([error3, cleanupError], "Realm execution and cleanup failed.");
150570
+ }
150571
+ }
150572
+ throw error3;
150573
+ } finally {
150574
+ if (state.disposal === void 0) await state.close();
150575
+ }
150576
+ }
150577
+ function readRealmOptions(value, oneShot = false) {
150578
+ const options = readDataRecord(value, "Realm options");
150579
+ const supported = /* @__PURE__ */ new Set([
150580
+ "bindings",
150581
+ "modules",
150582
+ "extensions",
150583
+ "grants",
150584
+ "budget",
150585
+ "signal",
150586
+ "sink",
150587
+ "randomSeed",
150588
+ "clock",
150589
+ "limits"
150590
+ ]);
150591
+ for (const [key3, entry] of Object.entries(options)) {
150592
+ if (supported.has(key3) || oneShot && (key3 === "filename" || entry === void 0)) continue;
150593
+ throw new TypeError(`Unsupported ${oneShot ? "extension-run" : "realm"} option '${key3}'.`);
150594
+ }
150595
+ return options;
150596
+ }
150597
+ var RealmState;
150598
+ var init_realm = __esm({
150599
+ "packages/safe-js/src/realm.ts"() {
150600
+ "use strict";
150601
+ init_budget2();
150602
+ init_compile_guard();
150603
+ init_globals();
150604
+ init_interpreter();
150605
+ init_jobs4();
150606
+ init_cancel2();
150607
+ init_running_state();
150608
+ init_resources();
150609
+ init_promise_tracker();
150610
+ init_host_bridge();
150611
+ init_host_capabilities();
150612
+ init_values();
150613
+ init_extensions();
150614
+ init_registry7();
150615
+ init_parser3();
150616
+ init_random();
150617
+ init_hash();
150618
+ init_shape();
150619
+ init_replay_data();
150620
+ RealmState = class {
150621
+ constructor(options) {
150622
+ this.options = options;
150623
+ const limitInput = readDataRecord(options.limits ?? {}, "Realm limits");
150624
+ this.limits = {
150625
+ extensions: 32,
150626
+ hostObjects: 1024,
150627
+ callbacks: 1024,
150628
+ guestReferences: 1024,
150629
+ cleanups: 1024,
150630
+ nestedEvaluations: 16
150631
+ };
150632
+ for (const [name, value] of Object.entries(limitInput)) {
150633
+ if (!Object.hasOwn(this.limits, name) || !Number.isSafeInteger(value) || Number(value) < 1)
150634
+ throw new TypeError("Realm limits must be positive safe integers with supported names.");
150635
+ this.limits[name] = Number(value);
150636
+ }
150637
+ if (options.extensions !== void 0 && (!Array.isArray(options.extensions) || types4.isProxy(options.extensions)))
150638
+ throw new TypeError("Extensions must be a registration array.");
150639
+ const registrations = options.extensions ?? [];
150640
+ const extensions = [];
150641
+ if (registrations.length > this.limits.extensions)
150642
+ throw new RangeError("Realm extension limit exceeded.");
150643
+ for (let index = 0; index < registrations.length; index++) {
150644
+ const descriptor = Object.getOwnPropertyDescriptor(registrations, String(index));
150645
+ if (descriptor === void 0 || !("value" in descriptor))
150646
+ throw new TypeError("Extension registrations require data properties, not accessors.");
150647
+ extensions.push(descriptor.value);
150648
+ }
150649
+ if (Reflect.ownKeys(registrations).length !== extensions.length + 1)
150650
+ throw new TypeError("Extension registrations have unsupported fields.");
150651
+ this.extensions = Object.freeze(extensions);
150652
+ if (this.extensions.length > this.limits.extensions)
150653
+ throw new RangeError("Realm extension limit exceeded.");
150654
+ this.globals = readDataRecord(options.bindings ?? {}, "Realm bindings");
150655
+ this.modules = readModules(options.modules);
150656
+ const grants = new Set(readStringList(options.grants ?? [], "Realm grants"));
150657
+ for (const extension of this.extensions) getExtensionSetup(extension);
150658
+ this.budget = options.budget ?? new Budget({ maxCallDepth: 1e3 });
150659
+ this.lease = this.budget.acquireCompileOwner(true);
150660
+ this.compilation = new CompileScope(this.lease.owner);
150661
+ this.bridge = {
150662
+ owner: this,
150663
+ assertActive: this.assertOpen,
150664
+ wrapCallback: this.wrapCallback,
150665
+ captureArguments: this.captureArguments,
150666
+ invoke: this.invokeHost,
150667
+ awaitResult: (operation) => this.nestedOperations.has(operation)
150668
+ };
150669
+ try {
150670
+ this.builtinBindings = createBuiltinBindings({
150671
+ budget: this.budget,
150672
+ compileOwner: this.lease.owner,
150673
+ sink: options.sink,
150674
+ clock: options.clock,
150675
+ random: createReplayableRandom({ seed: options.randomSeed }).next
150676
+ });
150677
+ const names = /* @__PURE__ */ new Set();
150678
+ const globals = /* @__PURE__ */ new Set([...Object.keys(this.builtinBindings), ...Object.keys(this.globals)]);
150679
+ const modules = new Map(
150680
+ Object.entries(this.modules).map(([name, exports]) => [name, new Set(Object.keys(exports))])
150681
+ );
150682
+ for (const extension of this.extensions) {
150683
+ const manifest = extension.manifest;
150684
+ if (names.has(manifest.name))
150685
+ throw new TypeError(`Duplicate extension '${manifest.name}'.`);
150686
+ names.add(manifest.name);
150687
+ for (const capability of manifest.capabilities ?? []) {
150688
+ if (!grants.has(capability))
150689
+ throw new TypeError(`Missing grant '${capability}' for extension '${manifest.name}'.`);
150690
+ }
150691
+ for (const name of manifest.globals ?? []) {
150692
+ if (globals.has(name)) throw new TypeError(`Conflicting global '${name}'.`);
150693
+ globals.add(name);
150694
+ }
150695
+ for (const [name, exports] of Object.entries(manifest.modules ?? {})) {
150696
+ const occupied = modules.get(name) ?? /* @__PURE__ */ new Set();
150697
+ for (const key3 of exports) {
150698
+ if (occupied.has(key3)) throw new TypeError(`Conflicting export '${name}.${key3}'.`);
150699
+ occupied.add(key3);
150700
+ }
150701
+ modules.set(name, occupied);
150702
+ }
150703
+ }
150704
+ options.signal?.addEventListener("abort", this.abort, { once: true });
150705
+ if (options.signal?.aborted) this.abort();
150706
+ this.budget.setRetainedValues(this, this.retainedRoots);
150707
+ this.tracker.onFatalRejection((error3) => this.poison(error3));
150708
+ } catch (error3) {
150709
+ this.compilation.dispose();
150710
+ this.lease.release();
150711
+ throw error3;
150712
+ }
150713
+ }
150714
+ options;
150715
+ budget;
150716
+ lease;
150717
+ compilation;
150718
+ controller = new AbortController();
150719
+ phase = new AsyncLocalStorage9();
150720
+ queue = new SandboxJobQueue();
150721
+ tracker = createSandboxPromiseRejectionTracker();
150722
+ bridge;
150723
+ limits;
150724
+ extensions;
150725
+ cleanups = [];
150726
+ callbacks = /* @__PURE__ */ new Map();
150727
+ pendingCallbacks = /* @__PURE__ */ new Set();
150728
+ callbackCache = /* @__PURE__ */ new WeakMap();
150729
+ hostObjects = /* @__PURE__ */ new Set();
150730
+ guestReferences = /* @__PURE__ */ new Map();
150731
+ retainedOperations = /* @__PURE__ */ new WeakMap();
150732
+ nestedOperations = /* @__PURE__ */ new WeakMap();
150733
+ convertedModules = /* @__PURE__ */ new Map();
150734
+ nativeConversions = { seen: /* @__PURE__ */ new WeakMap() };
150735
+ modules;
150736
+ globals;
150737
+ builtinBindings;
150738
+ scope;
150739
+ active;
150740
+ disposal;
150741
+ closed = false;
150742
+ initialized = false;
150743
+ nestedDepth = 0;
150744
+ failure;
150745
+ bridgeOptions = () => ({
150746
+ budget: this.budget,
150747
+ compileOwner: this.lease.owner,
150748
+ signal: this.controller.signal,
150749
+ realm: this.bridge
150750
+ });
150751
+ retainedRoots = () => [
150752
+ ...this.callbacks.values(),
150753
+ ...Array.from(this.pendingCallbacks, (pending) => pending.closure),
150754
+ ...this.guestReferences.values()
150755
+ ];
150756
+ captureArguments = (operation, args, copy) => {
150757
+ const from = this.retainedOperations.get(operation)?.from ?? args.length;
150758
+ const values = copy(args.slice(0, from));
150759
+ const captured = [];
150760
+ const rollback = () => {
150761
+ for (const reference of captured) {
150762
+ revokeGuestReference(reference, this);
150763
+ this.guestReferences.delete(reference);
150764
+ }
150765
+ };
150766
+ try {
150767
+ for (const value of args.slice(from)) {
150768
+ this.checkCollection(
150769
+ this.guestReferences.size + 1,
150770
+ this.limits.guestReferences,
150771
+ "guest reference"
150772
+ );
150773
+ const root = [value];
150774
+ const reference = createGuestReference(root, this, this.assertOpen);
150775
+ this.guestReferences.set(reference, root);
150776
+ captured.push(reference);
150777
+ values.push(reference);
150778
+ }
150779
+ if (captured.length > 0)
150780
+ this.budget.reconcileDataUsage(
150781
+ measureSandboxData([...this.scope?.retainedValues() ?? [], ...this.retainedRoots()])
150782
+ );
150783
+ return { args: values, rollback };
150784
+ } catch (error3) {
150785
+ rollback();
150786
+ if (error3 instanceof SandboxError) this.poison(error3);
150787
+ throw error3;
150788
+ }
150789
+ };
150790
+ releaseGuestReference = (reference) => {
150791
+ readGuestReference(reference, this);
150792
+ revokeGuestReference(reference, this);
150793
+ this.guestReferences.delete(reference);
150794
+ if (this.active === void 0)
150795
+ reconcileCompiledValues(
150796
+ this.budget,
150797
+ [...this.scope?.retainedValues() ?? [], ...this.retainedRoots()],
150798
+ this.compilation
150799
+ );
150800
+ };
150801
+ assertOpen = () => {
150802
+ if (this.failure !== void 0) throw this.failure.reason;
150803
+ if (this.closed) throw new Error("SafeJS realm is closed; capabilities are revoked.");
150804
+ this.controller.signal.throwIfAborted();
150805
+ };
150806
+ abort = () => {
150807
+ this.poison(this.options.signal?.reason ?? new SandboxError("aborted"));
150808
+ void this.close().catch(() => void 0);
150809
+ };
150810
+ poison(reason) {
150811
+ this.failure ??= { reason };
150812
+ this.controller.abort(reason);
150813
+ if (this.active === void 0)
150814
+ queueMicrotask(() => {
150815
+ void this.dispose().catch(() => void 0);
150816
+ });
150817
+ }
150818
+ chargeWork = (units = 1) => {
150819
+ this.assertOpen();
150820
+ if (!Number.isSafeInteger(units) || units < 0)
150821
+ throw new TypeError("Work charges must be non-negative safe integers.");
150822
+ try {
150823
+ for (let index = 0; index < units; index++) this.budget.visitNode();
150824
+ } catch (error3) {
150825
+ this.poison(error3);
150826
+ throw error3;
150827
+ }
150828
+ };
150829
+ onCleanup = (cleanup) => {
150830
+ this.assertOpen();
150831
+ if (typeof cleanup !== "function") throw new TypeError("Cleanup must be a function.");
150832
+ this.checkCollection(this.cleanups.length + 1, this.limits.cleanups, "cleanup");
150833
+ this.cleanups.push(cleanup);
150834
+ };
150835
+ checkCollection(count, limit, name) {
150836
+ this.assertOpen();
150837
+ try {
150838
+ this.budget.allocateCollectionEntries(count);
150839
+ } catch (error3) {
150840
+ this.poison(error3);
150841
+ throw error3;
150842
+ }
150843
+ if (count > limit) throw new RangeError(`Realm ${name} limit exceeded.`);
150844
+ }
150845
+ invokeHost = (operation, call) => {
150846
+ this.assertOpen();
150847
+ const phase = {
150848
+ active: true,
150849
+ extension: this.nestedOperations.get(operation),
150850
+ evaluating: false,
150851
+ pending: /* @__PURE__ */ new Set()
150852
+ };
150853
+ return this.phase.run(phase, () => {
150854
+ try {
150855
+ const result = call();
150856
+ if (types4.isPromise(result) || phase.pending.size > 0 || phase.failure !== void 0) {
150857
+ return Promise.resolve(result).then(
150858
+ async (value) => {
150859
+ await Promise.allSettled(phase.pending);
150860
+ if (phase.failure !== void 0) throw phase.failure.reason;
150861
+ this.assertOpen();
150862
+ return value;
150863
+ },
150864
+ async (error3) => {
150865
+ if (error3 instanceof SandboxError || phase.pending.size > 0) this.poison(error3);
150866
+ await Promise.allSettled(phase.pending);
150867
+ throw error3;
150868
+ }
150869
+ ).finally(() => {
150870
+ phase.active = false;
150871
+ });
150872
+ }
150873
+ this.assertOpen();
150874
+ phase.active = false;
150875
+ return result;
150876
+ } catch (error3) {
150877
+ phase.active = false;
150878
+ if (error3 instanceof SandboxError) this.poison(error3);
150879
+ if (phase.pending.size > 0) {
150880
+ this.poison(error3);
150881
+ return Promise.allSettled(phase.pending).then(() => {
150882
+ throw error3;
150883
+ });
150884
+ }
150885
+ throw error3;
150886
+ }
150887
+ });
150888
+ };
150889
+ importValue(value) {
150890
+ return copyHostValueToSandbox(
150891
+ value,
150892
+ [],
150893
+ this.bridgeOptions(),
150894
+ { seen: /* @__PURE__ */ new WeakMap() },
150895
+ "<realm>"
150896
+ );
150897
+ }
150898
+ exportValue(value) {
150899
+ return deepCopyFromSandbox(value, {
150900
+ compilation: this.compilation,
150901
+ wrapClosure: this.wrapCallback,
150902
+ unwrapHostObject: (object) => exportHostCapability(object, this)
150903
+ });
150904
+ }
150905
+ createHostObject = (definition) => {
150906
+ this.checkCollection(this.hostObjects.size + 1, this.limits.hostObjects, "host object");
150907
+ const object = createLiveHostObject(definition, {
150908
+ owner: this,
150909
+ assertActive: this.assertOpen,
150910
+ chargeWork: this.chargeWork,
150911
+ read: (operation) => {
150912
+ const value = this.invokeHost(operation, operation);
150913
+ if (types4.isPromise(value)) {
150914
+ void Promise.resolve(value).catch(() => void 0);
150915
+ throw new TypeError("Live property getters must be synchronous.");
150916
+ }
150917
+ return this.importValue(value);
150918
+ },
150919
+ write: (operation, value) => {
150920
+ const result = this.invokeHost(operation, () => operation(this.exportValue(value)));
150921
+ if (types4.isPromise(result)) {
150922
+ void Promise.resolve(result).catch(() => void 0);
150923
+ throw new TypeError("Live property setters must be synchronous.");
150924
+ }
150925
+ },
150926
+ method: (operation) => {
150927
+ const value = copyHostValueToSandbox(
150928
+ operation,
150929
+ [],
150930
+ this.bridgeOptions(),
150931
+ this.nativeConversions,
150932
+ "<host-method>"
150933
+ );
150934
+ if (!isSandboxClosure(value)) throw new TypeError("Invalid host method.");
150935
+ return value;
150936
+ }
150937
+ });
150938
+ this.hostObjects.add(object);
150939
+ try {
150940
+ this.budget.chargeDataUsage(1);
150941
+ } catch (error3) {
150942
+ this.poison(error3);
150943
+ throw error3;
150944
+ }
150945
+ return object;
150946
+ };
150947
+ wrapCallback = (closure) => {
150948
+ this.assertOpen();
150949
+ const existing = this.callbackCache.get(closure);
150950
+ if (existing !== void 0 && this.callbacks.has(existing)) return existing;
150951
+ this.checkCollection(this.callbacks.size + 1, this.limits.callbacks, "callback");
150952
+ const invokeCallback = this.invokeCallback;
150953
+ const callback = function(...args) {
150954
+ return invokeCallback(callback, { args, thisValue: this });
150955
+ };
150956
+ this.callbacks.set(callback, closure);
150957
+ this.callbackCache.set(closure, callback);
150958
+ registerGuestCallback(callback, {
150959
+ owner: this,
150960
+ closure,
150961
+ assertActive: () => {
150962
+ this.assertOpen();
150963
+ if (!this.callbacks.has(callback)) throw new TypeError("Guest callback is revoked.");
150964
+ }
150965
+ });
150966
+ try {
150967
+ this.budget.reconcileDataUsage(
150968
+ measureSandboxData([...this.scope?.retainedValues() ?? [], ...this.retainedRoots()])
150969
+ );
150970
+ } catch (error3) {
150971
+ this.poison(error3);
150972
+ throw error3;
150973
+ }
150974
+ return callback;
150975
+ };
150976
+ releaseCallback = (callback) => {
150977
+ readGuestCallback(callback, this);
150978
+ revokeGuestCallback(callback, this);
150979
+ this.callbacks.delete(callback);
150980
+ if (this.active === void 0)
150981
+ reconcileCompiledValues(
150982
+ this.budget,
150983
+ [...this.scope?.retainedValues() ?? [], ...this.retainedRoots()],
150984
+ this.compilation
150985
+ );
150986
+ };
150987
+ invokeCallback = async (callback, options = {}) => {
150988
+ if (this.closed || this.failure !== void 0) await this.dispose();
150989
+ this.assertOpen();
150990
+ const closure = readGuestCallback(callback, this);
150991
+ this.checkCollection(this.pendingCallbacks.size + 1, this.limits.callbacks, "pending callback");
150992
+ const record2 = { closure };
150993
+ this.pendingCallbacks.add(record2);
150994
+ const invoke2 = async () => {
150995
+ this.assertOpen();
150996
+ readGuestCallback(callback, this);
150997
+ const leave = enterRunningState(closure);
150998
+ const leaveCall = this.budget.enterCall();
150999
+ try {
151000
+ const values = this.importValue([
151001
+ options.thisValue,
151002
+ [...options.args ?? []]
151003
+ ]);
151004
+ const value = await closure.call(values[1], {
151005
+ thisValue: values[0],
151006
+ compilation: this.compilation,
151007
+ stack: []
151008
+ });
151009
+ const settled = await suspendJob(
151010
+ awaitSandboxValue(value, this.controller.signal, this.budget)
151011
+ );
151012
+ return this.exportValue(settled);
151013
+ } finally {
151014
+ leaveCall();
151015
+ leave();
151016
+ }
151017
+ };
151018
+ try {
151019
+ if (this.active !== void 0) {
151020
+ record2.promise = withSandboxPromiseRejectionTracker(
151021
+ this.tracker,
151022
+ () => runResources.run(
151023
+ { signal: this.controller.signal, add: this.onCleanup },
151024
+ () => withCancellationSignal(
151025
+ this.controller.signal,
151026
+ () => this.phase.getStore()?.active ? runAsyncPrefix(invoke2) : this.queue.run(invoke2)
151027
+ )
151028
+ )
151029
+ );
151030
+ } else {
151031
+ record2.promise = this.perform(() => this.queue.run(invoke2));
151032
+ }
151033
+ return await record2.promise;
151034
+ } catch (error3) {
151035
+ if (error3 instanceof SandboxError) this.poison(error3);
151036
+ throw error3;
151037
+ } finally {
151038
+ this.pendingCallbacks.delete(record2);
151039
+ if (!this.closed && this.active === void 0)
151040
+ reconcileCompiledValues(
151041
+ this.budget,
151042
+ [...this.scope?.retainedValues() ?? [], ...this.retainedRoots()],
151043
+ this.compilation
151044
+ );
151045
+ }
151046
+ };
151047
+ initialize() {
151048
+ if (this.initialized) return;
151049
+ this.assertOpen();
151050
+ this.initialized = true;
151051
+ for (const extension of this.extensions) {
151052
+ const context = Object.freeze({
151053
+ signal: this.controller.signal,
151054
+ onCleanup: this.onCleanup,
151055
+ chargeWork: this.chargeWork,
151056
+ createHostObject: this.createHostObject,
151057
+ invokeCallback: this.invokeCallback,
151058
+ releaseCallback: this.releaseCallback,
151059
+ releaseGuestReference: this.releaseGuestReference,
151060
+ retainGuestArguments: (operation, from) => {
151061
+ this.assertOpen();
151062
+ if (!extension.manifest.capabilities?.includes("guest:retain"))
151063
+ throw new TypeError("Retaining arguments requires the guest:retain grant.");
151064
+ if (typeof operation !== "function")
151065
+ throw new TypeError("Retained operation must be a function.");
151066
+ if (!Number.isSafeInteger(from) || from < 0)
151067
+ throw new TypeError("Argument index must be a non-negative safe integer.");
151068
+ if (this.scope !== void 0)
151069
+ throw new TypeError("Retained operations must be registered during setup.");
151070
+ const previous = this.retainedOperations.get(operation);
151071
+ if (previous !== void 0 && (previous.extension !== extension || previous.from !== from))
151072
+ throw new TypeError("Conflicting retained operation declaration.");
151073
+ this.retainedOperations.set(operation, { extension, from });
151074
+ return operation;
151075
+ },
151076
+ nestedOperation: (operation) => {
151077
+ this.assertOpen();
151078
+ if (!extension.manifest.capabilities?.includes("source:nested"))
151079
+ throw new TypeError("Nested source requires the source:nested grant.");
151080
+ if (typeof operation !== "function")
151081
+ throw new TypeError("Nested operation must be a function.");
151082
+ if (this.scope !== void 0)
151083
+ throw new TypeError("Nested operations must be registered during setup.");
151084
+ const owner = this.nestedOperations.get(operation);
151085
+ if (owner !== void 0 && owner !== extension)
151086
+ throw new TypeError("Nested operation already belongs to another extension.");
151087
+ this.nestedOperations.set(operation, extension);
151088
+ return operation;
151089
+ },
151090
+ evaluateNested: (source) => {
151091
+ const phase = this.phase.getStore();
151092
+ if (!extension.manifest.capabilities?.includes("source:nested") || !phase?.active || phase.extension !== extension || phase.evaluating) {
151093
+ const error3 = new SandboxError("reentry");
151094
+ this.poison(error3);
151095
+ const rejected = Promise.reject(error3);
151096
+ void rejected.catch(() => void 0);
151097
+ return rejected;
151098
+ }
151099
+ const pending = this.evaluateNested(source, extension);
151100
+ phase.pending.add(pending);
151101
+ void pending.then(
151102
+ () => {
151103
+ phase.pending.delete(pending);
151104
+ },
151105
+ (reason) => {
151106
+ phase.pending.delete(pending);
151107
+ phase.failure ??= { reason };
151108
+ }
151109
+ );
151110
+ return pending;
151111
+ }
151112
+ });
151113
+ const output = getExtensionSetup(extension)(context);
151114
+ if (types4.isPromise(output)) {
151115
+ void Promise.resolve(output).catch(() => void 0);
151116
+ throw new TypeError("Extension setup must be synchronous.");
151117
+ }
151118
+ const exports = readDataRecord(output, "Extension exports");
151119
+ if (Object.keys(exports).some((key3) => key3 !== "globals" && key3 !== "modules"))
151120
+ throw new TypeError("Unknown extension export field.");
151121
+ const globals = readDataRecord(
151122
+ exports.globals ?? {},
151123
+ "Extension globals"
151124
+ );
151125
+ const modules = readModules(exports.modules);
151126
+ assertNames(Object.keys(globals), extension.manifest.globals ?? [], "global");
151127
+ assertNames(Object.keys(modules), Object.keys(extension.manifest.modules ?? {}), "module");
151128
+ for (const [name, values] of Object.entries(modules)) {
151129
+ assertNames(Object.keys(values), extension.manifest.modules?.[name] ?? [], "module export");
151130
+ this.modules[name] ??= /* @__PURE__ */ Object.create(null);
151131
+ Object.assign(this.modules[name], values);
151132
+ }
151133
+ Object.assign(this.globals, globals);
151134
+ }
151135
+ const bindings = wrapCallerInjectedBindings(this.globals, this.bridgeOptions());
151136
+ this.scope = new Scope(this.builtinBindings, void 0, void 0, { chargeData: false }).child(
151137
+ bindings,
151138
+ { functionBoundary: true }
151139
+ );
151140
+ }
151141
+ async evaluateRaw(source, filename = "<realm>", nested = false) {
151142
+ this.assertOpen();
151143
+ if (typeof source !== "string") throw new TypeError("Realm source must be a string.");
151144
+ const module = parseExecutableModule(source, filename, this.lease.owner);
151145
+ this.initialize();
151146
+ const imports = resolveModuleImports(module, this.modules, {
151147
+ ...this.bridgeOptions(),
151148
+ wrappedModules: this.convertedModules
151149
+ });
151150
+ for (const [name, value] of Object.entries(imports)) {
151151
+ const binding = this.scope.lookup(name);
151152
+ if (!binding.found) this.scope.declare(name, "const", value);
151153
+ else if (binding.value !== value) throw new TypeError(`Conflicting import '${name}'.`);
151154
+ }
151155
+ const result = await interpret(
151156
+ {
151157
+ type: "BlockStatement",
151158
+ body: module.body.filter((statement) => statement.type !== "ImportDeclaration"),
151159
+ span: module.span
151160
+ },
151161
+ {
151162
+ scope: this.scope,
151163
+ useScopeDirectly: true,
151164
+ budget: this.budget,
151165
+ compilation: this.compilation,
151166
+ signal: this.controller.signal,
151167
+ surfaceUnhandledThrows: true,
151168
+ jobs: this.queue,
151169
+ nested,
151170
+ assertActive: this.assertOpen
151171
+ }
151172
+ );
151173
+ this.assertOpen();
151174
+ return result;
151175
+ }
151176
+ evaluateNested = async (source, extension) => {
151177
+ this.assertOpen();
151178
+ const phase = this.phase.getStore();
151179
+ if (!phase?.active || phase.extension !== extension || phase.evaluating || this.active === void 0)
151180
+ throw new SandboxError("reentry");
151181
+ const leave = this.budget.enterCall();
151182
+ phase.evaluating = true;
151183
+ try {
151184
+ if (++this.nestedDepth > this.limits.nestedEvaluations) {
151185
+ const error3 = new SandboxError({
151186
+ budget: "callDepth",
151187
+ current: this.nestedDepth,
151188
+ limit: this.limits.nestedEvaluations
151189
+ });
151190
+ this.poison(error3);
151191
+ throw error3;
151192
+ }
151193
+ const result = await this.evaluateRaw(source, "<nested>", true);
151194
+ if (!result.ok) throw new Error(result.error.message);
151195
+ } finally {
151196
+ this.nestedDepth--;
151197
+ phase.evaluating = false;
151198
+ leave();
151199
+ }
151200
+ };
151201
+ evaluate = async (source, options = {}) => this.perform(async () => {
151202
+ const result = await this.evaluateRaw(source, options.filename);
151203
+ if (!result.ok) {
151204
+ await this.dispose();
151205
+ return { ok: false, error: result.error, stats: result.stats };
151206
+ }
151207
+ return { ok: true, returnValue: this.exportValue(result.returnValue), stats: result.stats };
151208
+ });
151209
+ async perform(task) {
151210
+ if (this.closed || this.failure !== void 0) await this.dispose();
151211
+ this.assertOpen();
151212
+ if (this.active !== void 0) throw new SandboxError("reentry");
151213
+ const pending = Promise.resolve().then(
151214
+ () => withSandboxPromiseRejectionTracker(
151215
+ this.tracker,
151216
+ () => runResources.run(
151217
+ { signal: this.controller.signal, add: this.onCleanup },
151218
+ () => withCancellationSignal(this.controller.signal, task)
151219
+ )
151220
+ )
151221
+ );
151222
+ this.active = pending;
151223
+ try {
151224
+ const result = await pending;
151225
+ await this.queue.drain();
151226
+ const unhandled = await this.tracker.findUnhandledRejection();
151227
+ if (unhandled !== void 0) {
151228
+ const error3 = new Error(
151229
+ `Unhandled guest promise rejection: ${describeThrownValue(unhandled.reason)}`
151230
+ );
151231
+ error3.name = "UnhandledRejectionError";
151232
+ throw error3;
151233
+ }
151234
+ if (this.failure !== void 0) throw this.failure.reason;
151235
+ if (!this.closed)
151236
+ reconcileCompiledValues(
151237
+ this.budget,
151238
+ [...this.scope?.retainedValues() ?? [], ...this.retainedRoots()],
151239
+ this.compilation
151240
+ );
151241
+ return result;
151242
+ } catch (error3) {
151243
+ this.poison(error3);
151244
+ try {
151245
+ await this.dispose();
151246
+ } catch (cleanup) {
151247
+ throw new AggregateError([error3, cleanup], "Realm execution and cleanup failed.");
151248
+ }
151249
+ throw error3;
151250
+ } finally {
151251
+ this.active = void 0;
151252
+ }
151253
+ }
151254
+ close = () => {
151255
+ this.closed = true;
151256
+ this.controller.abort(new Error("SafeJS realm is closed."));
151257
+ if (this.phase.getStore()?.active) return this.dispose();
151258
+ return Promise.allSettled([
151259
+ this.active,
151260
+ ...Array.from(this.pendingCallbacks, (pending) => pending.promise)
151261
+ ]).then(() => this.dispose());
151262
+ };
151263
+ dispose() {
151264
+ if (this.disposal !== void 0) return this.disposal;
151265
+ this.closed = true;
151266
+ this.controller.abort(new Error("SafeJS realm is closed."));
151267
+ this.options.signal?.removeEventListener("abort", this.abort);
151268
+ for (const callback of this.callbacks.keys()) revokeGuestCallback(callback, this);
151269
+ this.callbacks.clear();
151270
+ for (const object of this.hostObjects) revokeHostObject(object, this);
151271
+ this.hostObjects.clear();
151272
+ for (const reference of this.guestReferences.keys()) revokeGuestReference(reference, this);
151273
+ this.guestReferences.clear();
151274
+ this.budget.setRetainedValues(this, void 0);
151275
+ this.disposal = (async () => {
151276
+ const errors2 = [];
151277
+ for (const cleanup of this.cleanups.splice(0).reverse()) {
151278
+ try {
151279
+ await cleanup();
151280
+ } catch (error3) {
151281
+ errors2.push(error3);
151282
+ }
151283
+ }
151284
+ this.scope = void 0;
151285
+ this.convertedModules.clear();
151286
+ for (const key3 of Object.keys(this.globals)) delete this.globals[key3];
151287
+ for (const key3 of Object.keys(this.modules)) delete this.modules[key3];
151288
+ for (const key3 of Object.keys(this.builtinBindings))
151289
+ Reflect.deleteProperty(this.builtinBindings, key3);
151290
+ this.nativeConversions.seen = /* @__PURE__ */ new WeakMap();
151291
+ reconcileCompiledValues(this.budget, [], this.compilation);
151292
+ this.compilation.dispose();
151293
+ this.lease.release();
151294
+ if (errors2.length > 0) throw new AggregateError(errors2, "Realm cleanup failed.");
151295
+ })();
151296
+ return this.disposal;
151297
+ }
151298
+ };
151299
+ }
151300
+ });
151301
+
149926
151302
  // packages/safe-js/src/snapshot/dump.ts
149927
151303
  function attachDumpController(result, controller) {
149928
151304
  Object.defineProperty(result, RUN_DUMP_CONTROLLER, {
@@ -150357,6 +151733,7 @@ var init_serialize = __esm({
150357
151733
  init_arrays();
150358
151734
  init_float32();
150359
151735
  init_float32array();
151736
+ init_date();
150360
151737
  init_values();
150361
151738
  UnsnapshotableValueError = class extends Error {
150362
151739
  path;
@@ -150493,11 +151870,12 @@ var init_replay_inputs = __esm({
150493
151870
  });
150494
151871
 
150495
151872
  // packages/safe-js/src/run.ts
150496
- import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
151873
+ import { AsyncLocalStorage as AsyncLocalStorage10 } from "node:async_hooks";
150497
151874
  function run(source, options = {}) {
151875
+ if (options.extensions !== void 0) return runWithExtensions(source, options);
150498
151876
  const lifecycle = {
150499
151877
  hostCallbackDepth: 0,
150500
- hostCallbackContext: new AsyncLocalStorage9()
151878
+ hostCallbackContext: new AsyncLocalStorage10()
150501
151879
  };
150502
151880
  const dumpController = createDumpController(lifecycle);
150503
151881
  const promiseTracker = createSandboxPromiseRejectionTracker();
@@ -150563,32 +151941,7 @@ function run(source, options = {}) {
150563
151941
  lifecycle
150564
151942
  })
150565
151943
  );
150566
- const builtinBindings = {
150567
- ...createConsoleJsonGlobals({
150568
- compileOwner: operation.owner,
150569
- budget,
150570
- hostCalls,
150571
- sink: options.sink
150572
- }),
150573
- ...createCollectionGlobals({ budget }),
150574
- Float32Array: createFloat32ArrayGlobal(budget),
150575
- ...createErrorGlobals({
150576
- budget
150577
- }),
150578
- ...createMathGlobals({
150579
- random: random?.generator.next
150580
- }),
150581
- ...createObjectArrayGlobals({
150582
- budget
150583
- }),
150584
- ...createMiscGlobals({
150585
- budget
150586
- }),
150587
- ...createPromiseGlobals({
150588
- budget
150589
- }),
150590
- ...createRegexGlobals(operation.owner)
150591
- };
151944
+ const builtinBindings = createBuiltinBindings({ compileOwner: operation.owner, budget, hostCalls, sink: options.sink, random: random?.generator.next, clock: options.clock });
150592
151945
  const importMeta = convertInitialInput(
150593
151946
  () => deepCopyToSandbox(options.importMeta ?? {})
150594
151947
  );
@@ -151045,6 +152398,7 @@ var UnhandledRejectionError, DEFAULT_MAX_CALL_DEPTH;
151045
152398
  var init_run7 = __esm({
151046
152399
  "packages/safe-js/src/run.ts"() {
151047
152400
  "use strict";
152401
+ init_realm();
151048
152402
  init_hash();
151049
152403
  init_resources();
151050
152404
  init_random();
@@ -151058,14 +152412,7 @@ var init_run7 = __esm({
151058
152412
  init_running_state();
151059
152413
  init_promise_tracker();
151060
152414
  init_host_call();
151061
- init_console_json();
151062
- init_collections();
151063
- init_float32array2();
151064
- init_error();
151065
- init_math();
151066
- init_regex2();
151067
- init_misc();
151068
- init_object_array();
152415
+ init_globals();
151069
152416
  init_host_bridge();
151070
152417
  init_interpreter();
151071
152418
  init_promise();
@@ -151414,7 +152761,7 @@ var init_find_exported = __esm({
151414
152761
  });
151415
152762
 
151416
152763
  // packages/safe-js/src/modules/agent.ts
151417
- import { AsyncLocalStorage as AsyncLocalStorage10 } from "node:async_hooks";
152764
+ import { AsyncLocalStorage as AsyncLocalStorage11 } from "node:async_hooks";
151418
152765
  function createSpawnUsageAccumulator() {
151419
152766
  let inputTokens = 0;
151420
152767
  let outputTokens = 0;
@@ -152317,7 +153664,7 @@ var init_agent3 = __esm({
152317
153664
  hostErrorData.set(this, { result });
152318
153665
  }
152319
153666
  };
152320
- activeUsageAccumulator = new AsyncLocalStorage10();
153667
+ activeUsageAccumulator = new AsyncLocalStorage11();
152321
153668
  oneAttemptRetryOptions = {
152322
153669
  maxAttempts: 1,
152323
153670
  backoffMs: 0,
@@ -154176,6 +155523,8 @@ var init_src48 = __esm({
154176
155523
  init_parse6();
154177
155524
  init_lint4();
154178
155525
  init_run7();
155526
+ init_realm();
155527
+ init_extensions();
154179
155528
  init_random();
154180
155529
  init_otel2();
154181
155530
  init_backend();
@@ -157943,7 +159292,7 @@ var init_package2 = __esm({
157943
159292
  "package.json"() {
157944
159293
  package_default2 = {
157945
159294
  name: "poe-code",
157946
- version: "14.0.5",
159295
+ version: "14.0.7",
157947
159296
  description: "CLI tool to configure Poe API for developer workflows.",
157948
159297
  license: "MIT",
157949
159298
  type: "module",