@poe-platform/safe-js 0.1.246 → 0.1.247

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.
@@ -7162,6 +7162,52 @@ function regexpIteratorState(value) {
7162
7162
  return state;
7163
7163
  }
7164
7164
 
7165
+ // packages/safe-js/src/interp/arguments.ts
7166
+ var sandboxArgumentsBrand = /* @__PURE__ */ Symbol("SandboxArguments");
7167
+ internalSymbols.add(sandboxArgumentsBrand);
7168
+ function createSandboxArguments(values) {
7169
+ const result = /* @__PURE__ */ (function() {
7170
+ return arguments;
7171
+ })();
7172
+ for (let index = 0; index < values.length; index += 1) {
7173
+ result[index] = values[index];
7174
+ }
7175
+ result.length = values.length;
7176
+ Object.defineProperty(result, sandboxArgumentsBrand, { value: true });
7177
+ return result;
7178
+ }
7179
+ function isSandboxArguments(value) {
7180
+ return typeof value === "object" && value !== null && Object.hasOwn(value, sandboxArgumentsBrand);
7181
+ }
7182
+ function getSandboxArgumentEntries(value) {
7183
+ return Object.entries(Object.getOwnPropertyDescriptors(value)).flatMap(
7184
+ ([key, descriptor]) => "value" in descriptor ? [[key, descriptor.value]] : []
7185
+ );
7186
+ }
7187
+ function copySandboxArgumentProperties(source, target, copyValue) {
7188
+ const names = Object.getOwnPropertyNames(source);
7189
+ if (!names.includes("length") || names.indexOf("length") > names.indexOf("callee")) {
7190
+ Reflect.deleteProperty(target, "length");
7191
+ }
7192
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(source))) {
7193
+ if (!("value" in descriptor)) {
7194
+ if (key !== "callee") throw new TypeError(`Cannot copy arguments accessor '${key}'.`);
7195
+ continue;
7196
+ }
7197
+ Object.defineProperty(target, key, { ...descriptor, value: copyValue(descriptor.value, key) });
7198
+ }
7199
+ const iterator = Object.getOwnPropertyDescriptor(source, Symbol.iterator);
7200
+ if (iterator === void 0) {
7201
+ Reflect.deleteProperty(target, Symbol.iterator);
7202
+ } else {
7203
+ if (iterator.value !== Array.prototype.values) {
7204
+ throw new TypeError("Cannot copy a replaced arguments iterator.");
7205
+ }
7206
+ Object.defineProperty(target, Symbol.iterator, iterator);
7207
+ }
7208
+ if (!Object.isExtensible(source)) Object.preventExtensions(target);
7209
+ }
7210
+
7165
7211
  // packages/safe-js/src/interp/boxed.ts
7166
7212
  import { types as types3 } from "node:util";
7167
7213
  var boxes = /* @__PURE__ */ new WeakSet();
@@ -7211,6 +7257,163 @@ function boxedDataProperties(value, includeSymbols = false) {
7211
7257
  });
7212
7258
  }
7213
7259
 
7260
+ // packages/safe-js/src/graph-depth.ts
7261
+ var MAX_DATA_DEPTH = 1024;
7262
+ var SnapshotBudgetError = class extends Error {
7263
+ code = "budgetExceeded";
7264
+ budget = "dataDepth";
7265
+ current;
7266
+ limit;
7267
+ path;
7268
+ constructor(path, current, limit = MAX_DATA_DEPTH) {
7269
+ super(`Snapshot budget exceeded for dataDepth at ${path}: ${current} > ${limit}.`);
7270
+ this.name = "SnapshotBudgetError";
7271
+ this.current = current;
7272
+ this.limit = limit;
7273
+ this.path = path;
7274
+ replaceErrorStack(this);
7275
+ }
7276
+ };
7277
+ function assertSandboxDataDepth(depth) {
7278
+ if (depth > MAX_DATA_DEPTH) {
7279
+ throw new SandboxError({ budget: "dataDepth", current: depth, limit: MAX_DATA_DEPTH });
7280
+ }
7281
+ }
7282
+ function assertSnapshotDataDepth(depth, path) {
7283
+ if (depth > MAX_DATA_DEPTH) throw new SnapshotBudgetError(path, depth);
7284
+ }
7285
+ function assertSnapshotGraphDepth(value, rootPath = "$") {
7286
+ walkGraphDepth(value, rootPath, (depth, path) => assertSnapshotDataDepth(depth, path));
7287
+ }
7288
+ function assertSandboxGraphDepth(value) {
7289
+ walkGraphDepth(value, "<root>", (depth) => assertSandboxDataDepth(depth));
7290
+ }
7291
+ function walkGraphDepth(root, rootPath, assertDepth) {
7292
+ const ancestors = /* @__PURE__ */ new WeakSet();
7293
+ const stack = [{ value: root, path: rootPath, depth: 0, exiting: false }];
7294
+ while (stack.length > 0) {
7295
+ const frame = stack.pop();
7296
+ if (typeof frame.value !== "object" || frame.value === null) continue;
7297
+ if (frame.exiting) {
7298
+ ancestors.delete(frame.value);
7299
+ continue;
7300
+ }
7301
+ assertDepth(frame.depth, frame.path);
7302
+ if (ancestors.has(frame.value)) continue;
7303
+ ancestors.add(frame.value);
7304
+ stack.push({ ...frame, exiting: true });
7305
+ const entries = graphEntries(frame.value);
7306
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
7307
+ const [key, entry] = entries[index];
7308
+ stack.push({
7309
+ value: entry,
7310
+ path: `${frame.path}${key}`,
7311
+ depth: frame.depth + 1,
7312
+ exiting: false
7313
+ });
7314
+ }
7315
+ }
7316
+ }
7317
+ function graphEntries(value) {
7318
+ const properties = regexGuestProperties.get(value);
7319
+ if (properties !== void 0) return Reflect.ownKeys(properties).flatMap((key) => {
7320
+ const descriptor = Object.getOwnPropertyDescriptor(properties, key);
7321
+ return "value" in descriptor ? [[`.${String(key)}`, descriptor.value]] : [];
7322
+ });
7323
+ if (isSandboxBox(value)) return boxedDataProperties(value).map(([key, descriptor]) => [`.${key}`, descriptor.value]);
7324
+ if (isSandboxArguments(value)) {
7325
+ return getSandboxArgumentEntries(value).map(([key, entry]) => [`.${key}`, entry]);
7326
+ }
7327
+ const map = isSandboxMap(value) ? value.entries : value instanceof Map ? value : void 0;
7328
+ if (map !== void 0) {
7329
+ return [...map.entries()].flatMap(([key, entry], index) => [
7330
+ [`.<map>[${index}].key`, key],
7331
+ [`.<map>[${index}].value`, entry]
7332
+ ]);
7333
+ }
7334
+ const set = isSandboxSet(value) ? value.values : value instanceof Set ? value : void 0;
7335
+ if (set !== void 0) {
7336
+ return [...set.values()].map((entry, index) => [`.<set>[${index}]`, entry]);
7337
+ }
7338
+ const entries = [];
7339
+ if (isSandboxCollectionIterator(value)) entries.push([".<collection>", collectionIteratorState(value).collection]);
7340
+ if (isSandboxRegExpIterator(value)) entries.push([".<matcher>", regexpIteratorState(value).matcher]);
7341
+ for (const key of Object.keys(value)) {
7342
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
7343
+ if (descriptor !== void 0 && "value" in descriptor)
7344
+ entries.push([Array.isArray(value) ? `[${key}]` : `.${key}`, descriptor.value]);
7345
+ }
7346
+ return entries;
7347
+ }
7348
+
7349
+ // packages/safe-js/src/interp/symbols.ts
7350
+ var wellKnownSymbols = Object.freeze({
7351
+ iterator: Symbol.iterator,
7352
+ asyncIterator: Symbol.asyncIterator,
7353
+ hasInstance: Symbol.hasInstance,
7354
+ isConcatSpreadable: Symbol.isConcatSpreadable,
7355
+ match: Symbol.match,
7356
+ matchAll: Symbol.matchAll,
7357
+ replace: Symbol.replace,
7358
+ search: Symbol.search,
7359
+ species: Symbol.species,
7360
+ split: Symbol.split,
7361
+ toPrimitive: Symbol.toPrimitive,
7362
+ toStringTag: Symbol.toStringTag,
7363
+ unscopables: Symbol.unscopables
7364
+ });
7365
+
7366
+ // packages/safe-js/src/interp/intrinsics.ts
7367
+ var identities = /* @__PURE__ */ new WeakMap();
7368
+ var realms2 = /* @__PURE__ */ new WeakMap();
7369
+ function registerBuiltinIdentities(budget, bindings) {
7370
+ let realm = realms2.get(budget);
7371
+ if (realm === void 0) realms2.set(budget, realm = /* @__PURE__ */ new Map());
7372
+ const pending = Object.entries(bindings).map(([name, value]) => [[name], value]);
7373
+ const visited = /* @__PURE__ */ new WeakSet();
7374
+ for (let index = 0; index < pending.length; index++) {
7375
+ const [path, value] = pending[index];
7376
+ if (value === null || typeof value !== "object") continue;
7377
+ const id = JSON.stringify(path);
7378
+ const previous = realm.get(id);
7379
+ if (previous !== void 0 && previous !== value)
7380
+ throw new TypeError(`Duplicate intrinsic identity: ${id}`);
7381
+ realm.set(id, value);
7382
+ if (!identities.has(value)) identities.set(value, id);
7383
+ if (visited.has(value)) continue;
7384
+ visited.add(value);
7385
+ const owner = isSandboxClosure(value) ? value.properties : value;
7386
+ if (owner === void 0) continue;
7387
+ for (const key of Reflect.ownKeys(owner)) {
7388
+ if (typeof key === "symbol" && internalSymbols.has(key)) continue;
7389
+ const descriptor = Object.getOwnPropertyDescriptor(owner, key);
7390
+ const symbolName = typeof key === "symbol" ? Object.entries(wellKnownSymbols).find(([, symbol]) => symbol === key)?.[0] : void 0;
7391
+ if (typeof key === "symbol" && symbolName === void 0)
7392
+ throw new TypeError("Intrinsic symbol keys must be well-known symbols.");
7393
+ const member = [...path, typeof key === "string" ? key : { symbol: symbolName }];
7394
+ if ("value" in descriptor) pending.push([member, descriptor.value]);
7395
+ for (const kind of ["get", "set"]) {
7396
+ const closure = accessorClosure(descriptor[kind]);
7397
+ if (closure !== void 0) pending.push([[...member, kind], closure]);
7398
+ }
7399
+ }
7400
+ }
7401
+ }
7402
+ function getIntrinsicIdentity(value) {
7403
+ return identities.get(value);
7404
+ }
7405
+ function resolveIntrinsicIdentity(budget, id) {
7406
+ const value = realms2.get(budget)?.get(id);
7407
+ if (value === void 0) throw new TypeError(`Unknown intrinsic identity: ${id}`);
7408
+ return value;
7409
+ }
7410
+ function listIntrinsicIdentities(budget) {
7411
+ return [...realms2.get(budget)?.keys() ?? []];
7412
+ }
7413
+ function releaseIntrinsicIdentities(budget) {
7414
+ realms2.delete(budget);
7415
+ }
7416
+
7214
7417
  // packages/safe-js/src/interp/host-capabilities.ts
