seroval 1.6.12 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,15 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  //#region src/core/compat.ts
3
3
  /**
4
- * References
5
- * - https://compat-table.github.io/compat-table/es6/
6
- * - MDN
4
+ * Public feature bits for `disabledFeatures`. Stays a runtime `enum` so the
5
+ * published declaration is unchanged for consumers. Its values must match
6
+ * the internal bits (checked by test/feature.test.ts).
7
7
  */
8
8
  let Feature = /* @__PURE__ */ function(Feature) {
9
9
  Feature[Feature["AggregateError"] = 1] = "AggregateError";
10
+ /**
11
+ * @deprecated Has no effect. Output always uses arrow functions.
12
+ */
10
13
  Feature[Feature["ArrowFunction"] = 2] = "ArrowFunction";
11
14
  Feature[Feature["ErrorPrototypeStack"] = 4] = "ErrorPrototypeStack";
12
15
  Feature[Feature["ObjectAssign"] = 8] = "ObjectAssign";
@@ -32,35 +35,15 @@ const SYM_TO_STRING_TAG = Symbol.toStringTag;
32
35
  const SYM_UNSCOPABLES = Symbol.unscopables;
33
36
  //#endregion
34
37
  //#region src/core/constants.ts
35
- const SYMBOL_STRING = {
36
- [0]: "Symbol.asyncIterator",
37
- [1]: "Symbol.hasInstance",
38
- [2]: "Symbol.isConcatSpreadable",
39
- [3]: "Symbol.iterator",
40
- [4]: "Symbol.match",
41
- [5]: "Symbol.matchAll",
42
- [6]: "Symbol.replace",
43
- [7]: "Symbol.search",
44
- [8]: "Symbol.species",
45
- [9]: "Symbol.split",
46
- [10]: "Symbol.toPrimitive",
47
- [11]: "Symbol.toStringTag",
48
- [12]: "Symbol.unscopables"
49
- };
50
- const INV_SYMBOL_REF = {
51
- [SYM_ASYNC_ITERATOR]: 0,
52
- [SYM_HAS_INSTANCE]: 1,
53
- [SYM_IS_CONCAT_SPREADABLE]: 2,
54
- [SYM_ITERATOR]: 3,
55
- [SYM_MATCH]: 4,
56
- [SYM_MATCH_ALL]: 5,
57
- [SYM_REPLACE]: 6,
58
- [SYM_SEARCH]: 7,
59
- [SYM_SPECIES]: 8,
60
- [SYM_SPLIT]: 9,
61
- [SYM_TO_PRIMITIVE]: 10,
62
- [SYM_TO_STRING_TAG]: 11,
63
- [SYM_UNSCOPABLES]: 12
38
+ const TEMPORAL_TYPE_NAME = {
39
+ [0]: "Instant",
40
+ [1]: "Duration",
41
+ [2]: "PlainDate",
42
+ [3]: "PlainDateTime",
43
+ [4]: "PlainMonthDay",
44
+ [5]: "PlainTime",
45
+ [6]: "PlainYearMonth",
46
+ [7]: "ZonedDateTime"
64
47
  };
65
48
  const SYMBOL_REF = {
66
49
  [0]: SYM_ASYNC_ITERATOR,
@@ -77,6 +60,18 @@ const SYMBOL_REF = {
77
60
  [11]: SYM_TO_STRING_TAG,
78
61
  [12]: SYM_UNSCOPABLES
79
62
  };
63
+ function createSymbolStringTable() {
64
+ const result = {};
65
+ for (let i = 0; i <= 12; i++) result[i] = SYMBOL_REF[i].description;
66
+ return result;
67
+ }
68
+ const SYMBOL_STRING = /* @__PURE__ */ createSymbolStringTable();
69
+ function createInverseSymbolTable() {
70
+ const result = {};
71
+ for (let i = 0; i <= 12; i++) result[SYMBOL_REF[i]] = i;
72
+ return result;
73
+ }
74
+ const INV_SYMBOL_REF = /* @__PURE__ */ createInverseSymbolTable();
80
75
  const CONSTANT_STRING = {
81
76
  [2]: "!0",
82
77
  [3]: "!1",
@@ -93,19 +88,10 @@ const CONSTANT_VAL = {
93
88
  [1]: void 0,
94
89
  [0]: null,
95
90
  [4]: -0,
96
- [5]: Number.POSITIVE_INFINITY,
97
- [6]: Number.NEGATIVE_INFINITY,
91
+ [5]: Infinity,
92
+ [6]: -Infinity,
98
93
  [7]: NaN
99
94
  };
100
- const ERROR_CONSTRUCTOR_STRING = {
101
- [0]: "Error",
102
- [1]: "EvalError",
103
- [2]: "RangeError",
104
- [3]: "ReferenceError",
105
- [4]: "SyntaxError",
106
- [5]: "TypeError",
107
- [6]: "URIError"
108
- };
109
95
  const ERROR_CONSTRUCTOR = {
110
96
  [0]: Error,
111
97
  [1]: EvalError,
@@ -115,9 +101,20 @@ const ERROR_CONSTRUCTOR = {
115
101
  [5]: TypeError,
116
102
  [6]: URIError
117
103
  };
104
+ function createErrorConstructorStringTable() {
105
+ const result = {};
106
+ for (let i = 0; i <= 6; i++) result[i] = ERROR_CONSTRUCTOR[i].name;
107
+ return result;
108
+ }
109
+ const ERROR_CONSTRUCTOR_STRING = /* @__PURE__ */ createErrorConstructorStringTable();
118
110
  //#endregion
119
111
  //#region src/core/node.ts
120
112
  function createSerovalNode(t, i, s, c, m, p, e, a, f, b, o, l) {
113
+ if (c === void 0 && m === void 0 && p === void 0 && e === void 0 && a === void 0 && f === void 0 && b === void 0 && o === void 0 && l === void 0) return {
114
+ t,
115
+ i,
116
+ s
117
+ };
121
118
  return {
122
119
  t,
123
120
  i,
@@ -136,7 +133,7 @@ function createSerovalNode(t, i, s, c, m, p, e, a, f, b, o, l) {
136
133
  //#endregion
137
134
  //#region src/core/literals.ts
138
135
  function createConstantNode(value) {
139
- return createSerovalNode(2, void 0, value, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
136
+ return createSerovalNode(2, void 0, value);
140
137
  }
141
138
  const TRUE_NODE = /* @__PURE__ */ createConstantNode(2);
142
139
  const FALSE_NODE = /* @__PURE__ */ createConstantNode(3);
@@ -149,60 +146,106 @@ const NAN_NODE = /* @__PURE__ */ createConstantNode(7);
149
146
  //#endregion
150
147
  //#region src/core/string.ts
151
148
  const MIN_JSON_STRINGIFY_LENGTH = 64;
152
- const JSON_ESCAPE_DIFFERENCES = /[\x00-\x07\x0b\x0e-\x1f<\u2028\u2029\ud800-\udfff]/;
153
- function serializeChar(str) {
154
- switch (str) {
155
- case "\"": return "\\\"";
156
- case "\\": return "\\\\";
157
- case "\n": return "\\n";
158
- case "\r": return "\\r";
159
- case "\b": return "\\b";
160
- case " ": return "\\t";
161
- case "\f": return "\\f";
162
- case "<": return "\\x3C";
163
- case "\u2028": return "\\u2028";
164
- case "\u2029": return "\\u2029";
149
+ const NEEDS_ESCAPE = /["\\\n\r\b\t\f<\u2028\u2029]/;
150
+ const JSON_ESCAPE_DIFFERENCES = /[\x00-\x07\x0b\x0e-\x1f\ud800-\udfff]/;
151
+ const LESS_THAN = /</g;
152
+ const LINE_SEPARATOR = /\u2028/g;
153
+ const PARAGRAPH_SEPARATOR = /\u2029/g;
154
+ function escapeCharCode(code) {
155
+ switch (code) {
156
+ case 34: return "\\\"";
157
+ case 92: return "\\\\";
158
+ case 10: return "\\n";
159
+ case 13: return "\\r";
160
+ case 8: return "\\b";
161
+ case 9: return "\\t";
162
+ case 12: return "\\f";
163
+ case 60: return "\\x3C";
164
+ case 8232: return "\\u2028";
165
+ case 8233: return "\\u2029";
165
166
  default: return;
166
167
  }
167
168
  }
168
169
  function serializeString(str) {
169
- if (str.length >= MIN_JSON_STRINGIFY_LENGTH && !JSON_ESCAPE_DIFFERENCES.test(str)) return JSON.stringify(str).slice(1, -1);
170
+ if (!NEEDS_ESCAPE.test(str)) return str;
171
+ if (str.length >= MIN_JSON_STRINGIFY_LENGTH && !JSON_ESCAPE_DIFFERENCES.test(str)) {
172
+ let result = JSON.stringify(str).slice(1, -1);
173
+ if (result.includes("<")) result = result.replace(LESS_THAN, "\\x3C");
174
+ if (result.includes("\u2028")) result = result.replace(LINE_SEPARATOR, "\\u2028");
175
+ if (result.includes("\u2029")) result = result.replace(PARAGRAPH_SEPARATOR, "\\u2029");
176
+ return result;
177
+ }
170
178
  let result = "";
171
179
  let lastPos = 0;
172
180
  let replacement;
173
181
  for (let i = 0, len = str.length; i < len; i++) {
174
- replacement = serializeChar(str[i]);
182
+ replacement = escapeCharCode(str.charCodeAt(i));
175
183
  if (replacement) {
176
184
  result += str.slice(lastPos, i) + replacement;
177
185
  lastPos = i + 1;
178
186
  }
179
187
  }
180
- if (lastPos === 0) result = str;
181
- else result += str.slice(lastPos);
182
- return result;
183
- }
184
- function deserializeReplacer(str) {
185
- switch (str) {
186
- case "\\\\": return "\\";
187
- case "\\\"": return "\"";
188
- case "\\n": return "\n";
189
- case "\\r": return "\r";
190
- case "\\b": return "\b";
191
- case "\\t": return " ";
192
- case "\\f": return "\f";
193
- case "\\x3C": return "<";
194
- case "\\u2028": return "\u2028";
195
- case "\\u2029": return "\u2029";
196
- default: return str;
197
- }
188
+ return result + str.slice(lastPos);
198
189
  }
190
+ const JSON_COMPATIBLE = /^(?:[^"\\\x00-\x1f]|\\["\\nrbtf])*$/;
191
+ const ESCAPE_SEQUENCE = /(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g;
199
192
  function deserializeString(str) {
200
- if (typeof str === "string" && !str.includes("\\")) return str;
201
- return str.replace(/(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g, deserializeReplacer);
193
+ if (typeof str !== "string") return str.replace(ESCAPE_SEQUENCE, deserializeString);
194
+ let index = str.indexOf("\\");
195
+ if (index === -1) return str;
196
+ if (JSON_COMPATIBLE.test(str)) return JSON.parse("\"" + str + "\"");
197
+ let result = "";
198
+ let lastPos = 0;
199
+ const last = str.length - 1;
200
+ while (index !== -1 && index < last) {
201
+ let replacement;
202
+ let length = 2;
203
+ switch (str.charCodeAt(index + 1)) {
204
+ case 92:
205
+ replacement = "\\";
206
+ break;
207
+ case 34:
208
+ replacement = "\"";
209
+ break;
210
+ case 110:
211
+ replacement = "\n";
212
+ break;
213
+ case 114:
214
+ replacement = "\r";
215
+ break;
216
+ case 98:
217
+ replacement = "\b";
218
+ break;
219
+ case 116:
220
+ replacement = " ";
221
+ break;
222
+ case 102:
223
+ replacement = "\f";
224
+ break;
225
+ case 120:
226
+ if (str.startsWith("3C", index + 2)) {
227
+ replacement = "<";
228
+ length = 4;
229
+ }
230
+ break;
231
+ case 117: if (str.startsWith("2028", index + 2)) {
232
+ replacement = "\u2028";
233
+ length = 6;
234
+ } else if (str.startsWith("2029", index + 2)) {
235
+ replacement = "\u2029";
236
+ length = 6;
237
+ }
238
+ }
239
+ if (replacement) {
240
+ result += str.slice(lastPos, index) + replacement;
241
+ lastPos = index + length;
242
+ index = str.indexOf("\\", lastPos);
243
+ } else index = str.indexOf("\\", index + 1);
244
+ }
245
+ return result + str.slice(lastPos);
202
246
  }
203
247
  //#endregion
204
248
  //#region src/core/errors.ts
205
- const { toString: objectToString } = Object.prototype;
206
249
  const STEP_ERROR_CODES = {
207
250
  parsing: 1,
208
251
  serialization: 2,
@@ -211,10 +254,9 @@ const STEP_ERROR_CODES = {
211
254
  function getErrorMessageProd(type) {
212
255
  return `Seroval Error (step: ${STEP_ERROR_CODES[type]})`;
213
256
  }
214
- const getErrorMessage = (type, cause) => getErrorMessageProd(type);
215
257
  var SerovalError = class extends Error {
216
258
  constructor(type, cause) {
217
- super(getErrorMessage(type, cause));
259
+ super(getErrorMessageProd(type));
218
260
  this.cause = cause;
219
261
  }
220
262
  };
@@ -257,6 +299,10 @@ var SerovalMissingInstanceError = class extends Error {
257
299
  super(getSpecificErrorMessage(4));
258
300
  }
259
301
  };
302
+ /**
303
+ * @deprecated Not thrown by seroval. A missing `createReference` key throws
304
+ * {@link SerovalMissingReferenceForIdError} instead.
305
+ */
260
306
  var SerovalMissingReferenceError = class extends Error {
261
307
  constructor(value) {
262
308
  super(getSpecificErrorMessage(5));
@@ -285,106 +331,40 @@ var SerovalConflictedNodeIdError = class extends Error {
285
331
  };
286
332
  var SerovalDepthLimitError = class extends Error {
287
333
  constructor(limit) {
288
- super(getSpecificErrorMessage(9));
334
+ super(getSpecificErrorMessage(10));
335
+ }
336
+ };
337
+ var SerovalAbortedError = class extends Error {
338
+ constructor() {
339
+ super(getSpecificErrorMessage(11));
340
+ }
341
+ };
342
+ var SerovalLiveStreamError = class extends Error {
343
+ constructor(reason) {
344
+ super(getSpecificErrorMessage(12));
345
+ this.reason = reason;
289
346
  }
290
347
  };
291
- //#endregion
292
- //#region src/core/keys.ts
293
- const REFERENCES_KEY = "__SEROVAL_REFS__";
294
- const GLOBAL_CONTEXT_R = `self.\$R`;
295
- function getCrossReferenceHeader(id) {
296
- if (id == null) return `${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||[]`;
297
- return `(${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||{})["${serializeString(id)}"]=[]`;
298
- }
299
- //#endregion
300
- //#region src/core/reference.ts
301
- const REFERENCE = /* @__PURE__ */ new Map();
302
- const INV_REFERENCE = /* @__PURE__ */ new Map();
303
- function createReference(id, value) {
304
- REFERENCE.set(value, id);
305
- INV_REFERENCE.set(id, value);
306
- return value;
307
- }
308
- function hasReferenceID(value) {
309
- return REFERENCE.has(value);
310
- }
311
- function hasReference(id) {
312
- return INV_REFERENCE.has(id);
313
- }
314
- function getReferenceID(value) {
315
- if (hasReferenceID(value)) return REFERENCE.get(value);
316
- throw new SerovalMissingReferenceError(value);
317
- }
318
- function getReference(id) {
319
- if (hasReference(id)) return INV_REFERENCE.get(id);
320
- throw new SerovalMissingReferenceForIdError(id);
321
- }
322
- if (typeof globalThis !== "undefined") Object.defineProperty(globalThis, REFERENCES_KEY, {
323
- value: INV_REFERENCE,
324
- configurable: true,
325
- writable: false,
326
- enumerable: false
327
- });
328
- else if (typeof window !== "undefined") Object.defineProperty(window, REFERENCES_KEY, {
329
- value: INV_REFERENCE,
330
- configurable: true,
331
- writable: false,
332
- enumerable: false
333
- });
334
- else if (typeof self !== "undefined") Object.defineProperty(self, REFERENCES_KEY, {
335
- value: INV_REFERENCE,
336
- configurable: true,
337
- writable: false,
338
- enumerable: false
339
- });
340
- else if (typeof global !== "undefined") Object.defineProperty(global, REFERENCES_KEY, {
341
- value: INV_REFERENCE,
342
- configurable: true,
343
- writable: false,
344
- enumerable: false
345
- });
346
348
  //#endregion
347
349
  //#region src/core/utils/error.ts
348
350
  function getErrorConstructor(error) {
349
- if (error instanceof EvalError) return 1;
350
- if (error instanceof RangeError) return 2;
351
- if (error instanceof ReferenceError) return 3;
352
- if (error instanceof SyntaxError) return 4;
353
- if (error instanceof TypeError) return 5;
354
- if (error instanceof URIError) return 6;
351
+ for (let i = 1; i <= 6; i++) if (error instanceof ERROR_CONSTRUCTOR[i]) return i;
355
352
  return 0;
356
353
  }
357
- function getInitialErrorOptions(error) {
358
- const construct = ERROR_CONSTRUCTOR_STRING[getErrorConstructor(error)];
359
- if (error.name !== construct) return { name: error.name };
360
- if (error.constructor.name !== construct) return { name: error.constructor.name };
361
- return {};
362
- }
363
354
  function getErrorOptions(error, features) {
364
- let options = getInitialErrorOptions(error);
365
- const names = Object.getOwnPropertyNames(error);
366
- for (let i = 0, len = names.length, name; i < len; i++) {
367
- name = names[i];
368
- if (name !== "name" && name !== "message") {
369
- if (name === "stack") {
370
- if (features & 4) {
371
- options = options || {};
372
- options[name] = error[name];
373
- }
374
- } else {
375
- options = options || {};
376
- options[name] = error[name];
377
- }
378
- }
379
- }
355
+ const options = Object.create(null);
356
+ const construct = ERROR_CONSTRUCTOR_STRING[getErrorConstructor(error)];
357
+ if (error.name !== construct) options.name = error.name;
358
+ else if (error.constructor.name !== construct) options.name = error.constructor.name;
359
+ for (const name of Object.getOwnPropertyNames(error)) if (name !== "name" && name !== "message" && (name !== "stack" || features & 4)) options[name] = error[name];
380
360
  return options;
381
361
  }
382
362
  //#endregion
383
363
  //#region src/core/utils/get-object-flag.ts
384
364
  function getObjectFlag(obj) {
365
+ if (Object.isExtensible(obj)) return 0;
385
366
  if (Object.isFrozen(obj)) return 3;
386
367
  if (Object.isSealed(obj)) return 2;
387
- if (Object.isExtensible(obj)) return 0;
388
368
  return 1;
389
369
  }
390
370
  //#endregion
@@ -419,86 +399,265 @@ function createNumberNode(value) {
419
399
  }
420
400
  if (value !== value) return NAN_NODE;
421
401
  if (Object.is(value, -0)) return NEG_ZERO_NODE;
422
- return createSerovalNode(0, void 0, value, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
402
+ return createSerovalNode(0, void 0, value);
423
403
  }
424
404
  function createStringNode(value) {
425
- return createSerovalNode(1, void 0, serializeString(value), void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
405
+ return createSerovalNode(1, void 0, serializeString(value));
426
406
  }
427
407
  function createBigIntNode(current) {
428
- return createSerovalNode(3, void 0, "" + current, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
408
+ return createSerovalNode(3, void 0, "" + current);
429
409
  }
430
410
  function createIndexedValueNode(id) {
431
- return createSerovalNode(4, id, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
411
+ return createSerovalNode(4, id);
432
412
  }
433
413
  function createDateNode(id, current) {
434
414
  const timestamp = current.valueOf();
435
- return createSerovalNode(5, id, timestamp !== timestamp ? "" : current.toISOString(), void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
415
+ return createSerovalNode(5, id, timestamp === timestamp ? current.toISOString() : "");
436
416
  }
437
417
  function createTemporalNode(id, type, current) {
438
- return createSerovalNode(36, id, current.toString(), type, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
418
+ return createSerovalNode(36, id, current.toString(), type);
439
419
  }
440
420
  function createRegExpNode(id, current) {
441
- return createSerovalNode(6, id, void 0, serializeString(current.source), current.flags, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
421
+ return createSerovalNode(6, id, void 0, serializeString(current.source), current.flags);
442
422
  }
443
423
  function createWKSymbolNode(id, current) {
444
- return createSerovalNode(17, id, INV_SYMBOL_REF[current], void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
424
+ return createSerovalNode(17, id, INV_SYMBOL_REF[current]);
445
425
  }
446
- function createReferenceNode(id, ref) {
447
- return createSerovalNode(18, id, serializeString(getReferenceID(ref)), void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
426
+ function createReferenceNode(id, referenceId) {
427
+ return createSerovalNode(18, id, serializeString(referenceId));
448
428
  }
449
429
  function createPluginNode(id, tag, value) {
450
- return createSerovalNode(25, id, value, serializeString(tag), void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
430
+ return createSerovalNode(25, id, value, serializeString(tag));
451
431
  }
452
432
  function createArrayNode(id, current, parsedItems) {
453
- return createSerovalNode(9, id, void 0, void 0, void 0, void 0, void 0, parsedItems, void 0, void 0, getObjectFlag(current), void 0);
433
+ return createSerovalNode(9, id, void 0, void 0, void 0, void 0, void 0, parsedItems, void 0, void 0, getObjectFlag(current));
454
434
  }
455
435
  function createBoxedNode(id, boxed) {
456
- return createSerovalNode(21, id, void 0, void 0, void 0, void 0, void 0, void 0, boxed, void 0, void 0, void 0);
436
+ return createSerovalNode(21, id, void 0, void 0, void 0, void 0, void 0, void 0, boxed);
457
437
  }
458
438
  const MAX_TYPED_ARRAY_LENGTH = 1e6;
459
- function createTypedArrayNode(id, current, buffer) {
460
- if (current.length > MAX_TYPED_ARRAY_LENGTH) throw new SerovalUnsupportedTypeError(current);
461
- return createSerovalNode(15, id, void 0, getTypedArrayName(current), void 0, void 0, void 0, void 0, buffer, current.byteOffset, void 0, current.length);
462
- }
463
- function createBigIntTypedArrayNode(id, current, buffer) {
464
- if (current.length > MAX_TYPED_ARRAY_LENGTH) throw new SerovalUnsupportedTypeError(current);
465
- return createSerovalNode(16, id, void 0, getTypedArrayName(current), void 0, void 0, void 0, void 0, buffer, current.byteOffset, void 0, current.length);
466
- }
467
- function createDataViewNode(id, current, buffer) {
468
- if (current.byteLength > MAX_TYPED_ARRAY_LENGTH) throw new SerovalUnsupportedTypeError(current);
469
- return createSerovalNode(20, id, void 0, void 0, void 0, void 0, void 0, void 0, buffer, current.byteOffset, void 0, current.byteLength);
470
- }
471
- function createErrorNode(id, current, options) {
472
- return createSerovalNode(13, id, getErrorConstructor(current), void 0, serializeString(current.message), options, void 0, void 0, void 0, void 0, void 0, void 0);
439
+ function createViewNode(type, id, current, buffer) {
440
+ const isDataView = type === 20;
441
+ const size = isDataView ? current.byteLength : current.length;
442
+ if (size > MAX_TYPED_ARRAY_LENGTH) throw new SerovalUnsupportedTypeError(current);
443
+ return createSerovalNode(type, id, void 0, isDataView ? void 0 : getTypedArrayName(current), void 0, void 0, void 0, void 0, buffer, current.byteOffset, void 0, size);
473
444
  }
474
- function createAggregateErrorNode(id, current, options) {
475
- return createSerovalNode(14, id, getErrorConstructor(current), void 0, serializeString(current.message), options, void 0, void 0, void 0, void 0, void 0, void 0);
445
+ function createErrorNode(type, id, current, options) {
446
+ return createSerovalNode(type, id, getErrorConstructor(current), void 0, serializeString(current.message), options);
476
447
  }
477
448
  function createSetNode(id, items) {
478
- return createSerovalNode(7, id, void 0, void 0, void 0, void 0, void 0, items, void 0, void 0, void 0, void 0);
449
+ return createSerovalNode(7, id, void 0, void 0, void 0, void 0, void 0, items);
479
450
  }
480
- function createIteratorFactoryInstanceNode(factory, items) {
481
- return createSerovalNode(28, void 0, void 0, void 0, void 0, void 0, void 0, [factory, items], void 0, void 0, void 0, void 0);
451
+ function createIteratorFactoryInstanceNode(type, factory, items) {
452
+ return createSerovalNode(type, void 0, void 0, void 0, void 0, void 0, void 0, [factory, items]);
482
453
  }
483
- function createAsyncIteratorFactoryInstanceNode(factory, items) {
484
- return createSerovalNode(30, void 0, void 0, void 0, void 0, void 0, void 0, [factory, items], void 0, void 0, void 0, void 0);
454
+ function createStreamConstructorNode(id, factory, sequence, live) {
455
+ return createSerovalNode(31, id, void 0, void 0, void 0, void 0, void 0, sequence, factory, void 0, void 0, live);
485
456
  }
486
- function createStreamConstructorNode(id, factory, sequence) {
487
- return createSerovalNode(31, id, void 0, void 0, void 0, void 0, void 0, sequence, factory, void 0, void 0, void 0);
488
- }
489
- function createStreamNextNode(id, parsed) {
490
- return createSerovalNode(32, id, void 0, void 0, void 0, void 0, void 0, void 0, parsed, void 0, void 0, void 0);
491
- }
492
- function createStreamThrowNode(id, parsed) {
493
- return createSerovalNode(33, id, void 0, void 0, void 0, void 0, void 0, void 0, parsed, void 0, void 0, void 0);
494
- }
495
- function createStreamReturnNode(id, parsed) {
496
- return createSerovalNode(34, id, void 0, void 0, void 0, void 0, void 0, void 0, parsed, void 0, void 0, void 0);
457
+ function createStreamEventNode(type, id, parsed) {
458
+ return createSerovalNode(type, id, void 0, void 0, void 0, void 0, void 0, void 0, parsed);
497
459
  }
498
460
  function createSequenceNode(id, sequence, throwAt, doneAt) {
499
461
  return createSerovalNode(35, id, throwAt, void 0, void 0, void 0, void 0, sequence, void 0, void 0, void 0, doneAt);
500
462
  }
501
463
  //#endregion
464
+ //#region src/core/live-stream.ts
465
+ function isLiveStream(value) {
466
+ return value instanceof LiveStream;
467
+ }
468
+ /**
469
+ * A single-consumer stream for incremental serialization. Unlike
470
+ * `createStream`, it keeps no history: at most one event is held, and the
471
+ * producer operation that sent it settles only when the consumer accepts it.
472
+ *
473
+ * An internal class rather than a tagged POJO: identity is checked with
474
+ * `instanceof`, which untrusted input cannot forge. The class is exported
475
+ * because bundlers cannot drop an unexported top-level class.
476
+ */
477
+ var LiveStream = class {
478
+ constructor(options) {
479
+ this.consumed = false;
480
+ this.closed = false;
481
+ this.cancelled = false;
482
+ this.options = options;
483
+ }
484
+ deliver(reader, record) {
485
+ record.delivered = true;
486
+ reader.resolve({
487
+ event: record.event,
488
+ accept: () => {
489
+ if (this.pending === record && record.delivered) {
490
+ const terminal = record.event.type !== "next";
491
+ record.event = void 0;
492
+ this.pending = void 0;
493
+ const resolve = record.resolve;
494
+ record.resolve = void 0;
495
+ record.reject = void 0;
496
+ if (terminal) {
497
+ this.closed = true;
498
+ this.options = void 0;
499
+ const waiter = this.waiting;
500
+ this.waiting = void 0;
501
+ waiter?.reject(new SerovalLiveStreamError("closed"));
502
+ }
503
+ resolve?.();
504
+ }
505
+ }
506
+ });
507
+ }
508
+ /** @internal */
509
+ push(event) {
510
+ if (this.cancelled) return Promise.reject(this.cancelReason);
511
+ if (this.closed) return Promise.reject(new SerovalLiveStreamError("closed"));
512
+ if (this.pending) return Promise.reject(new SerovalLiveStreamError("pending"));
513
+ return new Promise((resolve, reject) => {
514
+ const record = {
515
+ event,
516
+ delivered: false,
517
+ resolve,
518
+ reject
519
+ };
520
+ this.pending = record;
521
+ if (this.waiting) {
522
+ const waiter = this.waiting;
523
+ this.waiting = void 0;
524
+ this.deliver(waiter, record);
525
+ }
526
+ });
527
+ }
528
+ cancel(reason) {
529
+ if (this.cancelled || this.closed) return;
530
+ this.cancelled = true;
531
+ this.cancelReason = reason;
532
+ const record = this.pending;
533
+ const waiter = this.waiting;
534
+ this.pending = void 0;
535
+ this.waiting = void 0;
536
+ const callbackOwner = this.options;
537
+ this.options = void 0;
538
+ if (record) {
539
+ record.event = void 0;
540
+ const reject = record.reject;
541
+ record.resolve = void 0;
542
+ record.reject = void 0;
543
+ reject?.(reason);
544
+ }
545
+ if (waiter) waiter.reject(reason);
546
+ callbackOwner?.onCancel?.(reason);
547
+ }
548
+ read() {
549
+ if (this.cancelled) return Promise.reject(this.cancelReason);
550
+ if (this.closed) return Promise.reject(new SerovalLiveStreamError("closed"));
551
+ if (this.waiting) return Promise.reject(new SerovalLiveStreamError("reading"));
552
+ return new Promise((resolve, reject) => {
553
+ const next = {
554
+ resolve,
555
+ reject
556
+ };
557
+ if (this.pending && !this.pending.delivered) this.deliver(next, this.pending);
558
+ else this.waiting = next;
559
+ });
560
+ }
561
+ consume() {
562
+ if (this.consumed) throw new SerovalLiveStreamError("consumed");
563
+ this.consumed = true;
564
+ return {
565
+ read: () => this.read(),
566
+ cancel: (reason) => this.cancel(reason)
567
+ };
568
+ }
569
+ /**
570
+ * Consumes the stream through a replay-style listener, accepting each
571
+ * event as soon as it has been delivered. Use `consume` or `pump` when
572
+ * acceptance must wait for processing.
573
+ */
574
+ on(listener) {
575
+ const wrap = (key) => (value, accept) => {
576
+ listener[key](value);
577
+ accept();
578
+ };
579
+ return this.pump({
580
+ next: wrap("next"),
581
+ throw: wrap("throw"),
582
+ return: wrap("return")
583
+ });
584
+ }
585
+ /**
586
+ * Consumes the stream into a sink that controls acceptance. Returns the
587
+ * cancel function.
588
+ * @internal
589
+ */
590
+ pump(sink) {
591
+ const consumer = this.consume();
592
+ let current = sink;
593
+ function next() {
594
+ consumer.read().then((delivery) => {
595
+ const target = current;
596
+ if (!target) return;
597
+ const event = delivery.event;
598
+ let failure;
599
+ let failed = false;
600
+ try {
601
+ failure = target[event.type](event.type === "throw" ? event.error : event.value, delivery.accept);
602
+ } catch (error) {
603
+ failed = true;
604
+ failure = error;
605
+ }
606
+ if (failed || failure !== void 0) {
607
+ current = void 0;
608
+ try {
609
+ consumer.cancel(failure);
610
+ } finally {
611
+ target.done?.();
612
+ }
613
+ return;
614
+ }
615
+ if (event.type === "next") {
616
+ next();
617
+ return;
618
+ }
619
+ current = void 0;
620
+ target.done?.();
621
+ }, (reason) => {
622
+ const target = current;
623
+ current = void 0;
624
+ target?.error?.(reason);
625
+ });
626
+ }
627
+ next();
628
+ return consumer.cancel;
629
+ }
630
+ };
631
+ /**
632
+ * Creates a live stream and the producer that writes to it.
633
+ */
634
+ function createLiveStream(options) {
635
+ const stream = new LiveStream(options);
636
+ return {
637
+ stream,
638
+ producer: {
639
+ write(value) {
640
+ return stream.push({
641
+ type: "next",
642
+ value
643
+ });
644
+ },
645
+ close(value) {
646
+ return stream.push({
647
+ type: "return",
648
+ value
649
+ });
650
+ },
651
+ fail(error) {
652
+ return stream.push({
653
+ type: "throw",
654
+ error
655
+ });
656
+ }
657
+ }
658
+ };
659
+ }
660
+ //#endregion
502
661
  //#region src/core/opaque-reference.ts
503
662
  /**
504
663
  * An opaque reference allows hiding values from the serializer.
@@ -536,7 +695,7 @@ const PROMISE_FAILURE = (resolver, data) => {
536
695
  const SERIALIZED_PROMISE_CONSTRUCTOR = /* @__PURE__ */ PROMISE_CONSTRUCTOR.toString();
537
696
  const SERIALIZED_PROMISE_SUCCESS = /* @__PURE__ */ PROMISE_SUCCESS.toString();
538
697
  const SERIALIZED_PROMISE_FAILURE = /* @__PURE__ */ PROMISE_FAILURE.toString();
539
- const STREAM_CONSTRUCTOR = () => {
698
+ const STREAM_CONSTRUCTOR = (live) => {
540
699
  const buffer = [];
541
700
  const listeners = [];
542
701
  let alive = true;
@@ -544,6 +703,7 @@ const STREAM_CONSTRUCTOR = () => {
544
703
  let count = 0;
545
704
  const internal = {
546
705
  flush(value, mode, x) {
706
+ live > 1 || buffer.push(value);
547
707
  for (x = 0; x < count; x++) {
548
708
  const listener = listeners[x];
549
709
  if (listener) listener[mode](value);
@@ -557,6 +717,7 @@ const STREAM_CONSTRUCTOR = () => {
557
717
  }
558
718
  },
559
719
  on(listener, temp = 0) {
720
+ if (live > 1) throw new Error("Stream consumed");
560
721
  let subscribed = alive;
561
722
  if (alive) {
562
723
  for (temp = 0; temp < count; temp++) if (!listeners[temp]) break;
@@ -564,6 +725,10 @@ const STREAM_CONSTRUCTOR = () => {
564
725
  listeners[temp] = listener;
565
726
  }
566
727
  internal.up(listener);
728
+ if (live) {
729
+ live = 2;
730
+ buffer.length = 0;
731
+ }
567
732
  return () => {
568
733
  if (alive && subscribed) {
569
734
  subscribed = false;
@@ -580,14 +745,10 @@ const STREAM_CONSTRUCTOR = () => {
580
745
  return internal.on(listener);
581
746
  },
582
747
  next(value) {
583
- if (alive) {
584
- buffer.push(value);
585
- internal.flush(value, "next");
586
- }
748
+ if (alive) internal.flush(value, "next");
587
749
  },
588
750
  throw(value) {
589
751
  if (alive) {
590
- buffer.push(value);
591
752
  internal.flush(value, "throw");
592
753
  alive = false;
593
754
  success = false;
@@ -596,7 +757,6 @@ const STREAM_CONSTRUCTOR = () => {
596
757
  },
597
758
  return(value) {
598
759
  if (alive) {
599
- buffer.push(value);
600
760
  internal.flush(value, "return");
601
761
  alive = false;
602
762
  success = true;
@@ -718,7 +878,8 @@ const SERIALIZED_ARRAY_BUFFER_CONSTRUCTOR = /* @__PURE__ */ ARRAY_BUFFER_CONSTRU
718
878
  //#region src/core/sequence.ts
719
879
  /**
720
880
  * An internal class rather than a tagged POJO: identity is checked with
721
- * `instanceof`, which untrusted input cannot forge (the class is not exported).
881
+ * `instanceof`, which untrusted input cannot forge. The class is exported
882
+ * because bundlers cannot drop an unexported top-level class.
722
883
  * The eval-based `deserialize` path still rebuilds a `{__SEROVAL_SEQUENCE__…}`
723
884
  * POJO from embedded source - it has no access to this class - so a value read
724
885
  * back through `deserialize` is not an instance and, by design, is not treated
@@ -742,7 +903,7 @@ function createSequenceFromIterable(source) {
742
903
  let throwsAt = -1;
743
904
  let doneAt = -1;
744
905
  const iterator = source[SYM_ITERATOR]();
745
- while (true) try {
906
+ for (;;) try {
746
907
  const value = iterator.next();
747
908
  values.push(value.value);
748
909
  if (value.done) {
@@ -757,7 +918,7 @@ function createSequenceFromIterable(source) {
757
918
  }
758
919
  return createSequence(values, throwsAt, doneAt);
759
920
  }
760
- const createIterator = ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
921
+ const createIterator = /* @__PURE__ */ ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
761
922
  function sequenceToIterator(sequence) {
762
923
  return createIterator(sequence);
763
924
  }
@@ -788,7 +949,8 @@ const SPECIAL_REF_STRING = {
788
949
  //#region src/core/stream.ts
789
950
  /**
790
951
  * An internal class rather than a tagged POJO: identity is checked with
791
- * `instanceof`, which untrusted input cannot forge (the class is not exported).
952
+ * `instanceof`, which untrusted input cannot forge. The class is exported
953
+ * because bundlers cannot drop an unexported top-level class.
792
954
  *
793
955
  * The behavior is intentionally duplicated from `STREAM_CONSTRUCTOR`. That
794
956
  * constructor's source is embedded verbatim into the eval-based `deserialize`
@@ -798,18 +960,17 @@ const SPECIAL_REF_STRING = {
798
960
  * implementations in sync.
799
961
  */
800
962
  var Stream = class {
801
- constructor() {
963
+ constructor(live) {
802
964
  this.buffer = [];
803
965
  this.listeners = [];
804
966
  this.alive = true;
805
967
  this.success = false;
806
968
  this.count = 0;
969
+ this.live = live;
807
970
  }
808
971
  flush(value, mode) {
809
- for (let x = 0; x < this.count; x++) {
810
- var _this$listeners$x;
811
- (_this$listeners$x = this.listeners[x]) === null || _this$listeners$x === void 0 || _this$listeners$x[mode](value);
812
- }
972
+ this.live > 1 || this.buffer.push(value);
973
+ for (let x = 0; x < this.count; x++) this.listeners[x]?.[mode](value);
813
974
  }
814
975
  replay(listener) {
815
976
  for (let x = 0, z = this.buffer.length; x < z; x++) {
@@ -819,6 +980,7 @@ var Stream = class {
819
980
  }
820
981
  }
821
982
  on(listener) {
983
+ if (this.live > 1) throw new Error("Stream consumed");
822
984
  let subscribed = this.alive;
823
985
  let temp = 0;
824
986
  if (subscribed) {
@@ -827,6 +989,10 @@ var Stream = class {
827
989
  this.listeners[temp] = listener;
828
990
  }
829
991
  this.replay(listener);
992
+ if (this.live) {
993
+ this.live = 2;
994
+ this.buffer.length = 0;
995
+ }
830
996
  return () => {
831
997
  if (this.alive && subscribed) {
832
998
  subscribed = false;
@@ -836,15 +1002,25 @@ var Stream = class {
836
1002
  }
837
1003
  };
838
1004
  }
1005
+ /**
1006
+ * Returns the events of a stream that has ended, without subscribing, so a
1007
+ * live receiver is not consumed. The last value is the `return` or `throw`
1008
+ * value. Returns `undefined` while the stream is open, or when a live
1009
+ * receiver was already consumed and has no events left.
1010
+ * @internal
1011
+ */
1012
+ endedEvents() {
1013
+ if (this.alive || this.live > 1) return void 0;
1014
+ return {
1015
+ values: this.buffer.slice(),
1016
+ success: this.success
1017
+ };
1018
+ }
839
1019
  next(value) {
840
- if (this.alive) {
841
- this.buffer.push(value);
842
- this.flush(value, "next");
843
- }
1020
+ if (this.alive) this.flush(value, "next");
844
1021
  }
845
1022
  throw(value) {
846
1023
  if (this.alive) {
847
- this.buffer.push(value);
848
1024
  this.flush(value, "throw");
849
1025
  this.alive = false;
850
1026
  this.success = false;
@@ -853,7 +1029,6 @@ var Stream = class {
853
1029
  }
854
1030
  return(value) {
855
1031
  if (this.alive) {
856
- this.buffer.push(value);
857
1032
  this.flush(value, "return");
858
1033
  this.alive = false;
859
1034
  this.success = true;
@@ -862,46 +1037,12 @@ var Stream = class {
862
1037
  }
863
1038
  };
864
1039
  function isStream(value) {
865
- return value instanceof Stream;
1040
+ return value instanceof Stream || isLiveStream(value);
866
1041
  }
867
1042
  function createStream() {
868
1043
  return new Stream();
869
1044
  }
870
- function createStreamFromAsyncIterable(iterable, cleanups) {
871
- const stream = createStream();
872
- const iterator = iterable[SYM_ASYNC_ITERATOR]();
873
- let cancelled = false;
874
- let done = false;
875
- cleanups === null || cleanups === void 0 || cleanups.push(() => {
876
- if (!(done || cancelled)) {
877
- cancelled = true;
878
- Promise.resolve().then(() => {
879
- var _iterator$return;
880
- return (_iterator$return = iterator.return) === null || _iterator$return === void 0 ? void 0 : _iterator$return.call(iterator);
881
- }).catch(() => {});
882
- }
883
- });
884
- async function push() {
885
- try {
886
- while (!cancelled) {
887
- const value = await iterator.next();
888
- if (cancelled) return;
889
- if (value.done) {
890
- done = true;
891
- stream.return(value.value);
892
- break;
893
- }
894
- stream.next(value.value);
895
- }
896
- } catch (error) {
897
- done = true;
898
- if (!cancelled) stream.throw(error);
899
- }
900
- }
901
- push().catch(() => {});
902
- return stream;
903
- }
904
- const createAsyncIterable = ASYNC_ITERATOR_CONSTRUCTOR(SYM_ASYNC_ITERATOR, PROMISE_CONSTRUCTOR);
1045
+ const createAsyncIterable = /* @__PURE__ */ ASYNC_ITERATOR_CONSTRUCTOR(SYM_ASYNC_ITERATOR, PROMISE_CONSTRUCTOR);
905
1046
  function streamToAsyncIterable(stream) {
906
1047
  return createAsyncIterable(stream);
907
1048
  }
@@ -915,20 +1056,158 @@ async function promiseToResult(current) {
915
1056
  }
916
1057
  }
917
1058
  //#endregion
1059
+ //#region src/core/binary-browser.ts
1060
+ function encodeArrayBuffer$1(current) {
1061
+ const bytes = new Uint8Array(current);
1062
+ if (typeof bytes.toBase64 === "function") return bytes.toBase64();
1063
+ let result = "";
1064
+ for (let i = 0, len = bytes.length; i < len; i++) result += String.fromCharCode(bytes[i]);
1065
+ return btoa(result);
1066
+ }
1067
+ //#endregion
1068
+ //#region src/core/binary-neutral.ts
1069
+ const MIN_NATIVE_BASE64_LENGTH = 512;
1070
+ function encodeArrayBuffer(current) {
1071
+ if (typeof Buffer !== "undefined") return Buffer.from(current).toString("base64");
1072
+ return encodeArrayBuffer$1(current);
1073
+ }
1074
+ function decodeArrayBuffer(source) {
1075
+ if (source.length < MIN_NATIVE_BASE64_LENGTH || typeof Buffer === "undefined") return ARRAY_BUFFER_CONSTRUCTOR(source);
1076
+ const decoded = atob(source);
1077
+ const buffer = new ArrayBuffer(decoded.length);
1078
+ Buffer.from(buffer).write(decoded, "latin1");
1079
+ return buffer;
1080
+ }
1081
+ //#endregion
1082
+ //#region src/core/plugin.ts
1083
+ let SerovalMode = /* @__PURE__ */ function(SerovalMode) {
1084
+ SerovalMode[SerovalMode["Vanilla"] = 1] = "Vanilla";
1085
+ SerovalMode[SerovalMode["Cross"] = 2] = "Cross";
1086
+ return SerovalMode;
1087
+ }({});
1088
+ function createPlugin(plugin) {
1089
+ return plugin;
1090
+ }
1091
+ function dedupePlugins(deduped, plugins) {
1092
+ for (let i = 0, len = plugins.length; i < len; i++) {
1093
+ const current = plugins[i];
1094
+ if (!deduped.has(current)) {
1095
+ deduped.add(current);
1096
+ if (current.extends) dedupePlugins(deduped, current.extends);
1097
+ }
1098
+ }
1099
+ }
1100
+ const RESOLVED_PLUGINS = /* @__PURE__ */ new WeakMap();
1101
+ function matchResolved(resolved, plugins, added) {
1102
+ for (let i = 0, len = plugins.length; i < len; i++) {
1103
+ const current = plugins[i];
1104
+ if (current === resolved[added]) {
1105
+ added++;
1106
+ if (current.extends) {
1107
+ added = matchResolved(resolved, current.extends, added);
1108
+ if (added === -1) return -1;
1109
+ }
1110
+ } else {
1111
+ const index = resolved.indexOf(current);
1112
+ if (index === -1 || index >= added) return -1;
1113
+ }
1114
+ }
1115
+ return added;
1116
+ }
1117
+ function resolvePlugins(plugins) {
1118
+ if (plugins) {
1119
+ const cached = RESOLVED_PLUGINS.get(plugins);
1120
+ if (cached && matchResolved(cached, plugins, 0) === cached.length) return cached;
1121
+ const deduped = /* @__PURE__ */ new Set();
1122
+ dedupePlugins(deduped, plugins);
1123
+ const resolved = [...deduped];
1124
+ RESOLVED_PLUGINS.set(plugins, resolved);
1125
+ return resolved;
1126
+ }
1127
+ }
1128
+ /**
1129
+ * Returns the plugins that are tested for plain objects. It is the same array
1130
+ * when no plugin sets `skipPlainObjects`.
1131
+ */
1132
+ function getPlainObjectPlugins(plugins) {
1133
+ if (plugins) {
1134
+ for (let i = 0, len = plugins.length; i < len; i++) if (plugins[i].skipPlainObjects) {
1135
+ const result = plugins.filter((plugin) => !plugin.skipPlainObjects);
1136
+ return result.length ? result : void 0;
1137
+ }
1138
+ }
1139
+ return plugins;
1140
+ }
1141
+ //#endregion
1142
+ //#region src/core/keys.ts
1143
+ const REFERENCES_KEY = "__SEROVAL_REFS__";
1144
+ const GLOBAL_CONTEXT_R = `self.\$R`;
1145
+ function getCrossReferenceHeader(id) {
1146
+ if (id == null) return `${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||[]`;
1147
+ return `(${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||{})["${serializeString(id)}"]=[]`;
1148
+ }
1149
+ //#endregion
1150
+ //#region src/core/reference.ts
1151
+ const REFERENCE = /* @__PURE__ */ new Map();
1152
+ const INV_REFERENCE = /* @__PURE__ */ new Map();
1153
+ let installed = false;
1154
+ function getGlobalObject() {
1155
+ if (typeof globalThis !== "undefined") return globalThis;
1156
+ if (typeof window !== "undefined") return window;
1157
+ if (typeof self !== "undefined") return self;
1158
+ if (typeof global !== "undefined") return global;
1159
+ }
1160
+ function installReferenceStore() {
1161
+ if (!installed) {
1162
+ installed = true;
1163
+ const globalObject = getGlobalObject();
1164
+ if (globalObject) Object.defineProperty(globalObject, REFERENCES_KEY, {
1165
+ value: INV_REFERENCE,
1166
+ configurable: true,
1167
+ writable: false,
1168
+ enumerable: false
1169
+ });
1170
+ }
1171
+ }
1172
+ function createReference(id, value) {
1173
+ installReferenceStore();
1174
+ REFERENCE.set(value, id);
1175
+ INV_REFERENCE.set(id, value);
1176
+ return value;
1177
+ }
1178
+ function hasReference(id) {
1179
+ return INV_REFERENCE.has(id);
1180
+ }
1181
+ function getReferenceID(value) {
1182
+ return REFERENCE.get(value);
1183
+ }
1184
+ function getReference(id) {
1185
+ if (hasReference(id)) return INV_REFERENCE.get(id);
1186
+ throw new SerovalMissingReferenceForIdError(id);
1187
+ }
1188
+ //#endregion
918
1189
  //#region src/core/context/parser.ts
919
- function createBaseParserContext(mode, options) {
920
- var _options$compactArray;
1190
+ function createBaseParserContext(options) {
921
1191
  return {
922
1192
  plugins: options.plugins,
923
- mode,
1193
+ plainObjectPlugins: getPlainObjectPlugins(options.plugins),
924
1194
  marked: /* @__PURE__ */ new Set(),
925
- features: 127 ^ (options.disabledFeatures || 0),
926
- refs: options.refs || /* @__PURE__ */ new Map(),
1195
+ features: 127 ^ (options.disabledFeatures ?? 0),
1196
+ refs: options.refs ?? /* @__PURE__ */ new Map(),
927
1197
  depthLimit: options.depthLimit || 1e3,
928
- compactArrayBufferViews: (_options$compactArray = options.compactArrayBufferViews) !== null && _options$compactArray !== void 0 ? _options$compactArray : false
1198
+ compactArrayBufferViews: options.compactArrayBufferViews ?? false
929
1199
  };
930
1200
  }
931
1201
  /**
1202
+ * Returns the plugins to test for an object. Plain objects, whose prototype is
1203
+ * `Object.prototype`, skip the plugins that set `skipPlainObjects`. Checking
1204
+ * the prototype as well as `constructor` keeps instances whose prototype has
1205
+ * no own `constructor` property from skipping those plugins.
1206
+ */
1207
+ function getObjectPlugins(ctx, current, currentClass) {
1208
+ return currentClass === Object && Object.getPrototypeOf(current) === Object.prototype ? ctx.plainObjectPlugins : ctx.plugins;
1209
+ }
1210
+ /**
932
1211
  * Ensures that the value (based on an identifier) has been visited by the parser.
933
1212
  * @param ctx
934
1213
  * @param id
@@ -950,125 +1229,166 @@ function getNodeForIndexedValue(ctx, current) {
950
1229
  const registeredId = ctx.refs.get(current);
951
1230
  if (registeredId != null) {
952
1231
  markParserRef(ctx, registeredId);
953
- return {
954
- type: 1,
955
- value: createIndexedValueNode(registeredId)
956
- };
1232
+ return createIndexedValueNode(registeredId);
957
1233
  }
958
- return {
959
- type: 0,
960
- value: createIndexForValue(ctx, current)
961
- };
1234
+ return createIndexForValue(ctx, current);
962
1235
  }
963
1236
  function getReferenceNode(ctx, current) {
964
1237
  const indexed = getNodeForIndexedValue(ctx, current);
965
- if (indexed.type === 1) return indexed;
966
- if (hasReferenceID(current)) return {
967
- type: 2,
968
- value: createReferenceNode(indexed.value, current)
969
- };
970
- return indexed;
1238
+ if (typeof indexed !== "number") return indexed;
1239
+ const referenceId = getReferenceID(current);
1240
+ return referenceId === void 0 ? indexed : createReferenceNode(indexed, referenceId);
971
1241
  }
972
1242
  /**
973
1243
  * Parsing methods
974
1244
  */
975
1245
  function parseWellKnownSymbol(ctx, current) {
976
1246
  const ref = getReferenceNode(ctx, current);
977
- if (ref.type !== 0) return ref.value;
978
- if (current in INV_SYMBOL_REF) return createWKSymbolNode(ref.value, current);
1247
+ if (typeof ref !== "number") return ref;
1248
+ if (current in INV_SYMBOL_REF) return createWKSymbolNode(ref, current);
979
1249
  throw new SerovalUnsupportedTypeError(current);
980
1250
  }
981
1251
  function parseSpecialReference(ctx, ref) {
982
1252
  const result = getNodeForIndexedValue(ctx, SPECIAL_REFS[ref]);
983
- if (result.type === 1) return result.value;
984
- return createSerovalNode(26, result.value, ref, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
1253
+ if (typeof result !== "number") return result;
1254
+ return createSerovalNode(26, result, ref);
985
1255
  }
986
1256
  function parseIteratorFactory(ctx) {
987
1257
  const result = getNodeForIndexedValue(ctx, ITERATOR);
988
- if (result.type === 1) return result.value;
989
- return createSerovalNode(27, result.value, void 0, void 0, void 0, void 0, void 0, void 0, parseWellKnownSymbol(ctx, SYM_ITERATOR), void 0, void 0, void 0);
1258
+ if (typeof result !== "number") return result;
1259
+ return createSerovalNode(27, result, void 0, void 0, void 0, void 0, void 0, void 0, parseWellKnownSymbol(ctx, SYM_ITERATOR));
990
1260
  }
991
1261
  function parseAsyncIteratorFactory(ctx) {
992
1262
  const result = getNodeForIndexedValue(ctx, ASYNC_ITERATOR);
993
- if (result.type === 1) return result.value;
994
- return createSerovalNode(29, result.value, void 0, void 0, void 0, void 0, void 0, [parseSpecialReference(ctx, 1), parseWellKnownSymbol(ctx, SYM_ASYNC_ITERATOR)], void 0, void 0, void 0, void 0);
1263
+ if (typeof result !== "number") return result;
1264
+ return createSerovalNode(29, result, void 0, void 0, void 0, void 0, void 0, [parseSpecialReference(ctx, 1), parseWellKnownSymbol(ctx, SYM_ASYNC_ITERATOR)]);
995
1265
  }
996
- function createObjectNode(id, current, empty, record) {
997
- return createSerovalNode(empty ? 11 : 10, id, void 0, void 0, void 0, record, void 0, void 0, void 0, void 0, getObjectFlag(current), void 0);
1266
+ function getTemporalType(currentClass) {
1267
+ switch (currentClass) {
1268
+ case Temporal.Instant: return 0;
1269
+ case Temporal.Duration: return 1;
1270
+ case Temporal.PlainDate: return 2;
1271
+ case Temporal.PlainDateTime: return 3;
1272
+ case Temporal.PlainMonthDay: return 4;
1273
+ case Temporal.PlainTime: return 5;
1274
+ case Temporal.PlainYearMonth: return 6;
1275
+ case Temporal.ZonedDateTime: return 7;
1276
+ default: return;
1277
+ }
1278
+ }
1279
+ function getObjectClass(current) {
1280
+ const currentClass = current.constructor;
1281
+ if (currentClass !== void 0 && typeof currentClass !== "function") {
1282
+ const proto = Object.getPrototypeOf(current);
1283
+ return proto === null ? void 0 : proto.constructor;
1284
+ }
1285
+ return currentClass;
998
1286
  }
999
1287
  /**
1000
- * Gets the sentinel node for a Map. Call it before parsing the entries, so
1001
- * that an outer Map declares the sentinel before any Map inside it uses it.
1288
+ * Decides how an object is parsed. Shared by the sync, stream and async
1289
+ * parsers so the class checks and feature gates live in one place.
1002
1290
  */
1003
- function parseMapSentinel(ctx) {
1004
- return parseSpecialReference(ctx, 0);
1005
- }
1006
- function createMapNode(id, sentinel, k, v) {
1291
+ function getObjectKind(current, currentClass, features) {
1292
+ switch (currentClass) {
1293
+ case Object: return 1;
1294
+ case void 0: return 2;
1295
+ case Date: return 3;
1296
+ case Error:
1297
+ case EvalError:
1298
+ case RangeError:
1299
+ case ReferenceError:
1300
+ case SyntaxError:
1301
+ case TypeError:
1302
+ case URIError: return 4;
1303
+ case Number:
1304
+ case Boolean:
1305
+ case String:
1306
+ case BigInt: return 6;
1307
+ case ArrayBuffer: return 7;
1308
+ case Int8Array:
1309
+ case Int16Array:
1310
+ case Int32Array:
1311
+ case Uint8Array:
1312
+ case Uint16Array:
1313
+ case Uint32Array:
1314
+ case Uint8ClampedArray:
1315
+ case Float32Array:
1316
+ case Float64Array: return 8;
1317
+ case DataView: return 10;
1318
+ case Map: return 11;
1319
+ case Set: return 12;
1320
+ }
1321
+ if (currentClass === Promise || current instanceof Promise) return 13;
1322
+ if (features & 32 && currentClass === RegExp) return 14;
1323
+ if (features & 16 && (currentClass === BigInt64Array || currentClass === BigUint64Array)) return 9;
1324
+ if (features & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) return 5;
1325
+ if (features & 64 && typeof Temporal !== "undefined" && getTemporalType(currentClass) != null) return 15;
1326
+ if (current instanceof Error) return 4;
1327
+ if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) return 16;
1328
+ return 0;
1329
+ }
1330
+ function createObjectNode(id, current, empty, record) {
1331
+ return createSerovalNode(empty ? 11 : 10, id, void 0, void 0, void 0, record, void 0, void 0, void 0, void 0, getObjectFlag(current));
1332
+ }
1333
+ /**
1334
+ * Gets the sentinel node for a Map. Call it before parsing the entries, so
1335
+ * that an outer Map declares the sentinel before any Map inside it uses it.
1336
+ */
1337
+ function parseMapSentinel(ctx) {
1338
+ return parseSpecialReference(ctx, 0);
1339
+ }
1340
+ function createMapNode(id, sentinel, k, v) {
1007
1341
  return createSerovalNode(8, id, void 0, void 0, void 0, void 0, {
1008
1342
  k,
1009
1343
  v
1010
- }, void 0, sentinel, void 0, void 0, void 0);
1344
+ }, void 0, sentinel);
1011
1345
  }
1012
1346
  function createPromiseConstructorNode(ctx, id, resolver) {
1013
- return createSerovalNode(22, id, resolver, void 0, void 0, void 0, void 0, void 0, parseSpecialReference(ctx, 1), void 0, void 0, void 0);
1347
+ return createSerovalNode(22, id, resolver, void 0, void 0, void 0, void 0, void 0, parseSpecialReference(ctx, 1));
1014
1348
  }
1015
1349
  function getArrayBufferView(ctx, current) {
1016
1350
  if (!ctx.compactArrayBufferViews) return current;
1017
1351
  const buffer = new Uint8Array(current.buffer, current.byteOffset, current.byteLength).slice().buffer;
1018
1352
  return new (current instanceof DataView ? DataView : getTypedArrayConstructor(getTypedArrayName(current)))(buffer);
1019
1353
  }
1020
- function encodeArrayBuffer(current) {
1021
- if (typeof Buffer !== "undefined") return Buffer.from(current).toString("base64");
1022
- const bytes = new Uint8Array(current);
1023
- if (typeof bytes.toBase64 === "function") return bytes.toBase64();
1024
- let result = "";
1025
- for (let i = 0, len = bytes.length; i < len; i++) result += String.fromCharCode(bytes[i]);
1026
- return btoa(result);
1027
- }
1028
1354
  function createArrayBufferNode(ctx, id, current) {
1029
- return createSerovalNode(19, id, encodeArrayBuffer(current), void 0, void 0, void 0, void 0, void 0, parseSpecialReference(ctx, 5), void 0, void 0, void 0);
1355
+ return createSerovalNode(19, id, encodeArrayBuffer(current), void 0, void 0, void 0, void 0, void 0, parseSpecialReference(ctx, 5));
1030
1356
  }
1031
1357
  //#endregion
1032
1358
  //#region src/core/context/async-parser.ts
1033
- function createAsyncParserContext(mode, options) {
1034
- return {
1035
- base: createBaseParserContext(mode, options),
1036
- child: void 0
1037
- };
1359
+ function createAsyncParserContext(options) {
1360
+ return { base: createBaseParserContext(options) };
1038
1361
  }
1039
- var AsyncParsePluginContext = class {
1040
- constructor(_p, depth) {
1041
- this._p = _p;
1042
- this.depth = depth;
1043
- }
1044
- parse(current) {
1045
- return parseAsync(this._p, this.depth, current);
1046
- }
1047
- };
1048
1362
  async function parseItems$1(ctx, depth, current) {
1049
- const nodes = [];
1050
- for (let i = 0, len = current.length; i < len; i++) if (i in current) nodes[i] = await parseAsync(ctx, depth, current[i]);
1051
- else nodes[i] = 0;
1363
+ const len = current.length;
1364
+ const nodes = new Array(len);
1365
+ for (let i = 0, node; i < len; i++) if (i in current) {
1366
+ node = parseValueAsync(ctx, depth, current[i]);
1367
+ nodes[i] = node instanceof Promise ? await node : node;
1368
+ } else nodes[i] = 0;
1052
1369
  return nodes;
1053
1370
  }
1054
1371
  async function parseArray$1(ctx, depth, id, current) {
1055
1372
  return createArrayNode(id, current, await parseItems$1(ctx, depth, current));
1056
1373
  }
1057
1374
  async function parseProperties$1(ctx, depth, properties) {
1058
- const entries = Object.entries(properties);
1059
- const keyNodes = [];
1060
- const valueNodes = [];
1061
- for (let i = 0, len = entries.length; i < len; i++) {
1062
- keyNodes.push(serializeString(entries[i][0]));
1063
- valueNodes.push(await parseAsync(ctx, depth, entries[i][1]));
1375
+ const keys = Object.keys(properties);
1376
+ const len = keys.length;
1377
+ const keyNodes = new Array(len);
1378
+ const valueNodes = new Array(len);
1379
+ for (let i = 0, key, node; i < len; i++) {
1380
+ key = keys[i];
1381
+ keyNodes[i] = serializeString(key);
1382
+ node = parseValueAsync(ctx, depth, properties[key]);
1383
+ valueNodes[i] = node instanceof Promise ? await node : node;
1064
1384
  }
1065
1385
  if (SYM_ITERATOR in properties) {
1066
1386
  keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
1067
- valueNodes.push(createIteratorFactoryInstanceNode(parseIteratorFactory(ctx.base), await parseAsync(ctx, depth, createSequenceFromIterable(properties))));
1387
+ valueNodes.push(createIteratorFactoryInstanceNode(28, parseIteratorFactory(ctx.base), await parseAsync(ctx, depth, createSequenceFromIterable(properties))));
1068
1388
  }
1069
1389
  if (SYM_ASYNC_ITERATOR in properties) {
1070
1390
  keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
1071
- valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), await parseAsync(ctx, depth, createStreamFromAsyncIterable(properties))));
1391
+ valueNodes.push(createIteratorFactoryInstanceNode(30, parseAsyncIteratorFactory(ctx.base), await parseAsyncIterable$1(ctx, depth, properties)));
1072
1392
  }
1073
1393
  if (SYM_TO_STRING_TAG in properties) {
1074
1394
  keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
@@ -1089,167 +1409,183 @@ async function parsePlainObject$1(ctx, depth, id, current, empty) {
1089
1409
  async function parseBoxed$1(ctx, depth, id, current) {
1090
1410
  return createBoxedNode(id, await parseAsync(ctx, depth, current.valueOf()));
1091
1411
  }
1092
- async function parseTypedArray$1(ctx, depth, id, current) {
1093
- current = getArrayBufferView(ctx.base, current);
1094
- return createTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
1095
- }
1096
- async function parseBigIntTypedArray$1(ctx, depth, id, current) {
1412
+ async function parseView$1(ctx, depth, type, id, current) {
1097
1413
  current = getArrayBufferView(ctx.base, current);
1098
- return createBigIntTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
1414
+ return createViewNode(type, id, current, await parseAsync(ctx, depth, current.buffer));
1099
1415
  }
1100
- async function parseDataView$1(ctx, depth, id, current) {
1101
- current = getArrayBufferView(ctx.base, current);
1102
- return createDataViewNode(id, current, await parseAsync(ctx, depth, current.buffer));
1103
- }
1104
- async function parseError$1(ctx, depth, id, current) {
1105
- const options = getErrorOptions(current, ctx.base.features);
1106
- return createErrorNode(id, current, options ? await parseProperties$1(ctx, depth, options) : void 0);
1107
- }
1108
- async function parseAggregateError$1(ctx, depth, id, current) {
1416
+ async function parseError$1(ctx, depth, type, id, current) {
1109
1417
  const options = getErrorOptions(current, ctx.base.features);
1110
- return createAggregateErrorNode(id, current, options ? await parseProperties$1(ctx, depth, options) : void 0);
1418
+ return createErrorNode(type, id, current, options ? await parseProperties$1(ctx, depth, options) : void 0);
1111
1419
  }
1112
1420
  async function parseMap$1(ctx, depth, id, current) {
1113
1421
  const sentinel = parseMapSentinel(ctx.base);
1114
- const keyNodes = [];
1115
- const valueNodes = [];
1422
+ const keyNodes = new Array(current.size);
1423
+ const valueNodes = new Array(current.size);
1424
+ let node;
1425
+ let i = 0;
1116
1426
  for (const [key, value] of current.entries()) {
1117
- keyNodes.push(await parseAsync(ctx, depth, key));
1118
- valueNodes.push(await parseAsync(ctx, depth, value));
1427
+ node = parseValueAsync(ctx, depth, key);
1428
+ keyNodes[i] = node instanceof Promise ? await node : node;
1429
+ node = parseValueAsync(ctx, depth, value);
1430
+ valueNodes[i] = node instanceof Promise ? await node : node;
1431
+ i++;
1119
1432
  }
1120
1433
  return createMapNode(id, sentinel, keyNodes, valueNodes);
1121
1434
  }
1122
1435
  async function parseSet$1(ctx, depth, id, current) {
1123
- const items = [];
1124
- for (const item of current.keys()) items.push(await parseAsync(ctx, depth, item));
1436
+ const items = new Array(current.size);
1437
+ let node;
1438
+ let i = 0;
1439
+ for (const item of current.keys()) {
1440
+ node = parseValueAsync(ctx, depth, item);
1441
+ items[i++] = node instanceof Promise ? await node : node;
1442
+ }
1125
1443
  return createSetNode(id, items);
1126
1444
  }
1127
- async function parsePlugin$1(ctx, depth, id, current) {
1128
- const currentPlugins = ctx.base.plugins;
1445
+ async function parsePlugin$1(ctx, depth, id, current, currentPlugins) {
1129
1446
  if (currentPlugins) for (let i = 0, len = currentPlugins.length; i < len; i++) {
1130
1447
  const plugin = currentPlugins[i];
1131
- if (plugin.parse.async && plugin.test(current)) return createPluginNode(id, plugin.tag, await plugin.parse.async(current, new AsyncParsePluginContext(ctx, depth), { id }));
1448
+ if (plugin.parse.async && plugin.test(current)) return createPluginNode(id, plugin.tag, await plugin.parse.async(current, {
1449
+ parse: (value) => parseAsync(ctx, depth, value),
1450
+ parseStreamSource(source) {
1451
+ if (depth >= ctx.base.depthLimit) throw new SerovalDepthLimitError(ctx.base.depthLimit);
1452
+ return parseAsyncIterable$1(ctx, depth + 1, source);
1453
+ }
1454
+ }, { id }));
1132
1455
  }
1133
1456
  }
1134
1457
  async function parsePromise$1(ctx, depth, id, current) {
1135
1458
  const [status, result] = await promiseToResult(current);
1136
- return createSerovalNode(12, id, status, void 0, void 0, void 0, void 0, void 0, await parseAsync(ctx, depth, result), void 0, void 0, void 0);
1459
+ return createSerovalNode(12, id, status, void 0, void 0, void 0, void 0, void 0, await parseAsync(ctx, depth, result));
1137
1460
  }
1138
1461
  function parseStreamHandle(depth, id, current, resolve, reject) {
1139
1462
  const sequence = [];
1140
- const cleanup = current.on({
1141
- next: (value) => {
1142
- markParserRef(this.base, id);
1143
- parseAsync(this, depth, value).then((data) => {
1144
- sequence.push(createStreamNextNode(id, data));
1145
- }, (data) => {
1146
- reject(data);
1147
- cleanup();
1148
- });
1149
- },
1150
- throw: (value) => {
1151
- markParserRef(this.base, id);
1152
- parseAsync(this, depth, value).then((data) => {
1153
- sequence.push(createStreamThrowNode(id, data));
1154
- resolve(sequence);
1155
- cleanup();
1156
- }, (data) => {
1157
- reject(data);
1158
- cleanup();
1159
- });
1160
- },
1161
- return: (value) => {
1162
- markParserRef(this.base, id);
1163
- parseAsync(this, depth, value).then((data) => {
1164
- sequence.push(createStreamReturnNode(id, data));
1165
- resolve(sequence);
1166
- cleanup();
1167
- }, (data) => {
1168
- reject(data);
1169
- cleanup();
1170
- });
1463
+ let unparsed = 0;
1464
+ let ended = false;
1465
+ let settled = false;
1466
+ const fail = (error) => {
1467
+ if (!settled) {
1468
+ settled = true;
1469
+ try {
1470
+ cleanup(error);
1471
+ } catch {}
1472
+ reject(error);
1171
1473
  }
1172
- });
1474
+ };
1475
+ const handle = (type) => (value, accept) => {
1476
+ if (settled) return;
1477
+ markParserRef(this.base, id);
1478
+ const slot = sequence.push(void 0) - 1;
1479
+ unparsed++;
1480
+ if (type !== 32) ended = true;
1481
+ parseAsync(this, depth, value).then((data) => {
1482
+ if (!settled) {
1483
+ sequence[slot] = createStreamEventNode(type, id, data);
1484
+ unparsed--;
1485
+ accept?.();
1486
+ if (ended && unparsed === 0) {
1487
+ settled = true;
1488
+ try {
1489
+ cleanup();
1490
+ } catch (error) {
1491
+ reject(error);
1492
+ return;
1493
+ }
1494
+ resolve(sequence);
1495
+ }
1496
+ }
1497
+ }, fail);
1498
+ };
1499
+ const listener = {
1500
+ next: handle(32),
1501
+ throw: handle(33),
1502
+ return: handle(34)
1503
+ };
1504
+ const cleanup = isLiveStream(current) ? current.pump(listener) : current.on(listener);
1173
1505
  }
1174
1506
  async function parseStream$1(ctx, depth, id, current) {
1175
1507
  return createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), await new Promise(parseStreamHandle.bind(ctx, depth, id, current)));
1176
1508
  }
1509
+ /**
1510
+ * Collects an async iterable into a replay node, one value at a time.
1511
+ */
1512
+ async function parseAsyncIterable$1(ctx, depth, current) {
1513
+ const id = createIndexForValue(ctx.base, {});
1514
+ const reference = parseSpecialReference(ctx.base, 4);
1515
+ const iterator = current[SYM_ASYNC_ITERATOR]();
1516
+ const sequence = [];
1517
+ for (;;) {
1518
+ let result;
1519
+ try {
1520
+ result = await iterator.next();
1521
+ } catch (error) {
1522
+ markParserRef(ctx.base, id);
1523
+ sequence.push(createStreamEventNode(33, id, await parseAsync(ctx, depth, error)));
1524
+ break;
1525
+ }
1526
+ markParserRef(ctx.base, id);
1527
+ let parsed;
1528
+ try {
1529
+ parsed = await parseAsync(ctx, depth, result.value);
1530
+ } catch (error) {
1531
+ Promise.resolve().then(() => iterator.return?.()).catch(() => {});
1532
+ throw error;
1533
+ }
1534
+ sequence.push(createStreamEventNode(result.done ? 34 : 32, id, parsed));
1535
+ if (result.done) break;
1536
+ }
1537
+ return createStreamConstructorNode(id, reference, sequence);
1538
+ }
1177
1539
  async function parseSequence$1(ctx, depth, id, current) {
1178
- const nodes = [];
1179
- for (let i = 0, len = current.v.length; i < len; i++) nodes[i] = await parseAsync(ctx, depth, current.v[i]);
1540
+ const len = current.v.length;
1541
+ const nodes = new Array(len);
1542
+ for (let i = 0, node; i < len; i++) {
1543
+ node = parseValueAsync(ctx, depth, current.v[i]);
1544
+ nodes[i] = node instanceof Promise ? await node : node;
1545
+ }
1180
1546
  return createSequenceNode(id, nodes, current.t, current.d);
1181
1547
  }
1182
1548
  async function parseObjectAsync(ctx, depth, id, current) {
1183
1549
  if (Array.isArray(current)) return parseArray$1(ctx, depth, id, current);
1184
1550
  if (isStream(current)) return parseStream$1(ctx, depth, id, current);
1185
1551
  if (isSequence(current)) return parseSequence$1(ctx, depth, id, current);
1186
- let currentClass = current.constructor;
1187
- if (currentClass !== void 0 && typeof currentClass !== "function") {
1188
- const proto = Object.getPrototypeOf(current);
1189
- currentClass = proto === null ? void 0 : proto.constructor;
1190
- }
1552
+ const currentClass = getObjectClass(current);
1191
1553
  if (currentClass === OpaqueReference) return parseAsync(ctx, depth, current.replacement);
1192
- const parsed = await parsePlugin$1(ctx, depth, id, current);
1554
+ const parsed = await parsePlugin$1(ctx, depth, id, current, getObjectPlugins(ctx.base, current, currentClass));
1193
1555
  if (parsed) return parsed;
1194
- switch (currentClass) {
1195
- case Object: return parsePlainObject$1(ctx, depth, id, current, false);
1196
- case void 0: return parsePlainObject$1(ctx, depth, id, current, true);
1197
- case Date: return createDateNode(id, current);
1198
- case Error:
1199
- case EvalError:
1200
- case RangeError:
1201
- case ReferenceError:
1202
- case SyntaxError:
1203
- case TypeError:
1204
- case URIError: return parseError$1(ctx, depth, id, current);
1205
- case Number:
1206
- case Boolean:
1207
- case String:
1208
- case BigInt: return parseBoxed$1(ctx, depth, id, current);
1209
- case ArrayBuffer: return createArrayBufferNode(ctx.base, id, current);
1210
- case Int8Array:
1211
- case Int16Array:
1212
- case Int32Array:
1213
- case Uint8Array:
1214
- case Uint16Array:
1215
- case Uint32Array:
1216
- case Uint8ClampedArray:
1217
- case Float32Array:
1218
- case Float64Array: return parseTypedArray$1(ctx, depth, id, current);
1219
- case DataView: return parseDataView$1(ctx, depth, id, current);
1220
- case Map: return parseMap$1(ctx, depth, id, current);
1221
- case Set: return parseSet$1(ctx, depth, id, current);
1222
- }
1223
- if (currentClass === Promise || current instanceof Promise) return parsePromise$1(ctx, depth, id, current);
1224
- const currentFeatures = ctx.base.features;
1225
- if (currentFeatures & 32 && currentClass === RegExp) return createRegExpNode(id, current);
1226
- if (currentFeatures & 16) switch (currentClass) {
1227
- case BigInt64Array:
1228
- case BigUint64Array: return parseBigIntTypedArray$1(ctx, depth, id, current);
1229
- }
1230
- if (currentFeatures & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) return parseAggregateError$1(ctx, depth, id, current);
1231
- if (currentFeatures & 64 && typeof Temporal !== "undefined") switch (currentClass) {
1232
- case Temporal.Instant: return createTemporalNode(id, 0, current);
1233
- case Temporal.Duration: return createTemporalNode(id, 1, current);
1234
- case Temporal.PlainDate: return createTemporalNode(id, 2, current);
1235
- case Temporal.PlainDateTime: return createTemporalNode(id, 3, current);
1236
- case Temporal.PlainMonthDay: return createTemporalNode(id, 4, current);
1237
- case Temporal.PlainTime: return createTemporalNode(id, 5, current);
1238
- case Temporal.PlainYearMonth: return createTemporalNode(id, 6, current);
1239
- case Temporal.ZonedDateTime: return createTemporalNode(id, 7, current);
1240
- }
1241
- if (current instanceof Error) return parseError$1(ctx, depth, id, current);
1242
- if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) return parsePlainObject$1(ctx, depth, id, current, !!currentClass);
1243
- throw new SerovalUnsupportedTypeError(current);
1556
+ if (currentClass === Object) return parsePlainObject$1(ctx, depth, id, current, false);
1557
+ switch (getObjectKind(current, currentClass, ctx.base.features)) {
1558
+ case 2: return parsePlainObject$1(ctx, depth, id, current, true);
1559
+ case 3: return createDateNode(id, current);
1560
+ case 4: return parseError$1(ctx, depth, 13, id, current);
1561
+ case 5: return parseError$1(ctx, depth, 14, id, current);
1562
+ case 6: return parseBoxed$1(ctx, depth, id, current);
1563
+ case 7: return createArrayBufferNode(ctx.base, id, current);
1564
+ case 8: return parseView$1(ctx, depth, 15, id, current);
1565
+ case 9: return parseView$1(ctx, depth, 16, id, current);
1566
+ case 10: return parseView$1(ctx, depth, 20, id, current);
1567
+ case 11: return parseMap$1(ctx, depth, id, current);
1568
+ case 12: return parseSet$1(ctx, depth, id, current);
1569
+ case 13: return parsePromise$1(ctx, depth, id, current);
1570
+ case 14: return createRegExpNode(id, current);
1571
+ case 15: return createTemporalNode(id, getTemporalType(currentClass), current);
1572
+ case 16: return parsePlainObject$1(ctx, depth, id, current, !!currentClass);
1573
+ default: throw new SerovalUnsupportedTypeError(current);
1574
+ }
1244
1575
  }
1245
1576
  async function parseFunctionAsync(ctx, depth, current) {
1246
1577
  const ref = getReferenceNode(ctx.base, current);
1247
- if (ref.type !== 0) return ref.value;
1248
- const plugin = await parsePlugin$1(ctx, depth, ref.value, current);
1578
+ if (typeof ref !== "number") return ref;
1579
+ const plugin = await parsePlugin$1(ctx, depth, ref, current, ctx.base.plugins);
1249
1580
  if (plugin) return plugin;
1250
1581
  throw new SerovalUnsupportedTypeError(current);
1251
1582
  }
1252
- async function parseAsync(ctx, depth, current) {
1583
+ /**
1584
+ * Parses primitives and already-seen values synchronously; only objects and
1585
+ * functions come back as a Promise. Errors are thrown synchronously, which
1586
+ * an async caller turns into a rejection as before.
1587
+ */
1588
+ function parseValueAsync(ctx, depth, current) {
1253
1589
  if (depth >= ctx.base.depthLimit) throw new SerovalDepthLimitError(ctx.base.depthLimit);
1254
1590
  switch (typeof current) {
1255
1591
  case "boolean": return current ? TRUE_NODE : FALSE_NODE;
@@ -1260,7 +1596,7 @@ async function parseAsync(ctx, depth, current) {
1260
1596
  case "object":
1261
1597
  if (current) {
1262
1598
  const ref = getReferenceNode(ctx.base, current);
1263
- return ref.type === 0 ? await parseObjectAsync(ctx, depth + 1, ref.value, current) : ref.value;
1599
+ return typeof ref === "number" ? parseObjectAsync(ctx, depth + 1, ref, current) : ref;
1264
1600
  }
1265
1601
  return NULL_NODE;
1266
1602
  case "symbol": return parseWellKnownSymbol(ctx.base, current);
@@ -1268,6 +1604,9 @@ async function parseAsync(ctx, depth, current) {
1268
1604
  default: throw new SerovalUnsupportedTypeError(current);
1269
1605
  }
1270
1606
  }
1607
+ async function parseAsync(ctx, depth, current) {
1608
+ return await parseValueAsync(ctx, depth, current);
1609
+ }
1271
1610
  async function parseTopAsync(ctx, current) {
1272
1611
  try {
1273
1612
  return await parseAsync(ctx, 0, current);
@@ -1276,32 +1615,6 @@ async function parseTopAsync(ctx, current) {
1276
1615
  }
1277
1616
  }
1278
1617
  //#endregion
1279
- //#region src/core/plugin.ts
1280
- let SerovalMode = /* @__PURE__ */ function(SerovalMode) {
1281
- SerovalMode[SerovalMode["Vanilla"] = 1] = "Vanilla";
1282
- SerovalMode[SerovalMode["Cross"] = 2] = "Cross";
1283
- return SerovalMode;
1284
- }({});
1285
- function createPlugin(plugin) {
1286
- return plugin;
1287
- }
1288
- function dedupePlugins(deduped, plugins) {
1289
- for (let i = 0, len = plugins.length; i < len; i++) {
1290
- const current = plugins[i];
1291
- if (!deduped.has(current)) {
1292
- deduped.add(current);
1293
- if (current.extends) dedupePlugins(deduped, current.extends);
1294
- }
1295
- }
1296
- }
1297
- function resolvePlugins(plugins) {
1298
- if (plugins) {
1299
- const deduped = /* @__PURE__ */ new Set();
1300
- dedupePlugins(deduped, plugins);
1301
- return [...deduped];
1302
- }
1303
- }
1304
- //#endregion
1305
1618
  //#region src/core/utils/valid-properties.ts
1306
1619
  function isValidKey(key) {
1307
1620
  switch (key) {
@@ -1327,7 +1640,6 @@ function isValidSymbol(symbol) {
1327
1640
  //#endregion
1328
1641
  //#region src/core/context/deserializer.ts
1329
1642
  const DEFAULT_MAX_BASE64_LENGTH = 1e6;
1330
- const MIN_NATIVE_BASE64_LENGTH = 512;
1331
1643
  const MAX_BIGINT_LENGTH = 1e4;
1332
1644
  const MAX_REGEXP_SOURCE_LENGTH = 2e4;
1333
1645
  function applyObjectFlag(obj, flag) {
@@ -1339,68 +1651,50 @@ function applyObjectFlag(obj, flag) {
1339
1651
  }
1340
1652
  }
1341
1653
  const DEFAULT_DEPTH_LIMIT = 1e3;
1342
- function createBaseDeserializerContext(mode, options) {
1343
- var _options$maxBase64Len, _options$features;
1344
- const maxBase64Length = (_options$maxBase64Len = options.maxBase64Length) !== null && _options$maxBase64Len !== void 0 ? _options$maxBase64Len : DEFAULT_MAX_BASE64_LENGTH;
1654
+ function createBaseDeserializerContext(options) {
1655
+ const maxBase64Length = options.maxBase64Length ?? DEFAULT_MAX_BASE64_LENGTH;
1345
1656
  if (!Number.isSafeInteger(maxBase64Length) || maxBase64Length < 0) throw new RangeError("maxBase64Length must be a non-negative safe integer");
1346
- const refs = options.refs || /* @__PURE__ */ new Map();
1657
+ const refs = options.refs ?? /* @__PURE__ */ new Map();
1347
1658
  if (!("types" in refs)) Object.assign(refs, { types: /* @__PURE__ */ new Map() });
1348
1659
  return {
1349
- mode,
1350
1660
  plugins: options.plugins,
1351
1661
  refs,
1352
- features: (_options$features = options.features) !== null && _options$features !== void 0 ? _options$features : 127 ^ (options.disabledFeatures || 0),
1662
+ features: options.features ?? 127 ^ (options.disabledFeatures ?? 0),
1353
1663
  depthLimit: options.depthLimit || DEFAULT_DEPTH_LIMIT,
1354
1664
  maxBase64Length
1355
1665
  };
1356
1666
  }
1357
1667
  function createVanillaDeserializerContext(options) {
1358
1668
  return {
1359
- mode: 1,
1360
- base: createBaseDeserializerContext(1, options),
1361
- child: void 0,
1362
- state: { marked: new Set(options.markedRefs) }
1669
+ base: createBaseDeserializerContext(options),
1670
+ marked: new Set(options.markedRefs)
1363
1671
  };
1364
1672
  }
1365
1673
  function createCrossDeserializerContext(options) {
1366
1674
  return {
1367
- mode: 2,
1368
- base: createBaseDeserializerContext(2, options),
1369
- child: void 0
1675
+ base: createBaseDeserializerContext(options),
1676
+ marked: void 0
1370
1677
  };
1371
1678
  }
1372
- var DeserializePluginContext = class {
1373
- constructor(_p, depth) {
1374
- this._p = _p;
1375
- this.depth = depth;
1376
- }
1377
- deserialize(node) {
1378
- return deserialize$1(this._p, this.depth, node);
1379
- }
1380
- };
1381
1679
  function guardIndexedValue(ctx, id) {
1382
- if (id < 0 || !Number.isFinite(id) || !Number.isInteger(id)) throw new SerovalMalformedNodeError({
1680
+ const node = {
1383
1681
  t: 4,
1384
1682
  i: id
1385
- });
1386
- if (ctx.refs.has(id)) throw new Error("Conflicted ref id: " + id);
1683
+ };
1684
+ if (id < 0 || !Number.isInteger(id)) throw new SerovalMalformedNodeError(node);
1685
+ if (ctx.refs.has(id)) throw new SerovalConflictedNodeIdError(node);
1387
1686
  }
1388
1687
  function isThennable(value) {
1389
1688
  return !!value && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function";
1390
1689
  }
1391
- function assignIndexedValueVanilla(ctx, id, value) {
1392
- guardIndexedValue(ctx.base, id);
1393
- if (ctx.state.marked.has(id)) ctx.base.refs.set(id, value);
1394
- return value;
1395
- }
1396
- function assignIndexedValueCross(ctx, id, value) {
1690
+ const ignoreRejection = () => {};
1691
+ function assignIndexedValue$1(ctx, id, value) {
1397
1692
  guardIndexedValue(ctx.base, id);
1398
- ctx.base.refs.set(id, value);
1693
+ if (ctx.base.pending && value instanceof Promise) value.catch(ignoreRejection);
1694
+ const marked = ctx.marked;
1695
+ if (!marked || marked.has(id)) ctx.base.refs.set(id, value);
1399
1696
  return value;
1400
1697
  }
1401
- function assignIndexedValue$1(ctx, id, value) {
1402
- return ctx.mode === 1 ? assignIndexedValueVanilla(ctx, id, value) : assignIndexedValueCross(ctx, id, value);
1403
- }
1404
1698
  function deserializeKnownValue(node, record, key) {
1405
1699
  if (Object.hasOwn(record, key)) return record[key];
1406
1700
  throw new SerovalMalformedNodeError(node);
@@ -1457,7 +1751,8 @@ function deserializeProperties(ctx, depth, node, result) {
1457
1751
  const keys = node.k;
1458
1752
  validateNodeList(node, keys);
1459
1753
  validateNodeList(node, node.v);
1460
- if (keys.length > 0) for (let i = 0, vals = node.v, len = keys.length; i < len; i++) assignProperty(ctx, depth, result, keys[i], vals[i]);
1754
+ const len = keys.length;
1755
+ if (len > 0) for (let i = 0, vals = node.v; i < len; i++) assignProperty(ctx, depth, result, keys[i], vals[i]);
1461
1756
  return result;
1462
1757
  }
1463
1758
  function deserializeObject(ctx, depth, node) {
@@ -1471,35 +1766,8 @@ function deserializeDate(ctx, node) {
1471
1766
  }
1472
1767
  function deserializeTemporal(ctx, node) {
1473
1768
  if (!(ctx.base.features & 64)) throw new SerovalUnsupportedNodeError(node);
1474
- let value;
1475
- switch (node.c) {
1476
- case 0:
1477
- value = Temporal.Instant.from(node.s);
1478
- break;
1479
- case 1:
1480
- value = Temporal.Duration.from(node.s);
1481
- break;
1482
- case 2:
1483
- value = Temporal.PlainDate.from(node.s);
1484
- break;
1485
- case 3:
1486
- value = Temporal.PlainDateTime.from(node.s);
1487
- break;
1488
- case 4:
1489
- value = Temporal.PlainMonthDay.from(node.s);
1490
- break;
1491
- case 5:
1492
- value = Temporal.PlainTime.from(node.s);
1493
- break;
1494
- case 6:
1495
- value = Temporal.PlainYearMonth.from(node.s);
1496
- break;
1497
- case 7:
1498
- value = Temporal.ZonedDateTime.from(node.s);
1499
- break;
1500
- default: throw new SerovalMalformedNodeError(node);
1501
- }
1502
- return assignIndexedValue$1(ctx, node.i, value);
1769
+ const construct = Temporal[deserializeKnownValue(node, TEMPORAL_TYPE_NAME, node.c)];
1770
+ return assignIndexedValue$1(ctx, node.i, construct.from(node.s));
1503
1771
  }
1504
1772
  function deserializeRegExp(ctx, node) {
1505
1773
  if (ctx.base.features & 32) {
@@ -1525,32 +1793,15 @@ function deserializeMap(ctx, depth, node) {
1525
1793
  function deserializeArrayBuffer(ctx, node) {
1526
1794
  if (typeof node.s !== "string") throw new SerovalMalformedNodeError(node);
1527
1795
  if (node.s.length > ctx.base.maxBase64Length) throw new RangeError("ArrayBuffer exceeds maxBase64Length (" + ctx.base.maxBase64Length + ")");
1528
- const source = deserializeString(node.s);
1529
- let buffer;
1530
- if (source.length < MIN_NATIVE_BASE64_LENGTH || typeof Buffer === "undefined") buffer = ARRAY_BUFFER_CONSTRUCTOR(source);
1531
- else {
1532
- const decoded = atob(source);
1533
- buffer = new ArrayBuffer(decoded.length);
1534
- Buffer.from(buffer).write(decoded, "latin1");
1535
- }
1796
+ const buffer = decodeArrayBuffer(deserializeString(node.s));
1536
1797
  return assignIndexedValue$1(ctx, node.i, buffer);
1537
1798
  }
1538
- function deserializeTypedArray(ctx, depth, node) {
1539
- var _node$b;
1540
- const construct = getTypedArrayConstructor(node.c);
1799
+ function deserializeView(ctx, depth, node, construct) {
1541
1800
  const source = deserialize$1(ctx, depth, node.f);
1542
1801
  if (!(source instanceof ArrayBuffer)) throw new SerovalMalformedNodeError(node);
1543
- const offset = (_node$b = node.b) !== null && _node$b !== void 0 ? _node$b : 0;
1802
+ const offset = node.b ?? 0;
1544
1803
  if (offset < 0 || offset > source.byteLength) throw new SerovalMalformedNodeError(node);
1545
- return assignIndexedValue$1(ctx, node.i, new construct(source, offset, node.l));
1546
- }
1547
- function deserializeDataView(ctx, depth, node) {
1548
- var _node$b2;
1549
- const source = deserialize$1(ctx, depth, node.f);
1550
- if (!(source instanceof ArrayBuffer)) throw new SerovalMalformedNodeError(node);
1551
- const offset = (_node$b2 = node.b) !== null && _node$b2 !== void 0 ? _node$b2 : 0;
1552
- if (offset < 0 || offset > source.byteLength) throw new SerovalMalformedNodeError(node);
1553
- return assignIndexedValue$1(ctx, node.i, new DataView(source, offset, node.l));
1804
+ return assignIndexedValue$1(ctx, node.i, construct ? new construct(source, offset, node.l) : new DataView(source, offset, node.l));
1554
1805
  }
1555
1806
  function deserializeDictionary(ctx, depth, node, result) {
1556
1807
  if (node.p) {
@@ -1584,7 +1835,7 @@ function deserializePlugin(ctx, depth, node) {
1584
1835
  const tag = deserializeString(node.c);
1585
1836
  for (let i = 0, len = currentPlugins.length; i < len; i++) {
1586
1837
  const plugin = currentPlugins[i];
1587
- if (plugin.tag === tag) return assignIndexedValue$1(ctx, node.i, plugin.deserialize(node.s, new DeserializePluginContext(ctx, depth), { id: node.i }));
1838
+ if (plugin.tag === tag) return assignIndexedValue$1(ctx, node.i, plugin.deserialize(node.s, { deserialize: (current) => deserialize$1(ctx, depth, current) }, { id: node.i }));
1588
1839
  }
1589
1840
  }
1590
1841
  throw new SerovalMissingPluginError(node.c);
@@ -1592,6 +1843,7 @@ function deserializePlugin(ctx, depth, node) {
1592
1843
  function deserializePromiseConstructor(ctx, node) {
1593
1844
  const value = assignIndexedValue$1(ctx, node.i, assignIndexedValue$1(ctx, node.s, PROMISE_CONSTRUCTOR()).p);
1594
1845
  assignNodeType(ctx, node.s, 22);
1846
+ ctx.base.pending?.add(node.s);
1595
1847
  return value;
1596
1848
  }
1597
1849
  function deserializePromiseFulfill(ctx, depth, node) {
@@ -1602,6 +1854,7 @@ function deserializePromiseFulfill(ctx, depth, node) {
1602
1854
  if (isThennable(deserialized)) throw new SerovalMalformedNodeError(node.a[1]);
1603
1855
  if (node.t === 23) deferred.s(deserialized);
1604
1856
  else deferred.f(deserialized);
1857
+ ctx.base.pending?.delete(node.i);
1605
1858
  return;
1606
1859
  }
1607
1860
  throw new SerovalMissingInstanceError("Promise");
@@ -1619,37 +1872,21 @@ function deserializeAsyncIteratorFactoryInstance(ctx, depth, node) {
1619
1872
  return streamToAsyncIterable(source);
1620
1873
  }
1621
1874
  function deserializeStreamConstructor(ctx, depth, node) {
1622
- const result = assignIndexedValue$1(ctx, node.i, createStream());
1875
+ const result = assignIndexedValue$1(ctx, node.i, new Stream(node.l === 1 ? 1 : void 0));
1623
1876
  assignNodeType(ctx, node.i, 31);
1877
+ ctx.base.pending?.add(node.i);
1624
1878
  const items = node.a;
1625
1879
  validateNodeList(node, items);
1626
1880
  const len = items.length;
1627
1881
  if (len) for (let i = 0; i < len; i++) deserialize$1(ctx, depth, items[i]);
1628
1882
  return result;
1629
1883
  }
1630
- function deserializeStreamNext(ctx, depth, node) {
1631
- const deferred = ctx.base.refs.get(node.i);
1632
- if (deferred) {
1633
- validateNodeType(ctx, node, node.i, 31);
1634
- deferred.next(deserialize$1(ctx, depth, node.f));
1635
- return;
1636
- }
1637
- throw new SerovalMissingInstanceError("Stream");
1638
- }
1639
- function deserializeStreamThrow(ctx, depth, node) {
1884
+ function deserializeStreamCall(ctx, depth, node, method) {
1640
1885
  const deferred = ctx.base.refs.get(node.i);
1641
1886
  if (deferred) {
1642
1887
  validateNodeType(ctx, node, node.i, 31);
1643
- deferred.throw(deserialize$1(ctx, depth, node.f));
1644
- return;
1645
- }
1646
- throw new SerovalMissingInstanceError("Stream");
1647
- }
1648
- function deserializeStreamReturn(ctx, depth, node) {
1649
- const deferred = ctx.base.refs.get(node.i);
1650
- if (deferred) {
1651
- validateNodeType(ctx, node, node.i, 31);
1652
- deferred.return(deserialize$1(ctx, depth, node.f));
1888
+ deferred[method](deserialize$1(ctx, depth, node.f));
1889
+ if (method !== "next") ctx.base.pending?.delete(node.i);
1653
1890
  return;
1654
1891
  }
1655
1892
  throw new SerovalMissingInstanceError("Stream");
@@ -1668,6 +1905,7 @@ function deserializeSequence(ctx, depth, node) {
1668
1905
  const size = node.a.length;
1669
1906
  if (!(isSequenceIndex(node.s, size) && isSequenceIndex(node.l, size))) throw new SerovalMalformedNodeError(node);
1670
1907
  const result = assignIndexedValue$1(ctx, node.i, createSequence([], node.s, node.l));
1908
+ assignNodeType(ctx, node.i, 35);
1671
1909
  for (let i = 0; i < size; i++) result.v[i] = deserialize$1(ctx, depth, node.a[i]);
1672
1910
  return result;
1673
1911
  }
@@ -1692,8 +1930,8 @@ function deserialize$1(ctx, depth, node) {
1692
1930
  case 8: return deserializeMap(ctx, depth, node);
1693
1931
  case 19: return deserializeArrayBuffer(ctx, node);
1694
1932
  case 16:
1695
- case 15: return deserializeTypedArray(ctx, depth, node);
1696
- case 20: return deserializeDataView(ctx, depth, node);
1933
+ case 15: return deserializeView(ctx, depth, node, getTypedArrayConstructor(node.c));
1934
+ case 20: return deserializeView(ctx, depth, node);
1697
1935
  case 14: return deserializeAggregateError(ctx, depth, node);
1698
1936
  case 13: return deserializeError(ctx, depth, node);
1699
1937
  case 12: return deserializePromise(ctx, depth, node);
@@ -1706,9 +1944,9 @@ function deserialize$1(ctx, depth, node) {
1706
1944
  case 28: return deserializeIteratorFactoryInstance(ctx, depth, node);
1707
1945
  case 30: return deserializeAsyncIteratorFactoryInstance(ctx, depth, node);
1708
1946
  case 31: return deserializeStreamConstructor(ctx, depth, node);
1709
- case 32: return deserializeStreamNext(ctx, depth, node);
1710
- case 33: return deserializeStreamThrow(ctx, depth, node);
1711
- case 34: return deserializeStreamReturn(ctx, depth, node);
1947
+ case 32: return deserializeStreamCall(ctx, depth, node, "next");
1948
+ case 33: return deserializeStreamCall(ctx, depth, node, "throw");
1949
+ case 34: return deserializeStreamCall(ctx, depth, node, "return");
1712
1950
  case 27: return deserializeIteratorFactory(ctx, depth, node);
1713
1951
  case 29: return deserializeAsyncIteratorFactory(ctx, depth, node);
1714
1952
  case 35: return deserializeSequence(ctx, depth, node);
@@ -1723,11 +1961,31 @@ function deserializeTop(ctx, node) {
1723
1961
  throw new SerovalDeserializationError(error);
1724
1962
  }
1725
1963
  }
1964
+ /**
1965
+ * Rejects every pending promise and throws into every open stream tracked
1966
+ * by `ctx.base.pending`, then drops the bookkeeping so the context no longer
1967
+ * accepts deferred values. Does nothing once the bookkeeping is gone.
1968
+ */
1969
+ function abortDeferred(ctx, reason) {
1970
+ const pending = ctx.base.pending;
1971
+ if (pending) {
1972
+ ctx.base.pending = void 0;
1973
+ const refs = ctx.base.refs;
1974
+ const errors = [];
1975
+ for (const id of pending) try {
1976
+ const value = refs.get(id);
1977
+ if (refs.types.get(id) === 22) value.f(reason);
1978
+ else value.throw(reason);
1979
+ } catch (error) {
1980
+ errors.push(error);
1981
+ }
1982
+ if (errors.length) throw errors[0];
1983
+ }
1984
+ }
1726
1985
  //#endregion
1727
1986
  //#region src/core/function-string.ts
1728
1987
  const RETURN = () => T;
1729
- const SERIALIZED_RETURN = /* @__PURE__ */ RETURN.toString();
1730
- const IS_MODERN = /* @__PURE__ */ /=>/.test(SERIALIZED_RETURN);
1988
+ const IS_MODERN = /* @__PURE__ */ (/* @__PURE__ */ RETURN.toString()).includes("=>");
1731
1989
  function createFunction(parameters, body) {
1732
1990
  if (IS_MODERN) return (parameters.length === 1 ? parameters[0] : "(" + parameters.join(",") + ")") + "=>" + (body.startsWith("{") ? "(" + body + ")" : body);
1733
1991
  return "function(" + parameters.join(",") + "){return " + body + "}";
@@ -1755,10 +2013,13 @@ function getIdentifier(index) {
1755
2013
  }
1756
2014
  //#endregion
1757
2015
  //#region src/core/utils/is-valid-identifier.ts
1758
- const IDENTIFIER_CHECK = /^[$A-Z_][0-9A-Z_$]*$/i;
1759
2016
  function isValidIdentifier(name) {
1760
- const char = name[0];
1761
- return (char === "$" || char === "_" || char >= "A" && char <= "Z" || char >= "a" && char <= "z") && IDENTIFIER_CHECK.test(name);
2017
+ const len = name.length;
2018
+ for (let i = 0; i < len; i++) {
2019
+ const code = name.charCodeAt(i);
2020
+ if (!(code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 && i > 0 || code === 95 || code === 36)) return false;
2021
+ }
2022
+ return len > 0;
1762
2023
  }
1763
2024
  //#endregion
1764
2025
  //#region src/core/context/serializer.ts
@@ -1772,58 +2033,31 @@ function getAssignmentExpression(assignment) {
1772
2033
  }
1773
2034
  }
1774
2035
  const MAX_ASSIGNMENT_CHAIN_LENGTH = 100;
1775
- function mergeAssignments(assignments) {
1776
- const newAssignments = [];
1777
- let current = assignments[0];
2036
+ function resolveAssignments(assignments) {
2037
+ if (!assignments.length) return void 0;
2038
+ let previous = assignments[0];
2039
+ let expression = getAssignmentExpression(previous);
2040
+ let result = "";
1778
2041
  let chainLength = 1;
1779
- for (let i = 1, len = assignments.length, item, prev = current; i < len; i++) {
1780
- item = assignments[i];
2042
+ for (let index = 1, length = assignments.length; index < length; index++) {
2043
+ const assignment = assignments[index];
1781
2044
  if (chainLength === MAX_ASSIGNMENT_CHAIN_LENGTH) {
1782
- newAssignments.push(current);
1783
- current = item;
2045
+ result += expression + ",";
2046
+ expression = getAssignmentExpression(assignment);
1784
2047
  chainLength = 0;
1785
- } else if (item.t === 0 && prev.t === 0 && item.v === prev.v) current = {
1786
- t: 0,
1787
- s: item.s,
1788
- k: void 0,
1789
- v: getAssignmentExpression(current)
1790
- };
1791
- else if (item.t === 2 && prev.t === 2 && item.s === prev.s) current = {
1792
- t: 2,
1793
- s: getAssignmentExpression(current),
1794
- k: item.k,
1795
- v: item.v
1796
- };
1797
- else if (item.t === 1 && prev.t === 1 && item.s === prev.s) current = {
1798
- t: 1,
1799
- s: getAssignmentExpression(current),
1800
- k: void 0,
1801
- v: item.v
1802
- };
1803
- else if (item.t === 3 && prev.t === 2 && item.s === prev.s) current = {
1804
- t: 3,
1805
- s: getAssignmentExpression(current),
1806
- k: item.k,
1807
- v: void 0
1808
- };
2048
+ } else if (assignment.t === 0 && previous.t === 0 && assignment.v === previous.v) expression = assignment.s + "=" + expression;
2049
+ else if (assignment.t === 2 && previous.t === 2 && assignment.s === previous.s) expression += ".set(" + assignment.k + "," + assignment.v + ")";
2050
+ else if (assignment.t === 1 && previous.t === 1 && assignment.s === previous.s) expression += ".add(" + assignment.v + ")";
2051
+ else if (assignment.t === 3 && previous.t === 2 && assignment.s === previous.s) expression += ".delete(" + assignment.k + ")";
1809
2052
  else {
1810
- newAssignments.push(current);
1811
- current = item;
2053
+ result += expression + ",";
2054
+ expression = getAssignmentExpression(assignment);
1812
2055
  chainLength = 0;
1813
2056
  }
1814
2057
  chainLength++;
1815
- prev = item;
1816
- }
1817
- newAssignments.push(current);
1818
- return newAssignments;
1819
- }
1820
- function resolveAssignments(assignments) {
1821
- if (assignments.length) {
1822
- let result = "";
1823
- const merged = mergeAssignments(assignments);
1824
- for (let i = 0, len = merged.length; i < len; i++) result += getAssignmentExpression(merged[i]) + ",";
1825
- return result;
2058
+ previous = assignment;
1826
2059
  }
2060
+ return result + expression + ",";
1827
2061
  }
1828
2062
  const NULL_CONSTRUCTOR = "Object.create(null)";
1829
2063
  const SET_CONSTRUCTOR = "new Set";
@@ -1841,42 +2075,34 @@ function createBaseSerializerContext(mode, options) {
1841
2075
  mode,
1842
2076
  plugins: options.plugins,
1843
2077
  features: options.features,
1844
- marked: new Set(options.markedRefs),
2078
+ marked: Array.isArray(options.markedRefs) ? new Set(options.markedRefs) : options.markedRefs,
1845
2079
  stack: [],
1846
2080
  flags: [],
1847
- assignments: []
2081
+ assignments: [],
2082
+ assignAll: mode === 2 && !options.assignSharedRefsOnly
1848
2083
  };
1849
2084
  }
1850
2085
  function createVanillaSerializerState() {
1851
2086
  return {
1852
2087
  valid: /* @__PURE__ */ new Map(),
1853
- vars: []
2088
+ vars: [],
2089
+ sentinels: /* @__PURE__ */ new Set()
1854
2090
  };
1855
2091
  }
1856
2092
  function createVanillaSerializerContext(options) {
1857
2093
  return {
1858
2094
  mode: 1,
1859
2095
  base: createBaseSerializerContext(1, options),
1860
- state: createVanillaSerializerState(),
1861
- child: void 0
2096
+ state: createVanillaSerializerState()
1862
2097
  };
1863
2098
  }
1864
2099
  function createCrossSerializerContext(options) {
1865
2100
  return {
1866
2101
  mode: 2,
1867
2102
  base: createBaseSerializerContext(2, options),
1868
- state: options,
1869
- child: void 0
2103
+ state: options
1870
2104
  };
1871
2105
  }
1872
- var SerializePluginContext = class {
1873
- constructor(_p) {
1874
- this._p = _p;
1875
- }
1876
- serialize(node) {
1877
- return serialize$1(this._p, node);
1878
- }
1879
- };
1880
2106
  /**
1881
2107
  * Creates the reference param (identifier) from the given reference ID
1882
2108
  * Calling this function means the value has been referenced somewhere
@@ -1984,7 +2210,7 @@ function createArrayAssign(ctx, ref, index, value) {
1984
2210
  createAssignment(ctx.base, getRefParam(ctx, ref) + "[" + index + "]", value);
1985
2211
  }
1986
2212
  function createObjectAssign(ctx, ref, key, value) {
1987
- if (!isValidKey(key)) {
2213
+ if (key === "__proto__") {
1988
2214
  ctx.base.assignments.push({
1989
2215
  t: 4,
1990
2216
  s: getRefParam(ctx, ref),
@@ -2002,6 +2228,15 @@ function createSequenceAssign(ctx, ref, index, value) {
2002
2228
  * Checks if the value is in the stack. Stack here is a reference
2003
2229
  * structure to know if a object is to be accessed in a TDZ.
2004
2230
  */
2231
+ function getKeyKind(key) {
2232
+ const first = key.charCodeAt(0);
2233
+ if (first >= 48 && first <= 57) {
2234
+ const check = Number(key);
2235
+ return check >= 0 && check.toString() === key ? 2 : 0;
2236
+ }
2237
+ if (key === "Infinity") return 2;
2238
+ return isValidIdentifier(key) ? 1 : 0;
2239
+ }
2005
2240
  function isIndexedValueInStack(ctx, node) {
2006
2241
  return node.t === 4 && ctx.stack.includes(node.i);
2007
2242
  }
@@ -2028,7 +2263,7 @@ function hasMarkedNode(ctx, node) {
2028
2263
  * it.
2029
2264
  */
2030
2265
  function assignIndexedValue(ctx, index, value) {
2031
- if (ctx.mode === 1 && !isSerializerRefMarked(ctx.base, index)) return value;
2266
+ if (!ctx.base.assignAll && !isSerializerRefMarked(ctx.base, index)) return value;
2032
2267
  /**
2033
2268
  * In cross-reference, we have to assume that
2034
2269
  * every reference are going to be referenced
@@ -2036,12 +2271,13 @@ function assignIndexedValue(ctx, index, value) {
2036
2271
  * all of it into the reference array.
2037
2272
  *
2038
2273
  * otherwise in vanilla, we only do this if it
2039
- * is actually referenced
2274
+ * is actually referenced. `assignSharedRefsOnly` gives cross-reference
2275
+ * output the vanilla behavior.
2040
2276
  */
2041
2277
  return getRefParam(ctx, index) + "=" + value;
2042
2278
  }
2043
2279
  function serializeReference(node) {
2044
- return "__SEROVAL_REFS__.get(\"" + node.s + "\")";
2280
+ return REFERENCES_KEY + ".get(\"" + node.s + "\")";
2045
2281
  }
2046
2282
  function serializeArrayItem(ctx, id, item, index) {
2047
2283
  if (item) {
@@ -2075,16 +2311,15 @@ function serializeArray(ctx, node) {
2075
2311
  }
2076
2312
  function serializeProperty(ctx, source, key, val) {
2077
2313
  if (typeof key === "string") {
2078
- const check = Number(key);
2079
- const isIdentifier = check >= 0 && check.toString() === key || isValidIdentifier(key);
2314
+ const kind = getKeyKind(key);
2080
2315
  if (isIndexedValueInStack(ctx.base, val)) {
2081
2316
  const refParam = getRefParam(ctx, val.i);
2082
2317
  markSerializerRef(ctx.base, source.i);
2083
- if (isIdentifier && check !== check) createObjectAssign(ctx, source.i, key, refParam);
2084
- else createArrayAssign(ctx, source.i, isIdentifier ? key : "\"" + key + "\"", refParam);
2318
+ if (kind === 1) createObjectAssign(ctx, source.i, key, refParam);
2319
+ else createArrayAssign(ctx, source.i, kind === 2 ? key : "\"" + key + "\"", refParam);
2085
2320
  return "";
2086
2321
  }
2087
- if (isValidKey(key)) return (isIdentifier ? key : "\"" + key + "\"") + ":" + serialize$1(ctx, val);
2322
+ if (key !== "__proto__") return (kind === 0 ? "\"" + key + "\"" : key) + ":" + serialize$1(ctx, val);
2088
2323
  return "[\"" + key + "\"]:" + serialize$1(ctx, val);
2089
2324
  }
2090
2325
  return "[" + serialize$1(ctx, key) + "]:" + serialize$1(ctx, val);
@@ -2096,7 +2331,7 @@ function serializeProperties(ctx, source, record) {
2096
2331
  const values = record.v;
2097
2332
  ctx.base.stack.push(source.i);
2098
2333
  let result = serializeProperty(ctx, source, keys[0], values[0]);
2099
- for (let i = 1, item = result; i < len; i++) {
2334
+ for (let i = 1, item; i < len; i++) {
2100
2335
  item = serializeProperty(ctx, source, keys[i], values[i]);
2101
2336
  result += (item && result && ",") + item;
2102
2337
  }
@@ -2117,18 +2352,14 @@ function serializeWithObjectAssign(ctx, source, value, serialized) {
2117
2352
  function serializeStringKeyAssignment(ctx, source, mainAssignments, key, value) {
2118
2353
  const base = ctx.base;
2119
2354
  const serialized = serialize$1(ctx, value);
2120
- const check = Number(key);
2121
- const isIdentifier = check >= 0 && check.toString() === key || isValidIdentifier(key);
2122
- if (isIndexedValueInStack(base, value)) {
2123
- if (isIdentifier && check !== check) createObjectAssign(ctx, source.i, key, serialized);
2124
- else createArrayAssign(ctx, source.i, isIdentifier ? key : "\"" + key + "\"", serialized);
2125
- } else {
2126
- const parentAssignment = base.assignments;
2127
- base.assignments = mainAssignments;
2128
- if (isIdentifier && check !== check) createObjectAssign(ctx, source.i, key, serialized);
2129
- else createArrayAssign(ctx, source.i, isIdentifier ? key : "\"" + key + "\"", serialized);
2130
- base.assignments = parentAssignment;
2131
- }
2355
+ const parentAssignment = base.assignments;
2356
+ if (!isIndexedValueInStack(base, value)) base.assignments = mainAssignments;
2357
+ createKeyAssign(ctx, source.i, getKeyKind(key), key, serialized);
2358
+ base.assignments = parentAssignment;
2359
+ }
2360
+ function createKeyAssign(ctx, ref, kind, key, value) {
2361
+ if (kind === 1) createObjectAssign(ctx, ref, key, value);
2362
+ else createArrayAssign(ctx, ref, kind === 2 ? key : "\"" + key + "\"", value);
2132
2363
  }
2133
2364
  function serializeAssignment(ctx, source, mainAssignments, key, value) {
2134
2365
  if (typeof key === "string") serializeStringKeyAssignment(ctx, source, mainAssignments, key, value);
@@ -2159,7 +2390,7 @@ function serializeAssignments(ctx, source, node) {
2159
2390
  function serializeDictionary(ctx, node, init) {
2160
2391
  if (node.p) {
2161
2392
  const base = ctx.base;
2162
- if (base.features & 8) init = serializeWithObjectAssign(ctx, node, node.p, init);
2393
+ if (base.features & 8 && !node.p.k.includes("__proto__")) init = serializeWithObjectAssign(ctx, node, node.p, init);
2163
2394
  else {
2164
2395
  markSerializerRef(base, node.i);
2165
2396
  const assignments = serializeAssignments(ctx, node, node.p);
@@ -2175,18 +2406,8 @@ function serializeNullConstructor(ctx, node) {
2175
2406
  function serializeDate(node) {
2176
2407
  return "new Date(\"" + node.s + "\")";
2177
2408
  }
2178
- const TEMPORAL_CONSTRUCTOR = {
2179
- [0]: "Temporal.Instant",
2180
- [1]: "Temporal.Duration",
2181
- [2]: "Temporal.PlainDate",
2182
- [3]: "Temporal.PlainDateTime",
2183
- [4]: "Temporal.PlainMonthDay",
2184
- [5]: "Temporal.PlainTime",
2185
- [6]: "Temporal.PlainYearMonth",
2186
- [7]: "Temporal.ZonedDateTime"
2187
- };
2188
2409
  function serializeTemporal(ctx, node) {
2189
- if (ctx.base.features & 64) return TEMPORAL_CONSTRUCTOR[node.c] + ".from(\"" + node.s + "\")";
2410
+ if (ctx.base.features & 64) return "Temporal." + TEMPORAL_TYPE_NAME[node.c] + ".from(\"" + node.s + "\")";
2190
2411
  throw new SerovalUnsupportedNodeError(node);
2191
2412
  }
2192
2413
  function serializeRegExp(ctx, node) {
@@ -2213,7 +2434,7 @@ function serializeSet(ctx, node) {
2213
2434
  if (size > 0) {
2214
2435
  ctx.base.stack.push(id);
2215
2436
  let result = serializeSetItem(ctx, id, items[0]);
2216
- for (let i = 1, item = result; i < size; i++) {
2437
+ for (let i = 1, item; i < size; i++) {
2217
2438
  item = serializeSetItem(ctx, id, items[i]);
2218
2439
  result += (item && result && ",") + item;
2219
2440
  }
@@ -2222,7 +2443,7 @@ function serializeSet(ctx, node) {
2222
2443
  }
2223
2444
  return serialized;
2224
2445
  }
2225
- function serializeMapEntry(ctx, id, key, val, sentinel) {
2446
+ function serializeMapEntry(ctx, id, key, val, getSentinel) {
2226
2447
  const base = ctx.base;
2227
2448
  if (isIndexedValueInStack(base, key)) {
2228
2449
  const keyRef = getRefParam(ctx, key.i);
@@ -2233,6 +2454,7 @@ function serializeMapEntry(ctx, id, key, val, sentinel) {
2233
2454
  }
2234
2455
  if (val.t !== 4 && val.i != null && hasMarkedNode(base, val)) {
2235
2456
  markSerializerRef(base, val.i);
2457
+ const sentinel = getSentinel();
2236
2458
  const serialized = "(" + serialize$1(ctx, val) + ",[" + sentinel + "," + sentinel + "])";
2237
2459
  createSetAssignment(ctx, id, keyRef, getRefParam(ctx, val.i));
2238
2460
  createDeleteAssignment(ctx, id, sentinel);
@@ -2249,6 +2471,7 @@ function serializeMapEntry(ctx, id, key, val, sentinel) {
2249
2471
  markSerializerRef(base, id);
2250
2472
  if (key.t !== 4 && key.i != null && hasMarkedNode(base, key)) {
2251
2473
  markSerializerRef(base, key.i);
2474
+ const sentinel = getSentinel();
2252
2475
  const serialized = "(" + serialize$1(ctx, key) + ",[" + sentinel + "," + sentinel + "])";
2253
2476
  createSetAssignment(ctx, id, getRefParam(ctx, key.i), valueRef);
2254
2477
  createDeleteAssignment(ctx, id, sentinel);
@@ -2268,20 +2491,27 @@ function serializeMap(ctx, node) {
2268
2491
  const size = keys.length;
2269
2492
  const id = node.i;
2270
2493
  const sentinel = node.f;
2271
- const sentinelId = getRefParam(ctx, sentinel.i);
2494
+ let sentinelRef;
2495
+ const getSentinel = () => {
2496
+ if (sentinelRef == null) {
2497
+ sentinelRef = getRefParam(ctx, sentinel.i);
2498
+ if (ctx.mode === 1) ctx.state.sentinels.add(ctx.state.valid.get(sentinel.i));
2499
+ }
2500
+ return sentinelRef;
2501
+ };
2272
2502
  const base = ctx.base;
2273
2503
  if (size > 0) {
2274
2504
  const vals = node.e.v;
2275
2505
  base.stack.push(id);
2276
- let result = serializeMapEntry(ctx, id, keys[0], vals[0], sentinelId);
2277
- for (let i = 1, item = result; i < size; i++) {
2278
- item = serializeMapEntry(ctx, id, keys[i], vals[i], sentinelId);
2506
+ let result = serializeMapEntry(ctx, id, keys[0], vals[0], getSentinel);
2507
+ for (let i = 1, item; i < size; i++) {
2508
+ item = serializeMapEntry(ctx, id, keys[i], vals[i], getSentinel);
2279
2509
  result += (item && result && ",") + item;
2280
2510
  }
2281
2511
  base.stack.pop();
2282
2512
  if (result) serialized += "([" + result + "])";
2283
2513
  }
2284
- if (sentinel.t === 26) {
2514
+ if (ctx.mode === 2 && sentinel.t === 26) {
2285
2515
  markSerializerRef(base, sentinel.i);
2286
2516
  serialized = "(" + serialize$1(ctx, sentinel) + "," + serialized + ")";
2287
2517
  }
@@ -2290,11 +2520,8 @@ function serializeMap(ctx, node) {
2290
2520
  function serializeArrayBuffer(ctx, node) {
2291
2521
  return getConstructor(ctx, node.f) + "(\"" + node.s + "\")";
2292
2522
  }
2293
- function serializeTypedArray(ctx, node) {
2294
- return "new " + node.c + "(" + serialize$1(ctx, node.f) + "," + node.b + "," + node.l + ")";
2295
- }
2296
- function serializeDataView(ctx, node) {
2297
- return "new DataView(" + serialize$1(ctx, node.f) + "," + node.b + "," + node.l + ")";
2523
+ function serializeView(ctx, node) {
2524
+ return "new " + (node.t === 20 ? "DataView" : node.c) + "(" + serialize$1(ctx, node.f) + "," + node.b + "," + node.l + ")";
2298
2525
  }
2299
2526
  function serializeAggregateError(ctx, node) {
2300
2527
  const id = node.i;
@@ -2334,11 +2561,7 @@ function serializePromiseConstructor(ctx, node) {
2334
2561
  if (ctx.mode === 1) throw new SerovalUnsupportedNodeError(node);
2335
2562
  return "(" + assignIndexedValue(ctx, node.s, getConstructor(ctx, node.f) + "()") + ").p";
2336
2563
  }
2337
- function serializePromiseResolve(ctx, node) {
2338
- if (ctx.mode === 1) throw new SerovalUnsupportedNodeError(node);
2339
- return getConstructor(ctx, node.a[0]) + "(" + getRefParam(ctx, node.i) + "," + serialize$1(ctx, node.a[1]) + ")";
2340
- }
2341
- function serializePromiseReject(ctx, node) {
2564
+ function serializePromiseResult(ctx, node) {
2342
2565
  if (ctx.mode === 1) throw new SerovalUnsupportedNodeError(node);
2343
2566
  return getConstructor(ctx, node.a[0]) + "(" + getRefParam(ctx, node.i) + "," + serialize$1(ctx, node.a[1]) + ")";
2344
2567
  }
@@ -2346,10 +2569,7 @@ function serializePlugin(ctx, node) {
2346
2569
  const currentPlugins = ctx.base.plugins;
2347
2570
  if (currentPlugins) for (let i = 0, len = currentPlugins.length; i < len; i++) {
2348
2571
  const plugin = currentPlugins[i];
2349
- if (plugin.tag === node.c) {
2350
- if (ctx.child == null) ctx.child = new SerializePluginContext(ctx);
2351
- return plugin.serialize(node.s, ctx.child, { id: node.i });
2352
- }
2572
+ if (plugin.tag === node.c) return plugin.serialize(node.s, { serialize: (current) => serialize$1(ctx, current) }, { id: node.i });
2353
2573
  }
2354
2574
  throw new SerovalMissingPluginError(node.c);
2355
2575
  }
@@ -2386,11 +2606,8 @@ function serializeAsyncIteratorFactory(ctx, node) {
2386
2606
  if (result) return result + iterator + ")";
2387
2607
  return iterator;
2388
2608
  }
2389
- function serializeAsyncIteratorFactoryInstance(ctx, node) {
2390
- return getConstructor(ctx, node.a[0]) + "(" + serialize$1(ctx, node.a[1]) + ")";
2391
- }
2392
2609
  function serializeStreamConstructor(ctx, node) {
2393
- const result = assignIndexedValue(ctx, node.i, getConstructor(ctx, node.f) + "()");
2610
+ const result = assignIndexedValue(ctx, node.i, getConstructor(ctx, node.f) + (node.l === 1 ? "(1)" : "()"));
2394
2611
  const len = node.a.length;
2395
2612
  if (len) {
2396
2613
  let values = serialize$1(ctx, node.a[0]);
@@ -2399,14 +2616,8 @@ function serializeStreamConstructor(ctx, node) {
2399
2616
  }
2400
2617
  return result;
2401
2618
  }
2402
- function serializeStreamNext(ctx, node) {
2403
- return getRefParam(ctx, node.i) + ".next(" + serialize$1(ctx, node.f) + ")";
2404
- }
2405
- function serializeStreamThrow(ctx, node) {
2406
- return getRefParam(ctx, node.i) + ".throw(" + serialize$1(ctx, node.f) + ")";
2407
- }
2408
- function serializeStreamReturn(ctx, node) {
2409
- return getRefParam(ctx, node.i) + ".return(" + serialize$1(ctx, node.f) + ")";
2619
+ function serializeStreamCall(ctx, node, method) {
2620
+ return getRefParam(ctx, node.i) + "." + method + "(" + serialize$1(ctx, node.f) + ")";
2410
2621
  }
2411
2622
  function serializeSequenceItem(ctx, id, index, item) {
2412
2623
  const base = ctx.base;
@@ -2424,7 +2635,7 @@ function serializeSequence(ctx, node) {
2424
2635
  if (size > 0) {
2425
2636
  ctx.base.stack.push(id);
2426
2637
  let result = serializeSequenceItem(ctx, id, 0, items[0]);
2427
- for (let i = 1, item = result; i < size; i++) {
2638
+ for (let i = 1, item; i < size; i++) {
2428
2639
  item = serializeSequenceItem(ctx, id, i, items[i]);
2429
2640
  result += (item && result && ",") + item;
2430
2641
  }
@@ -2446,8 +2657,8 @@ function serializeAssignable(ctx, node) {
2446
2657
  case 8: return serializeMap(ctx, node);
2447
2658
  case 19: return serializeArrayBuffer(ctx, node);
2448
2659
  case 16:
2449
- case 15: return serializeTypedArray(ctx, node);
2450
- case 20: return serializeDataView(ctx, node);
2660
+ case 15:
2661
+ case 20: return serializeView(ctx, node);
2451
2662
  case 14: return serializeAggregateError(ctx, node);
2452
2663
  case 13: return serializeError(ctx, node);
2453
2664
  case 12: return serializePromise(ctx, node);
@@ -2467,20 +2678,20 @@ function serialize$1(ctx, node) {
2467
2678
  case 1: return "\"" + node.s + "\"";
2468
2679
  case 3: return node.s + "n";
2469
2680
  case 4: return getRefParam(ctx, node.i);
2470
- case 23: return serializePromiseResolve(ctx, node);
2471
- case 24: return serializePromiseReject(ctx, node);
2681
+ case 23:
2682
+ case 24: return serializePromiseResult(ctx, node);
2472
2683
  case 27: return serializeIteratorFactory(ctx, node);
2473
- case 28: return serializeIteratorFactoryInstance(ctx, node);
2684
+ case 28:
2685
+ case 30: return serializeIteratorFactoryInstance(ctx, node);
2474
2686
  case 29: return serializeAsyncIteratorFactory(ctx, node);
2475
- case 30: return serializeAsyncIteratorFactoryInstance(ctx, node);
2476
2687
  case 31: return serializeStreamConstructor(ctx, node);
2477
- case 32: return serializeStreamNext(ctx, node);
2478
- case 33: return serializeStreamThrow(ctx, node);
2479
- case 34: return serializeStreamReturn(ctx, node);
2688
+ case 32: return serializeStreamCall(ctx, node, "next");
2689
+ case 33: return serializeStreamCall(ctx, node, "throw");
2690
+ case 34: return serializeStreamCall(ctx, node, "return");
2480
2691
  default: return assignIndexedValue(ctx, node.i, serializeAssignable(ctx, node));
2481
2692
  }
2482
2693
  }
2483
- function serializeTopVanilla(ctx, tree) {
2694
+ function serializeVanilla(ctx, tree) {
2484
2695
  const result = serialize$1(ctx, tree);
2485
2696
  if (tree.i != null && ctx.state.vars.length) {
2486
2697
  const patches = resolvePatches(ctx.base);
@@ -2491,12 +2702,18 @@ function serializeTopVanilla(ctx, tree) {
2491
2702
  if (!result.startsWith(index + "=")) body = index + "=" + body;
2492
2703
  body = "(" + body + ")";
2493
2704
  }
2705
+ const sentinels = ctx.state.sentinels;
2706
+ if (sentinels.size) {
2707
+ let declarations = "";
2708
+ for (const index of sentinels) declarations += ctx.state.vars[index] + "=[],";
2709
+ body = "(" + declarations + body + ")";
2710
+ }
2494
2711
  return "(" + createFunction(ctx.state.vars, body) + ")()";
2495
2712
  }
2496
2713
  if (tree.t === 10) return "(" + result + ")";
2497
2714
  return result;
2498
2715
  }
2499
- function serializeTopCross(ctx, tree) {
2716
+ function serializeCross(ctx, tree) {
2500
2717
  const result = serialize$1(ctx, tree);
2501
2718
  const id = tree.i;
2502
2719
  if (id == null) return result;
@@ -2504,7 +2721,11 @@ function serializeTopCross(ctx, tree) {
2504
2721
  const ref = getRefParam(ctx, id);
2505
2722
  const scopeId = ctx.state.scopeId;
2506
2723
  const params = scopeId == null ? "" : "$R";
2507
- const body = patches ? "(" + result + "," + patches + ref + ")" : result;
2724
+ let body = result;
2725
+ if (patches) {
2726
+ if (!ctx.base.assignAll && !result.startsWith(ref + "=")) body = ref + "=" + result;
2727
+ body = "(" + body + "," + patches + ref + ")";
2728
+ }
2508
2729
  if (params === "") {
2509
2730
  if (tree.t === 10 && !patches) return "(" + body + ")";
2510
2731
  return body;
@@ -2512,76 +2733,35 @@ function serializeTopCross(ctx, tree) {
2512
2733
  const args = scopeId == null ? "()" : "($R[\"" + serializeString(scopeId) + "\"])";
2513
2734
  return "(" + createFunction([params], body) + ")" + args;
2514
2735
  }
2515
- //#endregion
2516
- //#region src/core/context/sync-parser.ts
2517
- function createSyncParserContext(mode, options) {
2518
- return {
2519
- type: 1,
2520
- base: createBaseParserContext(mode, options),
2521
- child: void 0
2522
- };
2736
+ function wrapSerializationError(error) {
2737
+ return error instanceof SerovalSerializationError ? error : new SerovalSerializationError(error);
2523
2738
  }
2524
- var SyncParsePluginContext = class {
2525
- constructor(_p, depth) {
2526
- this._p = _p;
2527
- this.depth = depth;
2528
- }
2529
- parse(current) {
2530
- return parseSOS(this._p, this.depth, current);
2531
- }
2532
- };
2533
- var StreamParsePluginContext = class {
2534
- constructor(_p, depth) {
2535
- this._p = _p;
2536
- this.depth = depth;
2537
- }
2538
- parse(current) {
2539
- return parseSOS(this._p, this.depth, current);
2540
- }
2541
- parseWithError(current) {
2542
- return parseWithError(this._p, this.depth, current);
2543
- }
2544
- isAlive() {
2545
- return this._p.state.alive;
2546
- }
2547
- pushPendingState() {
2548
- pushPendingState(this._p);
2549
- }
2550
- popPendingState() {
2551
- popPendingState(this._p);
2552
- }
2553
- onParse(node) {
2554
- onParse(this._p, node);
2555
- }
2556
- onError(error) {
2557
- onError(this._p, error);
2739
+ function serializeTopVanilla(ctx, tree) {
2740
+ try {
2741
+ return serializeVanilla(ctx, tree);
2742
+ } catch (error) {
2743
+ throw wrapSerializationError(error);
2558
2744
  }
2559
- addCleanup(callback) {
2560
- this._p.state.cleanups.push(callback);
2745
+ }
2746
+ function serializeTopCross(ctx, tree) {
2747
+ try {
2748
+ return serializeCross(ctx, tree);
2749
+ } catch (error) {
2750
+ throw wrapSerializationError(error);
2561
2751
  }
2562
- };
2563
- function createStreamParserState(options) {
2564
- return {
2565
- alive: true,
2566
- pending: 0,
2567
- initial: true,
2568
- buffer: [],
2569
- onParse: options.onParse,
2570
- onError: options.onError,
2571
- onDone: options.onDone,
2572
- cleanups: []
2573
- };
2574
2752
  }
2575
- function createStreamParserContext(options) {
2753
+ //#endregion
2754
+ //#region src/core/context/sync-parser.ts
2755
+ function createSyncParserContext(options) {
2576
2756
  return {
2577
- type: 2,
2578
- base: createBaseParserContext(2, options),
2579
- state: createStreamParserState(options)
2757
+ type: 1,
2758
+ base: createBaseParserContext(options)
2580
2759
  };
2581
2760
  }
2582
2761
  function parseItems(ctx, depth, current) {
2583
- const nodes = [];
2584
- for (let i = 0, len = current.length; i < len; i++) if (i in current) nodes[i] = parseSOS(ctx, depth, current[i]);
2762
+ const len = current.length;
2763
+ const nodes = new Array(len);
2764
+ for (let i = 0; i < len; i++) if (i in current) nodes[i] = parseSOS(ctx, depth, current[i]);
2585
2765
  else nodes[i] = 0;
2586
2766
  return nodes;
2587
2767
  }
@@ -2589,20 +2769,22 @@ function parseArray(ctx, depth, id, current) {
2589
2769
  return createArrayNode(id, current, parseItems(ctx, depth, current));
2590
2770
  }
2591
2771
  function parseProperties(ctx, depth, properties) {
2592
- const entries = Object.entries(properties);
2593
- const keyNodes = [];
2594
- const valueNodes = [];
2595
- for (let i = 0, len = entries.length; i < len; i++) {
2596
- keyNodes.push(serializeString(entries[i][0]));
2597
- valueNodes.push(parseSOS(ctx, depth, entries[i][1]));
2772
+ const keys = Object.keys(properties);
2773
+ const len = keys.length;
2774
+ const keyNodes = new Array(len);
2775
+ const valueNodes = new Array(len);
2776
+ for (let i = 0, key; i < len; i++) {
2777
+ key = keys[i];
2778
+ keyNodes[i] = serializeString(key);
2779
+ valueNodes[i] = parseSOS(ctx, depth, properties[key]);
2598
2780
  }
2599
2781
  if (SYM_ITERATOR in properties) {
2600
2782
  keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
2601
- valueNodes.push(createIteratorFactoryInstanceNode(parseIteratorFactory(ctx.base), parseSOS(ctx, depth, createSequenceFromIterable(properties))));
2783
+ valueNodes.push(createIteratorFactoryInstanceNode(28, parseIteratorFactory(ctx.base), parseSOS(ctx, depth, createSequenceFromIterable(properties))));
2602
2784
  }
2603
2785
  if (SYM_ASYNC_ITERATOR in properties) {
2604
2786
  keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
2605
- valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), parseSOS(ctx, depth, ctx.type === 1 ? createStream() : createStreamFromAsyncIterable(properties, ctx.state.cleanups))));
2787
+ valueNodes.push(createIteratorFactoryInstanceNode(30, parseAsyncIteratorFactory(ctx.base), parseAsyncIterable(ctx, depth, properties)));
2606
2788
  }
2607
2789
  if (SYM_TO_STRING_TAG in properties) {
2608
2790
  keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
@@ -2617,188 +2799,131 @@ function parseProperties(ctx, depth, properties) {
2617
2799
  v: valueNodes
2618
2800
  };
2619
2801
  }
2802
+ function parseAsyncIterable(ctx, depth, current) {
2803
+ if (ctx.type !== 2) throw new SerovalUnsupportedTypeError(current);
2804
+ const id = createIndexForValue(ctx.base, {});
2805
+ const result = createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), []);
2806
+ ctx.state.iterable(ctx, depth, id, current);
2807
+ return result;
2808
+ }
2620
2809
  function parsePlainObject(ctx, depth, id, current, empty) {
2621
2810
  return createObjectNode(id, current, empty, parseProperties(ctx, depth, current));
2622
2811
  }
2623
2812
  function parseBoxed(ctx, depth, id, current) {
2624
2813
  return createBoxedNode(id, parseSOS(ctx, depth, current.valueOf()));
2625
2814
  }
2626
- function parseTypedArray(ctx, depth, id, current) {
2627
- current = getArrayBufferView(ctx.base, current);
2628
- return createTypedArrayNode(id, current, parseSOS(ctx, depth, current.buffer));
2629
- }
2630
- function parseBigIntTypedArray(ctx, depth, id, current) {
2815
+ function parseView(ctx, depth, type, id, current) {
2631
2816
  current = getArrayBufferView(ctx.base, current);
2632
- return createBigIntTypedArrayNode(id, current, parseSOS(ctx, depth, current.buffer));
2633
- }
2634
- function parseDataView(ctx, depth, id, current) {
2635
- current = getArrayBufferView(ctx.base, current);
2636
- return createDataViewNode(id, current, parseSOS(ctx, depth, current.buffer));
2637
- }
2638
- function parseError(ctx, depth, id, current) {
2639
- const options = getErrorOptions(current, ctx.base.features);
2640
- return createErrorNode(id, current, options ? parseProperties(ctx, depth, options) : void 0);
2817
+ return createViewNode(type, id, current, parseSOS(ctx, depth, current.buffer));
2641
2818
  }
2642
- function parseAggregateError(ctx, depth, id, current) {
2819
+ function parseError(ctx, depth, type, id, current) {
2643
2820
  const options = getErrorOptions(current, ctx.base.features);
2644
- return createAggregateErrorNode(id, current, options ? parseProperties(ctx, depth, options) : void 0);
2821
+ return createErrorNode(type, id, current, options ? parseProperties(ctx, depth, options) : void 0);
2645
2822
  }
2646
2823
  function parseMap(ctx, depth, id, current) {
2647
2824
  const sentinel = parseMapSentinel(ctx.base);
2648
- const keyNodes = [];
2649
- const valueNodes = [];
2825
+ const keyNodes = new Array(current.size);
2826
+ const valueNodes = new Array(current.size);
2827
+ let i = 0;
2650
2828
  for (const [key, value] of current.entries()) {
2651
- keyNodes.push(parseSOS(ctx, depth, key));
2652
- valueNodes.push(parseSOS(ctx, depth, value));
2829
+ keyNodes[i] = parseSOS(ctx, depth, key);
2830
+ valueNodes[i] = parseSOS(ctx, depth, value);
2831
+ i++;
2653
2832
  }
2654
2833
  return createMapNode(id, sentinel, keyNodes, valueNodes);
2655
2834
  }
2656
2835
  function parseSet(ctx, depth, id, current) {
2657
- const items = [];
2658
- for (const item of current.keys()) items.push(parseSOS(ctx, depth, item));
2836
+ const items = new Array(current.size);
2837
+ let i = 0;
2838
+ for (const item of current.keys()) items[i++] = parseSOS(ctx, depth, item);
2659
2839
  return createSetNode(id, items);
2660
2840
  }
2661
- function parseStream(ctx, depth, id, current) {
2662
- const result = createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), []);
2663
- if (ctx.type === 1) return result;
2664
- pushPendingState(ctx);
2665
- current.on({
2666
- next: (value) => {
2667
- if (ctx.state.alive) {
2668
- const parsed = parseWithError(ctx, depth, value);
2669
- if (parsed) onParse(ctx, createStreamNextNode(id, parsed));
2670
- }
2671
- },
2672
- throw: (value) => {
2673
- if (ctx.state.alive) {
2674
- const parsed = parseWithError(ctx, depth, value);
2675
- if (parsed) onParse(ctx, createStreamThrowNode(id, parsed));
2676
- }
2677
- popPendingState(ctx);
2678
- },
2679
- return: (value) => {
2680
- if (ctx.state.alive) {
2681
- const parsed = parseWithError(ctx, depth, value);
2682
- if (parsed) onParse(ctx, createStreamReturnNode(id, parsed));
2683
- }
2684
- popPendingState(ctx);
2685
- }
2686
- });
2687
- return result;
2841
+ /**
2842
+ * Sends the events of a stream that has ended, so the copy gets all of them.
2843
+ * A stream that is still open throws, because the other sync modes cannot
2844
+ * send its later events.
2845
+ */
2846
+ function parseEndedStream(ctx, depth, id, current) {
2847
+ const events = current.endedEvents();
2848
+ if (!events) throw new SerovalUnsupportedTypeError(current);
2849
+ const values = events.values;
2850
+ const last = values.length - 1;
2851
+ const sequence = new Array(values.length);
2852
+ if (last >= 0) markParserRef(ctx.base, id);
2853
+ for (let i = 0; i <= last; i++) sequence[i] = createStreamEventNode(i < last ? 32 : events.success ? 34 : 33, id, parseSOS(ctx, depth, values[i]));
2854
+ return sequence;
2688
2855
  }
2689
- function handlePromiseSuccess(id, depth, data) {
2690
- if (this.state.alive) {
2691
- const parsed = parseWithError(this, depth, data);
2692
- if (parsed) onParse(this, createSerovalNode(23, id, void 0, void 0, void 0, void 0, void 0, [parseSpecialReference(this.base, 2), parsed], void 0, void 0, void 0, void 0));
2693
- popPendingState(this);
2856
+ function parseStream(ctx, depth, id, current) {
2857
+ const reference = parseSpecialReference(ctx.base, 4);
2858
+ if (ctx.type === 2) {
2859
+ const result = createStreamConstructorNode(id, reference, []);
2860
+ ctx.state.stream(ctx, depth, id, current);
2861
+ return result;
2694
2862
  }
2863
+ return createStreamConstructorNode(id, reference, parseEndedStream(ctx, depth, id, current));
2695
2864
  }
2696
- function handlePromiseFailure(id, depth, data) {
2697
- if (this.state.alive) {
2698
- const parsed = parseWithError(this, depth, data);
2699
- if (parsed) onParse(this, createSerovalNode(24, id, void 0, void 0, void 0, void 0, void 0, [parseSpecialReference(this.base, 3), parsed], void 0, void 0, void 0, void 0));
2700
- }
2701
- popPendingState(this);
2865
+ function parseLiveStream(ctx, depth, id, current) {
2866
+ if (ctx.type !== 2) throw new SerovalUnsupportedTypeError(current);
2867
+ const result = createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), [], 1);
2868
+ ctx.state.live(ctx, depth, id, current);
2869
+ return result;
2702
2870
  }
2703
2871
  function parsePromise(ctx, depth, id, current) {
2872
+ if (ctx.type !== 2) throw new SerovalUnsupportedTypeError(current);
2704
2873
  const resolver = createIndexForValue(ctx.base, {});
2705
- if (ctx.type === 2) {
2706
- pushPendingState(ctx);
2707
- current.then(handlePromiseSuccess.bind(ctx, resolver, depth), handlePromiseFailure.bind(ctx, resolver, depth));
2708
- }
2874
+ ctx.state.promise(ctx, resolver, depth, current);
2709
2875
  return createPromiseConstructorNode(ctx.base, id, resolver);
2710
2876
  }
2711
2877
  function parsePluginSync(ctx, depth, id, current, currentPlugins) {
2712
2878
  for (let i = 0, len = currentPlugins.length; i < len; i++) {
2713
2879
  const plugin = currentPlugins[i];
2714
- if (plugin.parse.sync && plugin.test(current)) return createPluginNode(id, plugin.tag, plugin.parse.sync(current, new SyncParsePluginContext(ctx, depth), { id }));
2880
+ if (plugin.parse.sync && plugin.test(current)) return createPluginNode(id, plugin.tag, plugin.parse.sync(current, { parse: (value) => parseSOS(ctx, depth, value) }, { id }));
2715
2881
  }
2716
2882
  }
2717
- function parsePluginStream(ctx, depth, id, current, currentPlugins) {
2718
- for (let i = 0, len = currentPlugins.length; i < len; i++) {
2719
- const plugin = currentPlugins[i];
2720
- if (plugin.parse.stream && plugin.test(current)) return createPluginNode(id, plugin.tag, plugin.parse.stream(current, new StreamParsePluginContext(ctx, depth), { id }));
2721
- }
2722
- }
2723
- function parsePlugin(ctx, depth, id, current) {
2724
- const currentPlugins = ctx.base.plugins;
2725
- if (currentPlugins) return ctx.type === 1 ? parsePluginSync(ctx, depth, id, current, currentPlugins) : parsePluginStream(ctx, depth, id, current, currentPlugins);
2883
+ function parsePlugin(ctx, depth, id, current, currentPlugins) {
2884
+ if (currentPlugins) return ctx.type === 1 ? parsePluginSync(ctx, depth, id, current, currentPlugins) : ctx.state.plugin(ctx, depth, id, current, currentPlugins);
2726
2885
  }
2727
2886
  function parseSequence(ctx, depth, id, current) {
2728
- const nodes = [];
2729
- for (let i = 0, len = current.v.length; i < len; i++) nodes[i] = parseSOS(ctx, depth, current.v[i]);
2887
+ const len = current.v.length;
2888
+ const nodes = new Array(len);
2889
+ for (let i = 0; i < len; i++) nodes[i] = parseSOS(ctx, depth, current.v[i]);
2730
2890
  return createSequenceNode(id, nodes, current.t, current.d);
2731
2891
  }
2732
2892
  function parseObjectPhase2(ctx, depth, id, current, currentClass) {
2733
- switch (currentClass) {
2734
- case Object: return parsePlainObject(ctx, depth, id, current, false);
2735
- case void 0: return parsePlainObject(ctx, depth, id, current, true);
2736
- case Date: return createDateNode(id, current);
2737
- case Error:
2738
- case EvalError:
2739
- case RangeError:
2740
- case ReferenceError:
2741
- case SyntaxError:
2742
- case TypeError:
2743
- case URIError: return parseError(ctx, depth, id, current);
2744
- case Number:
2745
- case Boolean:
2746
- case String:
2747
- case BigInt: return parseBoxed(ctx, depth, id, current);
2748
- case ArrayBuffer: return createArrayBufferNode(ctx.base, id, current);
2749
- case Int8Array:
2750
- case Int16Array:
2751
- case Int32Array:
2752
- case Uint8Array:
2753
- case Uint16Array:
2754
- case Uint32Array:
2755
- case Uint8ClampedArray:
2756
- case Float32Array:
2757
- case Float64Array: return parseTypedArray(ctx, depth, id, current);
2758
- case DataView: return parseDataView(ctx, depth, id, current);
2759
- case Map: return parseMap(ctx, depth, id, current);
2760
- case Set: return parseSet(ctx, depth, id, current);
2761
- }
2762
- if (currentClass === Promise || current instanceof Promise) return parsePromise(ctx, depth, id, current);
2763
- const currentFeatures = ctx.base.features;
2764
- if (currentFeatures & 32 && currentClass === RegExp) return createRegExpNode(id, current);
2765
- if (currentFeatures & 16) switch (currentClass) {
2766
- case BigInt64Array:
2767
- case BigUint64Array: return parseBigIntTypedArray(ctx, depth, id, current);
2768
- }
2769
- if (currentFeatures & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) return parseAggregateError(ctx, depth, id, current);
2770
- if (currentFeatures & 64 && typeof Temporal !== "undefined") switch (currentClass) {
2771
- case Temporal.Instant: return createTemporalNode(id, 0, current);
2772
- case Temporal.Duration: return createTemporalNode(id, 1, current);
2773
- case Temporal.PlainDate: return createTemporalNode(id, 2, current);
2774
- case Temporal.PlainDateTime: return createTemporalNode(id, 3, current);
2775
- case Temporal.PlainMonthDay: return createTemporalNode(id, 4, current);
2776
- case Temporal.PlainTime: return createTemporalNode(id, 5, current);
2777
- case Temporal.PlainYearMonth: return createTemporalNode(id, 6, current);
2778
- case Temporal.ZonedDateTime: return createTemporalNode(id, 7, current);
2779
- }
2780
- if (current instanceof Error) return parseError(ctx, depth, id, current);
2781
- if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) return parsePlainObject(ctx, depth, id, current, !!currentClass);
2782
- throw new SerovalUnsupportedTypeError(current);
2893
+ if (currentClass === Object) return parsePlainObject(ctx, depth, id, current, false);
2894
+ switch (getObjectKind(current, currentClass, ctx.base.features)) {
2895
+ case 2: return parsePlainObject(ctx, depth, id, current, true);
2896
+ case 3: return createDateNode(id, current);
2897
+ case 4: return parseError(ctx, depth, 13, id, current);
2898
+ case 5: return parseError(ctx, depth, 14, id, current);
2899
+ case 6: return parseBoxed(ctx, depth, id, current);
2900
+ case 7: return createArrayBufferNode(ctx.base, id, current);
2901
+ case 8: return parseView(ctx, depth, 15, id, current);
2902
+ case 9: return parseView(ctx, depth, 16, id, current);
2903
+ case 10: return parseView(ctx, depth, 20, id, current);
2904
+ case 11: return parseMap(ctx, depth, id, current);
2905
+ case 12: return parseSet(ctx, depth, id, current);
2906
+ case 13: return parsePromise(ctx, depth, id, current);
2907
+ case 14: return createRegExpNode(id, current);
2908
+ case 15: return createTemporalNode(id, getTemporalType(currentClass), current);
2909
+ case 16: return parsePlainObject(ctx, depth, id, current, !!currentClass);
2910
+ default: throw new SerovalUnsupportedTypeError(current);
2911
+ }
2783
2912
  }
2784
2913
  function parseObject(ctx, depth, id, current) {
2785
2914
  if (Array.isArray(current)) return parseArray(ctx, depth, id, current);
2786
- if (isStream(current)) return parseStream(ctx, depth, id, current);
2915
+ if (isStream(current)) return isLiveStream(current) ? parseLiveStream(ctx, depth, id, current) : parseStream(ctx, depth, id, current);
2787
2916
  if (isSequence(current)) return parseSequence(ctx, depth, id, current);
2788
- let currentClass = current.constructor;
2789
- if (currentClass !== void 0 && typeof currentClass !== "function") {
2790
- const proto = Object.getPrototypeOf(current);
2791
- currentClass = proto === null ? void 0 : proto.constructor;
2792
- }
2917
+ const currentClass = getObjectClass(current);
2793
2918
  if (currentClass === OpaqueReference) return parseSOS(ctx, depth, current.replacement);
2794
- const parsed = parsePlugin(ctx, depth, id, current);
2919
+ const parsed = parsePlugin(ctx, depth, id, current, getObjectPlugins(ctx.base, current, currentClass));
2795
2920
  if (parsed) return parsed;
2796
2921
  return parseObjectPhase2(ctx, depth, id, current, currentClass);
2797
2922
  }
2798
2923
  function parseFunction(ctx, depth, current) {
2799
2924
  const ref = getReferenceNode(ctx.base, current);
2800
- if (ref.type !== 0) return ref.value;
2801
- const plugin = parsePlugin(ctx, depth, ref.value, current);
2925
+ if (typeof ref !== "number") return ref;
2926
+ const plugin = parsePlugin(ctx, depth, ref, current, ctx.base.plugins);
2802
2927
  if (plugin) return plugin;
2803
2928
  throw new SerovalUnsupportedTypeError(current);
2804
2929
  }
@@ -2813,7 +2938,7 @@ function parseSOS(ctx, depth, current) {
2813
2938
  case "object":
2814
2939
  if (current) {
2815
2940
  const ref = getReferenceNode(ctx.base, current);
2816
- return ref.type === 0 ? parseObject(ctx, depth + 1, ref.value, current) : ref.value;
2941
+ return typeof ref === "number" ? parseObject(ctx, depth + 1, ref, current) : ref;
2817
2942
  }
2818
2943
  return NULL_NODE;
2819
2944
  case "symbol": return parseWellKnownSymbol(ctx.base, current);
@@ -2828,63 +2953,431 @@ function parseTop(ctx, current) {
2828
2953
  throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
2829
2954
  }
2830
2955
  }
2831
- function onParse(ctx, node) {
2832
- if (ctx.state.initial) ctx.state.buffer.push(node);
2833
- else onParseInternal(ctx, node, false);
2956
+ //#endregion
2957
+ //#region src/core/context/stream-parser.ts
2958
+ /**
2959
+ * Streaming parse mode. Everything here is reached through the function
2960
+ * fields of the stream parser state, which only `createStreamParserContext`
2961
+ * sets, so synchronous consumers (`serialize`, `toJSON`) never bundle it.
2962
+ */
2963
+ function createStreamParsePluginContext(ctx, depth) {
2964
+ const state = ctx.state;
2965
+ function parse(current) {
2966
+ state.parsing++;
2967
+ try {
2968
+ return parseSOS(ctx, depth, current);
2969
+ } finally {
2970
+ state.parsing--;
2971
+ if (!state.alive) releaseParserValues(ctx);
2972
+ }
2973
+ }
2974
+ return {
2975
+ parse,
2976
+ parseStreamSource(current) {
2977
+ state.parsing++;
2978
+ try {
2979
+ if (depth >= ctx.base.depthLimit) throw new SerovalDepthLimitError(ctx.base.depthLimit);
2980
+ const id = createIndexForValue(ctx.base, {});
2981
+ const node = createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), [], 1);
2982
+ iterateAsync(ctx, depth + 1, id, current, true);
2983
+ return node;
2984
+ } finally {
2985
+ state.parsing--;
2986
+ if (!state.alive) releaseParserValues(ctx);
2987
+ }
2988
+ },
2989
+ parseWithError(current) {
2990
+ try {
2991
+ return parse(current);
2992
+ } catch (error) {
2993
+ stopStreamParse(ctx, 1, error);
2994
+ return;
2995
+ }
2996
+ },
2997
+ isAlive: () => state.alive,
2998
+ pushPendingState: () => {
2999
+ pushPendingState(ctx);
3000
+ },
3001
+ popPendingState: () => {
3002
+ popPendingState(ctx);
3003
+ },
3004
+ onParse(node) {
3005
+ if (state.alive) {
3006
+ state.queue.push({
3007
+ node,
3008
+ initial: false,
3009
+ accept: void 0
3010
+ });
3011
+ drainOutput(ctx);
3012
+ }
3013
+ },
3014
+ onError(error) {
3015
+ stopStreamParse(ctx, 1, error);
3016
+ },
3017
+ addCleanup(callback) {
3018
+ addCleanup(ctx, callback);
3019
+ }
3020
+ };
3021
+ }
3022
+ function getStreamParsePluginContext(ctx, depth) {
3023
+ const contexts = ctx.state.pluginContexts;
3024
+ return contexts[depth] ?? (contexts[depth] = createStreamParsePluginContext(ctx, depth));
2834
3025
  }
2835
- function onError(ctx, error) {
2836
- if (ctx.state.onError) ctx.state.onError(error);
2837
- else throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
3026
+ function addCleanup(ctx, callback) {
3027
+ if (ctx.state.alive) ctx.state.cleanups.push(callback);
3028
+ else callback();
2838
3029
  }
2839
- function onDone(ctx) {
2840
- if (ctx.state.onDone) ctx.state.onDone();
2841
- for (let i = 0, len = ctx.state.cleanups.length; i < len; i++) ctx.state.cleanups[i]();
3030
+ function parsePluginStream(ctx, depth, id, current, currentPlugins) {
3031
+ for (let i = 0, len = currentPlugins.length; i < len; i++) {
3032
+ const plugin = currentPlugins[i];
3033
+ if (plugin.parse.stream && plugin.test(current)) return createPluginNode(id, plugin.tag, plugin.parse.stream(current, getStreamParsePluginContext(ctx, depth), { id }));
3034
+ }
3035
+ }
3036
+ /**
3037
+ * One listener shape serves both `Stream.on` (no accept) and
3038
+ * `LiveStream.pump` (accept tied to record acceptance). Handlers return the
3039
+ * parse error so the pump can stop the source.
3040
+ */
3041
+ function streamListener(ctx, depth, id, subscription) {
3042
+ const handle = (type, terminal) => (value, accept) => {
3043
+ let failure = void 0;
3044
+ if (ctx.state.alive) try {
3045
+ failure = parseEvent(ctx, depth, value, createStreamEventNode.bind(null, type, id), accept);
3046
+ } catch (error) {
3047
+ if (!subscription?.active) throw error;
3048
+ subscription.failure ?? (subscription.failure = { value: error });
3049
+ failure = error;
3050
+ }
3051
+ if (terminal && !accept) popPendingState(ctx);
3052
+ return failure;
3053
+ };
3054
+ return {
3055
+ next: handle(32, false),
3056
+ throw: handle(33, true),
3057
+ return: handle(34, true),
3058
+ done() {
3059
+ popPendingState(ctx);
3060
+ },
3061
+ error(reason) {
3062
+ if (ctx.state.alive) stopStreamParse(ctx, 1, reason);
3063
+ }
3064
+ };
2842
3065
  }
2843
- function onParseInternal(ctx, node, initial) {
3066
+ function subscribeStream(ctx, depth, id, current) {
3067
+ pushPendingState(ctx);
3068
+ const subscription = {
3069
+ active: true,
3070
+ failure: void 0
3071
+ };
3072
+ let cleanup;
3073
+ try {
3074
+ cleanup = current.on(streamListener(ctx, depth, id, subscription));
3075
+ } finally {
3076
+ subscription.active = false;
3077
+ }
2844
3078
  try {
2845
- ctx.state.onParse(node, initial);
3079
+ addCleanup(ctx, cleanup);
2846
3080
  } catch (error) {
2847
- onError(ctx, error);
3081
+ subscription.failure ?? (subscription.failure = { value: error });
2848
3082
  }
3083
+ const failure = subscription.failure;
3084
+ subscription.failure = void 0;
3085
+ if (failure) throw failure.value;
3086
+ }
3087
+ function consumeLiveStream(ctx, depth, id, current) {
3088
+ const cancel = current.pump(streamListener(ctx, depth, id));
3089
+ pushPendingState(ctx);
3090
+ addCleanup(ctx, () => {
3091
+ cancel(ctx.state.reason);
3092
+ });
3093
+ }
3094
+ function wrapPromiseResult(ctx, type, id, node) {
3095
+ return createSerovalNode(type, id, void 0, void 0, void 0, void 0, void 0, [parseSpecialReference(ctx.base, type === 23 ? 2 : 3), node], void 0, void 0, void 0, void 0);
3096
+ }
3097
+ function handlePromise(type, id, depth, data) {
3098
+ if (this.state.alive) parseEvent(this, depth, data, wrapPromiseResult.bind(null, this, type, id), void 0);
3099
+ popPendingState(this);
3100
+ }
3101
+ function watchPromise(ctx, resolver, depth, current) {
3102
+ pushPendingState(ctx);
3103
+ current.then(handlePromise.bind(ctx, 23, resolver, depth), handlePromise.bind(ctx, 24, resolver, depth));
3104
+ }
3105
+ function returnIterator(iterator) {
3106
+ Promise.resolve().then(() => iterator.return?.()).catch(() => {});
3107
+ }
3108
+ /**
3109
+ * Drives an async iterator directly. The next value is pulled only after the
3110
+ * record for the previous one has been accepted, and cancellation returns
3111
+ * the iterator once.
3112
+ */
3113
+ function iterateAsync(ctx, depth, id, current, forwardReason) {
3114
+ const iterator = current[SYM_ASYNC_ITERATOR]();
3115
+ const listener = streamListener(ctx, depth, id);
3116
+ let active = true;
3117
+ function stop() {
3118
+ if (active) {
3119
+ active = false;
3120
+ if (forwardReason) try {
3121
+ Promise.resolve(iterator.return?.(ctx.state.reason)).catch(() => {});
3122
+ } catch {}
3123
+ else returnIterator(iterator);
3124
+ }
3125
+ }
3126
+ function pull() {
3127
+ if (active) iterator.next().then((result) => {
3128
+ if (active) {
3129
+ if (result.done) {
3130
+ active = false;
3131
+ listener.return(result.value, void 0);
3132
+ } else if (listener.next(result.value, pull) !== void 0) {
3133
+ stop();
3134
+ listener.done();
3135
+ }
3136
+ }
3137
+ }, (error) => {
3138
+ if (active) {
3139
+ active = false;
3140
+ listener.throw(error, void 0);
3141
+ }
3142
+ });
3143
+ }
3144
+ pushPendingState(ctx);
3145
+ addCleanup(ctx, stop);
3146
+ pull();
3147
+ }
3148
+ function createStreamParserState(options) {
3149
+ return {
3150
+ alive: true,
3151
+ pending: 0,
3152
+ parsing: 0,
3153
+ queue: [],
3154
+ writing: false,
3155
+ inFlight: void 0,
3156
+ reason: void 0,
3157
+ onParse: options.onParse,
3158
+ onError: options.onError,
3159
+ onDone: options.onDone,
3160
+ cleanups: [],
3161
+ pluginContexts: [],
3162
+ stream: subscribeStream,
3163
+ live: consumeLiveStream,
3164
+ promise: watchPromise,
3165
+ iterable: iterateAsync,
3166
+ plugin: parsePluginStream
3167
+ };
3168
+ }
3169
+ function createStreamParserContext(options) {
3170
+ return {
3171
+ type: 2,
3172
+ base: createBaseParserContext(options),
3173
+ state: createStreamParserState(options)
3174
+ };
2849
3175
  }
2850
3176
  function pushPendingState(ctx) {
2851
- ctx.state.pending++;
3177
+ if (ctx.state.alive) ctx.state.pending++;
2852
3178
  }
2853
3179
  function popPendingState(ctx) {
2854
- if (--ctx.state.pending <= 0) onDone(ctx);
3180
+ if (ctx.state.alive) {
3181
+ ctx.state.pending--;
3182
+ checkStreamParse(ctx);
3183
+ }
2855
3184
  }
2856
- function parseWithError(ctx, depth, current) {
3185
+ /**
3186
+ * Parses a value that arrived after the root. Its record is queued before
3187
+ * parsing starts so that records discovered inside it follow it, and it is
3188
+ * dropped again if parsing fails. Returns the parse error after reporting
3189
+ * it, or `undefined`.
3190
+ */
3191
+ function parseEvent(ctx, depth, value, wrap, accept) {
3192
+ const state = ctx.state;
3193
+ const record = {
3194
+ node: void 0,
3195
+ initial: false,
3196
+ accept
3197
+ };
3198
+ let failure;
3199
+ state.queue.push(record);
3200
+ state.parsing++;
2857
3201
  try {
2858
- return parseSOS(ctx, depth, current);
2859
- } catch (err) {
2860
- onError(ctx, err);
2861
- return;
3202
+ record.node = wrap(parseSOS(ctx, depth, value));
3203
+ } catch (error) {
3204
+ failure = { value: error };
3205
+ } finally {
3206
+ state.parsing--;
3207
+ if (!state.alive) releaseParserValues(ctx);
2862
3208
  }
3209
+ if (failure) stopStreamParse(ctx, 1, failure.value);
3210
+ else drainOutput(ctx);
3211
+ return failure?.value;
3212
+ }
3213
+ /**
3214
+ * Emits queued records one at a time. A callback that returns a promise
3215
+ * pauses emission until it settles; the source event behind the record is
3216
+ * accepted only after that.
3217
+ */
3218
+ function drainOutput(ctx) {
3219
+ const state = ctx.state;
3220
+ if (state.writing || state.parsing > 0) return;
3221
+ while (state.alive && state.queue.length > 0) {
3222
+ const record = state.queue.shift();
3223
+ if (!record.node) continue;
3224
+ let pending;
3225
+ state.writing = true;
3226
+ state.inFlight = record;
3227
+ state.parsing++;
3228
+ try {
3229
+ if (!state.onParse) throw new Error("Stream output callback is unavailable");
3230
+ const result = state.onParse(record.node, record.initial);
3231
+ if (result !== null && (typeof result === "object" || typeof result === "function")) {
3232
+ const then = Reflect.get(result, "then");
3233
+ if (typeof then === "function") pending = new Promise((resolve, reject) => {
3234
+ Reflect.apply(then, result, [resolve, reject]);
3235
+ });
3236
+ }
3237
+ } catch (error) {
3238
+ releaseRecord(record);
3239
+ stopStreamParse(ctx, 1, error);
3240
+ return;
3241
+ } finally {
3242
+ state.parsing--;
3243
+ if (!state.alive) releaseParserValues(ctx);
3244
+ }
3245
+ record.node = void 0;
3246
+ if (pending) {
3247
+ if (!state.alive) releaseRecord(record);
3248
+ pending.then(() => {
3249
+ state.writing = false;
3250
+ state.inFlight = void 0;
3251
+ if (state.alive) {
3252
+ const accept = record.accept;
3253
+ releaseRecord(record);
3254
+ accept?.();
3255
+ drainOutput(ctx);
3256
+ }
3257
+ }, (error) => {
3258
+ state.writing = false;
3259
+ state.inFlight = void 0;
3260
+ releaseRecord(record);
3261
+ stopStreamParse(ctx, 1, error);
3262
+ });
3263
+ return;
3264
+ }
3265
+ if (!state.alive) {
3266
+ releaseRecord(record);
3267
+ return;
3268
+ }
3269
+ state.writing = false;
3270
+ state.inFlight = void 0;
3271
+ const accept = record.accept;
3272
+ releaseRecord(record);
3273
+ accept?.();
3274
+ }
3275
+ checkStreamParse(ctx);
3276
+ }
3277
+ function checkStreamParse(ctx) {
3278
+ const state = ctx.state;
3279
+ if (state.alive && state.parsing === 0 && state.pending <= 0 && state.queue.length === 0 && !state.writing) stopStreamParse(ctx, 0);
2863
3280
  }
2864
3281
  function startStreamParse(ctx, current) {
2865
- const parsed = parseWithError(ctx, 0, current);
2866
- if (parsed) {
2867
- onParseInternal(ctx, parsed, true);
2868
- ctx.state.initial = false;
2869
- flushStreamParse(ctx, ctx.state);
2870
- if (ctx.state.pending <= 0) destroyStreamParse(ctx);
3282
+ const state = ctx.state;
3283
+ let parsed;
3284
+ let failure;
3285
+ state.parsing++;
3286
+ try {
3287
+ parsed = parseSOS(ctx, 0, current);
3288
+ } catch (error) {
3289
+ failure = { value: error };
3290
+ } finally {
3291
+ state.parsing--;
3292
+ if (!state.alive) releaseParserValues(ctx);
3293
+ }
3294
+ if (failure) {
3295
+ if (state.alive) stopStreamParse(ctx, 1, failure.value);
3296
+ else throw failure.value;
3297
+ } else if (parsed && state.alive) {
3298
+ state.queue.unshift({
3299
+ node: parsed,
3300
+ initial: true,
3301
+ accept: void 0
3302
+ });
3303
+ drainOutput(ctx);
3304
+ }
3305
+ }
3306
+ function runCleanups(state) {
3307
+ const cleanups = state.cleanups;
3308
+ let failure;
3309
+ state.cleanups = [];
3310
+ for (const record of state.queue) releaseRecord(record);
3311
+ state.queue.length = 0;
3312
+ if (state.inFlight) releaseRecord(state.inFlight);
3313
+ state.inFlight = void 0;
3314
+ for (let i = 0, len = cleanups.length; i < len; i++) try {
3315
+ cleanups[i]();
3316
+ } catch (error) {
3317
+ failure ?? (failure = { value: error });
2871
3318
  }
3319
+ if (failure) throw failure.value;
2872
3320
  }
2873
- function flushStreamParse(ctx, state) {
2874
- for (let i = 0, len = state.buffer.length; i < len; i++) onParseInternal(ctx, state.buffer[i], false);
3321
+ function releaseRecord(record) {
3322
+ record.node = void 0;
3323
+ record.accept = void 0;
2875
3324
  }
2876
- function destroyStreamParse(ctx) {
2877
- if (ctx.state.alive) {
2878
- onDone(ctx);
2879
- ctx.state.alive = false;
3325
+ function releaseParserValues(ctx) {
3326
+ ctx.base.refs = /* @__PURE__ */ new Map();
3327
+ ctx.base.marked.clear();
3328
+ ctx.base.plugins = void 0;
3329
+ ctx.base.plainObjectPlugins = void 0;
3330
+ ctx.state.pluginContexts = [];
3331
+ if (ctx.state.parsing === 0) ctx.state.reason = void 0;
3332
+ }
3333
+ /**
3334
+ * Ends the parse once: `onDone` on success, `onError` on failure, and every
3335
+ * cleanup either way.
3336
+ */
3337
+ function stopStreamParse(ctx, mode, reason) {
3338
+ const state = ctx.state;
3339
+ if (state.alive) {
3340
+ state.alive = false;
3341
+ const onError = state.onError;
3342
+ const onDone = state.onDone;
3343
+ if (mode === 1 && !onError && !(reason instanceof SerovalParserError)) reason = new SerovalParserError(reason);
3344
+ state.reason = reason;
3345
+ state.onParse = void 0;
3346
+ state.onError = void 0;
3347
+ state.onDone = void 0;
3348
+ state.writing = false;
3349
+ state.parsing++;
3350
+ let failure;
3351
+ try {
3352
+ if (mode === 1) {
3353
+ if (onError) onError(reason);
3354
+ else throw reason;
3355
+ } else if (mode === 0) onDone?.();
3356
+ } catch (error) {
3357
+ failure = { value: error };
3358
+ }
3359
+ try {
3360
+ runCleanups(state);
3361
+ } catch (error) {
3362
+ failure ?? (failure = { value: error });
3363
+ } finally {
3364
+ state.parsing--;
3365
+ releaseParserValues(ctx);
3366
+ state.pending = 0;
3367
+ }
3368
+ if (failure) throw failure.value;
2880
3369
  }
2881
3370
  }
3371
+ function destroyStreamParse(ctx, reason) {
3372
+ stopStreamParse(ctx, 2, reason);
3373
+ }
2882
3374
  //#endregion
2883
3375
  //#region src/core/cross/index.ts
2884
3376
  function crossSerialize(source, options = {}) {
2885
3377
  const plugins = resolvePlugins(options.plugins);
2886
- const ctx = createSyncParserContext(2, {
3378
+ const ctx = createSyncParserContext({
2887
3379
  compactArrayBufferViews: options.compactArrayBufferViews,
3380
+ depthLimit: options.depthLimit,
2888
3381
  plugins,
2889
3382
  disabledFeatures: options.disabledFeatures,
2890
3383
  refs: options.refs
@@ -2894,13 +3387,15 @@ function crossSerialize(source, options = {}) {
2894
3387
  plugins,
2895
3388
  features: ctx.base.features,
2896
3389
  scopeId: options.scopeId,
2897
- markedRefs: ctx.base.marked
3390
+ markedRefs: ctx.base.marked,
3391
+ assignSharedRefsOnly: options.assignSharedRefsOnly
2898
3392
  }), tree);
2899
3393
  }
2900
3394
  async function crossSerializeAsync(source, options = {}) {
2901
3395
  const plugins = resolvePlugins(options.plugins);
2902
- const ctx = createAsyncParserContext(2, {
3396
+ const ctx = createAsyncParserContext({
2903
3397
  compactArrayBufferViews: options.compactArrayBufferViews,
3398
+ depthLimit: options.depthLimit,
2904
3399
  plugins,
2905
3400
  disabledFeatures: options.disabledFeatures,
2906
3401
  refs: options.refs
@@ -2910,13 +3405,15 @@ async function crossSerializeAsync(source, options = {}) {
2910
3405
  plugins,
2911
3406
  features: ctx.base.features,
2912
3407
  scopeId: options.scopeId,
2913
- markedRefs: ctx.base.marked
3408
+ markedRefs: ctx.base.marked,
3409
+ assignSharedRefsOnly: options.assignSharedRefsOnly
2914
3410
  }), tree);
2915
3411
  }
2916
3412
  function toCrossJSON(source, options = {}) {
2917
3413
  const plugins = resolvePlugins(options.plugins);
2918
- return parseTop(createSyncParserContext(2, {
3414
+ return parseTop(createSyncParserContext({
2919
3415
  compactArrayBufferViews: options.compactArrayBufferViews,
3416
+ depthLimit: options.depthLimit,
2920
3417
  plugins,
2921
3418
  disabledFeatures: options.disabledFeatures,
2922
3419
  refs: options.refs
@@ -2924,8 +3421,9 @@ function toCrossJSON(source, options = {}) {
2924
3421
  }
2925
3422
  async function toCrossJSONAsync(source, options = {}) {
2926
3423
  const plugins = resolvePlugins(options.plugins);
2927
- return await parseTopAsync(createAsyncParserContext(2, {
3424
+ return await parseTopAsync(createAsyncParserContext({
2928
3425
  compactArrayBufferViews: options.compactArrayBufferViews,
3426
+ depthLimit: options.depthLimit,
2929
3427
  plugins,
2930
3428
  disabledFeatures: options.disabledFeatures,
2931
3429
  refs: options.refs
@@ -2933,8 +3431,11 @@ async function toCrossJSONAsync(source, options = {}) {
2933
3431
  }
2934
3432
  function crossSerializeStream(source, options) {
2935
3433
  const plugins = resolvePlugins(options.plugins);
3434
+ const onSerialize = options.onSerialize;
3435
+ const scopeId = options.scopeId;
2936
3436
  const ctx = createStreamParserContext({
2937
3437
  compactArrayBufferViews: options.compactArrayBufferViews,
3438
+ depthLimit: options.depthLimit,
2938
3439
  plugins,
2939
3440
  refs: options.refs,
2940
3441
  disabledFeatures: options.disabledFeatures,
@@ -2942,17 +3443,10 @@ function crossSerializeStream(source, options) {
2942
3443
  const serial = createCrossSerializerContext({
2943
3444
  plugins,
2944
3445
  features: ctx.base.features,
2945
- scopeId: options.scopeId,
3446
+ scopeId,
2946
3447
  markedRefs: ctx.base.marked
2947
3448
  });
2948
- let serialized;
2949
- try {
2950
- serialized = serializeTopCross(serial, node);
2951
- } catch (err) {
2952
- if (options.onError) options.onError(err);
2953
- return;
2954
- }
2955
- options.onSerialize(serialized, initial);
3449
+ return onSerialize(serializeTopCross(serial, node), initial);
2956
3450
  },
2957
3451
  onError: options.onError,
2958
3452
  onDone: options.onDone
@@ -2975,22 +3469,39 @@ function toCrossJSONStream(source, options) {
2975
3469
  startStreamParse(ctx, source);
2976
3470
  return destroyStreamParse.bind(null, ctx);
2977
3471
  }
2978
- function fromCrossJSON(source, options) {
2979
- const plugins = resolvePlugins(options.plugins);
2980
- return deserializeTop(createCrossDeserializerContext({
3472
+ function createFromCrossJSONContext(options) {
3473
+ return createCrossDeserializerContext({
2981
3474
  maxBase64Length: options.maxBase64Length,
2982
- plugins,
3475
+ plugins: resolvePlugins(options.plugins),
2983
3476
  refs: options.refs,
2984
3477
  features: options.features,
2985
3478
  disabledFeatures: options.disabledFeatures,
2986
3479
  depthLimit: options.depthLimit
2987
- }), source);
3480
+ });
3481
+ }
3482
+ function fromCrossJSON(source, options) {
3483
+ return deserializeTop(createFromCrossJSONContext(options), source);
3484
+ }
3485
+ function createCrossDeserializer(options) {
3486
+ const ctx = createFromCrossJSONContext(options);
3487
+ ctx.base.pending = /* @__PURE__ */ new Set();
3488
+ return {
3489
+ deserialize(node) {
3490
+ if (!ctx.base.pending) throw new SerovalAbortedError();
3491
+ return deserializeTop(ctx, node);
3492
+ },
3493
+ get pending() {
3494
+ return ctx.base.pending?.size ?? 0;
3495
+ },
3496
+ abort(reason) {
3497
+ abortDeferred(ctx, reason);
3498
+ }
3499
+ };
2988
3500
  }
2989
3501
  //#endregion
2990
3502
  //#region src/core/Serializer.ts
2991
3503
  var Serializer = class {
2992
3504
  constructor(options) {
2993
- this.options = options;
2994
3505
  this.alive = true;
2995
3506
  this.flushed = false;
2996
3507
  this.done = false;
@@ -2999,32 +3510,52 @@ var Serializer = class {
2999
3510
  this.refs = /* @__PURE__ */ new Map();
3000
3511
  this.keys = /* @__PURE__ */ new Set();
3001
3512
  this.ids = 0;
3513
+ this.options = options;
3002
3514
  this.plugins = resolvePlugins(options.plugins);
3003
3515
  }
3004
3516
  write(key, value) {
3005
- if (this.alive && !this.flushed) {
3517
+ const options = this.options;
3518
+ if (this.alive && !this.flushed && options) {
3006
3519
  this.pending++;
3007
3520
  this.keys.add(key);
3008
- this.cleanups.push(crossSerializeStream(value, {
3521
+ const cleanup = crossSerializeStream(value, {
3009
3522
  plugins: this.plugins,
3010
- scopeId: this.options.scopeId,
3523
+ scopeId: options.scopeId,
3011
3524
  refs: this.refs,
3012
- disabledFeatures: this.options.disabledFeatures,
3013
- compactArrayBufferViews: this.options.compactArrayBufferViews,
3014
- onError: this.options.onError,
3525
+ disabledFeatures: options.disabledFeatures,
3526
+ compactArrayBufferViews: options.compactArrayBufferViews,
3527
+ depthLimit: options.depthLimit,
3528
+ onError: (error) => {
3529
+ let failure;
3530
+ try {
3531
+ if (options.onError) options.onError(error);
3532
+ else throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
3533
+ } catch (handlerError) {
3534
+ failure = { value: handlerError };
3535
+ }
3536
+ try {
3537
+ this.finishWrite();
3538
+ } catch (finishError) {
3539
+ failure ?? (failure = { value: finishError });
3540
+ }
3541
+ if (failure) throw failure.value;
3542
+ },
3015
3543
  onSerialize: (data, initial) => {
3016
- if (this.alive) this.options.onData(initial ? this.options.globalIdentifier + "[\"" + serializeString(key) + "\"]=" + data : data);
3544
+ const current = this.options;
3545
+ if (this.alive && current) current.onData(initial ? current.globalIdentifier + "[\"" + serializeString(key) + "\"]=" + data : data);
3017
3546
  },
3018
3547
  onDone: () => {
3019
- if (this.alive) {
3020
- this.pending--;
3021
- if (this.pending <= 0 && this.flushed && !this.done && this.options.onDone) {
3022
- this.options.onDone();
3023
- this.done = true;
3024
- }
3025
- }
3548
+ this.finishWrite();
3026
3549
  }
3027
- }));
3550
+ });
3551
+ if (this.alive) this.cleanups.push(cleanup);
3552
+ else cleanup();
3553
+ }
3554
+ }
3555
+ finishWrite() {
3556
+ if (this.alive) {
3557
+ this.pending--;
3558
+ if (this.pending <= 0 && this.flushed && !this.done) this.close();
3028
3559
  }
3029
3560
  }
3030
3561
  getNextID() {
@@ -3039,20 +3570,36 @@ var Serializer = class {
3039
3570
  flush() {
3040
3571
  if (this.alive) {
3041
3572
  this.flushed = true;
3042
- if (this.pending <= 0 && !this.done && this.options.onDone) {
3043
- this.options.onDone();
3044
- this.done = true;
3045
- }
3573
+ if (this.pending <= 0 && !this.done) this.close();
3046
3574
  }
3047
3575
  }
3048
3576
  close() {
3577
+ this.finish();
3578
+ }
3579
+ finish() {
3049
3580
  if (this.alive) {
3050
- for (let i = 0, len = this.cleanups.length; i < len; i++) this.cleanups[i]();
3051
- if (!this.done && this.options.onDone) {
3052
- this.options.onDone();
3581
+ this.alive = false;
3582
+ const options = this.options;
3583
+ this.options = void 0;
3584
+ this.plugins = void 0;
3585
+ const cleanups = this.cleanups;
3586
+ this.cleanups = [];
3587
+ let failure;
3588
+ for (let index = 0, length = cleanups.length; index < length; index++) try {
3589
+ cleanups[index]();
3590
+ } catch (error) {
3591
+ failure ?? (failure = { value: error });
3592
+ }
3593
+ this.refs.clear();
3594
+ if (!this.done) {
3053
3595
  this.done = true;
3596
+ try {
3597
+ options?.onDone?.();
3598
+ } catch (error) {
3599
+ failure ?? (failure = { value: error });
3600
+ }
3054
3601
  }
3055
- this.alive = false;
3602
+ if (failure) throw failure.value;
3056
3603
  }
3057
3604
  }
3058
3605
  };
@@ -3060,8 +3607,9 @@ var Serializer = class {
3060
3607
  //#region src/core/tree/index.ts
3061
3608
  function serialize(source, options = {}) {
3062
3609
  const plugins = resolvePlugins(options.plugins);
3063
- const ctx = createSyncParserContext(1, {
3610
+ const ctx = createSyncParserContext({
3064
3611
  compactArrayBufferViews: options.compactArrayBufferViews,
3612
+ depthLimit: options.depthLimit,
3065
3613
  plugins,
3066
3614
  disabledFeatures: options.disabledFeatures
3067
3615
  });
@@ -3074,8 +3622,9 @@ function serialize(source, options = {}) {
3074
3622
  }
3075
3623
  async function serializeAsync(source, options = {}) {
3076
3624
  const plugins = resolvePlugins(options.plugins);
3077
- const ctx = createAsyncParserContext(1, {
3625
+ const ctx = createAsyncParserContext({
3078
3626
  compactArrayBufferViews: options.compactArrayBufferViews,
3627
+ depthLimit: options.depthLimit,
3079
3628
  plugins,
3080
3629
  disabledFeatures: options.disabledFeatures
3081
3630
  });
@@ -3091,8 +3640,9 @@ function deserialize(source) {
3091
3640
  }
3092
3641
  function toJSON(source, options = {}) {
3093
3642
  const plugins = resolvePlugins(options.plugins);
3094
- const ctx = createSyncParserContext(1, {
3643
+ const ctx = createSyncParserContext({
3095
3644
  compactArrayBufferViews: options.compactArrayBufferViews,
3645
+ depthLimit: options.depthLimit,
3096
3646
  plugins,
3097
3647
  disabledFeatures: options.disabledFeatures
3098
3648
  });
@@ -3104,8 +3654,9 @@ function toJSON(source, options = {}) {
3104
3654
  }
3105
3655
  async function toJSONAsync(source, options = {}) {
3106
3656
  const plugins = resolvePlugins(options.plugins);
3107
- const ctx = createAsyncParserContext(1, {
3657
+ const ctx = createAsyncParserContext({
3108
3658
  compactArrayBufferViews: options.compactArrayBufferViews,
3659
+ depthLimit: options.depthLimit,
3109
3660
  plugins,
3110
3661
  disabledFeatures: options.disabledFeatures
3111
3662
  });
@@ -3123,11 +3674,11 @@ function compileJSON(source, options = {}) {
3123
3674
  }), source.t);
3124
3675
  }
3125
3676
  function fromJSON(source, options = {}) {
3126
- var _source$f;
3127
3677
  const plugins = resolvePlugins(options.plugins);
3128
- const disabledFeatures = options.disabledFeatures || 0;
3129
- const sourceFeatures = (_source$f = source.f) !== null && _source$f !== void 0 ? _source$f : 127;
3678
+ const disabledFeatures = options.disabledFeatures ?? 0;
3679
+ const sourceFeatures = source.f ?? 127;
3130
3680
  return deserializeTop(createVanillaDeserializerContext({
3681
+ depthLimit: options.depthLimit,
3131
3682
  maxBase64Length: options.maxBase64Length,
3132
3683
  plugins,
3133
3684
  markedRefs: source.m,
@@ -3137,12 +3688,16 @@ function fromJSON(source, options = {}) {
3137
3688
  }
3138
3689
  //#endregion
3139
3690
  exports.Feature = Feature;
3691
+ exports.LiveStream = LiveStream;
3140
3692
  exports.OpaqueReference = OpaqueReference;
3693
+ exports.Sequence = Sequence;
3141
3694
  exports.Serializer = Serializer;
3695
+ exports.SerovalAbortedError = SerovalAbortedError;
3142
3696
  exports.SerovalConflictedNodeIdError = SerovalConflictedNodeIdError;
3143
3697
  exports.SerovalDepthLimitError = SerovalDepthLimitError;
3144
3698
  exports.SerovalDeserializationError = SerovalDeserializationError;
3145
3699
  exports.SerovalError = SerovalError;
3700
+ exports.SerovalLiveStreamError = SerovalLiveStreamError;
3146
3701
  exports.SerovalMalformedNodeError = SerovalMalformedNodeError;
3147
3702
  exports.SerovalMissingInstanceError = SerovalMissingInstanceError;
3148
3703
  exports.SerovalMissingPluginError = SerovalMissingPluginError;
@@ -3154,7 +3709,10 @@ exports.SerovalSerializationError = SerovalSerializationError;
3154
3709
  exports.SerovalUnknownTypedArrayError = SerovalUnknownTypedArrayError;
3155
3710
  exports.SerovalUnsupportedNodeError = SerovalUnsupportedNodeError;
3156
3711
  exports.SerovalUnsupportedTypeError = SerovalUnsupportedTypeError;
3712
+ exports.Stream = Stream;
3157
3713
  exports.compileJSON = compileJSON;
3714
+ exports.createCrossDeserializer = createCrossDeserializer;
3715
+ exports.createLiveStream = createLiveStream;
3158
3716
  exports.createPlugin = createPlugin;
3159
3717
  exports.createReference = createReference;
3160
3718
  exports.createStream = createStream;
@@ -3165,6 +3723,8 @@ exports.deserialize = deserialize;
3165
3723
  exports.fromCrossJSON = fromCrossJSON;
3166
3724
  exports.fromJSON = fromJSON;
3167
3725
  exports.getCrossReferenceHeader = getCrossReferenceHeader;
3726
+ exports.getPlainObjectPlugins = getPlainObjectPlugins;
3727
+ exports.isLiveStream = isLiveStream;
3168
3728
  exports.isStream = isStream;
3169
3729
  exports.resolvePlugins = resolvePlugins;
3170
3730
  exports.serialize = serialize;