7215
7418
  import { types as types4 } from "node:util";
7216
7419
  var MAX_INDEXED_LENGTH = 65536;
@@ -7555,491 +7758,46 @@ function namedKeys(state) {
7555
7758
  });
7556
7759
  }
7557
7760
 
7558
- // packages/safe-js/src/interp/values.ts
7559
- import { types as nodeTypes } from "node:util";
7560
-
7561
- // packages/safe-js/src/interp/promise-tracker.ts
7562
- import { AsyncLocalStorage } from "node:async_hooks";
7563
- var SandboxPromiseRejectionTracker = class {
7564
- records = /* @__PURE__ */ new Set();
7565
- recordsByPromise = /* @__PURE__ */ new WeakMap();
7566
- fatalRejection;
7567
- fatalWaiters = /* @__PURE__ */ new Set();
7568
- get failure() {
7569
- return this.fatalRejection;
7570
- }
7571
- onFatalRejection(interrupt) {
7572
- if (this.fatalRejection === void 0) this.fatalWaiters.add(interrupt);
7573
- else interrupt(this.fatalRejection);
7574
- return () => this.fatalWaiters.delete(interrupt);
7575
- }
7576
- interruptOnFatalRejection(pending) {
7577
- return new Promise((resolve, reject) => {
7578
- const detach = this.onFatalRejection(reject);
7579
- pending.then(
7580
- (value) => {
7581
- detach();
7582
- resolve(value);
7583
- },
7584
- (reason) => {
7585
- detach();
7586
- reject(reason);
7587
- }
7588
- );
7589
- });
7590
- }
7591
- observe(promise) {
7592
- const record3 = this.recordsByPromise.get(promise);
7593
- if (record3 !== void 0) {
7594
- record3.observed = true;
7595
- }
7596
- }
7597
- track(promise, outcome) {
7598
- const existing = this.recordsByPromise.get(promise);
7599
- if (existing !== void 0 && outcome === void 0) {
7600
- return;
7601
- }
7602
- const record3 = existing ?? {
7603
- observed: false,
7604
- promise,
7605
- rejected: false
7606
- };
7607
- this.records.add(record3);
7608
- this.recordsByPromise.set(promise, record3);
7609
- const pending = outcome ?? promise.promise;
7610
- pending.then(
7611
- () => void 0,
7612
- (reason) => {
7613
- if (this.fatalRejection === void 0 && reason instanceof SandboxError && (reason.code === "budgetExceeded" || reason.code === "reentry")) {
7614
- this.fatalRejection = reason;
7615
- for (const interrupt of this.fatalWaiters) interrupt(reason);
7616
- this.fatalWaiters.clear();
7617
- }
7618
- if (record3.rejected) return;
7619
- record3.rejected = true;
7620
- record3.rejectionReason = reason;
7621
- }
7622
- );
7623
- pending.catch(() => void 0);
7624
- }
7625
- async findUnhandledRejection() {
7626
- await flushPromiseJobs();
7627
- if (this.fatalRejection !== void 0) throw this.fatalRejection;
7628
- for (const record3 of this.records) {
7629
- if (record3.rejected && !record3.observed) {
7630
- return {
7631
- reason: record3.rejectionReason,
7632
- span: record3.promise.span
7633
- };
7634
- }
7635
- }
7636
- return void 0;
7637
- }
7638
- };
7639
- var activePromiseTracker = new AsyncLocalStorage();
7640
- var fatalRejectionCleanup = new AsyncLocalStorage();
7641
- function assertPromiseExecutionAllowed() {
7642
- const failure = activePromiseTracker.getStore()?.failure;
7643
- if (failure !== void 0 && fatalRejectionCleanup.getStore() !== true) throw failure;
7644
- }
7645
- function onFatalPromiseRejection(interrupt) {
7646
- if (fatalRejectionCleanup.getStore() === true) return void 0;
7647
- return activePromiseTracker.getStore()?.onFatalRejection(interrupt);
7648
- }
7649
- function interruptOnFatalPromiseRejection(pending) {
7650
- if (fatalRejectionCleanup.getStore() === true) return pending;
7651
- return activePromiseTracker.getStore()?.interruptOnFatalRejection(pending) ?? pending;
7652
- }
7653
- function withFatalPromiseCleanup(callback) {
7654
- return fatalRejectionCleanup.run(true, callback);
7655
- }
7656
- function createSandboxPromiseRejectionTracker() {
7657
- return new SandboxPromiseRejectionTracker();
7658
- }
7659
- function observeSandboxPromise(promise) {
7660
- activePromiseTracker.getStore()?.observe(promise);
7661
- }
7662
- function trackSandboxPromise(promise, outcome) {
7663
- activePromiseTracker.getStore()?.track(promise, outcome);
7664
- }
7665
- function withSandboxPromiseRejectionTracker(tracker, callback) {
7666
- return activePromiseTracker.run(tracker, callback);
7667
- }
7668
- async function flushPromiseJobs() {
7669
- for (let index = 0; index < 20; index += 1) {
7670
- await Promise.resolve();
7671
- }
7672
- }
7673
-
7674
- // packages/safe-js/src/interp/promise-replay.ts
7675
- import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
7676
-
7677
- // packages/safe-js/src/snapshot/bigint.ts
7678
- function validateBigIntData(value) {
7679
- if (typeof value !== "string" || value.length === 0) throw new TypeError("Invalid BigInt snapshot value.");
7680
- if (value === "0") return;
7681
- const start = value[0] === "-" ? 1 : 0;
7682
- if (start === value.length || value[start] === "0") throw new TypeError("Invalid BigInt snapshot value.");
7683
- for (let index = start; index < value.length; index++) {
7684
- const code = value.charCodeAt(index);
7685
- if (code < 48 || code > 57) throw new TypeError("Invalid BigInt snapshot value.");
7686
- }
7687
- }
7688
-
7689
- // packages/safe-js/src/interp/symbols.ts
7690
- var wellKnownSymbols = Object.freeze({
7691
- iterator: Symbol.iterator,
7692
- asyncIterator: Symbol.asyncIterator,
7693
- hasInstance: Symbol.hasInstance,
7694
- isConcatSpreadable: Symbol.isConcatSpreadable,
7695
- match: Symbol.match,
7696
- matchAll: Symbol.matchAll,
7697
- replace: Symbol.replace,
7698
- search: Symbol.search,
7699
- species: Symbol.species,
7700
- split: Symbol.split,
7701
- toPrimitive: Symbol.toPrimitive,
7702
- toStringTag: Symbol.toStringTag,
7703
- unscopables: Symbol.unscopables
7704
- });
7705
-
7706
- // packages/safe-js/src/snapshot/symbols.ts
7707
- function symbolData(value) {
7708
- const wellKnown = Object.keys(wellKnownSymbols).find((key) => wellKnownSymbols[key] === value);
7709
- return {
7710
- kind: "symbol",
7711
- ...wellKnown === void 0 ? value.description === void 0 ? {} : { description: value.description } : { wellKnown }
7712
- };
7713
- }
7714
- function serializeSymbol(value, heapIds, heap) {
7715
- let id = heapIds.get(value);
7716
- if (id === void 0) {
7717
- id = heapIds.size + 1;
7718
- heapIds.set(value, id);
7719
- heap[String(id)] = symbolData(value);
7720
- }
7721
- return { kind: "ref", id };
7722
- }
7723
- function ownSerializableSymbolKeys(value) {
7724
- return Object.getOwnPropertySymbols(value).filter((key) => !internalSymbols.has(key));
7725
- }
7726
- function serializeSymbolProperties(value, encode) {
7727
- return ownSerializableSymbolKeys(value).map((key) => {
7728
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
7729
- if (!("value" in descriptor)) throw new TypeError("Symbol accessor properties cannot be serialized.");
7730
- return [encode(key), { value: encode(descriptor.value), enumerable: descriptor.enumerable === true, writable: descriptor.writable === true, configurable: descriptor.configurable === true }];
7731
- });
7732
- }
7733
- function restoreSymbolProperties(target, entries, decode) {
7734
- for (const [key, descriptor] of entries ?? []) {
7735
- const symbol = decode(key);
7736
- if (typeof symbol !== "symbol") throw new TypeError("Expected a symbol property key");
7737
- Object.defineProperty(target, symbol, { ...descriptor, value: decode(descriptor.value) });
7738
- }
7739
- }
7740
-
7741
- // packages/safe-js/src/snapshot/regexp-properties.ts
7742
- function hasCustomRegexProperties(value) {
7743
- const properties = getRegexProperties(value);
7744
- return Reflect.ownKeys(properties).length !== 1 || !Object.isExtensible(properties) || Object.getOwnPropertyDescriptor(properties, "lastIndex")?.writable !== true;
7745
- }
7746
- function serializeRegexProperties(value, encode) {
7747
- if (!hasCustomRegexProperties(value)) return {};
7748
- const source = getRegexProperties(value);
7749
- const properties = /* @__PURE__ */ Object.create(null);
7750
- for (const key of Object.getOwnPropertyNames(source)) {
7751
- const descriptor = Object.getOwnPropertyDescriptor(source, key);
7752
- if (!("value" in descriptor)) throw new TypeError("RegExp accessor properties cannot be serialized as data.");
7753
- properties[key] = {
7754
- value: encode(descriptor.value),
7755
- enumerable: descriptor.enumerable === true,
7756
- configurable: descriptor.configurable === true,
7757
- writable: descriptor.writable === true
7758
- };
7759
- }
7760
- const symbolEntries = serializeSymbolProperties(source, encode);
7761
- return {
7762
- properties,
7763
- ...symbolEntries.length === 0 ? {} : { symbolEntries },
7764
- ...Object.isExtensible(source) ? {} : { extensible: false }
7765
- };
7766
- }
7767
- function validateRegexProperties(data) {
7768
- const descriptor = (value) => {
7769
- if (typeof value !== "object" || value === null || Array.isArray(value) || !Object.hasOwn(value, "value") || !["enumerable", "configurable", "writable"].every((key) => Object.hasOwn(value, key) && typeof value[key] === "boolean") || Object.keys(value).some((key) => !["value", "enumerable", "configurable", "writable"].includes(key)))
7770
- throw new TypeError("Invalid RegExp data property descriptor.");
7771
- };
7772
- if (data.extensible !== void 0 && typeof data.extensible !== "boolean")
7773
- throw new TypeError("Invalid RegExp extensibility.");
7774
- if (data.properties !== void 0) {
7775
- if (typeof data.properties !== "object" || data.properties === null || Array.isArray(data.properties))
7776
- throw new TypeError("Invalid RegExp property data.");
7777
- for (const entry of Object.values(data.properties)) descriptor(entry);
7778
- }
7779
- if (data.symbolEntries !== void 0) {
7780
- if (!Array.isArray(data.symbolEntries)) throw new TypeError("Invalid RegExp symbol properties.");
7781
- for (const entry of data.symbolEntries) {
7782
- if (!Array.isArray(entry) || entry.length !== 2) throw new TypeError("Invalid RegExp symbol property.");
7783
- descriptor(entry[1]);
7784
- }
7785
- }
7786
- }
7787
- function restoreRegexProperties(value, data, decode) {
7788
- validateRegexProperties(data);
7789
- const properties = getRegexProperties(value);
7790
- for (const [key, descriptor] of Object.entries(data.properties ?? {}))
7791
- Object.defineProperty(properties, key, { ...descriptor, value: decode(descriptor.value) });
7792
- restoreSymbolProperties(properties, data.symbolEntries, decode);
7793
- if (data.extensible === false) Object.preventExtensions(properties);
7794
- }
7795
-
7796
- // packages/safe-js/src/snapshot/validation.ts
7797
- import { types as types6 } from "node:util";
7798
-
7799
- // packages/safe-js/src/interp/arguments.ts
7800
- var sandboxArgumentsBrand = /* @__PURE__ */ Symbol("SandboxArguments");
7801
- internalSymbols.add(sandboxArgumentsBrand);
7802
- function createSandboxArguments(values) {
7803
- const result = /* @__PURE__ */ (function() {
7804
- return arguments;
7805
- })();
7806
- for (let index = 0; index < values.length; index += 1) {
7807
- result[index] = values[index];
7808
- }
7809
- result.length = values.length;
7810
- Object.defineProperty(result, sandboxArgumentsBrand, { value: true });
7811
- return result;
7812
- }
7813
- function isSandboxArguments(value) {
7814
- return typeof value === "object" && value !== null && Object.hasOwn(value, sandboxArgumentsBrand);
7815
- }
7816
- function getSandboxArgumentEntries(value) {
7817
- return Object.entries(Object.getOwnPropertyDescriptors(value)).flatMap(
7818
- ([key, descriptor]) => "value" in descriptor ? [[key, descriptor.value]] : []
7819
- );
7820
- }
7821
- function copySandboxArgumentProperties(source, target, copyValue) {
7822
- const names = Object.getOwnPropertyNames(source);
7823
- if (!names.includes("length") || names.indexOf("length") > names.indexOf("callee")) {
7824
- Reflect.deleteProperty(target, "length");
7825
- }
7826
- for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(source))) {
7827
- if (!("value" in descriptor)) {
7828
- if (key !== "callee") throw new TypeError(`Cannot copy arguments accessor '${key}'.`);
7829
- continue;
7830
- }
7831
- Object.defineProperty(target, key, { ...descriptor, value: copyValue(descriptor.value, key) });
7832
- }
7833
- const iterator = Object.getOwnPropertyDescriptor(source, Symbol.iterator);
7834
- if (iterator === void 0) {
7835
- Reflect.deleteProperty(target, Symbol.iterator);
7836
- } else {
7837
- if (iterator.value !== Array.prototype.values) {
7838
- throw new TypeError("Cannot copy a replaced arguments iterator.");
7839
- }
7840
- Object.defineProperty(target, Symbol.iterator, iterator);
7841
- }
7842
- if (!Object.isExtensible(source)) Object.preventExtensions(target);
7843
- }
7844
-
7845
- // packages/safe-js/src/graph-depth.ts
7846
- var MAX_DATA_DEPTH = 1024;
7847
- var SnapshotBudgetError = class extends Error {
7848
- code = "budgetExceeded";
7849
- budget = "dataDepth";
7850
- current;
7851
- limit;
7852
- path;
7853
- constructor(path, current, limit = MAX_DATA_DEPTH) {
7854
- super(`Snapshot budget exceeded for dataDepth at ${path}: ${current} > ${limit}.`);
7855
- this.name = "SnapshotBudgetError";
7856
- this.current = current;
7857
- this.limit = limit;
7858
- this.path = path;
7859
- replaceErrorStack(this);
7860
- }
7861
- };
7862
- function assertSandboxDataDepth(depth) {
7863
- if (depth > MAX_DATA_DEPTH) {
7864
- throw new SandboxError({ budget: "dataDepth", current: depth, limit: MAX_DATA_DEPTH });
7865
- }
7866
- }
7867
- function assertSnapshotDataDepth(depth, path) {
7868
- if (depth > MAX_DATA_DEPTH) throw new SnapshotBudgetError(path, depth);
7869
- }
7870
- function assertSnapshotGraphDepth(value, rootPath = "$") {
7871
- walkGraphDepth(value, rootPath, (depth, path) => assertSnapshotDataDepth(depth, path));
7872
- }
7873
- function assertSandboxGraphDepth(value) {
7874
- walkGraphDepth(value, "<root>", (depth) => assertSandboxDataDepth(depth));
7875
- }
7876
- function walkGraphDepth(root, rootPath, assertDepth) {
7877
- const ancestors = /* @__PURE__ */ new WeakSet();
7878
- const stack = [{ value: root, path: rootPath, depth: 0, exiting: false }];
7879
- while (stack.length > 0) {
7880
- const frame = stack.pop();
7881
- if (typeof frame.value !== "object" || frame.value === null) continue;
7882
- if (frame.exiting) {
7883
- ancestors.delete(frame.value);
7884
- continue;
7885
- }
7886
- assertDepth(frame.depth, frame.path);
7887
- if (ancestors.has(frame.value)) continue;
7888
- ancestors.add(frame.value);
7889
- stack.push({ ...frame, exiting: true });
7890
- const entries = graphEntries(frame.value);
7891
- for (let index = entries.length - 1; index >= 0; index -= 1) {
7892
- const [key, entry] = entries[index];
7893
- stack.push({
7894
- value: entry,
7895
- path: `${frame.path}${key}`,
7896
- depth: frame.depth + 1,
7897
- exiting: false
7898
- });
7899
- }
7900
- }
7901
- }
7902
- function graphEntries(value) {
7903
- const properties = regexGuestProperties.get(value);
7904
- if (properties !== void 0) return Reflect.ownKeys(properties).flatMap((key) => {
7905
- const descriptor = Object.getOwnPropertyDescriptor(properties, key);
7906
- return "value" in descriptor ? [[`.${String(key)}`, descriptor.value]] : [];
7907
- });
7908
- if (isSandboxBox(value)) return boxedDataProperties(value).map(([key, descriptor]) => [`.${key}`, descriptor.value]);
7909
- if (isSandboxArguments(value)) {
7910
- return getSandboxArgumentEntries(value).map(([key, entry]) => [`.${key}`, entry]);
7911
- }
7912
- const map = isSandboxMap(value) ? value.entries : value instanceof Map ? value : void 0;
7913
- if (map !== void 0) {
7914
- return [...map.entries()].flatMap(([key, entry], index) => [
7915
- [`.<map>[${index}].key`, key],
7916
- [`.<map>[${index}].value`, entry]
7917
- ]);
7918
- }
7919
- const set = isSandboxSet(value) ? value.values : value instanceof Set ? value : void 0;
7920
- if (set !== void 0) {
7921
- return [...set.values()].map((entry, index) => [`.<set>[${index}]`, entry]);
7922
- }
7923
- const entries = [];
7924
- if (isSandboxCollectionIterator(value)) entries.push([".<collection>", collectionIteratorState(value).collection]);
7925
- if (isSandboxRegExpIterator(value)) entries.push([".<matcher>", regexpIteratorState(value).matcher]);
7926
- for (const key of Object.keys(value)) {
7927
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
7928
- if (descriptor !== void 0 && "value" in descriptor)
7929
- entries.push([Array.isArray(value) ? `[${key}]` : `.${key}`, descriptor.value]);
7930
- }
7931
- return entries;
7932
- }
7933
-
7934
- // packages/safe-js/src/interp/closure-origin.ts
7935
- var origins = /* @__PURE__ */ new WeakMap();
7936
- var generatorOrigins = /* @__PURE__ */ new WeakMap();
7937
- function registerClosureOrigin(closure, node, context) {
7938
- origins.set(closure, { node, scope: context.scope, environment: context.functionEnvironment });
7939
- }
7940
- function getClosureOrigin(value) {
7941
- return origins.get(value);
7942
- }
7943
- function registerGeneratorOrigin(generator, node, scope, context) {
7944
- const origin = { node, scope, closureScope: context.scope, environment: context.functionEnvironment };
7945
- generatorOrigins.set(generator, origin);
7946
- return origin;
7947
- }
7948
- function getGeneratorOrigin(value) {
7949
- return generatorOrigins.get(value);
7950
- }
7951
-
7952
- // packages/safe-js/src/interp/intrinsics.ts
7953
- var identities = /* @__PURE__ */ new WeakMap();
7954
- var realms2 = /* @__PURE__ */ new WeakMap();
7955
- function registerBuiltinIdentities(budget, bindings) {
7956
- let realm = realms2.get(budget);
7957
- if (realm === void 0) realms2.set(budget, realm = /* @__PURE__ */ new Map());
7958
- const pending = Object.entries(bindings).map(([name, value]) => [[name], value]);
7959
- const visited = /* @__PURE__ */ new WeakSet();
7960
- for (let index = 0; index < pending.length; index++) {
7961
- const [path, value] = pending[index];
7962
- if (value === null || typeof value !== "object") continue;
7963
- const id = JSON.stringify(path);
7964
- const previous = realm.get(id);
7965
- if (previous !== void 0 && previous !== value)
7966
- throw new TypeError(`Duplicate intrinsic identity: ${id}`);
7967
- realm.set(id, value);
7968
- if (!identities.has(value)) identities.set(value, id);
7969
- if (visited.has(value)) continue;
7970
- visited.add(value);
7971
- const owner = isSandboxClosure(value) ? value.properties : value;
7972
- if (owner === void 0) continue;
7973
- for (const key of Reflect.ownKeys(owner)) {
7974
- if (typeof key === "symbol" && internalSymbols.has(key)) continue;
7975
- const descriptor = Object.getOwnPropertyDescriptor(owner, key);
7976
- const symbolName = typeof key === "symbol" ? Object.entries(wellKnownSymbols).find(([, symbol]) => symbol === key)?.[0] : void 0;
7977
- if (typeof key === "symbol" && symbolName === void 0)
7978
- throw new TypeError("Intrinsic symbol keys must be well-known symbols.");
7979
- const member = [...path, typeof key === "string" ? key : { symbol: symbolName }];
7980
- if ("value" in descriptor) pending.push([member, descriptor.value]);
7981
- for (const kind of ["get", "set"]) {
7982
- const closure = accessorClosure(descriptor[kind]);
7983
- if (closure !== void 0) pending.push([[...member, kind], closure]);
7984
- }
7985
- }
7986
- }
7987
- }
7988
- function getIntrinsicIdentity(value) {
7989
- return identities.get(value);
7990
- }
7991
- function resolveIntrinsicIdentity(budget, id) {
7992
- const value = realms2.get(budget)?.get(id);
7993
- if (value === void 0) throw new TypeError(`Unknown intrinsic identity: ${id}`);
7994
- return value;
7995
- }
7996
- function listIntrinsicIdentities(budget) {
7997
- return [...realms2.get(budget)?.keys() ?? []];
7998
- }
7999
- function releaseIntrinsicIdentities(budget) {
8000
- realms2.delete(budget);
8001
- }
8002
-
8003
- // packages/safe-js/src/interp/object-model.ts
8004
- var guestClosures = /* @__PURE__ */ new WeakSet();
8005
- var functionProperties = /* @__PURE__ */ new WeakMap();
8006
- var prototypes = /* @__PURE__ */ new WeakMap();
8007
- var intrinsicPrototypes = /* @__PURE__ */ new WeakMap();
8008
- var boxedPrototypes = /* @__PURE__ */ new WeakMap();
8009
- var regexPrototypes = /* @__PURE__ */ new WeakMap();
8010
- var initialRegexDescriptors = /* @__PURE__ */ new WeakMap();
8011
- var intrinsicPrototypeRoots = /* @__PURE__ */ new WeakMap();
8012
- var intrinsicConstructors = /* @__PURE__ */ new WeakMap();
8013
- var intrinsicFunctions = /* @__PURE__ */ new WeakSet();
8014
- var initialBoxedMethods = /* @__PURE__ */ new WeakMap();
8015
- var descriptorObjects = /* @__PURE__ */ new WeakSet();
8016
- function registerGuestClosure(closure) {
8017
- guestClosures.add(closure);
8018
- }
8019
- function isGuestClosure(value) {
8020
- return typeof value === "object" && value !== null && guestClosures.has(value);
8021
- }
8022
- function getGuestFunctionProperties(closure) {
8023
- return functionProperties.get(closure);
8024
- }
8025
- function materializeFunctionProperties(closure) {
8026
- if (!isGuestClosure(closure)) throw new TypeError("Host function properties are read only.");
8027
- const existing = functionProperties.get(closure);
8028
- if (existing !== void 0) return existing;
8029
- const properties = /* @__PURE__ */ Object.create(null);
8030
- Object.defineProperties(properties, {
8031
- length: { value: closure.length ?? 0, configurable: true },
8032
- name: { value: closure.name ?? "", configurable: true }
8033
- });
8034
- if (closure.construct !== void 0 && closure.boundTarget === void 0) {
8035
- const prototype = /* @__PURE__ */ Object.create(null);
8036
- Object.defineProperty(prototype, "constructor", {
8037
- value: closure,
8038
- writable: true,
8039
- configurable: true
8040
- });
8041
- descriptorObjects.add(prototype);
8042
- Object.defineProperty(properties, "prototype", { value: prototype, writable: true });
7761
+ // packages/safe-js/src/interp/object-model.ts
7762
+ var guestClosures = /* @__PURE__ */ new WeakSet();
7763
+ var functionProperties = /* @__PURE__ */ new WeakMap();
7764
+ var prototypes = /* @__PURE__ */ new WeakMap();
7765
+ var intrinsicPrototypes = /* @__PURE__ */ new WeakMap();
7766
+ var boxedPrototypes = /* @__PURE__ */ new WeakMap();
7767
+ var regexPrototypes = /* @__PURE__ */ new WeakMap();
7768
+ var initialRegexDescriptors = /* @__PURE__ */ new WeakMap();
7769
+ var intrinsicPrototypeRoots = /* @__PURE__ */ new WeakMap();
7770
+ var intrinsicConstructors = /* @__PURE__ */ new WeakMap();
7771
+ var intrinsicFunctions = /* @__PURE__ */ new WeakSet();
7772
+ var initialBoxedMethods = /* @__PURE__ */ new WeakMap();
7773
+ var descriptorObjects = /* @__PURE__ */ new WeakSet();
7774
+ function registerGuestClosure(closure) {
7775
+ guestClosures.add(closure);
7776
+ }
7777
+ function isGuestClosure(value) {
7778
+ return typeof value === "object" && value !== null && guestClosures.has(value);
7779
+ }
7780
+ function getGuestFunctionProperties(closure) {
7781
+ return functionProperties.get(closure);
7782
+ }
7783
+ function materializeFunctionProperties(closure) {
7784
+ if (!isGuestClosure(closure)) throw new TypeError("Host function properties are read only.");
7785
+ const existing = functionProperties.get(closure);
7786
+ if (existing !== void 0) return existing;
7787
+ const properties = /* @__PURE__ */ Object.create(null);
7788
+ Object.defineProperties(properties, {
7789
+ length: { value: closure.length ?? 0, configurable: true },
7790
+ name: { value: closure.name ?? "", configurable: true }
7791
+ });
7792
+ if (closure.construct !== void 0 && closure.boundTarget === void 0) {
7793
+ const prototype = /* @__PURE__ */ Object.create(null);
7794
+ Object.defineProperty(prototype, "constructor", {
7795
+ value: closure,
7796
+ writable: true,
7797
+ configurable: true
7798
+ });
7799
+ descriptorObjects.add(prototype);
7800
+ Object.defineProperty(properties, "prototype", { value: prototype, writable: true });
8043
7801
  }
8044
7802
  descriptorObjects.add(properties);
8045
7803
  functionProperties.set(closure, properties);
@@ -8139,117 +7897,376 @@ function trackIntrinsicState(budget, root, owner, targets) {
8139
7897
  ])
8140
7898
  );
8141
7899
  }
8142
- function releaseObjectPrototype(budget) {
8143
- releaseTemplateObjects(budget);
8144
- releaseIntrinsicIdentities(budget);
8145
- for (const prototype of intrinsicPrototypeRoots.get(budget) ?? []) budget.setRetainedValues(prototype, void 0);
8146
- intrinsicPrototypeRoots.delete(budget);
8147
- boxedPrototypes.delete(budget);
8148
- regexPrototypes.delete(budget);
8149
- initialRegexDescriptors.delete(budget);
8150
- intrinsicPrototypes.delete(budget);
7900
+ function releaseObjectPrototype(budget) {
7901
+ releaseTemplateObjects(budget);
7902
+ releaseIntrinsicIdentities(budget);
7903
+ for (const prototype of intrinsicPrototypeRoots.get(budget) ?? []) budget.setRetainedValues(prototype, void 0);
7904
+ intrinsicPrototypeRoots.delete(budget);
7905
+ boxedPrototypes.delete(budget);
7906
+ regexPrototypes.delete(budget);
7907
+ initialRegexDescriptors.delete(budget);
7908
+ intrinsicPrototypes.delete(budget);
7909
+ }
7910
+ function getSandboxPrototype(value, budget) {
7911
+ if (prototypes.has(value)) return prototypes.get(value) ?? null;
7912
+ if (budget !== void 0 && isSandboxRegex(value)) return regexPrototypes.get(budget) ?? null;
7913
+ if (budget !== void 0 && isSandboxBox(value)) {
7914
+ const prototype = getBoxedPrototype(boxedValue(value), budget);
7915
+ if (prototype !== void 0 && prototype !== value) return prototype;
7916
+ }
7917
+ return budget !== void 0 && !isSandboxClosure(value) && isPrototypeRecord(value) ? intrinsicPrototypes.get(budget) ?? null : null;
7918
+ }
7919
+ function hasExplicitSandboxPrototype(value) {
7920
+ return prototypes.has(value);
7921
+ }
7922
+ function hasNullObjectPrototype(value) {
7923
+ return prototypes.get(value) === null && !Array.isArray(value) && !isSandboxClosure(value) && !isSandboxRegex(value);
7924
+ }
7925
+ function getSandboxPropertyDescriptor(value, key, budget) {
7926
+ const hostProperties = isSandboxClosure(value) ? value.properties : void 0;
7927
+ if (isSandboxClosure(value) && !isGuestClosure(value))
7928
+ return hostProperties === void 0 ? void 0 : Object.getOwnPropertyDescriptor(hostProperties, key);
7929
+ let current = value;
7930
+ let depth = 0;
7931
+ while (typeof current === "object" && current !== null && (Array.isArray(current) || isSandboxDate(current) || isSandboxRegex(current) || isPrototypeRecord(current))) {
7932
+ const properties = isGuestClosure(current) ? getGuestFunctionProperties(current) : isSandboxRegex(current) ? getRegexProperties(current) : current;
7933
+ const descriptor = properties === void 0 ? void 0 : Object.getOwnPropertyDescriptor(properties, key);
7934
+ if (descriptor !== void 0) return descriptor;
7935
+ current = getSandboxPrototype(current, budget);
7936
+ if (current !== null) {
7937
+ budget?.visitNode();
7938
+ assertSandboxDataDepth(++depth);
7939
+ }
7940
+ }
7941
+ return void 0;
7942
+ }
7943
+ function getSandboxDataProperty(value, key, budget) {
7944
+ let current = value;
7945
+ let depth = 0;
7946
+ while (typeof current === "object" && current !== null) {
7947
+ if (isGuestHostObject(current)) return typeof key === "symbol" ? void 0 : getHostObjectMember(current, String(key));
7948
+ if (isSandboxRegex(current)) return Object.getOwnPropertyDescriptor(getRegexProperties(current), key)?.value;
7949
+ if (isGuestClosure(current)) {
7950
+ const entry = getGuestFunctionProperty(current, key);
7951
+ if (entry !== void 0 || Object.hasOwn(current.properties ?? {}, key)) return entry;
7952
+ } else if (isSandboxClosure(current)) {
7953
+ const properties = current.properties;
7954
+ return properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0;
7955
+ }
7956
+ if (isSandboxMap(current) || isSandboxSet(current) || isSandboxPromise(current) || isSandboxRegex(current) || isSandboxGenerator(current))
7957
+ return void 0;
7958
+ if (!isSandboxClosure(current) && Object.hasOwn(current, key)) return current[key];
7959
+ current = getSandboxPrototype(current, budget);
7960
+ if (current !== null) {
7961
+ budget?.visitNode();
7962
+ assertSandboxDataDepth(++depth);
7963
+ }
7964
+ }
7965
+ return void 0;
7966
+ }
7967
+ function setSandboxPrototype(value, prototype, budget) {
7968
+ if (budget !== void 0 && intrinsicPrototypes.get(budget) === value && prototype !== null) {
7969
+ throw new TypeError("Object.prototype has an immutable null prototype.");
7970
+ }
7971
+ if (!Array.isArray(value) && !isSandboxRegex(value) && !isPrototypeRecord(value) || prototype !== null && !Array.isArray(prototype) && !isPrototypeRecord(prototype)) {
7972
+ throw new TypeError(
7973
+ "Prototype links require ordinary sandbox objects, arrays, or guest functions."
7974
+ );
7975
+ }
7976
+ if (prototypes.has(value) && getSandboxPrototype(value, budget) === prototype) return;
7977
+ if (!Object.isExtensible(isGuestClosure(value) ? materializeFunctionProperties(value) : isSandboxRegex(value) ? getRegexProperties(value) : value)) {
7978
+ throw new TypeError("Cannot change the prototype of a non-extensible object.");
7979
+ }
7980
+ let depth = 0;
7981
+ for (let current = prototype; current !== null; current = getSandboxPrototype(current, budget)) {
7982
+ budget?.visitNode();
7983
+ assertSandboxDataDepth(depth++);
7984
+ if (current === value) throw new TypeError("Cyclic prototype value.");
7985
+ }
7986
+ prototypes.set(value, prototype);
7987
+ }
7988
+ function isPrototypeRecord(value) {
7989
+ if (isGuestClosure(value)) return true;
7990
+ if (isGuestHostObject(value)) return false;
7991
+ if (isSandboxClosure(value) || isSandboxGenerator(value) || isSandboxMap(value) || isSandboxPromise(value) || isSandboxRegex(value) || isSandboxSet(value))
7992
+ return false;
7993
+ const prototype = Object.getPrototypeOf(value);
7994
+ return prototype === null || prototype === Object.prototype;
7995
+ }
7996
+ function markDescriptorObject(value) {
7997
+ descriptorObjects.add(value);
7998
+ }
7999
+ function hasManagedDescriptors(value) {
8000
+ return descriptorObjects.has(value);
8001
+ }
8002
+ function hasGuestObjectState(value) {
8003
+ const intrinsicUnchanged = intrinsicConstructors.get(value);
8004
+ if (intrinsicUnchanged !== void 0) return !intrinsicUnchanged();
8005
+ if (isLiveCapability(value)) return true;
8006
+ if (functionProperties.has(value) || prototypes.has(value) && !hasNullObjectPrototype(value)) return true;
8007
+ if (isSandboxBox(value) || isSandboxDate(value)) return false;
8008
+ return descriptorObjects.has(value) && Object.values(Object.getOwnPropertyDescriptors(value)).some(
8009
+ (descriptor) => !descriptor.enumerable || !descriptor.configurable || !descriptor.writable
8010
+ );
8011
+ }
8012
+
8013
+ // packages/safe-js/src/interp/raw-json.ts
8014
+ var rawJsonValues = /* @__PURE__ */ new WeakSet();
8015
+ function createRawJson(text) {
8016
+ if (text.length === 0 || text.trim() !== text) throw new SyntaxError("Invalid raw JSON text.");
8017
+ const parsed = JSON.parse(text);
8018
+ if (typeof parsed === "object" && parsed !== null) throw new SyntaxError("Raw JSON requires a primitive value.");
8019
+ const value = /* @__PURE__ */ Object.create(null);
8020
+ value.rawJSON = text;
8021
+ setSandboxPrototype(value, null);
8022
+ Object.freeze(value);
8023
+ rawJsonValues.add(value);
8024
+ return value;
8025
+ }
8026
+ function isRawJson(value) {
8027
+ return typeof value === "object" && value !== null && rawJsonValues.has(value);
8028
+ }
8029
+
8030
+ // packages/safe-js/src/interp/values.ts
8031
+ import { types as nodeTypes } from "node:util";
8032
+
8033
+ // packages/safe-js/src/interp/promise-tracker.ts
8034
+ import { AsyncLocalStorage } from "node:async_hooks";
8035
+ var SandboxPromiseRejectionTracker = class {
8036
+ records = /* @__PURE__ */ new Set();
8037
+ recordsByPromise = /* @__PURE__ */ new WeakMap();
8038
+ fatalRejection;
8039
+ fatalWaiters = /* @__PURE__ */ new Set();
8040
+ get failure() {
8041
+ return this.fatalRejection;
8042
+ }
8043
+ onFatalRejection(interrupt) {
8044
+ if (this.fatalRejection === void 0) this.fatalWaiters.add(interrupt);
8045
+ else interrupt(this.fatalRejection);
8046
+ return () => this.fatalWaiters.delete(interrupt);
8047
+ }
8048
+ interruptOnFatalRejection(pending) {
8049
+ return new Promise((resolve, reject) => {
8050
+ const detach = this.onFatalRejection(reject);
8051
+ pending.then(
8052
+ (value) => {
8053
+ detach();
8054
+ resolve(value);
8055
+ },
8056
+ (reason) => {
8057
+ detach();
8058
+ reject(reason);
8059
+ }
8060
+ );
8061
+ });
8062
+ }
8063
+ observe(promise) {
8064
+ const record3 = this.recordsByPromise.get(promise);
8065
+ if (record3 !== void 0) {
8066
+ record3.observed = true;
8067
+ }
8068
+ }
8069
+ track(promise, outcome) {
8070
+ const existing = this.recordsByPromise.get(promise);
8071
+ if (existing !== void 0 && outcome === void 0) {
8072
+ return;
8073
+ }
8074
+ const record3 = existing ?? {
8075
+ observed: false,
8076
+ promise,
8077
+ rejected: false
8078
+ };
8079
+ this.records.add(record3);
8080
+ this.recordsByPromise.set(promise, record3);
8081
+ const pending = outcome ?? promise.promise;
8082
+ pending.then(
8083
+ () => void 0,
8084
+ (reason) => {
8085
+ if (this.fatalRejection === void 0 && reason instanceof SandboxError && (reason.code === "budgetExceeded" || reason.code === "reentry")) {
8086
+ this.fatalRejection = reason;
8087
+ for (const interrupt of this.fatalWaiters) interrupt(reason);
8088
+ this.fatalWaiters.clear();
8089
+ }
8090
+ if (record3.rejected) return;
8091
+ record3.rejected = true;
8092
+ record3.rejectionReason = reason;
8093
+ }
8094
+ );
8095
+ pending.catch(() => void 0);
8096
+ }
8097
+ async findUnhandledRejection() {
8098
+ await flushPromiseJobs();
8099
+ if (this.fatalRejection !== void 0) throw this.fatalRejection;
8100
+ for (const record3 of this.records) {
8101
+ if (record3.rejected && !record3.observed) {
8102
+ return {
8103
+ reason: record3.rejectionReason,
8104
+ span: record3.promise.span
8105
+ };
8106
+ }
8107
+ }
8108
+ return void 0;
8109
+ }
8110
+ };
8111
+ var activePromiseTracker = new AsyncLocalStorage();
8112
+ var fatalRejectionCleanup = new AsyncLocalStorage();
8113
+ function assertPromiseExecutionAllowed() {
8114
+ const failure = activePromiseTracker.getStore()?.failure;
8115
+ if (failure !== void 0 && fatalRejectionCleanup.getStore() !== true) throw failure;
8116
+ }
8117
+ function onFatalPromiseRejection(interrupt) {
8118
+ if (fatalRejectionCleanup.getStore() === true) return void 0;
8119
+ return activePromiseTracker.getStore()?.onFatalRejection(interrupt);
8151
8120
  }
8152
- function getSandboxPrototype(value, budget) {
8153
- if (prototypes.has(value)) return prototypes.get(value) ?? null;
8154
- if (budget !== void 0 && isSandboxRegex(value)) return regexPrototypes.get(budget) ?? null;
8155
- if (budget !== void 0 && isSandboxBox(value)) {
8156
- const prototype = getBoxedPrototype(boxedValue(value), budget);
8157
- if (prototype !== void 0 && prototype !== value) return prototype;
8158
- }
8159
- return budget !== void 0 && !isSandboxClosure(value) && isPrototypeRecord(value) ? intrinsicPrototypes.get(budget) ?? null : null;
8121
+ function interruptOnFatalPromiseRejection(pending) {
8122
+ if (fatalRejectionCleanup.getStore() === true) return pending;
8123
+ return activePromiseTracker.getStore()?.interruptOnFatalRejection(pending) ?? pending;
8160
8124
  }
8161
- function hasExplicitSandboxPrototype(value) {
8162
- return prototypes.has(value);
8125
+ function withFatalPromiseCleanup(callback) {
8126
+ return fatalRejectionCleanup.run(true, callback);
8163
8127
  }
8164
- function hasNullObjectPrototype(value) {
8165
- return prototypes.get(value) === null && !Array.isArray(value) && !isSandboxClosure(value) && !isSandboxRegex(value);
8128
+ function createSandboxPromiseRejectionTracker() {
8129
+ return new SandboxPromiseRejectionTracker();
8166
8130
  }
8167
- function getSandboxPropertyDescriptor(value, key, budget) {
8168
- const hostProperties = isSandboxClosure(value) ? value.properties : void 0;
8169
- if (isSandboxClosure(value) && !isGuestClosure(value))
8170
- return hostProperties === void 0 ? void 0 : Object.getOwnPropertyDescriptor(hostProperties, key);
8171
- let current = value;
8172
- let depth = 0;
8173
- while (typeof current === "object" && current !== null && (Array.isArray(current) || isSandboxDate(current) || isSandboxRegex(current) || isPrototypeRecord(current))) {
8174
- const properties = isGuestClosure(current) ? getGuestFunctionProperties(current) : isSandboxRegex(current) ? getRegexProperties(current) : current;
8175
- const descriptor = properties === void 0 ? void 0 : Object.getOwnPropertyDescriptor(properties, key);
8176
- if (descriptor !== void 0) return descriptor;
8177
- current = getSandboxPrototype(current, budget);
8178
- if (current !== null) {
8179
- budget?.visitNode();
8180
- assertSandboxDataDepth(++depth);
8181
- }
8131
+ function observeSandboxPromise(promise) {
8132
+ activePromiseTracker.getStore()?.observe(promise);
8133
+ }
8134
+ function trackSandboxPromise(promise, outcome) {
8135
+ activePromiseTracker.getStore()?.track(promise, outcome);
8136
+ }
8137
+ function withSandboxPromiseRejectionTracker(tracker, callback) {
8138
+ return activePromiseTracker.run(tracker, callback);
8139
+ }
8140
+ async function flushPromiseJobs() {
8141
+ for (let index = 0; index < 20; index += 1) {
8142
+ await Promise.resolve();
8182
8143
  }
8183
- return void 0;
8184
8144
  }
8185
- function getSandboxDataProperty(value, key, budget) {
8186
- let current = value;
8187
- let depth = 0;
8188
- while (typeof current === "object" && current !== null) {
8189
- if (isGuestHostObject(current)) return typeof key === "symbol" ? void 0 : getHostObjectMember(current, String(key));
8190
- if (isSandboxRegex(current)) return Object.getOwnPropertyDescriptor(getRegexProperties(current), key)?.value;
8191
- if (isGuestClosure(current)) {
8192
- const entry = getGuestFunctionProperty(current, key);
8193
- if (entry !== void 0 || Object.hasOwn(current.properties ?? {}, key)) return entry;
8194
- } else if (isSandboxClosure(current)) {
8195
- const properties = current.properties;
8196
- return properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0;
8197
- }
8198
- if (isSandboxMap(current) || isSandboxSet(current) || isSandboxPromise(current) || isSandboxRegex(current) || isSandboxGenerator(current))
8199
- return void 0;
8200
- if (!isSandboxClosure(current) && Object.hasOwn(current, key)) return current[key];
8201
- current = getSandboxPrototype(current, budget);
8202
- if (current !== null) {
8203
- budget?.visitNode();
8204
- assertSandboxDataDepth(++depth);
8205
- }
8145
+
8146
+ // packages/safe-js/src/interp/promise-replay.ts
8147
+ import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
8148
+
8149
+ // packages/safe-js/src/snapshot/bigint.ts
8150
+ function validateBigIntData(value) {
8151
+ if (typeof value !== "string" || value.length === 0) throw new TypeError("Invalid BigInt snapshot value.");
8152
+ if (value === "0") return;
8153
+ const start = value[0] === "-" ? 1 : 0;
8154
+ if (start === value.length || value[start] === "0") throw new TypeError("Invalid BigInt snapshot value.");
8155
+ for (let index = start; index < value.length; index++) {
8156
+ const code = value.charCodeAt(index);
8157
+ if (code < 48 || code > 57) throw new TypeError("Invalid BigInt snapshot value.");
8206
8158
  }
8207
- return void 0;
8208
8159
  }
8209
- function setSandboxPrototype(value, prototype, budget) {
8210
- if (budget !== void 0 && intrinsicPrototypes.get(budget) === value && prototype !== null) {
8211
- throw new TypeError("Object.prototype has an immutable null prototype.");
8160
+
8161
+ // packages/safe-js/src/snapshot/symbols.ts
8162
+ function symbolData(value) {
8163
+ const wellKnown = Object.keys(wellKnownSymbols).find((key) => wellKnownSymbols[key] === value);
8164
+ return {
8165
+ kind: "symbol",
8166
+ ...wellKnown === void 0 ? value.description === void 0 ? {} : { description: value.description } : { wellKnown }
8167
+ };
8168
+ }
8169
+ function serializeSymbol(value, heapIds, heap) {
8170
+ let id = heapIds.get(value);
8171
+ if (id === void 0) {
8172
+ id = heapIds.size + 1;
8173
+ heapIds.set(value, id);
8174
+ heap[String(id)] = symbolData(value);
8212
8175
  }
8213
- if (!Array.isArray(value) && !isSandboxRegex(value) && !isPrototypeRecord(value) || prototype !== null && !Array.isArray(prototype) && !isPrototypeRecord(prototype)) {
8214
- throw new TypeError(
8215
- "Prototype links require ordinary sandbox objects, arrays, or guest functions."
8216
- );
8176
+ return { kind: "ref", id };
8177
+ }
8178
+ function ownSerializableSymbolKeys(value) {
8179
+ return Object.getOwnPropertySymbols(value).filter((key) => !internalSymbols.has(key));
8180
+ }
8181
+ function serializeSymbolProperties(value, encode) {
8182
+ return ownSerializableSymbolKeys(value).map((key) => {
8183
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
8184
+ if (!("value" in descriptor)) throw new TypeError("Symbol accessor properties cannot be serialized.");
8185
+ return [encode(key), { value: encode(descriptor.value), enumerable: descriptor.enumerable === true, writable: descriptor.writable === true, configurable: descriptor.configurable === true }];
8186
+ });
8187
+ }
8188
+ function restoreSymbolProperties(target, entries, decode) {
8189
+ for (const [key, descriptor] of entries ?? []) {
8190
+ const symbol = decode(key);
8191
+ if (typeof symbol !== "symbol") throw new TypeError("Expected a symbol property key");
8192
+ Object.defineProperty(target, symbol, { ...descriptor, value: decode(descriptor.value) });
8217
8193
  }
8218
- if (prototypes.has(value) && getSandboxPrototype(value, budget) === prototype) return;
8219
- if (!Object.isExtensible(isGuestClosure(value) ? materializeFunctionProperties(value) : isSandboxRegex(value) ? getRegexProperties(value) : value)) {
8220
- throw new TypeError("Cannot change the prototype of a non-extensible object.");
8194
+ }
8195
+
8196
+ // packages/safe-js/src/snapshot/regexp-properties.ts
8197
+ function hasCustomRegexProperties(value) {
8198
+ const properties = getRegexProperties(value);
8199
+ return Reflect.ownKeys(properties).length !== 1 || !Object.isExtensible(properties) || Object.getOwnPropertyDescriptor(properties, "lastIndex")?.writable !== true;
8200
+ }
8201
+ function serializeRegexProperties(value, encode) {
8202
+ if (!hasCustomRegexProperties(value)) return {};
8203
+ const source = getRegexProperties(value);
8204
+ const properties = /* @__PURE__ */ Object.create(null);
8205
+ for (const key of Object.getOwnPropertyNames(source)) {
8206
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
8207
+ if (!("value" in descriptor)) throw new TypeError("RegExp accessor properties cannot be serialized as data.");
8208
+ properties[key] = {
8209
+ value: encode(descriptor.value),
8210
+ enumerable: descriptor.enumerable === true,
8211
+ configurable: descriptor.configurable === true,
8212
+ writable: descriptor.writable === true
8213
+ };
8221
8214
  }
8222
- let depth = 0;
8223
- for (let current = prototype; current !== null; current = getSandboxPrototype(current, budget)) {
8224
- budget?.visitNode();
8225
- assertSandboxDataDepth(depth++);
8226
- if (current === value) throw new TypeError("Cyclic prototype value.");
8215
+ const symbolEntries = serializeSymbolProperties(source, encode);
8216
+ return {
8217
+ properties,
8218
+ ...symbolEntries.length === 0 ? {} : { symbolEntries },
8219
+ ...Object.isExtensible(source) ? {} : { extensible: false }
8220
+ };
8221
+ }
8222
+ function validateRegexProperties(data) {
8223
+ const descriptor = (value) => {
8224
+ if (typeof value !== "object" || value === null || Array.isArray(value) || !Object.hasOwn(value, "value") || !["enumerable", "configurable", "writable"].every((key) => Object.hasOwn(value, key) && typeof value[key] === "boolean") || Object.keys(value).some((key) => !["value", "enumerable", "configurable", "writable"].includes(key)))
8225
+ throw new TypeError("Invalid RegExp data property descriptor.");
8226
+ };
8227
+ if (data.extensible !== void 0 && typeof data.extensible !== "boolean")
8228
+ throw new TypeError("Invalid RegExp extensibility.");
8229
+ if (data.properties !== void 0) {
8230
+ if (typeof data.properties !== "object" || data.properties === null || Array.isArray(data.properties))
8231
+ throw new TypeError("Invalid RegExp property data.");
8232
+ for (const entry of Object.values(data.properties)) descriptor(entry);
8233
+ }
8234
+ if (data.symbolEntries !== void 0) {
8235
+ if (!Array.isArray(data.symbolEntries)) throw new TypeError("Invalid RegExp symbol properties.");
8236
+ for (const entry of data.symbolEntries) {
8237
+ if (!Array.isArray(entry) || entry.length !== 2) throw new TypeError("Invalid RegExp symbol property.");
8238
+ descriptor(entry[1]);
8239
+ }
8227
8240
  }
8228
- prototypes.set(value, prototype);
8229
8241
  }
8230
- function isPrototypeRecord(value) {
8231
- if (isGuestClosure(value)) return true;
8232
- if (isGuestHostObject(value)) return false;
8233
- if (isSandboxClosure(value) || isSandboxGenerator(value) || isSandboxMap(value) || isSandboxPromise(value) || isSandboxRegex(value) || isSandboxSet(value))
8234
- return false;
8235
- const prototype = Object.getPrototypeOf(value);
8236
- return prototype === null || prototype === Object.prototype;
8242
+ function restoreRegexProperties(value, data, decode) {
8243
+ validateRegexProperties(data);
8244
+ const properties = getRegexProperties(value);
8245
+ for (const [key, descriptor] of Object.entries(data.properties ?? {}))
8246
+ Object.defineProperty(properties, key, { ...descriptor, value: decode(descriptor.value) });
8247
+ restoreSymbolProperties(properties, data.symbolEntries, decode);
8248
+ if (data.extensible === false) Object.preventExtensions(properties);
8237
8249
  }
8238
- function markDescriptorObject(value) {
8239
- descriptorObjects.add(value);
8250
+
8251
+ // packages/safe-js/src/snapshot/validation.ts
8252
+ import { types as types6 } from "node:util";
8253
+
8254
+ // packages/safe-js/src/interp/closure-origin.ts
8255
+ var origins = /* @__PURE__ */ new WeakMap();
8256
+ var generatorOrigins = /* @__PURE__ */ new WeakMap();
8257
+ function registerClosureOrigin(closure, node, context) {
8258
+ origins.set(closure, { node, scope: context.scope, environment: context.functionEnvironment });
8240
8259
  }
8241
- function hasManagedDescriptors(value) {
8242
- return descriptorObjects.has(value);
8260
+ function getClosureOrigin(value) {
8261
+ return origins.get(value);
8243
8262
  }
8244
- function hasGuestObjectState(value) {
8245
- const intrinsicUnchanged = intrinsicConstructors.get(value);
8246
- if (intrinsicUnchanged !== void 0) return !intrinsicUnchanged();
8247
- if (isLiveCapability(value)) return true;
8248
- if (functionProperties.has(value) || prototypes.has(value) && !hasNullObjectPrototype(value)) return true;
8249
- if (isSandboxBox(value) || isSandboxDate(value)) return false;
8250
- return descriptorObjects.has(value) && Object.values(Object.getOwnPropertyDescriptors(value)).some(
8251
- (descriptor) => !descriptor.enumerable || !descriptor.configurable || !descriptor.writable
8252
- );
8263
+ function registerGeneratorOrigin(generator, node, scope, context) {
8264
+ const origin = { node, scope, closureScope: context.scope, environment: context.functionEnvironment };
8265
+ generatorOrigins.set(generator, origin);
8266
+ return origin;
8267
+ }
8268
+ function getGeneratorOrigin(value) {
8269
+ return generatorOrigins.get(value);
8253
8270
  }
8254
8271
 
8255
8272
  // packages/safe-js/src/interp/scope.ts
@@ -18733,6 +18750,8 @@ function encodeReplayData(value, options = {}) {
18733
18750
  id: capabilityId,
18734
18751
  properties: child(entry.properties, "properties")
18735
18752
  };
18753
+ } else if (isRawJson(entry)) {
18754
+ nodes[id] = { kind: "raw-json", text: entry.rawJSON };
18736
18755
  } else if (nativeBoxedValue(entry) !== void 0) {
18737
18756
  const properties = /* @__PURE__ */ Object.create(null);
18738
18757
  let symbolIndex = 0;
@@ -18969,6 +18988,13 @@ function decodeReplayData(input, options = {}, parent) {
18969
18988
  if (!node.extensible) Object.preventExtensions(result3);
18970
18989
  return result3;
18971
18990
  }
18991
+ if (kind === "raw-json") {
18992
+ if (Object.keys(node).some((key) => !["kind", "text"].includes(key)) || typeof own(node, "text") !== "string")
18993
+ throw new TypeError("Invalid replay raw JSON fields.");
18994
+ const result3 = createRawJson(own(node, "text"));
18995
+ restored.set(id, result3);
18996
+ return result3;
18997
+ }
18972
18998
  if (kind === "date") {
18973
18999
  if (Object.keys(node).some((key) => !["kind", "time", "properties", "symbolProperties", "extensible"].includes(key))) throw new TypeError("Invalid serialized Date fields.");
18974
19000
  if (node.extensible !== void 0 && typeof node.extensible !== "boolean") throw new TypeError("Invalid replay Date extensibility.");
@@ -21049,6 +21075,7 @@ function syncIterator(iterator) {
21049
21075
 
21050
21076
  // packages/safe-js/src/snapshot/guest-heap.ts
21051
21077
  function captureGuestHeapNode(value, encode) {
21078
+ if (isRawJson(value)) return { kind: "raw-json", text: value.rawJSON };
21052
21079
  const intrinsic = getIntrinsicIdentity(value);
21053
21080
  if (intrinsic !== void 0) {
21054
21081
  const state2 = captureObjectState(value, encode);
@@ -21685,6 +21712,22 @@ function createConsoleJsonGlobals(options) {
21685
21712
  const sink = options.sink ?? console;
21686
21713
  return {
21687
21714
  JSON: {
21715
+ rawJSON: createSandboxClosure({
21716
+ sandbox: true,
21717
+ name: "rawJSON",
21718
+ length: 1,
21719
+ call: async ([value], context) => {
21720
+ const text = await sandboxString(value, options.budget, context);
21721
+ options.budget.visitNode(text.length);
21722
+ return createRawJson(options.budget.allocateString(text));
21723
+ }
21724
+ }),
21725
+ isRawJSON: createSandboxClosure({
21726
+ sandbox: true,
21727
+ name: "isRawJSON",
21728
+ length: 1,
21729
+ call: ([value]) => isRawJson(value)
21730
+ }),
21688
21731
  parse: createSandboxClosure({
21689
21732
  sandbox: true,
21690
21733
  length: 2,
@@ -21839,6 +21882,7 @@ async function stringifyProperty(key, holder, state, indent = "") {
21839
21882
  }
21840
21883
  }
21841
21884
  async function stringifyValue(value, state, indent) {
21885
+ if (isRawJson(value)) return value.rawJSON;
21842
21886
  if (isSandboxBox(value)) {
21843
21887
  const primitive = boxedValue(value);
21844
21888
  value = typeof primitive === "number" ? await sandboxNumber(value, state.budget, state.context) : typeof primitive === "string" ? await sandboxString(value, state.budget, state.context) : typeof primitive === "symbol" ? value : primitive;
@@ -22812,6 +22856,12 @@ function absent(value) {
22812
22856
  }
22813
22857
  function validateGuestHeapNode(raw, heap, maxArrayLength = 4294967295) {
22814
22858
  const node = record2(raw);
22859
+ if (node.kind === "raw-json") {
22860
+ fields(node, ["kind", "text"]);
22861
+ if (typeof node.text !== "string") throw new TypeError("Invalid raw JSON source.");
22862
+ createRawJson(node.text);
22863
+ return true;
22864
+ }
22815
22865
  if (!["intrinsic", "guest-function", "guest-generator", "scope-frame", "guest-object", "guest-array"].includes(String(node.kind))) return false;
22816
22866
  const reference = (value, kinds) => {
22817
22867
  const ref = record2(value);
@@ -24792,6 +24842,13 @@ function copyToSandbox(value, state, path = "<root>", cloneSandboxCollections =
24792
24842
  return value;
24793
24843
  }
24794
24844
  if (isLiveCapability(value)) throw new TypeError("Live capabilities require their owning realm bridge.");
24845
+ if (isRawJson(value)) {
24846
+ const existing = state.seen.get(value);
24847
+ if (existing !== void 0) return existing;
24848
+ const copy = createRawJson(value.rawJSON);
24849
+ state.seen.set(value, copy);
24850
+ return copy;
24851
+ }
24795
24852
  if (isSandboxRegex(value)) {
24796
24853
  if (!cloneSandboxCollections) return value;
24797
24854
  const existing = state.seen.get(value);
@@ -39464,4 +39521,4 @@ export {
39464
39521
  FileSnapshotBackend,
39465
39522
  run
39466
39523
  };
39467
- //# sourceMappingURL=chunk-SIFD2ANX.js.map
39524
+ //# sourceMappingURL=chunk-TL2QKHPX.js.map