seroval 1.5.6 → 1.6.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.
Files changed (117) hide show
  1. package/dist/dev/index.cjs +2954 -0
  2. package/dist/dev/index.d.cts +761 -0
  3. package/dist/dev/index.d.ts +761 -0
  4. package/dist/dev/index.js +2917 -0
  5. package/dist/index.cjs +2947 -0
  6. package/dist/index.d.cts +761 -0
  7. package/dist/index.d.ts +761 -0
  8. package/dist/index.js +2910 -0
  9. package/package.json +23 -21
  10. package/dist/cjs/development/index.cjs +0 -4232
  11. package/dist/cjs/development/index.cjs.map +0 -7
  12. package/dist/cjs/production/index.cjs +0 -3
  13. package/dist/esm/development/index.mjs +0 -4209
  14. package/dist/esm/development/index.mjs.map +0 -7
  15. package/dist/esm/production/index.mjs +0 -3
  16. package/dist/types/core/Serializer.d.ts +0 -28
  17. package/dist/types/core/Serializer.d.ts.map +0 -1
  18. package/dist/types/core/base-primitives.d.ts +0 -28
  19. package/dist/types/core/base-primitives.d.ts.map +0 -1
  20. package/dist/types/core/compat.d.ts +0 -15
  21. package/dist/types/core/compat.d.ts.map +0 -1
  22. package/dist/types/core/constants.d.ts +0 -105
  23. package/dist/types/core/constants.d.ts.map +0 -1
  24. package/dist/types/core/constructors.d.ts +0 -50
  25. package/dist/types/core/constructors.d.ts.map +0 -1
  26. package/dist/types/core/context/async-parser.d.ts +0 -20
  27. package/dist/types/core/context/async-parser.d.ts.map +0 -1
  28. package/dist/types/core/context/deserializer.d.ts +0 -52
  29. package/dist/types/core/context/deserializer.d.ts.map +0 -1
  30. package/dist/types/core/context/parser.d.ts +0 -62
  31. package/dist/types/core/context/parser.d.ts.map +0 -1
  32. package/dist/types/core/context/serializer.d.ts +0 -103
  33. package/dist/types/core/context/serializer.d.ts.map +0 -1
  34. package/dist/types/core/context/sync-parser.d.ts +0 -61
  35. package/dist/types/core/context/sync-parser.d.ts.map +0 -1
  36. package/dist/types/core/cross/index.d.ts +0 -24
  37. package/dist/types/core/cross/index.d.ts.map +0 -1
  38. package/dist/types/core/errors.d.ts +0 -47
  39. package/dist/types/core/errors.d.ts.map +0 -1
  40. package/dist/types/core/function-string.d.ts +0 -3
  41. package/dist/types/core/function-string.d.ts.map +0 -1
  42. package/dist/types/core/keys.d.ts +0 -4
  43. package/dist/types/core/keys.d.ts.map +0 -1
  44. package/dist/types/core/literals.d.ts +0 -10
  45. package/dist/types/core/literals.d.ts.map +0 -1
  46. package/dist/types/core/node.d.ts +0 -8
  47. package/dist/types/core/node.d.ts.map +0 -1
  48. package/dist/types/core/opaque-reference.d.ts +0 -9
  49. package/dist/types/core/opaque-reference.d.ts.map +0 -1
  50. package/dist/types/core/plugin.d.ts +0 -52
  51. package/dist/types/core/plugin.d.ts.map +0 -1
  52. package/dist/types/core/reference.d.ts +0 -6
  53. package/dist/types/core/reference.d.ts.map +0 -1
  54. package/dist/types/core/sequence.d.ts +0 -11
  55. package/dist/types/core/sequence.d.ts.map +0 -1
  56. package/dist/types/core/special-reference.d.ts +0 -16
  57. package/dist/types/core/special-reference.d.ts.map +0 -1
  58. package/dist/types/core/stream.d.ts +0 -17
  59. package/dist/types/core/stream.d.ts.map +0 -1
  60. package/dist/types/core/string.d.ts +0 -4
  61. package/dist/types/core/string.d.ts.map +0 -1
  62. package/dist/types/core/symbols.d.ts +0 -14
  63. package/dist/types/core/symbols.d.ts.map +0 -1
  64. package/dist/types/core/tree/index.d.ts +0 -21
  65. package/dist/types/core/tree/index.d.ts.map +0 -1
  66. package/dist/types/core/types.d.ts +0 -233
  67. package/dist/types/core/types.d.ts.map +0 -1
  68. package/dist/types/core/utils/error.d.ts +0 -6
  69. package/dist/types/core/utils/error.d.ts.map +0 -1
  70. package/dist/types/core/utils/get-identifier.d.ts +0 -2
  71. package/dist/types/core/utils/get-identifier.d.ts.map +0 -1
  72. package/dist/types/core/utils/get-object-flag.d.ts +0 -3
  73. package/dist/types/core/utils/get-object-flag.d.ts.map +0 -1
  74. package/dist/types/core/utils/is-valid-identifier.d.ts +0 -2
  75. package/dist/types/core/utils/is-valid-identifier.d.ts.map +0 -1
  76. package/dist/types/core/utils/promise-to-result.d.ts +0 -2
  77. package/dist/types/core/utils/promise-to-result.d.ts.map +0 -1
  78. package/dist/types/core/utils/typed-array.d.ts +0 -6
  79. package/dist/types/core/utils/typed-array.d.ts.map +0 -1
  80. package/dist/types/core/utils/valid-properties.d.ts +0 -3
  81. package/dist/types/core/utils/valid-properties.d.ts.map +0 -1
  82. package/dist/types/index.d.ts +0 -18
  83. package/dist/types/index.d.ts.map +0 -1
  84. package/src/core/Serializer.ts +0 -119
  85. package/src/core/base-primitives.ts +0 -537
  86. package/src/core/compat.ts +0 -23
  87. package/src/core/constants.ts +0 -202
  88. package/src/core/constructors.ts +0 -265
  89. package/src/core/context/async-parser.ts +0 -666
  90. package/src/core/context/deserializer.ts +0 -832
  91. package/src/core/context/parser.ts +0 -335
  92. package/src/core/context/serializer.ts +0 -1524
  93. package/src/core/context/sync-parser.ts +0 -943
  94. package/src/core/cross/index.ts +0 -190
  95. package/src/core/errors.ts +0 -196
  96. package/src/core/function-string.ts +0 -31
  97. package/src/core/keys.ts +0 -17
  98. package/src/core/literals.ts +0 -43
  99. package/src/core/node.ts +0 -40
  100. package/src/core/opaque-reference.ts +0 -9
  101. package/src/core/plugin.ts +0 -105
  102. package/src/core/reference.ts +0 -66
  103. package/src/core/sequence.ts +0 -59
  104. package/src/core/special-reference.ts +0 -42
  105. package/src/core/stream.ts +0 -71
  106. package/src/core/string.ts +0 -86
  107. package/src/core/symbols.ts +0 -20
  108. package/src/core/tree/index.ts +0 -134
  109. package/src/core/types.ts +0 -377
  110. package/src/core/utils/error.ts +0 -73
  111. package/src/core/utils/get-identifier.ts +0 -18
  112. package/src/core/utils/get-object-flag.ts +0 -14
  113. package/src/core/utils/is-valid-identifier.ts +0 -12
  114. package/src/core/utils/promise-to-result.ts +0 -9
  115. package/src/core/utils/typed-array.ts +0 -56
  116. package/src/core/utils/valid-properties.ts +0 -34
  117. package/src/index.ts +0 -36
package/dist/index.js ADDED
@@ -0,0 +1,2910 @@
1
+ //#region src/core/compat.ts
2
+ /**
3
+ * References
4
+ * - https://compat-table.github.io/compat-table/es6/
5
+ * - MDN
6
+ */
7
+ let Feature = /* @__PURE__ */ function(Feature) {
8
+ Feature[Feature["AggregateError"] = 1] = "AggregateError";
9
+ Feature[Feature["ArrowFunction"] = 2] = "ArrowFunction";
10
+ Feature[Feature["ErrorPrototypeStack"] = 4] = "ErrorPrototypeStack";
11
+ Feature[Feature["ObjectAssign"] = 8] = "ObjectAssign";
12
+ Feature[Feature["BigIntTypedArray"] = 16] = "BigIntTypedArray";
13
+ Feature[Feature["RegExp"] = 32] = "RegExp";
14
+ Feature[Feature["Temporal"] = 64] = "Temporal";
15
+ return Feature;
16
+ }({});
17
+ //#endregion
18
+ //#region src/core/symbols.ts
19
+ const SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
20
+ const SYM_HAS_INSTANCE = Symbol.hasInstance;
21
+ const SYM_IS_CONCAT_SPREADABLE = Symbol.isConcatSpreadable;
22
+ const SYM_ITERATOR = Symbol.iterator;
23
+ const SYM_MATCH = Symbol.match;
24
+ const SYM_MATCH_ALL = Symbol.matchAll;
25
+ const SYM_REPLACE = Symbol.replace;
26
+ const SYM_SEARCH = Symbol.search;
27
+ const SYM_SPECIES = Symbol.species;
28
+ const SYM_SPLIT = Symbol.split;
29
+ const SYM_TO_PRIMITIVE = Symbol.toPrimitive;
30
+ const SYM_TO_STRING_TAG = Symbol.toStringTag;
31
+ const SYM_UNSCOPABLES = Symbol.unscopables;
32
+ //#endregion
33
+ //#region src/core/constants.ts
34
+ const SYMBOL_STRING = {
35
+ [0]: "Symbol.asyncIterator",
36
+ [1]: "Symbol.hasInstance",
37
+ [2]: "Symbol.isConcatSpreadable",
38
+ [3]: "Symbol.iterator",
39
+ [4]: "Symbol.match",
40
+ [5]: "Symbol.matchAll",
41
+ [6]: "Symbol.replace",
42
+ [7]: "Symbol.search",
43
+ [8]: "Symbol.species",
44
+ [9]: "Symbol.split",
45
+ [10]: "Symbol.toPrimitive",
46
+ [11]: "Symbol.toStringTag",
47
+ [12]: "Symbol.unscopables"
48
+ };
49
+ const INV_SYMBOL_REF = {
50
+ [SYM_ASYNC_ITERATOR]: 0,
51
+ [SYM_HAS_INSTANCE]: 1,
52
+ [SYM_IS_CONCAT_SPREADABLE]: 2,
53
+ [SYM_ITERATOR]: 3,
54
+ [SYM_MATCH]: 4,
55
+ [SYM_MATCH_ALL]: 5,
56
+ [SYM_REPLACE]: 6,
57
+ [SYM_SEARCH]: 7,
58
+ [SYM_SPECIES]: 8,
59
+ [SYM_SPLIT]: 9,
60
+ [SYM_TO_PRIMITIVE]: 10,
61
+ [SYM_TO_STRING_TAG]: 11,
62
+ [SYM_UNSCOPABLES]: 12
63
+ };
64
+ const SYMBOL_REF = {
65
+ [0]: SYM_ASYNC_ITERATOR,
66
+ [1]: SYM_HAS_INSTANCE,
67
+ [2]: SYM_IS_CONCAT_SPREADABLE,
68
+ [3]: SYM_ITERATOR,
69
+ [4]: SYM_MATCH,
70
+ [5]: SYM_MATCH_ALL,
71
+ [6]: SYM_REPLACE,
72
+ [7]: SYM_SEARCH,
73
+ [8]: SYM_SPECIES,
74
+ [9]: SYM_SPLIT,
75
+ [10]: SYM_TO_PRIMITIVE,
76
+ [11]: SYM_TO_STRING_TAG,
77
+ [12]: SYM_UNSCOPABLES
78
+ };
79
+ const CONSTANT_STRING = {
80
+ [2]: "!0",
81
+ [3]: "!1",
82
+ [1]: "void 0",
83
+ [0]: "null",
84
+ [4]: "-0",
85
+ [5]: "1/0",
86
+ [6]: "-1/0",
87
+ [7]: "0/0"
88
+ };
89
+ const CONSTANT_VAL = {
90
+ [2]: true,
91
+ [3]: false,
92
+ [1]: void 0,
93
+ [0]: null,
94
+ [4]: -0,
95
+ [5]: Number.POSITIVE_INFINITY,
96
+ [6]: Number.NEGATIVE_INFINITY,
97
+ [7]: NaN
98
+ };
99
+ const ERROR_CONSTRUCTOR_STRING = {
100
+ [0]: "Error",
101
+ [1]: "EvalError",
102
+ [2]: "RangeError",
103
+ [3]: "ReferenceError",
104
+ [4]: "SyntaxError",
105
+ [5]: "TypeError",
106
+ [6]: "URIError"
107
+ };
108
+ const ERROR_CONSTRUCTOR = {
109
+ [0]: Error,
110
+ [1]: EvalError,
111
+ [2]: RangeError,
112
+ [3]: ReferenceError,
113
+ [4]: SyntaxError,
114
+ [5]: TypeError,
115
+ [6]: URIError
116
+ };
117
+ //#endregion
118
+ //#region src/core/node.ts
119
+ function createSerovalNode(t, i, s, c, m, p, e, a, f, b, o, l) {
120
+ return {
121
+ t,
122
+ i,
123
+ s,
124
+ c,
125
+ m,
126
+ p,
127
+ e,
128
+ a,
129
+ f,
130
+ b,
131
+ o,
132
+ l
133
+ };
134
+ }
135
+ //#endregion
136
+ //#region src/core/literals.ts
137
+ function createConstantNode(value) {
138
+ return createSerovalNode(2, void 0, value, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
139
+ }
140
+ const TRUE_NODE = /* @__PURE__ */ createConstantNode(2);
141
+ const FALSE_NODE = /* @__PURE__ */ createConstantNode(3);
142
+ const UNDEFINED_NODE = /* @__PURE__ */ createConstantNode(1);
143
+ const NULL_NODE = /* @__PURE__ */ createConstantNode(0);
144
+ const NEG_ZERO_NODE = /* @__PURE__ */ createConstantNode(4);
145
+ const INFINITY_NODE = /* @__PURE__ */ createConstantNode(5);
146
+ const NEG_INFINITY_NODE = /* @__PURE__ */ createConstantNode(6);
147
+ const NAN_NODE = /* @__PURE__ */ createConstantNode(7);
148
+ //#endregion
149
+ //#region src/core/string.ts
150
+ function serializeChar(str) {
151
+ switch (str) {
152
+ case "\"": return "\\\"";
153
+ case "\\": return "\\\\";
154
+ case "\n": return "\\n";
155
+ case "\r": return "\\r";
156
+ case "\b": return "\\b";
157
+ case " ": return "\\t";
158
+ case "\f": return "\\f";
159
+ case "<": return "\\x3C";
160
+ case "\u2028": return "\\u2028";
161
+ case "\u2029": return "\\u2029";
162
+ default: return;
163
+ }
164
+ }
165
+ function serializeString(str) {
166
+ let result = "";
167
+ let lastPos = 0;
168
+ let replacement;
169
+ for (let i = 0, len = str.length; i < len; i++) {
170
+ replacement = serializeChar(str[i]);
171
+ if (replacement) {
172
+ result += str.slice(lastPos, i) + replacement;
173
+ lastPos = i + 1;
174
+ }
175
+ }
176
+ if (lastPos === 0) result = str;
177
+ else result += str.slice(lastPos);
178
+ return result;
179
+ }
180
+ function deserializeReplacer(str) {
181
+ switch (str) {
182
+ case "\\\\": return "\\";
183
+ case "\\\"": return "\"";
184
+ case "\\n": return "\n";
185
+ case "\\r": return "\r";
186
+ case "\\b": return "\b";
187
+ case "\\t": return " ";
188
+ case "\\f": return "\f";
189
+ case "\\x3C": return "<";
190
+ case "\\u2028": return "\u2028";
191
+ case "\\u2029": return "\u2029";
192
+ default: return str;
193
+ }
194
+ }
195
+ function deserializeString(str) {
196
+ return str.replace(/(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g, deserializeReplacer);
197
+ }
198
+ //#endregion
199
+ //#region src/core/keys.ts
200
+ const REFERENCES_KEY = "__SEROVAL_REFS__";
201
+ const GLOBAL_CONTEXT_R = `self.\$R`;
202
+ function getCrossReferenceHeader(id) {
203
+ if (id == null) return `${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||[]`;
204
+ return `(${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||{})["${serializeString(id)}"]=[]`;
205
+ }
206
+ //#endregion
207
+ //#region src/core/reference.ts
208
+ const REFERENCE = /* @__PURE__ */ new Map();
209
+ const INV_REFERENCE = /* @__PURE__ */ new Map();
210
+ function createReference(id, value) {
211
+ REFERENCE.set(value, id);
212
+ INV_REFERENCE.set(id, value);
213
+ return value;
214
+ }
215
+ function hasReferenceID(value) {
216
+ return REFERENCE.has(value);
217
+ }
218
+ function hasReference(id) {
219
+ return INV_REFERENCE.has(id);
220
+ }
221
+ function getReferenceID(value) {
222
+ if (hasReferenceID(value)) return REFERENCE.get(value);
223
+ throw new SerovalMissingReferenceError(value);
224
+ }
225
+ function getReference(id) {
226
+ if (hasReference(id)) return INV_REFERENCE.get(id);
227
+ throw new SerovalMissingReferenceForIdError(id);
228
+ }
229
+ if (typeof globalThis !== "undefined") Object.defineProperty(globalThis, REFERENCES_KEY, {
230
+ value: INV_REFERENCE,
231
+ configurable: true,
232
+ writable: false,
233
+ enumerable: false
234
+ });
235
+ else if (typeof window !== "undefined") Object.defineProperty(window, REFERENCES_KEY, {
236
+ value: INV_REFERENCE,
237
+ configurable: true,
238
+ writable: false,
239
+ enumerable: false
240
+ });
241
+ else if (typeof self !== "undefined") Object.defineProperty(self, REFERENCES_KEY, {
242
+ value: INV_REFERENCE,
243
+ configurable: true,
244
+ writable: false,
245
+ enumerable: false
246
+ });
247
+ else if (typeof global !== "undefined") Object.defineProperty(global, REFERENCES_KEY, {
248
+ value: INV_REFERENCE,
249
+ configurable: true,
250
+ writable: false,
251
+ enumerable: false
252
+ });
253
+ //#endregion
254
+ //#region src/core/utils/error.ts
255
+ function getErrorConstructor(error) {
256
+ if (error instanceof EvalError) return 1;
257
+ if (error instanceof RangeError) return 2;
258
+ if (error instanceof ReferenceError) return 3;
259
+ if (error instanceof SyntaxError) return 4;
260
+ if (error instanceof TypeError) return 5;
261
+ if (error instanceof URIError) return 6;
262
+ return 0;
263
+ }
264
+ function getInitialErrorOptions(error) {
265
+ const construct = ERROR_CONSTRUCTOR_STRING[getErrorConstructor(error)];
266
+ if (error.name !== construct) return { name: error.name };
267
+ if (error.constructor.name !== construct) return { name: error.constructor.name };
268
+ return {};
269
+ }
270
+ function getErrorOptions(error, features) {
271
+ let options = getInitialErrorOptions(error);
272
+ const names = Object.getOwnPropertyNames(error);
273
+ for (let i = 0, len = names.length, name; i < len; i++) {
274
+ name = names[i];
275
+ if (name !== "name" && name !== "message") if (name === "stack") {
276
+ if (features & 4) {
277
+ options = options || {};
278
+ options[name] = error[name];
279
+ }
280
+ } else {
281
+ options = options || {};
282
+ options[name] = error[name];
283
+ }
284
+ }
285
+ return options;
286
+ }
287
+ //#endregion
288
+ //#region src/core/utils/get-object-flag.ts
289
+ function getObjectFlag(obj) {
290
+ if (Object.isFrozen(obj)) return 3;
291
+ if (Object.isSealed(obj)) return 2;
292
+ if (Object.isExtensible(obj)) return 0;
293
+ return 1;
294
+ }
295
+ //#endregion
296
+ //#region src/core/base-primitives.ts
297
+ function createNumberNode(value) {
298
+ switch (value) {
299
+ case Number.POSITIVE_INFINITY: return INFINITY_NODE;
300
+ case Number.NEGATIVE_INFINITY: return NEG_INFINITY_NODE;
301
+ }
302
+ if (value !== value) return NAN_NODE;
303
+ if (Object.is(value, -0)) return NEG_ZERO_NODE;
304
+ return createSerovalNode(0, void 0, value, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
305
+ }
306
+ function createStringNode(value) {
307
+ 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);
308
+ }
309
+ function createBigIntNode(current) {
310
+ return createSerovalNode(3, void 0, "" + current, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
311
+ }
312
+ function createIndexedValueNode(id) {
313
+ return createSerovalNode(4, id, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
314
+ }
315
+ function createDateNode(id, current) {
316
+ const timestamp = current.valueOf();
317
+ 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);
318
+ }
319
+ function createTemporalNode(id, type, current) {
320
+ return createSerovalNode(36, id, current.toString(), type, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
321
+ }
322
+ function createRegExpNode(id, current) {
323
+ 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);
324
+ }
325
+ function createWKSymbolNode(id, current) {
326
+ 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);
327
+ }
328
+ function createReferenceNode(id, ref) {
329
+ 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);
330
+ }
331
+ function createPluginNode(id, tag, value) {
332
+ return createSerovalNode(25, id, value, serializeString(tag), void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
333
+ }
334
+ function createArrayNode(id, current, parsedItems) {
335
+ return createSerovalNode(9, id, void 0, void 0, void 0, void 0, void 0, parsedItems, void 0, void 0, getObjectFlag(current), void 0);
336
+ }
337
+ function createBoxedNode(id, boxed) {
338
+ return createSerovalNode(21, id, void 0, void 0, void 0, void 0, void 0, void 0, boxed, void 0, void 0, void 0);
339
+ }
340
+ function createTypedArrayNode(id, current, buffer) {
341
+ return createSerovalNode(15, id, void 0, current.constructor.name, void 0, void 0, void 0, void 0, buffer, current.byteOffset, void 0, current.length);
342
+ }
343
+ function createBigIntTypedArrayNode(id, current, buffer) {
344
+ return createSerovalNode(16, id, void 0, current.constructor.name, void 0, void 0, void 0, void 0, buffer, current.byteOffset, void 0, current.length);
345
+ }
346
+ function createDataViewNode(id, current, buffer) {
347
+ return createSerovalNode(20, id, void 0, void 0, void 0, void 0, void 0, void 0, buffer, current.byteOffset, void 0, current.byteLength);
348
+ }
349
+ function createErrorNode(id, current, options) {
350
+ return createSerovalNode(13, id, getErrorConstructor(current), void 0, serializeString(current.message), options, void 0, void 0, void 0, void 0, void 0, void 0);
351
+ }
352
+ function createAggregateErrorNode(id, current, options) {
353
+ return createSerovalNode(14, id, getErrorConstructor(current), void 0, serializeString(current.message), options, void 0, void 0, void 0, void 0, void 0, void 0);
354
+ }
355
+ function createSetNode(id, items) {
356
+ return createSerovalNode(7, id, void 0, void 0, void 0, void 0, void 0, items, void 0, void 0, void 0, void 0);
357
+ }
358
+ function createIteratorFactoryInstanceNode(factory, items) {
359
+ 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);
360
+ }
361
+ function createAsyncIteratorFactoryInstanceNode(factory, items) {
362
+ 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);
363
+ }
364
+ function createStreamConstructorNode(id, factory, sequence) {
365
+ return createSerovalNode(31, id, void 0, void 0, void 0, void 0, void 0, sequence, factory, void 0, void 0, void 0);
366
+ }
367
+ function createStreamNextNode(id, parsed) {
368
+ return createSerovalNode(32, id, void 0, void 0, void 0, void 0, void 0, void 0, parsed, void 0, void 0, void 0);
369
+ }
370
+ function createStreamThrowNode(id, parsed) {
371
+ return createSerovalNode(33, id, void 0, void 0, void 0, void 0, void 0, void 0, parsed, void 0, void 0, void 0);
372
+ }
373
+ function createStreamReturnNode(id, parsed) {
374
+ return createSerovalNode(34, id, void 0, void 0, void 0, void 0, void 0, void 0, parsed, void 0, void 0, void 0);
375
+ }
376
+ function createSequenceNode(id, sequence, throwAt, doneAt) {
377
+ return createSerovalNode(35, id, throwAt, void 0, void 0, void 0, void 0, sequence, void 0, void 0, void 0, doneAt);
378
+ }
379
+ //#endregion
380
+ //#region src/core/errors.ts
381
+ const { toString: objectToString } = Object.prototype;
382
+ const STEP_ERROR_CODES = {
383
+ parsing: 1,
384
+ serialization: 2,
385
+ deserialization: 3
386
+ };
387
+ function getErrorMessageProd(type) {
388
+ return `Seroval Error (step: ${STEP_ERROR_CODES[type]})`;
389
+ }
390
+ const getErrorMessage = (type, cause) => getErrorMessageProd(type);
391
+ var SerovalError = class extends Error {
392
+ constructor(type, cause) {
393
+ super(getErrorMessage(type, cause));
394
+ this.cause = cause;
395
+ }
396
+ };
397
+ var SerovalParserError = class extends SerovalError {
398
+ constructor(cause) {
399
+ super("parsing", cause);
400
+ }
401
+ };
402
+ var SerovalSerializationError = class extends SerovalError {
403
+ constructor(cause) {
404
+ super("serialization", cause);
405
+ }
406
+ };
407
+ var SerovalDeserializationError = class extends SerovalError {
408
+ constructor(cause) {
409
+ super("deserialization", cause);
410
+ }
411
+ };
412
+ function getSpecificErrorMessage(code) {
413
+ return `Seroval Error (specific: ${code})`;
414
+ }
415
+ var SerovalUnsupportedTypeError = class extends Error {
416
+ constructor(value) {
417
+ super(getSpecificErrorMessage(1));
418
+ this.value = value;
419
+ }
420
+ };
421
+ var SerovalUnsupportedNodeError = class extends Error {
422
+ constructor(node) {
423
+ super(getSpecificErrorMessage(2));
424
+ }
425
+ };
426
+ var SerovalMissingPluginError = class extends Error {
427
+ constructor(tag) {
428
+ super(getSpecificErrorMessage(3));
429
+ }
430
+ };
431
+ var SerovalMissingInstanceError = class extends Error {
432
+ constructor(tag) {
433
+ super(getSpecificErrorMessage(4));
434
+ }
435
+ };
436
+ var SerovalMissingReferenceError = class extends Error {
437
+ constructor(value) {
438
+ super(getSpecificErrorMessage(5));
439
+ this.value = value;
440
+ }
441
+ };
442
+ var SerovalMissingReferenceForIdError = class extends Error {
443
+ constructor(id) {
444
+ super(getSpecificErrorMessage(6));
445
+ }
446
+ };
447
+ var SerovalUnknownTypedArrayError = class extends Error {
448
+ constructor(name) {
449
+ super(getSpecificErrorMessage(7));
450
+ }
451
+ };
452
+ var SerovalMalformedNodeError = class extends Error {
453
+ constructor(node) {
454
+ super(getSpecificErrorMessage(8));
455
+ }
456
+ };
457
+ var SerovalConflictedNodeIdError = class extends Error {
458
+ constructor(node) {
459
+ super(getSpecificErrorMessage(9));
460
+ }
461
+ };
462
+ var SerovalDepthLimitError = class extends Error {
463
+ constructor(limit) {
464
+ super(getSpecificErrorMessage(9));
465
+ }
466
+ };
467
+ //#endregion
468
+ //#region src/core/opaque-reference.ts
469
+ /**
470
+ * An opaque reference allows hiding values from the serializer.
471
+ */
472
+ var OpaqueReference = class {
473
+ constructor(value, replacement) {
474
+ this.value = value;
475
+ this.replacement = replacement;
476
+ }
477
+ };
478
+ //#endregion
479
+ //#region src/core/constructors.ts
480
+ const PROMISE_CONSTRUCTOR = () => {
481
+ const resolver = {
482
+ p: 0,
483
+ s: 0,
484
+ f: 0
485
+ };
486
+ resolver.p = new Promise((resolve, reject) => {
487
+ resolver.s = resolve;
488
+ resolver.f = reject;
489
+ });
490
+ return resolver;
491
+ };
492
+ const PROMISE_SUCCESS = (resolver, data) => {
493
+ resolver.s(data);
494
+ resolver.p.s = 1;
495
+ resolver.p.v = data;
496
+ };
497
+ const PROMISE_FAILURE = (resolver, data) => {
498
+ resolver.f(data);
499
+ resolver.p.s = 2;
500
+ resolver.p.v = data;
501
+ };
502
+ const SERIALIZED_PROMISE_CONSTRUCTOR = /* @__PURE__ */ PROMISE_CONSTRUCTOR.toString();
503
+ const SERIALIZED_PROMISE_SUCCESS = /* @__PURE__ */ PROMISE_SUCCESS.toString();
504
+ const SERIALIZED_PROMISE_FAILURE = /* @__PURE__ */ PROMISE_FAILURE.toString();
505
+ const STREAM_CONSTRUCTOR = () => {
506
+ const buffer = [];
507
+ const listeners = [];
508
+ let alive = true;
509
+ let success = false;
510
+ let count = 0;
511
+ const internal = {
512
+ flush(value, mode, x) {
513
+ for (x = 0; x < count; x++) if (listeners[x]) listeners[x][mode](value);
514
+ },
515
+ up(listener, x, z, current) {
516
+ for (x = 0, z = buffer.length; x < z; x++) {
517
+ current = buffer[x];
518
+ if (!alive && x === z - 1) listener[success ? "return" : "throw"](current);
519
+ else listener.next(current);
520
+ }
521
+ },
522
+ on(listener, temp) {
523
+ if (alive) {
524
+ temp = count++;
525
+ listeners[temp] = listener;
526
+ }
527
+ internal.up(listener);
528
+ return () => {
529
+ if (alive) {
530
+ listeners[temp] = listeners[count];
531
+ listeners[count--] = void 0;
532
+ }
533
+ };
534
+ }
535
+ };
536
+ return {
537
+ __SEROVAL_STREAM__: true,
538
+ on(listener) {
539
+ return internal.on(listener);
540
+ },
541
+ next(value) {
542
+ if (alive) {
543
+ buffer.push(value);
544
+ internal.flush(value, "next");
545
+ }
546
+ },
547
+ throw(value) {
548
+ if (alive) {
549
+ buffer.push(value);
550
+ internal.flush(value, "throw");
551
+ alive = false;
552
+ success = false;
553
+ listeners.length = 0;
554
+ }
555
+ },
556
+ return(value) {
557
+ if (alive) {
558
+ buffer.push(value);
559
+ internal.flush(value, "return");
560
+ alive = false;
561
+ success = true;
562
+ listeners.length = 0;
563
+ }
564
+ }
565
+ };
566
+ };
567
+ const SERIALIZED_STREAM_CONSTRUCTOR = /* @__PURE__ */ STREAM_CONSTRUCTOR.toString();
568
+ const ITERATOR_CONSTRUCTOR = (symbol) => (sequence) => () => {
569
+ let index = 0;
570
+ const instance = {
571
+ [symbol]() {
572
+ return instance;
573
+ },
574
+ next() {
575
+ if (index > sequence.d) return {
576
+ done: true,
577
+ value: void 0
578
+ };
579
+ const currentIndex = index++;
580
+ const data = sequence.v[currentIndex];
581
+ if (currentIndex === sequence.t) throw data;
582
+ return {
583
+ done: currentIndex === sequence.d,
584
+ value: data
585
+ };
586
+ }
587
+ };
588
+ return instance;
589
+ };
590
+ const SERIALIZED_ITERATOR_CONSTRUCTOR = /* @__PURE__ */ ITERATOR_CONSTRUCTOR.toString();
591
+ const ASYNC_ITERATOR_CONSTRUCTOR = (symbol, createPromise) => (stream) => () => {
592
+ let count = 0;
593
+ let doneAt = -1;
594
+ let isThrow = false;
595
+ const buffer = [];
596
+ const pending = [];
597
+ const internal = { finalize(i = 0, len = pending.length) {
598
+ for (; i < len; i++) pending[i].s({
599
+ done: true,
600
+ value: void 0
601
+ });
602
+ } };
603
+ stream.on({
604
+ next(value) {
605
+ const temp = pending.shift();
606
+ if (temp) temp.s({
607
+ done: false,
608
+ value
609
+ });
610
+ buffer.push(value);
611
+ },
612
+ throw(value) {
613
+ const temp = pending.shift();
614
+ if (temp) temp.f(value);
615
+ internal.finalize();
616
+ doneAt = buffer.length;
617
+ isThrow = true;
618
+ buffer.push(value);
619
+ },
620
+ return(value) {
621
+ const temp = pending.shift();
622
+ if (temp) temp.s({
623
+ done: true,
624
+ value
625
+ });
626
+ internal.finalize();
627
+ doneAt = buffer.length;
628
+ buffer.push(value);
629
+ }
630
+ });
631
+ const instance = {
632
+ [symbol]() {
633
+ return instance;
634
+ },
635
+ next() {
636
+ if (doneAt === -1) {
637
+ const index = count++;
638
+ if (index >= buffer.length) {
639
+ const temp = createPromise();
640
+ pending.push(temp);
641
+ return temp.p;
642
+ }
643
+ return {
644
+ done: false,
645
+ value: buffer[index]
646
+ };
647
+ }
648
+ if (count > doneAt) return {
649
+ done: true,
650
+ value: void 0
651
+ };
652
+ const index = count++;
653
+ const value = buffer[index];
654
+ if (index !== doneAt) return {
655
+ done: false,
656
+ value
657
+ };
658
+ if (isThrow) throw value;
659
+ return {
660
+ done: true,
661
+ value
662
+ };
663
+ }
664
+ };
665
+ return instance;
666
+ };
667
+ const SERIALIZED_ASYNC_ITERATOR_CONSTRUCTOR = /* @__PURE__ */ ASYNC_ITERATOR_CONSTRUCTOR.toString();
668
+ const ARRAY_BUFFER_CONSTRUCTOR = (b64) => {
669
+ const decoded = atob(b64);
670
+ const length = decoded.length;
671
+ const arr = new Uint8Array(length);
672
+ for (let i = 0; i < length; i++) arr[i] = decoded.charCodeAt(i);
673
+ return arr.buffer;
674
+ };
675
+ const SERIALIZED_ARRAY_BUFFER_CONSTRUCTOR = /* @__PURE__ */ ARRAY_BUFFER_CONSTRUCTOR.toString();
676
+ //#endregion
677
+ //#region src/core/sequence.ts
678
+ function isSequence(value) {
679
+ return "__SEROVAL_SEQUENCE__" in value;
680
+ }
681
+ function createSequence(values, throwAt, doneAt) {
682
+ return {
683
+ __SEROVAL_SEQUENCE__: true,
684
+ v: values,
685
+ t: throwAt,
686
+ d: doneAt
687
+ };
688
+ }
689
+ function createSequenceFromIterable(source) {
690
+ const values = [];
691
+ let throwsAt = -1;
692
+ let doneAt = -1;
693
+ const iterator = source[SYM_ITERATOR]();
694
+ while (true) try {
695
+ const value = iterator.next();
696
+ values.push(value.value);
697
+ if (value.done) {
698
+ doneAt = values.length - 1;
699
+ break;
700
+ }
701
+ } catch (error) {
702
+ throwsAt = values.length;
703
+ values.push(error);
704
+ }
705
+ return createSequence(values, throwsAt, doneAt);
706
+ }
707
+ const createIterator = ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
708
+ function sequenceToIterator(sequence) {
709
+ return createIterator(sequence);
710
+ }
711
+ //#endregion
712
+ //#region src/core/special-reference.ts
713
+ const ITERATOR = {};
714
+ const ASYNC_ITERATOR = {};
715
+ /**
716
+ * Placeholder references
717
+ */
718
+ const SPECIAL_REFS = {
719
+ [0]: {},
720
+ [1]: {},
721
+ [2]: {},
722
+ [3]: {},
723
+ [4]: {},
724
+ [5]: {}
725
+ };
726
+ const SPECIAL_REF_STRING = {
727
+ [0]: "[]",
728
+ [1]: SERIALIZED_PROMISE_CONSTRUCTOR,
729
+ [2]: SERIALIZED_PROMISE_SUCCESS,
730
+ [3]: SERIALIZED_PROMISE_FAILURE,
731
+ [4]: SERIALIZED_STREAM_CONSTRUCTOR,
732
+ [5]: SERIALIZED_ARRAY_BUFFER_CONSTRUCTOR
733
+ };
734
+ //#endregion
735
+ //#region src/core/stream.ts
736
+ function isStream(value) {
737
+ return "__SEROVAL_STREAM__" in value;
738
+ }
739
+ function createStream() {
740
+ return STREAM_CONSTRUCTOR();
741
+ }
742
+ function createStreamFromAsyncIterable(iterable) {
743
+ const stream = createStream();
744
+ const iterator = iterable[SYM_ASYNC_ITERATOR]();
745
+ async function push() {
746
+ try {
747
+ const value = await iterator.next();
748
+ if (value.done) stream.return(value.value);
749
+ else {
750
+ stream.next(value.value);
751
+ await push();
752
+ }
753
+ } catch (error) {
754
+ stream.throw(error);
755
+ }
756
+ }
757
+ push().catch(() => {});
758
+ return stream;
759
+ }
760
+ const createAsyncIterable = ASYNC_ITERATOR_CONSTRUCTOR(SYM_ASYNC_ITERATOR, PROMISE_CONSTRUCTOR);
761
+ function streamToAsyncIterable(stream) {
762
+ return createAsyncIterable(stream);
763
+ }
764
+ //#endregion
765
+ //#region src/core/utils/promise-to-result.ts
766
+ async function promiseToResult(current) {
767
+ try {
768
+ return [1, await current];
769
+ } catch (e) {
770
+ return [0, e];
771
+ }
772
+ }
773
+ //#endregion
774
+ //#region src/core/context/parser.ts
775
+ function createBaseParserContext(mode, options) {
776
+ return {
777
+ plugins: options.plugins,
778
+ mode,
779
+ marked: /* @__PURE__ */ new Set(),
780
+ features: 127 ^ (options.disabledFeatures || 0),
781
+ refs: options.refs || /* @__PURE__ */ new Map(),
782
+ depthLimit: options.depthLimit || 1e3
783
+ };
784
+ }
785
+ /**
786
+ * Ensures that the value (based on an identifier) has been visited by the parser.
787
+ * @param ctx
788
+ * @param id
789
+ */
790
+ function markParserRef(ctx, id) {
791
+ ctx.marked.add(id);
792
+ }
793
+ /**
794
+ * Creates an identifier for a value
795
+ * @param ctx
796
+ * @param current
797
+ */
798
+ function createIndexForValue(ctx, current) {
799
+ const id = ctx.refs.size;
800
+ ctx.refs.set(current, id);
801
+ return id;
802
+ }
803
+ function getNodeForIndexedValue(ctx, current) {
804
+ const registeredId = ctx.refs.get(current);
805
+ if (registeredId != null) {
806
+ markParserRef(ctx, registeredId);
807
+ return {
808
+ type: 1,
809
+ value: createIndexedValueNode(registeredId)
810
+ };
811
+ }
812
+ return {
813
+ type: 0,
814
+ value: createIndexForValue(ctx, current)
815
+ };
816
+ }
817
+ function getReferenceNode(ctx, current) {
818
+ const indexed = getNodeForIndexedValue(ctx, current);
819
+ if (indexed.type === 1) return indexed;
820
+ if (hasReferenceID(current)) return {
821
+ type: 2,
822
+ value: createReferenceNode(indexed.value, current)
823
+ };
824
+ return indexed;
825
+ }
826
+ /**
827
+ * Parsing methods
828
+ */
829
+ function parseWellKnownSymbol(ctx, current) {
830
+ const ref = getReferenceNode(ctx, current);
831
+ if (ref.type !== 0) return ref.value;
832
+ if (current in INV_SYMBOL_REF) return createWKSymbolNode(ref.value, current);
833
+ throw new SerovalUnsupportedTypeError(current);
834
+ }
835
+ function parseSpecialReference(ctx, ref) {
836
+ const result = getNodeForIndexedValue(ctx, SPECIAL_REFS[ref]);
837
+ if (result.type === 1) return result.value;
838
+ return createSerovalNode(26, result.value, ref, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
839
+ }
840
+ function parseIteratorFactory(ctx) {
841
+ const result = getNodeForIndexedValue(ctx, ITERATOR);
842
+ if (result.type === 1) return result.value;
843
+ 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);
844
+ }
845
+ function parseAsyncIteratorFactory(ctx) {
846
+ const result = getNodeForIndexedValue(ctx, ASYNC_ITERATOR);
847
+ if (result.type === 1) return result.value;
848
+ 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);
849
+ }
850
+ function createObjectNode(id, current, empty, record) {
851
+ 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);
852
+ }
853
+ function createMapNode(ctx, id, k, v) {
854
+ return createSerovalNode(8, id, void 0, void 0, void 0, void 0, {
855
+ k,
856
+ v
857
+ }, void 0, parseSpecialReference(ctx, 0), void 0, void 0, void 0);
858
+ }
859
+ function createPromiseConstructorNode(ctx, id, resolver) {
860
+ return createSerovalNode(22, id, resolver, void 0, void 0, void 0, void 0, void 0, parseSpecialReference(ctx, 1), void 0, void 0, void 0);
861
+ }
862
+ function createArrayBufferNode(ctx, id, current) {
863
+ const bytes = new Uint8Array(current);
864
+ let result = "";
865
+ for (let i = 0, len = bytes.length; i < len; i++) result += String.fromCharCode(bytes[i]);
866
+ return createSerovalNode(19, id, serializeString(btoa(result)), void 0, void 0, void 0, void 0, void 0, parseSpecialReference(ctx, 5), void 0, void 0, void 0);
867
+ }
868
+ //#endregion
869
+ //#region src/core/context/async-parser.ts
870
+ function createAsyncParserContext(mode, options) {
871
+ return {
872
+ base: createBaseParserContext(mode, options),
873
+ child: void 0
874
+ };
875
+ }
876
+ var AsyncParsePluginContext = class {
877
+ constructor(_p, depth) {
878
+ this._p = _p;
879
+ this.depth = depth;
880
+ }
881
+ parse(current) {
882
+ return parseAsync(this._p, this.depth, current);
883
+ }
884
+ };
885
+ async function parseItems$1(ctx, depth, current) {
886
+ const nodes = [];
887
+ for (let i = 0, len = current.length; i < len; i++) if (i in current) nodes[i] = await parseAsync(ctx, depth, current[i]);
888
+ else nodes[i] = 0;
889
+ return nodes;
890
+ }
891
+ async function parseArray$1(ctx, depth, id, current) {
892
+ return createArrayNode(id, current, await parseItems$1(ctx, depth, current));
893
+ }
894
+ async function parseProperties$1(ctx, depth, properties) {
895
+ const entries = Object.entries(properties);
896
+ const keyNodes = [];
897
+ const valueNodes = [];
898
+ for (let i = 0, len = entries.length; i < len; i++) {
899
+ keyNodes.push(serializeString(entries[i][0]));
900
+ valueNodes.push(await parseAsync(ctx, depth, entries[i][1]));
901
+ }
902
+ if (SYM_ITERATOR in properties) {
903
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
904
+ valueNodes.push(createIteratorFactoryInstanceNode(parseIteratorFactory(ctx.base), await parseAsync(ctx, depth, createSequenceFromIterable(properties))));
905
+ }
906
+ if (SYM_ASYNC_ITERATOR in properties) {
907
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
908
+ valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), await parseAsync(ctx, depth, createStreamFromAsyncIterable(properties))));
909
+ }
910
+ if (SYM_TO_STRING_TAG in properties) {
911
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
912
+ valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
913
+ }
914
+ if (SYM_IS_CONCAT_SPREADABLE in properties) {
915
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
916
+ valueNodes.push(properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE);
917
+ }
918
+ return {
919
+ k: keyNodes,
920
+ v: valueNodes
921
+ };
922
+ }
923
+ async function parsePlainObject$1(ctx, depth, id, current, empty) {
924
+ return createObjectNode(id, current, empty, await parseProperties$1(ctx, depth, current));
925
+ }
926
+ async function parseBoxed$1(ctx, depth, id, current) {
927
+ return createBoxedNode(id, await parseAsync(ctx, depth, current.valueOf()));
928
+ }
929
+ async function parseTypedArray$1(ctx, depth, id, current) {
930
+ return createTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
931
+ }
932
+ async function parseBigIntTypedArray$1(ctx, depth, id, current) {
933
+ return createBigIntTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
934
+ }
935
+ async function parseDataView$1(ctx, depth, id, current) {
936
+ return createDataViewNode(id, current, await parseAsync(ctx, depth, current.buffer));
937
+ }
938
+ async function parseError$1(ctx, depth, id, current) {
939
+ const options = getErrorOptions(current, ctx.base.features);
940
+ return createErrorNode(id, current, options ? await parseProperties$1(ctx, depth, options) : void 0);
941
+ }
942
+ async function parseAggregateError$1(ctx, depth, id, current) {
943
+ const options = getErrorOptions(current, ctx.base.features);
944
+ return createAggregateErrorNode(id, current, options ? await parseProperties$1(ctx, depth, options) : void 0);
945
+ }
946
+ async function parseMap$1(ctx, depth, id, current) {
947
+ const keyNodes = [];
948
+ const valueNodes = [];
949
+ for (const [key, value] of current.entries()) {
950
+ keyNodes.push(await parseAsync(ctx, depth, key));
951
+ valueNodes.push(await parseAsync(ctx, depth, value));
952
+ }
953
+ return createMapNode(ctx.base, id, keyNodes, valueNodes);
954
+ }
955
+ async function parseSet$1(ctx, depth, id, current) {
956
+ const items = [];
957
+ for (const item of current.keys()) items.push(await parseAsync(ctx, depth, item));
958
+ return createSetNode(id, items);
959
+ }
960
+ async function parsePlugin$1(ctx, depth, id, current) {
961
+ const currentPlugins = ctx.base.plugins;
962
+ if (currentPlugins) for (let i = 0, len = currentPlugins.length; i < len; i++) {
963
+ const plugin = currentPlugins[i];
964
+ if (plugin.parse.async && plugin.test(current)) return createPluginNode(id, plugin.tag, await plugin.parse.async(current, new AsyncParsePluginContext(ctx, depth), { id }));
965
+ }
966
+ }
967
+ async function parsePromise$1(ctx, depth, id, current) {
968
+ const [status, result] = await promiseToResult(current);
969
+ 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);
970
+ }
971
+ function parseStreamHandle(depth, id, current, resolve, reject) {
972
+ const sequence = [];
973
+ const cleanup = current.on({
974
+ next: (value) => {
975
+ markParserRef(this.base, id);
976
+ parseAsync(this, depth, value).then((data) => {
977
+ sequence.push(createStreamNextNode(id, data));
978
+ }, (data) => {
979
+ reject(data);
980
+ cleanup();
981
+ });
982
+ },
983
+ throw: (value) => {
984
+ markParserRef(this.base, id);
985
+ parseAsync(this, depth, value).then((data) => {
986
+ sequence.push(createStreamThrowNode(id, data));
987
+ resolve(sequence);
988
+ cleanup();
989
+ }, (data) => {
990
+ reject(data);
991
+ cleanup();
992
+ });
993
+ },
994
+ return: (value) => {
995
+ markParserRef(this.base, id);
996
+ parseAsync(this, depth, value).then((data) => {
997
+ sequence.push(createStreamReturnNode(id, data));
998
+ resolve(sequence);
999
+ cleanup();
1000
+ }, (data) => {
1001
+ reject(data);
1002
+ cleanup();
1003
+ });
1004
+ }
1005
+ });
1006
+ }
1007
+ async function parseStream$1(ctx, depth, id, current) {
1008
+ return createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), await new Promise(parseStreamHandle.bind(ctx, depth, id, current)));
1009
+ }
1010
+ async function parseSequence$1(ctx, depth, id, current) {
1011
+ const nodes = [];
1012
+ for (let i = 0, len = current.v.length; i < len; i++) nodes[i] = await parseAsync(ctx, depth, current.v[i]);
1013
+ return createSequenceNode(id, nodes, current.t, current.d);
1014
+ }
1015
+ async function parseObjectAsync(ctx, depth, id, current) {
1016
+ if (Array.isArray(current)) return parseArray$1(ctx, depth, id, current);
1017
+ if (isStream(current)) return parseStream$1(ctx, depth, id, current);
1018
+ if (isSequence(current)) return parseSequence$1(ctx, depth, id, current);
1019
+ let currentClass = current.constructor;
1020
+ if (currentClass !== void 0 && typeof currentClass !== "function") {
1021
+ const proto = Object.getPrototypeOf(current);
1022
+ currentClass = proto === null ? void 0 : proto.constructor;
1023
+ }
1024
+ if (currentClass === OpaqueReference) return parseAsync(ctx, depth, current.replacement);
1025
+ const parsed = await parsePlugin$1(ctx, depth, id, current);
1026
+ if (parsed) return parsed;
1027
+ switch (currentClass) {
1028
+ case Object: return parsePlainObject$1(ctx, depth, id, current, false);
1029
+ case void 0: return parsePlainObject$1(ctx, depth, id, current, true);
1030
+ case Date: return createDateNode(id, current);
1031
+ case Error:
1032
+ case EvalError:
1033
+ case RangeError:
1034
+ case ReferenceError:
1035
+ case SyntaxError:
1036
+ case TypeError:
1037
+ case URIError: return parseError$1(ctx, depth, id, current);
1038
+ case Number:
1039
+ case Boolean:
1040
+ case String:
1041
+ case BigInt: return parseBoxed$1(ctx, depth, id, current);
1042
+ case ArrayBuffer: return createArrayBufferNode(ctx.base, id, current);
1043
+ case Int8Array:
1044
+ case Int16Array:
1045
+ case Int32Array:
1046
+ case Uint8Array:
1047
+ case Uint16Array:
1048
+ case Uint32Array:
1049
+ case Uint8ClampedArray:
1050
+ case Float32Array:
1051
+ case Float64Array: return parseTypedArray$1(ctx, depth, id, current);
1052
+ case DataView: return parseDataView$1(ctx, depth, id, current);
1053
+ case Map: return parseMap$1(ctx, depth, id, current);
1054
+ case Set: return parseSet$1(ctx, depth, id, current);
1055
+ default: break;
1056
+ }
1057
+ if (currentClass === Promise || current instanceof Promise) return parsePromise$1(ctx, depth, id, current);
1058
+ const currentFeatures = ctx.base.features;
1059
+ if (currentFeatures & 32 && currentClass === RegExp) return createRegExpNode(id, current);
1060
+ if (currentFeatures & 16) switch (currentClass) {
1061
+ case BigInt64Array:
1062
+ case BigUint64Array: return parseBigIntTypedArray$1(ctx, depth, id, current);
1063
+ default: break;
1064
+ }
1065
+ if (currentFeatures & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) return parseAggregateError$1(ctx, depth, id, current);
1066
+ if (currentFeatures & 64 && typeof Temporal !== "undefined") switch (currentClass) {
1067
+ case Temporal.Instant: return createTemporalNode(id, 0, current);
1068
+ case Temporal.Duration: return createTemporalNode(id, 1, current);
1069
+ case Temporal.PlainDate: return createTemporalNode(id, 2, current);
1070
+ case Temporal.PlainDateTime: return createTemporalNode(id, 3, current);
1071
+ case Temporal.PlainMonthDay: return createTemporalNode(id, 4, current);
1072
+ case Temporal.PlainTime: return createTemporalNode(id, 5, current);
1073
+ case Temporal.PlainYearMonth: return createTemporalNode(id, 6, current);
1074
+ case Temporal.ZonedDateTime: return createTemporalNode(id, 7, current);
1075
+ default: break;
1076
+ }
1077
+ if (current instanceof Error) return parseError$1(ctx, depth, id, current);
1078
+ if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) return parsePlainObject$1(ctx, depth, id, current, !!currentClass);
1079
+ throw new SerovalUnsupportedTypeError(current);
1080
+ }
1081
+ async function parseFunctionAsync(ctx, depth, current) {
1082
+ const ref = getReferenceNode(ctx.base, current);
1083
+ if (ref.type !== 0) return ref.value;
1084
+ const plugin = await parsePlugin$1(ctx, depth, ref.value, current);
1085
+ if (plugin) return plugin;
1086
+ throw new SerovalUnsupportedTypeError(current);
1087
+ }
1088
+ async function parseAsync(ctx, depth, current) {
1089
+ if (depth >= ctx.base.depthLimit) throw new SerovalDepthLimitError(ctx.base.depthLimit);
1090
+ switch (typeof current) {
1091
+ case "boolean": return current ? TRUE_NODE : FALSE_NODE;
1092
+ case "undefined": return UNDEFINED_NODE;
1093
+ case "string": return createStringNode(current);
1094
+ case "number": return createNumberNode(current);
1095
+ case "bigint": return createBigIntNode(current);
1096
+ case "object":
1097
+ if (current) {
1098
+ const ref = getReferenceNode(ctx.base, current);
1099
+ return ref.type === 0 ? await parseObjectAsync(ctx, depth + 1, ref.value, current) : ref.value;
1100
+ }
1101
+ return NULL_NODE;
1102
+ case "symbol": return parseWellKnownSymbol(ctx.base, current);
1103
+ case "function": return parseFunctionAsync(ctx, depth, current);
1104
+ default: throw new SerovalUnsupportedTypeError(current);
1105
+ }
1106
+ }
1107
+ async function parseTopAsync(ctx, current) {
1108
+ try {
1109
+ return await parseAsync(ctx, 0, current);
1110
+ } catch (error) {
1111
+ throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
1112
+ }
1113
+ }
1114
+ //#endregion
1115
+ //#region src/core/plugin.ts
1116
+ let SerovalMode = /* @__PURE__ */ function(SerovalMode) {
1117
+ SerovalMode[SerovalMode["Vanilla"] = 1] = "Vanilla";
1118
+ SerovalMode[SerovalMode["Cross"] = 2] = "Cross";
1119
+ return SerovalMode;
1120
+ }({});
1121
+ function createPlugin(plugin) {
1122
+ return plugin;
1123
+ }
1124
+ function dedupePlugins(deduped, plugins) {
1125
+ for (let i = 0, len = plugins.length; i < len; i++) {
1126
+ const current = plugins[i];
1127
+ if (!deduped.has(current)) {
1128
+ deduped.add(current);
1129
+ if (current.extends) dedupePlugins(deduped, current.extends);
1130
+ }
1131
+ }
1132
+ }
1133
+ function resolvePlugins(plugins) {
1134
+ if (plugins) {
1135
+ const deduped = /* @__PURE__ */ new Set();
1136
+ dedupePlugins(deduped, plugins);
1137
+ return [...deduped];
1138
+ }
1139
+ }
1140
+ //#endregion
1141
+ //#region src/core/utils/typed-array.ts
1142
+ function getTypedArrayConstructor(name) {
1143
+ switch (name) {
1144
+ case "Int8Array": return Int8Array;
1145
+ case "Int16Array": return Int16Array;
1146
+ case "Int32Array": return Int32Array;
1147
+ case "Uint8Array": return Uint8Array;
1148
+ case "Uint16Array": return Uint16Array;
1149
+ case "Uint32Array": return Uint32Array;
1150
+ case "Uint8ClampedArray": return Uint8ClampedArray;
1151
+ case "Float32Array": return Float32Array;
1152
+ case "Float64Array": return Float64Array;
1153
+ case "BigInt64Array": return BigInt64Array;
1154
+ case "BigUint64Array": return BigUint64Array;
1155
+ default: throw new SerovalUnknownTypedArrayError(name);
1156
+ }
1157
+ }
1158
+ //#endregion
1159
+ //#region src/core/utils/valid-properties.ts
1160
+ function isValidKey(key) {
1161
+ switch (key) {
1162
+ case "constructor":
1163
+ case "__proto__":
1164
+ case "prototype":
1165
+ case "__defineGetter__":
1166
+ case "__defineSetter__":
1167
+ case "__lookupGetter__":
1168
+ case "__lookupSetter__": return false;
1169
+ default: return true;
1170
+ }
1171
+ }
1172
+ function isValidSymbol(symbol) {
1173
+ switch (symbol) {
1174
+ case SYM_ASYNC_ITERATOR:
1175
+ case SYM_IS_CONCAT_SPREADABLE:
1176
+ case SYM_TO_STRING_TAG:
1177
+ case SYM_ITERATOR: return true;
1178
+ default: return false;
1179
+ }
1180
+ }
1181
+ //#endregion
1182
+ //#region src/core/context/deserializer.ts
1183
+ const MAX_BASE64_LENGTH = 1e6;
1184
+ const MAX_BIGINT_LENGTH = 1e4;
1185
+ const MAX_REGEXP_SOURCE_LENGTH = 2e4;
1186
+ function applyObjectFlag(obj, flag) {
1187
+ switch (flag) {
1188
+ case 3: return Object.freeze(obj);
1189
+ case 1: return Object.preventExtensions(obj);
1190
+ case 2: return Object.seal(obj);
1191
+ default: return obj;
1192
+ }
1193
+ }
1194
+ const DEFAULT_DEPTH_LIMIT = 1e3;
1195
+ function createBaseDeserializerContext(mode, options) {
1196
+ var _options$features;
1197
+ const refs = options.refs || /* @__PURE__ */ new Map();
1198
+ if (!("types" in refs)) Object.assign(refs, { types: /* @__PURE__ */ new Map() });
1199
+ return {
1200
+ mode,
1201
+ plugins: options.plugins,
1202
+ refs,
1203
+ features: (_options$features = options.features) !== null && _options$features !== void 0 ? _options$features : 127 ^ (options.disabledFeatures || 0),
1204
+ depthLimit: options.depthLimit || DEFAULT_DEPTH_LIMIT
1205
+ };
1206
+ }
1207
+ function createVanillaDeserializerContext(options) {
1208
+ return {
1209
+ mode: 1,
1210
+ base: createBaseDeserializerContext(1, options),
1211
+ child: void 0,
1212
+ state: { marked: new Set(options.markedRefs) }
1213
+ };
1214
+ }
1215
+ function createCrossDeserializerContext(options) {
1216
+ return {
1217
+ mode: 2,
1218
+ base: createBaseDeserializerContext(2, options),
1219
+ child: void 0
1220
+ };
1221
+ }
1222
+ var DeserializePluginContext = class {
1223
+ constructor(_p, depth) {
1224
+ this._p = _p;
1225
+ this.depth = depth;
1226
+ }
1227
+ deserialize(node) {
1228
+ return deserialize$1(this._p, this.depth, node);
1229
+ }
1230
+ };
1231
+ function guardIndexedValue(ctx, id) {
1232
+ if (id < 0 || !Number.isFinite(id) || !Number.isInteger(id)) throw new SerovalMalformedNodeError({
1233
+ t: 4,
1234
+ i: id
1235
+ });
1236
+ if (ctx.refs.has(id)) throw new Error("Conflicted ref id: " + id);
1237
+ }
1238
+ function assignIndexedValueVanilla(ctx, id, value) {
1239
+ guardIndexedValue(ctx.base, id);
1240
+ if (ctx.state.marked.has(id)) ctx.base.refs.set(id, value);
1241
+ return value;
1242
+ }
1243
+ function assignIndexedValueCross(ctx, id, value) {
1244
+ guardIndexedValue(ctx.base, id);
1245
+ ctx.base.refs.set(id, value);
1246
+ return value;
1247
+ }
1248
+ function assignIndexedValue$1(ctx, id, value) {
1249
+ return ctx.mode === 1 ? assignIndexedValueVanilla(ctx, id, value) : assignIndexedValueCross(ctx, id, value);
1250
+ }
1251
+ function deserializeKnownValue(node, record, key) {
1252
+ if (Object.hasOwn(record, key)) return record[key];
1253
+ throw new SerovalMalformedNodeError(node);
1254
+ }
1255
+ function deserializeReference(ctx, node) {
1256
+ return assignIndexedValue$1(ctx, node.i, getReference(deserializeString(node.s)));
1257
+ }
1258
+ function deserializeArray(ctx, depth, node) {
1259
+ const items = node.a;
1260
+ const len = items.length;
1261
+ const result = assignIndexedValue$1(ctx, node.i, new Array(len));
1262
+ for (let i = 0, item; i < len; i++) {
1263
+ item = items[i];
1264
+ if (item) result[i] = deserialize$1(ctx, depth, item);
1265
+ }
1266
+ applyObjectFlag(result, node.o);
1267
+ return result;
1268
+ }
1269
+ function assignStringProperty(object, key, value) {
1270
+ if (isValidKey(key)) object[key] = value;
1271
+ else Object.defineProperty(object, key, {
1272
+ value,
1273
+ configurable: true,
1274
+ enumerable: true,
1275
+ writable: true
1276
+ });
1277
+ }
1278
+ function assignProperty(ctx, depth, object, key, value) {
1279
+ if (typeof key === "string") assignStringProperty(object, deserializeString(key), deserialize$1(ctx, depth, value));
1280
+ else {
1281
+ const actual = deserialize$1(ctx, depth, key);
1282
+ switch (typeof actual) {
1283
+ case "string":
1284
+ assignStringProperty(object, actual, deserialize$1(ctx, depth, value));
1285
+ break;
1286
+ case "symbol":
1287
+ if (isValidSymbol(actual)) object[actual] = deserialize$1(ctx, depth, value);
1288
+ break;
1289
+ default: throw new SerovalMalformedNodeError(key);
1290
+ }
1291
+ }
1292
+ }
1293
+ function assignNodeType(ctx, id, type) {
1294
+ ctx.base.refs.types.set(id, type);
1295
+ }
1296
+ function validateNodeType(ctx, node, id, type) {
1297
+ if (ctx.base.refs.types.get(id) !== type) throw new SerovalMalformedNodeError(node);
1298
+ }
1299
+ function deserializeProperties(ctx, depth, node, result) {
1300
+ const keys = node.k;
1301
+ 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]);
1302
+ return result;
1303
+ }
1304
+ function deserializeObject(ctx, depth, node) {
1305
+ const result = assignIndexedValue$1(ctx, node.i, node.t === 10 ? {} : Object.create(null));
1306
+ deserializeProperties(ctx, depth, node.p, result);
1307
+ applyObjectFlag(result, node.o);
1308
+ return result;
1309
+ }
1310
+ function deserializeDate(ctx, node) {
1311
+ return assignIndexedValue$1(ctx, node.i, new Date(node.s));
1312
+ }
1313
+ function deserializeTemporal(ctx, node) {
1314
+ if (!(ctx.base.features & 64)) throw new SerovalUnsupportedNodeError(node);
1315
+ let value;
1316
+ switch (node.c) {
1317
+ case 0:
1318
+ value = Temporal.Instant.from(node.s);
1319
+ break;
1320
+ case 1:
1321
+ value = Temporal.Duration.from(node.s);
1322
+ break;
1323
+ case 2:
1324
+ value = Temporal.PlainDate.from(node.s);
1325
+ break;
1326
+ case 3:
1327
+ value = Temporal.PlainDateTime.from(node.s);
1328
+ break;
1329
+ case 4:
1330
+ value = Temporal.PlainMonthDay.from(node.s);
1331
+ break;
1332
+ case 5:
1333
+ value = Temporal.PlainTime.from(node.s);
1334
+ break;
1335
+ case 6:
1336
+ value = Temporal.PlainYearMonth.from(node.s);
1337
+ break;
1338
+ case 7:
1339
+ value = Temporal.ZonedDateTime.from(node.s);
1340
+ break;
1341
+ default: throw new SerovalMalformedNodeError(node);
1342
+ }
1343
+ return assignIndexedValue$1(ctx, node.i, value);
1344
+ }
1345
+ function deserializeRegExp(ctx, node) {
1346
+ if (ctx.base.features & 32) {
1347
+ const source = deserializeString(node.c);
1348
+ if (source.length > MAX_REGEXP_SOURCE_LENGTH) throw new SerovalMalformedNodeError(node);
1349
+ return assignIndexedValue$1(ctx, node.i, new RegExp(source, node.m));
1350
+ }
1351
+ throw new SerovalUnsupportedNodeError(node);
1352
+ }
1353
+ function deserializeSet(ctx, depth, node) {
1354
+ const result = assignIndexedValue$1(ctx, node.i, /* @__PURE__ */ new Set());
1355
+ for (let i = 0, items = node.a, len = items.length; i < len; i++) result.add(deserialize$1(ctx, depth, items[i]));
1356
+ return result;
1357
+ }
1358
+ function deserializeMap(ctx, depth, node) {
1359
+ const result = assignIndexedValue$1(ctx, node.i, /* @__PURE__ */ new Map());
1360
+ for (let i = 0, keys = node.e.k, vals = node.e.v, len = keys.length; i < len; i++) result.set(deserialize$1(ctx, depth, keys[i]), deserialize$1(ctx, depth, vals[i]));
1361
+ return result;
1362
+ }
1363
+ function deserializeArrayBuffer(ctx, node) {
1364
+ if (node.s.length > MAX_BASE64_LENGTH) throw new SerovalMalformedNodeError(node);
1365
+ return assignIndexedValue$1(ctx, node.i, ARRAY_BUFFER_CONSTRUCTOR(deserializeString(node.s)));
1366
+ }
1367
+ function deserializeTypedArray(ctx, depth, node) {
1368
+ var _node$b;
1369
+ const construct = getTypedArrayConstructor(node.c);
1370
+ const source = deserialize$1(ctx, depth, node.f);
1371
+ const offset = (_node$b = node.b) !== null && _node$b !== void 0 ? _node$b : 0;
1372
+ if (offset < 0 || offset > source.byteLength) throw new SerovalMalformedNodeError(node);
1373
+ return assignIndexedValue$1(ctx, node.i, new construct(source, offset, node.l));
1374
+ }
1375
+ function deserializeDataView(ctx, depth, node) {
1376
+ var _node$b2;
1377
+ const source = deserialize$1(ctx, depth, node.f);
1378
+ const offset = (_node$b2 = node.b) !== null && _node$b2 !== void 0 ? _node$b2 : 0;
1379
+ if (offset < 0 || offset > source.byteLength) throw new SerovalMalformedNodeError(node);
1380
+ return assignIndexedValue$1(ctx, node.i, new DataView(source, offset, node.l));
1381
+ }
1382
+ function deserializeDictionary(ctx, depth, node, result) {
1383
+ if (node.p) {
1384
+ const fields = deserializeProperties(ctx, depth, node.p, {});
1385
+ Object.defineProperties(result, Object.getOwnPropertyDescriptors(fields));
1386
+ }
1387
+ return result;
1388
+ }
1389
+ function deserializeAggregateError(ctx, depth, node) {
1390
+ return deserializeDictionary(ctx, depth, node, assignIndexedValue$1(ctx, node.i, new AggregateError([], deserializeString(node.m))));
1391
+ }
1392
+ function deserializeError(ctx, depth, node) {
1393
+ const construct = deserializeKnownValue(node, ERROR_CONSTRUCTOR, node.s);
1394
+ return deserializeDictionary(ctx, depth, node, assignIndexedValue$1(ctx, node.i, new construct(deserializeString(node.m))));
1395
+ }
1396
+ function deserializePromise(ctx, depth, node) {
1397
+ const deferred = PROMISE_CONSTRUCTOR();
1398
+ const result = assignIndexedValue$1(ctx, node.i, deferred.p);
1399
+ const deserialized = deserialize$1(ctx, depth, node.f);
1400
+ if (node.s) deferred.s(deserialized);
1401
+ else deferred.f(deserialized);
1402
+ return result;
1403
+ }
1404
+ function deserializeBoxed(ctx, depth, node) {
1405
+ return assignIndexedValue$1(ctx, node.i, Object(deserialize$1(ctx, depth, node.f)));
1406
+ }
1407
+ function deserializePlugin(ctx, depth, node) {
1408
+ const currentPlugins = ctx.base.plugins;
1409
+ if (currentPlugins) {
1410
+ const tag = deserializeString(node.c);
1411
+ for (let i = 0, len = currentPlugins.length; i < len; i++) {
1412
+ const plugin = currentPlugins[i];
1413
+ if (plugin.tag === tag) return assignIndexedValue$1(ctx, node.i, plugin.deserialize(node.s, new DeserializePluginContext(ctx, depth), { id: node.i }));
1414
+ }
1415
+ }
1416
+ throw new SerovalMissingPluginError(node.c);
1417
+ }
1418
+ function deserializePromiseConstructor(ctx, node) {
1419
+ const value = assignIndexedValue$1(ctx, node.i, assignIndexedValue$1(ctx, node.s, PROMISE_CONSTRUCTOR()).p);
1420
+ assignNodeType(ctx, node.s, 22);
1421
+ return value;
1422
+ }
1423
+ function deserializePromiseResolve(ctx, depth, node) {
1424
+ const deferred = ctx.base.refs.get(node.i);
1425
+ if (deferred) {
1426
+ validateNodeType(ctx, node, node.i, 22);
1427
+ deferred.s(deserialize$1(ctx, depth, node.a[1]));
1428
+ return;
1429
+ }
1430
+ throw new SerovalMissingInstanceError("Promise");
1431
+ }
1432
+ function deserializePromiseReject(ctx, depth, node) {
1433
+ const deferred = ctx.base.refs.get(node.i);
1434
+ if (deferred) {
1435
+ validateNodeType(ctx, node, node.i, 22);
1436
+ deferred.f(deserialize$1(ctx, depth, node.a[1]));
1437
+ return;
1438
+ }
1439
+ throw new SerovalMissingInstanceError("Promise");
1440
+ }
1441
+ function deserializeIteratorFactoryInstance(ctx, depth, node) {
1442
+ deserialize$1(ctx, depth, node.a[0]);
1443
+ return sequenceToIterator(deserialize$1(ctx, depth, node.a[1]));
1444
+ }
1445
+ function deserializeAsyncIteratorFactoryInstance(ctx, depth, node) {
1446
+ deserialize$1(ctx, depth, node.a[0]);
1447
+ return streamToAsyncIterable(deserialize$1(ctx, depth, node.a[1]));
1448
+ }
1449
+ function deserializeStreamConstructor(ctx, depth, node) {
1450
+ const result = assignIndexedValue$1(ctx, node.i, createStream());
1451
+ assignNodeType(ctx, node.i, 31);
1452
+ const items = node.a;
1453
+ const len = items.length;
1454
+ if (len) for (let i = 0; i < len; i++) deserialize$1(ctx, depth, items[i]);
1455
+ return result;
1456
+ }
1457
+ function deserializeStreamNext(ctx, depth, node) {
1458
+ const deferred = ctx.base.refs.get(node.i);
1459
+ if (deferred) {
1460
+ validateNodeType(ctx, node, node.i, 31);
1461
+ deferred.next(deserialize$1(ctx, depth, node.f));
1462
+ return;
1463
+ }
1464
+ throw new SerovalMissingInstanceError("Stream");
1465
+ }
1466
+ function deserializeStreamThrow(ctx, depth, node) {
1467
+ const deferred = ctx.base.refs.get(node.i);
1468
+ if (deferred) {
1469
+ validateNodeType(ctx, node, node.i, 31);
1470
+ deferred.throw(deserialize$1(ctx, depth, node.f));
1471
+ return;
1472
+ }
1473
+ throw new SerovalMissingInstanceError("Stream");
1474
+ }
1475
+ function deserializeStreamReturn(ctx, depth, node) {
1476
+ const deferred = ctx.base.refs.get(node.i);
1477
+ if (deferred) {
1478
+ validateNodeType(ctx, node, node.i, 31);
1479
+ deferred.return(deserialize$1(ctx, depth, node.f));
1480
+ return;
1481
+ }
1482
+ throw new SerovalMissingInstanceError("Stream");
1483
+ }
1484
+ function deserializeIteratorFactory(ctx, depth, node) {
1485
+ deserialize$1(ctx, depth, node.f);
1486
+ }
1487
+ function deserializeAsyncIteratorFactory(ctx, depth, node) {
1488
+ deserialize$1(ctx, depth, node.a[1]);
1489
+ }
1490
+ function deserializeSequence(ctx, depth, node) {
1491
+ const result = assignIndexedValue$1(ctx, node.i, createSequence([], node.s, node.l));
1492
+ for (let i = 0, len = node.a.length; i < len; i++) result.v[i] = deserialize$1(ctx, depth, node.a[i]);
1493
+ return result;
1494
+ }
1495
+ function deserialize$1(ctx, depth, node) {
1496
+ if (depth > ctx.base.depthLimit) throw new SerovalDepthLimitError(ctx.base.depthLimit);
1497
+ depth += 1;
1498
+ switch (node.t) {
1499
+ case 2: return deserializeKnownValue(node, CONSTANT_VAL, node.s);
1500
+ case 0: return Number(node.s);
1501
+ case 1: return deserializeString(String(node.s));
1502
+ case 3:
1503
+ if (String(node.s).length > MAX_BIGINT_LENGTH) throw new SerovalMalformedNodeError(node);
1504
+ return BigInt(node.s);
1505
+ case 4: return ctx.base.refs.get(node.i);
1506
+ case 18: return deserializeReference(ctx, node);
1507
+ case 9: return deserializeArray(ctx, depth, node);
1508
+ case 10:
1509
+ case 11: return deserializeObject(ctx, depth, node);
1510
+ case 5: return deserializeDate(ctx, node);
1511
+ case 6: return deserializeRegExp(ctx, node);
1512
+ case 7: return deserializeSet(ctx, depth, node);
1513
+ case 8: return deserializeMap(ctx, depth, node);
1514
+ case 19: return deserializeArrayBuffer(ctx, node);
1515
+ case 16:
1516
+ case 15: return deserializeTypedArray(ctx, depth, node);
1517
+ case 20: return deserializeDataView(ctx, depth, node);
1518
+ case 14: return deserializeAggregateError(ctx, depth, node);
1519
+ case 13: return deserializeError(ctx, depth, node);
1520
+ case 12: return deserializePromise(ctx, depth, node);
1521
+ case 17: return deserializeKnownValue(node, SYMBOL_REF, node.s);
1522
+ case 21: return deserializeBoxed(ctx, depth, node);
1523
+ case 25: return deserializePlugin(ctx, depth, node);
1524
+ case 22: return deserializePromiseConstructor(ctx, node);
1525
+ case 23: return deserializePromiseResolve(ctx, depth, node);
1526
+ case 24: return deserializePromiseReject(ctx, depth, node);
1527
+ case 28: return deserializeIteratorFactoryInstance(ctx, depth, node);
1528
+ case 30: return deserializeAsyncIteratorFactoryInstance(ctx, depth, node);
1529
+ case 31: return deserializeStreamConstructor(ctx, depth, node);
1530
+ case 32: return deserializeStreamNext(ctx, depth, node);
1531
+ case 33: return deserializeStreamThrow(ctx, depth, node);
1532
+ case 34: return deserializeStreamReturn(ctx, depth, node);
1533
+ case 27: return deserializeIteratorFactory(ctx, depth, node);
1534
+ case 29: return deserializeAsyncIteratorFactory(ctx, depth, node);
1535
+ case 35: return deserializeSequence(ctx, depth, node);
1536
+ case 36: return deserializeTemporal(ctx, node);
1537
+ default: throw new SerovalUnsupportedNodeError(node);
1538
+ }
1539
+ }
1540
+ function deserializeTop(ctx, node) {
1541
+ try {
1542
+ return deserialize$1(ctx, 0, node);
1543
+ } catch (error) {
1544
+ throw new SerovalDeserializationError(error);
1545
+ }
1546
+ }
1547
+ //#endregion
1548
+ //#region src/core/function-string.ts
1549
+ const RETURN = () => T;
1550
+ const SERIALIZED_RETURN = /* @__PURE__ */ RETURN.toString();
1551
+ const IS_MODERN = /* @__PURE__ */ /=>/.test(SERIALIZED_RETURN);
1552
+ function createFunction(parameters, body) {
1553
+ if (IS_MODERN) return (parameters.length === 1 ? parameters[0] : "(" + parameters.join(",") + ")") + "=>" + (body.startsWith("{") ? "(" + body + ")" : body);
1554
+ return "function(" + parameters.join(",") + "){return " + body + "}";
1555
+ }
1556
+ function createEffectfulFunction(parameters, body) {
1557
+ if (IS_MODERN) return (parameters.length === 1 ? parameters[0] : "(" + parameters.join(",") + ")") + "=>{" + body + "}";
1558
+ return "function(" + parameters.join(",") + "){" + body + "}";
1559
+ }
1560
+ //#endregion
1561
+ //#region src/core/utils/get-identifier.ts
1562
+ const REF_START_CHARS = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_";
1563
+ const REF_START_CHARS_LEN = 34;
1564
+ const REF_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
1565
+ const REF_CHARS_LEN = 64;
1566
+ function getIdentifier(index) {
1567
+ let mod = index % REF_START_CHARS_LEN;
1568
+ let ref = REF_START_CHARS[mod];
1569
+ index = (index - mod) / REF_START_CHARS_LEN;
1570
+ while (index > 0) {
1571
+ mod = index % REF_CHARS_LEN;
1572
+ ref += REF_CHARS[mod];
1573
+ index = (index - mod) / REF_CHARS_LEN;
1574
+ }
1575
+ return ref;
1576
+ }
1577
+ //#endregion
1578
+ //#region src/core/utils/is-valid-identifier.ts
1579
+ const IDENTIFIER_CHECK = /^[$A-Z_][0-9A-Z_$]*$/i;
1580
+ function isValidIdentifier(name) {
1581
+ const char = name[0];
1582
+ return (char === "$" || char === "_" || char >= "A" && char <= "Z" || char >= "a" && char <= "z") && IDENTIFIER_CHECK.test(name);
1583
+ }
1584
+ //#endregion
1585
+ //#region src/core/context/serializer.ts
1586
+ function getAssignmentExpression(assignment) {
1587
+ switch (assignment.t) {
1588
+ case 0: return assignment.s + "=" + assignment.v;
1589
+ case 2: return assignment.s + ".set(" + assignment.k + "," + assignment.v + ")";
1590
+ case 1: return assignment.s + ".add(" + assignment.v + ")";
1591
+ case 3: return assignment.s + ".delete(" + assignment.k + ")";
1592
+ case 4: return "Object.defineProperty(" + assignment.s + ",\"__proto__\",{value:" + assignment.k + ",configurable:!0,enumerable:!0,writable:!0})";
1593
+ }
1594
+ }
1595
+ function mergeAssignments(assignments) {
1596
+ const newAssignments = [];
1597
+ let current = assignments[0];
1598
+ for (let i = 1, len = assignments.length, item, prev = current; i < len; i++) {
1599
+ item = assignments[i];
1600
+ if (item.t === 0 && item.v === prev.v) current = {
1601
+ t: 0,
1602
+ s: item.s,
1603
+ k: void 0,
1604
+ v: getAssignmentExpression(current)
1605
+ };
1606
+ else if (item.t === 2 && item.s === prev.s) current = {
1607
+ t: 2,
1608
+ s: getAssignmentExpression(current),
1609
+ k: item.k,
1610
+ v: item.v
1611
+ };
1612
+ else if (item.t === 1 && item.s === prev.s) current = {
1613
+ t: 1,
1614
+ s: getAssignmentExpression(current),
1615
+ k: void 0,
1616
+ v: item.v
1617
+ };
1618
+ else if (item.t === 3 && item.s === prev.s) current = {
1619
+ t: 3,
1620
+ s: getAssignmentExpression(current),
1621
+ k: item.k,
1622
+ v: void 0
1623
+ };
1624
+ else {
1625
+ newAssignments.push(current);
1626
+ current = item;
1627
+ }
1628
+ prev = item;
1629
+ }
1630
+ newAssignments.push(current);
1631
+ return newAssignments;
1632
+ }
1633
+ function resolveAssignments(assignments) {
1634
+ if (assignments.length) {
1635
+ let result = "";
1636
+ const merged = mergeAssignments(assignments);
1637
+ for (let i = 0, len = merged.length; i < len; i++) result += getAssignmentExpression(merged[i]) + ",";
1638
+ return result;
1639
+ }
1640
+ }
1641
+ const NULL_CONSTRUCTOR = "Object.create(null)";
1642
+ const SET_CONSTRUCTOR = "new Set";
1643
+ const MAP_CONSTRUCTOR = "new Map";
1644
+ const PROMISE_RESOLVE = "Promise.resolve";
1645
+ const PROMISE_REJECT = "Promise.reject";
1646
+ const OBJECT_FLAG_CONSTRUCTOR = {
1647
+ [3]: "Object.freeze",
1648
+ [2]: "Object.seal",
1649
+ [1]: "Object.preventExtensions",
1650
+ [0]: void 0
1651
+ };
1652
+ function createBaseSerializerContext(mode, options) {
1653
+ return {
1654
+ mode,
1655
+ plugins: options.plugins,
1656
+ features: options.features,
1657
+ marked: new Set(options.markedRefs),
1658
+ stack: [],
1659
+ flags: [],
1660
+ assignments: []
1661
+ };
1662
+ }
1663
+ function createVanillaSerializerState() {
1664
+ return {
1665
+ valid: /* @__PURE__ */ new Map(),
1666
+ vars: []
1667
+ };
1668
+ }
1669
+ function createVanillaSerializerContext(options) {
1670
+ return {
1671
+ mode: 1,
1672
+ base: createBaseSerializerContext(1, options),
1673
+ state: createVanillaSerializerState(),
1674
+ child: void 0
1675
+ };
1676
+ }
1677
+ function createCrossSerializerContext(options) {
1678
+ return {
1679
+ mode: 2,
1680
+ base: createBaseSerializerContext(2, options),
1681
+ state: options,
1682
+ child: void 0
1683
+ };
1684
+ }
1685
+ var SerializePluginContext = class {
1686
+ constructor(_p) {
1687
+ this._p = _p;
1688
+ }
1689
+ serialize(node) {
1690
+ return serialize$1(this._p, node);
1691
+ }
1692
+ };
1693
+ /**
1694
+ * Creates the reference param (identifier) from the given reference ID
1695
+ * Calling this function means the value has been referenced somewhere
1696
+ */
1697
+ function getVanillaRefParam(state, index) {
1698
+ /**
1699
+ * Creates a new reference ID from a given reference ID
1700
+ * This new reference ID means that the reference itself
1701
+ * has been referenced at least once, and is used to generate
1702
+ * the variables
1703
+ */
1704
+ let actualIndex = state.valid.get(index);
1705
+ if (actualIndex == null) {
1706
+ actualIndex = state.valid.size;
1707
+ state.valid.set(index, actualIndex);
1708
+ }
1709
+ let identifier = state.vars[actualIndex];
1710
+ if (identifier == null) {
1711
+ identifier = getIdentifier(actualIndex);
1712
+ state.vars[actualIndex] = identifier;
1713
+ }
1714
+ return identifier;
1715
+ }
1716
+ function getCrossRefParam(id) {
1717
+ return "$R[" + id + "]";
1718
+ }
1719
+ /**
1720
+ * Converts the ID of a reference into a identifier string
1721
+ * that is used to refer to the object instance in the
1722
+ * generated script.
1723
+ */
1724
+ function getRefParam(ctx, id) {
1725
+ return ctx.mode === 1 ? getVanillaRefParam(ctx.state, id) : getCrossRefParam(id);
1726
+ }
1727
+ function markSerializerRef(ctx, id) {
1728
+ ctx.marked.add(id);
1729
+ }
1730
+ function isSerializerRefMarked(ctx, id) {
1731
+ return ctx.marked.has(id);
1732
+ }
1733
+ function pushObjectFlag(ctx, flag, id) {
1734
+ if (flag !== 0) {
1735
+ markSerializerRef(ctx.base, id);
1736
+ ctx.base.flags.push({
1737
+ type: flag,
1738
+ value: getRefParam(ctx, id)
1739
+ });
1740
+ }
1741
+ }
1742
+ function resolveFlags(ctx) {
1743
+ let result = "";
1744
+ for (let i = 0, current = ctx.flags, len = current.length; i < len; i++) {
1745
+ const flag = current[i];
1746
+ result += OBJECT_FLAG_CONSTRUCTOR[flag.type] + "(" + flag.value + "),";
1747
+ }
1748
+ return result;
1749
+ }
1750
+ function resolvePatches(ctx) {
1751
+ const assignments = resolveAssignments(ctx.assignments);
1752
+ const flags = resolveFlags(ctx);
1753
+ if (assignments) {
1754
+ if (flags) return assignments + flags;
1755
+ return assignments;
1756
+ }
1757
+ return flags;
1758
+ }
1759
+ /**
1760
+ * Generates the inlined assignment for the reference
1761
+ * This is different from the assignments array as this one
1762
+ * signifies creation rather than mutation
1763
+ */
1764
+ function createAssignment(ctx, source, value) {
1765
+ ctx.assignments.push({
1766
+ t: 0,
1767
+ s: source,
1768
+ k: void 0,
1769
+ v: value
1770
+ });
1771
+ }
1772
+ function createAddAssignment(ctx, ref, value) {
1773
+ ctx.base.assignments.push({
1774
+ t: 1,
1775
+ s: getRefParam(ctx, ref),
1776
+ k: void 0,
1777
+ v: value
1778
+ });
1779
+ }
1780
+ function createSetAssignment(ctx, ref, key, value) {
1781
+ ctx.base.assignments.push({
1782
+ t: 2,
1783
+ s: getRefParam(ctx, ref),
1784
+ k: key,
1785
+ v: value
1786
+ });
1787
+ }
1788
+ function createDeleteAssignment(ctx, ref, key) {
1789
+ ctx.base.assignments.push({
1790
+ t: 3,
1791
+ s: getRefParam(ctx, ref),
1792
+ k: key,
1793
+ v: void 0
1794
+ });
1795
+ }
1796
+ function createArrayAssign(ctx, ref, index, value) {
1797
+ createAssignment(ctx.base, getRefParam(ctx, ref) + "[" + index + "]", value);
1798
+ }
1799
+ function createObjectAssign(ctx, ref, key, value) {
1800
+ if (!isValidKey(key)) {
1801
+ ctx.base.assignments.push({
1802
+ t: 4,
1803
+ s: getRefParam(ctx, ref),
1804
+ k: value,
1805
+ v: void 0
1806
+ });
1807
+ return;
1808
+ }
1809
+ createAssignment(ctx.base, getRefParam(ctx, ref) + "." + key, value);
1810
+ }
1811
+ function createSequenceAssign(ctx, ref, index, value) {
1812
+ createAssignment(ctx.base, getRefParam(ctx, ref) + ".v[" + index + "]", value);
1813
+ }
1814
+ /**
1815
+ * Checks if the value is in the stack. Stack here is a reference
1816
+ * structure to know if a object is to be accessed in a TDZ.
1817
+ */
1818
+ function isIndexedValueInStack(ctx, node) {
1819
+ return node.t === 4 && ctx.stack.includes(node.i);
1820
+ }
1821
+ /**
1822
+ * Produces an assignment expression. `id` generates a reference
1823
+ * parameter (through `getRefParam`) and has the option to
1824
+ * return the reference parameter directly or assign a value to
1825
+ * it.
1826
+ */
1827
+ function assignIndexedValue(ctx, index, value) {
1828
+ if (ctx.mode === 1 && !isSerializerRefMarked(ctx.base, index)) return value;
1829
+ /**
1830
+ * In cross-reference, we have to assume that
1831
+ * every reference are going to be referenced
1832
+ * in the future, and so we need to store
1833
+ * all of it into the reference array.
1834
+ *
1835
+ * otherwise in vanilla, we only do this if it
1836
+ * is actually referenced
1837
+ */
1838
+ return getRefParam(ctx, index) + "=" + value;
1839
+ }
1840
+ function serializeReference(node) {
1841
+ return "__SEROVAL_REFS__.get(\"" + node.s + "\")";
1842
+ }
1843
+ function serializeArrayItem(ctx, id, item, index) {
1844
+ if (item) {
1845
+ if (isIndexedValueInStack(ctx.base, item)) {
1846
+ markSerializerRef(ctx.base, id);
1847
+ createArrayAssign(ctx, id, index, getRefParam(ctx, item.i));
1848
+ return "";
1849
+ }
1850
+ return serialize$1(ctx, item);
1851
+ }
1852
+ return "";
1853
+ }
1854
+ function serializeArray(ctx, node) {
1855
+ const id = node.i;
1856
+ const list = node.a;
1857
+ const len = list.length;
1858
+ if (len > 0) {
1859
+ ctx.base.stack.push(id);
1860
+ let values = serializeArrayItem(ctx, id, list[0], 0);
1861
+ let isHoley = values === "";
1862
+ for (let i = 1, item; i < len; i++) {
1863
+ item = serializeArrayItem(ctx, id, list[i], i);
1864
+ values += "," + item;
1865
+ isHoley = item === "";
1866
+ }
1867
+ ctx.base.stack.pop();
1868
+ pushObjectFlag(ctx, node.o, node.i);
1869
+ return "[" + values + (isHoley ? ",]" : "]");
1870
+ }
1871
+ return "[]";
1872
+ }
1873
+ function serializeProperty(ctx, source, key, val) {
1874
+ if (typeof key === "string") {
1875
+ const check = Number(key);
1876
+ const isIdentifier = check >= 0 && check.toString() === key || isValidIdentifier(key);
1877
+ if (isIndexedValueInStack(ctx.base, val)) {
1878
+ const refParam = getRefParam(ctx, val.i);
1879
+ markSerializerRef(ctx.base, source.i);
1880
+ if (isIdentifier && check !== check) createObjectAssign(ctx, source.i, key, refParam);
1881
+ else createArrayAssign(ctx, source.i, isIdentifier ? key : "\"" + key + "\"", refParam);
1882
+ return "";
1883
+ }
1884
+ if (isValidKey(key)) return (isIdentifier ? key : "\"" + key + "\"") + ":" + serialize$1(ctx, val);
1885
+ return "[\"" + key + "\"]:" + serialize$1(ctx, val);
1886
+ }
1887
+ return "[" + serialize$1(ctx, key) + "]:" + serialize$1(ctx, val);
1888
+ }
1889
+ function serializeProperties(ctx, source, record) {
1890
+ const keys = record.k;
1891
+ const len = keys.length;
1892
+ if (len > 0) {
1893
+ const values = record.v;
1894
+ ctx.base.stack.push(source.i);
1895
+ let result = serializeProperty(ctx, source, keys[0], values[0]);
1896
+ for (let i = 1, item = result; i < len; i++) {
1897
+ item = serializeProperty(ctx, source, keys[i], values[i]);
1898
+ result += (item && result && ",") + item;
1899
+ }
1900
+ ctx.base.stack.pop();
1901
+ return "{" + result + "}";
1902
+ }
1903
+ return "{}";
1904
+ }
1905
+ function serializeObject(ctx, node) {
1906
+ pushObjectFlag(ctx, node.o, node.i);
1907
+ return serializeProperties(ctx, node, node.p);
1908
+ }
1909
+ function serializeWithObjectAssign(ctx, source, value, serialized) {
1910
+ const fields = serializeProperties(ctx, source, value);
1911
+ if (fields !== "{}") return "Object.assign(" + serialized + "," + fields + ")";
1912
+ return serialized;
1913
+ }
1914
+ function serializeStringKeyAssignment(ctx, source, mainAssignments, key, value) {
1915
+ const base = ctx.base;
1916
+ const serialized = serialize$1(ctx, value);
1917
+ const check = Number(key);
1918
+ const isIdentifier = check >= 0 && check.toString() === key || isValidIdentifier(key);
1919
+ if (isIndexedValueInStack(base, value)) if (isIdentifier && check !== check) createObjectAssign(ctx, source.i, key, serialized);
1920
+ else createArrayAssign(ctx, source.i, isIdentifier ? key : "\"" + key + "\"", serialized);
1921
+ else {
1922
+ const parentAssignment = base.assignments;
1923
+ base.assignments = mainAssignments;
1924
+ if (isIdentifier && check !== check) createObjectAssign(ctx, source.i, key, serialized);
1925
+ else createArrayAssign(ctx, source.i, isIdentifier ? key : "\"" + key + "\"", serialized);
1926
+ base.assignments = parentAssignment;
1927
+ }
1928
+ }
1929
+ function serializeAssignment(ctx, source, mainAssignments, key, value) {
1930
+ if (typeof key === "string") serializeStringKeyAssignment(ctx, source, mainAssignments, key, value);
1931
+ else {
1932
+ const base = ctx.base;
1933
+ const parent = base.stack;
1934
+ base.stack = [];
1935
+ const serialized = serialize$1(ctx, value);
1936
+ base.stack = parent;
1937
+ const parentAssignment = base.assignments;
1938
+ base.assignments = mainAssignments;
1939
+ createArrayAssign(ctx, source.i, serialize$1(ctx, key), serialized);
1940
+ base.assignments = parentAssignment;
1941
+ }
1942
+ }
1943
+ function serializeAssignments(ctx, source, node) {
1944
+ const keys = node.k;
1945
+ const len = keys.length;
1946
+ if (len > 0) {
1947
+ const mainAssignments = [];
1948
+ const values = node.v;
1949
+ ctx.base.stack.push(source.i);
1950
+ for (let i = 0; i < len; i++) serializeAssignment(ctx, source, mainAssignments, keys[i], values[i]);
1951
+ ctx.base.stack.pop();
1952
+ return resolveAssignments(mainAssignments);
1953
+ }
1954
+ }
1955
+ function serializeDictionary(ctx, node, init) {
1956
+ if (node.p) {
1957
+ const base = ctx.base;
1958
+ if (base.features & 8) init = serializeWithObjectAssign(ctx, node, node.p, init);
1959
+ else {
1960
+ markSerializerRef(base, node.i);
1961
+ const assignments = serializeAssignments(ctx, node, node.p);
1962
+ if (assignments) return "(" + assignIndexedValue(ctx, node.i, init) + "," + assignments + getRefParam(ctx, node.i) + ")";
1963
+ }
1964
+ }
1965
+ return init;
1966
+ }
1967
+ function serializeNullConstructor(ctx, node) {
1968
+ pushObjectFlag(ctx, node.o, node.i);
1969
+ return serializeDictionary(ctx, node, NULL_CONSTRUCTOR);
1970
+ }
1971
+ function serializeDate(node) {
1972
+ return "new Date(\"" + node.s + "\")";
1973
+ }
1974
+ const TEMPORAL_CONSTRUCTOR = {
1975
+ [0]: "Temporal.Instant",
1976
+ [1]: "Temporal.Duration",
1977
+ [2]: "Temporal.PlainDate",
1978
+ [3]: "Temporal.PlainDateTime",
1979
+ [4]: "Temporal.PlainMonthDay",
1980
+ [5]: "Temporal.PlainTime",
1981
+ [6]: "Temporal.PlainYearMonth",
1982
+ [7]: "Temporal.ZonedDateTime"
1983
+ };
1984
+ function serializeTemporal(ctx, node) {
1985
+ if (ctx.base.features & 64) return TEMPORAL_CONSTRUCTOR[node.c] + ".from(\"" + node.s + "\")";
1986
+ throw new SerovalUnsupportedNodeError(node);
1987
+ }
1988
+ function serializeRegExp(ctx, node) {
1989
+ if (ctx.base.features & 32) return "/" + deserializeString(node.c) + "/" + node.m;
1990
+ throw new SerovalUnsupportedNodeError(node);
1991
+ }
1992
+ function serializeSetItem(ctx, id, item) {
1993
+ const base = ctx.base;
1994
+ if (isIndexedValueInStack(base, item)) {
1995
+ markSerializerRef(base, id);
1996
+ createAddAssignment(ctx, id, getRefParam(ctx, item.i));
1997
+ return "";
1998
+ }
1999
+ return serialize$1(ctx, item);
2000
+ }
2001
+ function serializeSet(ctx, node) {
2002
+ let serialized = SET_CONSTRUCTOR;
2003
+ const items = node.a;
2004
+ const size = items.length;
2005
+ const id = node.i;
2006
+ if (size > 0) {
2007
+ ctx.base.stack.push(id);
2008
+ let result = serializeSetItem(ctx, id, items[0]);
2009
+ for (let i = 1, item = result; i < size; i++) {
2010
+ item = serializeSetItem(ctx, id, items[i]);
2011
+ result += (item && result && ",") + item;
2012
+ }
2013
+ ctx.base.stack.pop();
2014
+ if (result) serialized += "([" + result + "])";
2015
+ }
2016
+ return serialized;
2017
+ }
2018
+ function serializeMapEntry(ctx, id, key, val, sentinel) {
2019
+ const base = ctx.base;
2020
+ if (isIndexedValueInStack(base, key)) {
2021
+ const keyRef = getRefParam(ctx, key.i);
2022
+ markSerializerRef(base, id);
2023
+ if (isIndexedValueInStack(base, val)) {
2024
+ createSetAssignment(ctx, id, keyRef, getRefParam(ctx, val.i));
2025
+ return "";
2026
+ }
2027
+ if (val.t !== 4 && val.i != null && isSerializerRefMarked(base, val.i)) {
2028
+ const serialized = "(" + serialize$1(ctx, val) + ",[" + sentinel + "," + sentinel + "])";
2029
+ createSetAssignment(ctx, id, keyRef, getRefParam(ctx, val.i));
2030
+ createDeleteAssignment(ctx, id, sentinel);
2031
+ return serialized;
2032
+ }
2033
+ const parent = base.stack;
2034
+ base.stack = [];
2035
+ createSetAssignment(ctx, id, keyRef, serialize$1(ctx, val));
2036
+ base.stack = parent;
2037
+ return "";
2038
+ }
2039
+ if (isIndexedValueInStack(base, val)) {
2040
+ const valueRef = getRefParam(ctx, val.i);
2041
+ markSerializerRef(base, id);
2042
+ if (key.t !== 4 && key.i != null && isSerializerRefMarked(base, key.i)) {
2043
+ const serialized = "(" + serialize$1(ctx, key) + ",[" + sentinel + "," + sentinel + "])";
2044
+ createSetAssignment(ctx, id, getRefParam(ctx, key.i), valueRef);
2045
+ createDeleteAssignment(ctx, id, sentinel);
2046
+ return serialized;
2047
+ }
2048
+ const parent = base.stack;
2049
+ base.stack = [];
2050
+ createSetAssignment(ctx, id, serialize$1(ctx, key), valueRef);
2051
+ base.stack = parent;
2052
+ return "";
2053
+ }
2054
+ return "[" + serialize$1(ctx, key) + "," + serialize$1(ctx, val) + "]";
2055
+ }
2056
+ function serializeMap(ctx, node) {
2057
+ let serialized = MAP_CONSTRUCTOR;
2058
+ const keys = node.e.k;
2059
+ const size = keys.length;
2060
+ const id = node.i;
2061
+ const sentinel = node.f;
2062
+ const sentinelId = getRefParam(ctx, sentinel.i);
2063
+ const base = ctx.base;
2064
+ if (size > 0) {
2065
+ const vals = node.e.v;
2066
+ base.stack.push(id);
2067
+ let result = serializeMapEntry(ctx, id, keys[0], vals[0], sentinelId);
2068
+ for (let i = 1, item = result; i < size; i++) {
2069
+ item = serializeMapEntry(ctx, id, keys[i], vals[i], sentinelId);
2070
+ result += (item && result && ",") + item;
2071
+ }
2072
+ base.stack.pop();
2073
+ if (result) serialized += "([" + result + "])";
2074
+ }
2075
+ if (sentinel.t === 26) {
2076
+ markSerializerRef(base, sentinel.i);
2077
+ serialized = "(" + serialize$1(ctx, sentinel) + "," + serialized + ")";
2078
+ }
2079
+ return serialized;
2080
+ }
2081
+ function serializeArrayBuffer(ctx, node) {
2082
+ return getConstructor(ctx, node.f) + "(\"" + node.s + "\")";
2083
+ }
2084
+ function serializeTypedArray(ctx, node) {
2085
+ return "new " + node.c + "(" + serialize$1(ctx, node.f) + "," + node.b + "," + node.l + ")";
2086
+ }
2087
+ function serializeDataView(ctx, node) {
2088
+ return "new DataView(" + serialize$1(ctx, node.f) + "," + node.b + "," + node.l + ")";
2089
+ }
2090
+ function serializeAggregateError(ctx, node) {
2091
+ const id = node.i;
2092
+ ctx.base.stack.push(id);
2093
+ const serialized = serializeDictionary(ctx, node, "new AggregateError([],\"" + node.m + "\")");
2094
+ ctx.base.stack.pop();
2095
+ return serialized;
2096
+ }
2097
+ function serializeError(ctx, node) {
2098
+ return serializeDictionary(ctx, node, "new " + ERROR_CONSTRUCTOR_STRING[node.s] + "(\"" + node.m + "\")");
2099
+ }
2100
+ function serializePromise(ctx, node) {
2101
+ let serialized;
2102
+ const fulfilled = node.f;
2103
+ const id = node.i;
2104
+ const promiseConstructor = node.s ? PROMISE_RESOLVE : PROMISE_REJECT;
2105
+ const base = ctx.base;
2106
+ if (isIndexedValueInStack(base, fulfilled)) {
2107
+ const ref = getRefParam(ctx, fulfilled.i);
2108
+ serialized = promiseConstructor + (node.s ? "().then(" + createFunction([], ref) + ")" : "().catch(" + createEffectfulFunction([], "throw " + ref) + ")");
2109
+ } else {
2110
+ base.stack.push(id);
2111
+ const result = serialize$1(ctx, fulfilled);
2112
+ base.stack.pop();
2113
+ serialized = promiseConstructor + "(" + result + ")";
2114
+ }
2115
+ return serialized;
2116
+ }
2117
+ function serializeBoxed(ctx, node) {
2118
+ return "Object(" + serialize$1(ctx, node.f) + ")";
2119
+ }
2120
+ function getConstructor(ctx, node) {
2121
+ const current = serialize$1(ctx, node);
2122
+ return node.t === 4 ? current : "(" + current + ")";
2123
+ }
2124
+ function serializePromiseConstructor(ctx, node) {
2125
+ if (ctx.mode === 1) throw new SerovalUnsupportedNodeError(node);
2126
+ return "(" + assignIndexedValue(ctx, node.s, getConstructor(ctx, node.f) + "()") + ").p";
2127
+ }
2128
+ function serializePromiseResolve(ctx, node) {
2129
+ if (ctx.mode === 1) throw new SerovalUnsupportedNodeError(node);
2130
+ return getConstructor(ctx, node.a[0]) + "(" + getRefParam(ctx, node.i) + "," + serialize$1(ctx, node.a[1]) + ")";
2131
+ }
2132
+ function serializePromiseReject(ctx, node) {
2133
+ if (ctx.mode === 1) throw new SerovalUnsupportedNodeError(node);
2134
+ return getConstructor(ctx, node.a[0]) + "(" + getRefParam(ctx, node.i) + "," + serialize$1(ctx, node.a[1]) + ")";
2135
+ }
2136
+ function serializePlugin(ctx, node) {
2137
+ const currentPlugins = ctx.base.plugins;
2138
+ if (currentPlugins) for (let i = 0, len = currentPlugins.length; i < len; i++) {
2139
+ const plugin = currentPlugins[i];
2140
+ if (plugin.tag === node.c) {
2141
+ if (ctx.child == null) ctx.child = new SerializePluginContext(ctx);
2142
+ return plugin.serialize(node.s, ctx.child, { id: node.i });
2143
+ }
2144
+ }
2145
+ throw new SerovalMissingPluginError(node.c);
2146
+ }
2147
+ function serializeIteratorFactory(ctx, node) {
2148
+ let result = "";
2149
+ let initialized = false;
2150
+ if (node.f.t !== 4) {
2151
+ markSerializerRef(ctx.base, node.f.i);
2152
+ result = "(" + serialize$1(ctx, node.f) + ",";
2153
+ initialized = true;
2154
+ }
2155
+ result += assignIndexedValue(ctx, node.i, "(" + SERIALIZED_ITERATOR_CONSTRUCTOR + ")(" + getRefParam(ctx, node.f.i) + ")");
2156
+ if (initialized) result += ")";
2157
+ return result;
2158
+ }
2159
+ function serializeIteratorFactoryInstance(ctx, node) {
2160
+ return getConstructor(ctx, node.a[0]) + "(" + serialize$1(ctx, node.a[1]) + ")";
2161
+ }
2162
+ function serializeAsyncIteratorFactory(ctx, node) {
2163
+ const promise = node.a[0];
2164
+ const symbol = node.a[1];
2165
+ const base = ctx.base;
2166
+ let result = "";
2167
+ if (promise.t !== 4) {
2168
+ markSerializerRef(base, promise.i);
2169
+ result += "(" + serialize$1(ctx, promise);
2170
+ }
2171
+ if (symbol.t !== 4) {
2172
+ markSerializerRef(base, symbol.i);
2173
+ result += (result ? "," : "(") + serialize$1(ctx, symbol);
2174
+ }
2175
+ if (result) result += ",";
2176
+ const iterator = assignIndexedValue(ctx, node.i, "(" + SERIALIZED_ASYNC_ITERATOR_CONSTRUCTOR + ")(" + getRefParam(ctx, symbol.i) + "," + getRefParam(ctx, promise.i) + ")");
2177
+ if (result) return result + iterator + ")";
2178
+ return iterator;
2179
+ }
2180
+ function serializeAsyncIteratorFactoryInstance(ctx, node) {
2181
+ return getConstructor(ctx, node.a[0]) + "(" + serialize$1(ctx, node.a[1]) + ")";
2182
+ }
2183
+ function serializeStreamConstructor(ctx, node) {
2184
+ const result = assignIndexedValue(ctx, node.i, getConstructor(ctx, node.f) + "()");
2185
+ const len = node.a.length;
2186
+ if (len) {
2187
+ let values = serialize$1(ctx, node.a[0]);
2188
+ for (let i = 1; i < len; i++) values += "," + serialize$1(ctx, node.a[i]);
2189
+ return "(" + result + "," + values + "," + getRefParam(ctx, node.i) + ")";
2190
+ }
2191
+ return result;
2192
+ }
2193
+ function serializeStreamNext(ctx, node) {
2194
+ return getRefParam(ctx, node.i) + ".next(" + serialize$1(ctx, node.f) + ")";
2195
+ }
2196
+ function serializeStreamThrow(ctx, node) {
2197
+ return getRefParam(ctx, node.i) + ".throw(" + serialize$1(ctx, node.f) + ")";
2198
+ }
2199
+ function serializeStreamReturn(ctx, node) {
2200
+ return getRefParam(ctx, node.i) + ".return(" + serialize$1(ctx, node.f) + ")";
2201
+ }
2202
+ function serializeSequenceItem(ctx, id, index, item) {
2203
+ const base = ctx.base;
2204
+ if (isIndexedValueInStack(base, item)) {
2205
+ markSerializerRef(base, id);
2206
+ createSequenceAssign(ctx, id, index, getRefParam(ctx, item.i));
2207
+ return "";
2208
+ }
2209
+ return serialize$1(ctx, item);
2210
+ }
2211
+ function serializeSequence(ctx, node) {
2212
+ const items = node.a;
2213
+ const size = items.length;
2214
+ const id = node.i;
2215
+ if (size > 0) {
2216
+ ctx.base.stack.push(id);
2217
+ let result = serializeSequenceItem(ctx, id, 0, items[0]);
2218
+ for (let i = 1, item = result; i < size; i++) {
2219
+ item = serializeSequenceItem(ctx, id, i, items[i]);
2220
+ result += (item && result && ",") + item;
2221
+ }
2222
+ ctx.base.stack.pop();
2223
+ if (result) return "{__SEROVAL_SEQUENCE__:!0,v:[" + result + "],t:" + node.s + ",d:" + node.l + "}";
2224
+ }
2225
+ return "{__SEROVAL_SEQUENCE__:!0,v:[],t:-1,d:0}";
2226
+ }
2227
+ function serializeAssignable(ctx, node) {
2228
+ switch (node.t) {
2229
+ case 17: return SYMBOL_STRING[node.s];
2230
+ case 18: return serializeReference(node);
2231
+ case 9: return serializeArray(ctx, node);
2232
+ case 10: return serializeObject(ctx, node);
2233
+ case 11: return serializeNullConstructor(ctx, node);
2234
+ case 5: return serializeDate(node);
2235
+ case 6: return serializeRegExp(ctx, node);
2236
+ case 7: return serializeSet(ctx, node);
2237
+ case 8: return serializeMap(ctx, node);
2238
+ case 19: return serializeArrayBuffer(ctx, node);
2239
+ case 16:
2240
+ case 15: return serializeTypedArray(ctx, node);
2241
+ case 20: return serializeDataView(ctx, node);
2242
+ case 14: return serializeAggregateError(ctx, node);
2243
+ case 13: return serializeError(ctx, node);
2244
+ case 12: return serializePromise(ctx, node);
2245
+ case 21: return serializeBoxed(ctx, node);
2246
+ case 22: return serializePromiseConstructor(ctx, node);
2247
+ case 25: return serializePlugin(ctx, node);
2248
+ case 26: return SPECIAL_REF_STRING[node.s];
2249
+ case 35: return serializeSequence(ctx, node);
2250
+ case 36: return serializeTemporal(ctx, node);
2251
+ default: throw new SerovalUnsupportedNodeError(node);
2252
+ }
2253
+ }
2254
+ function serialize$1(ctx, node) {
2255
+ switch (node.t) {
2256
+ case 2: return CONSTANT_STRING[node.s];
2257
+ case 0: return "" + node.s;
2258
+ case 1: return "\"" + node.s + "\"";
2259
+ case 3: return node.s + "n";
2260
+ case 4: return getRefParam(ctx, node.i);
2261
+ case 23: return serializePromiseResolve(ctx, node);
2262
+ case 24: return serializePromiseReject(ctx, node);
2263
+ case 27: return serializeIteratorFactory(ctx, node);
2264
+ case 28: return serializeIteratorFactoryInstance(ctx, node);
2265
+ case 29: return serializeAsyncIteratorFactory(ctx, node);
2266
+ case 30: return serializeAsyncIteratorFactoryInstance(ctx, node);
2267
+ case 31: return serializeStreamConstructor(ctx, node);
2268
+ case 32: return serializeStreamNext(ctx, node);
2269
+ case 33: return serializeStreamThrow(ctx, node);
2270
+ case 34: return serializeStreamReturn(ctx, node);
2271
+ default: return assignIndexedValue(ctx, node.i, serializeAssignable(ctx, node));
2272
+ }
2273
+ }
2274
+ function serializeTopVanilla(ctx, tree) {
2275
+ const result = serialize$1(ctx, tree);
2276
+ if (tree.i != null && ctx.state.vars.length) {
2277
+ const patches = resolvePatches(ctx.base);
2278
+ let body = result;
2279
+ if (patches) {
2280
+ const index = getRefParam(ctx, tree.i);
2281
+ body = result + "," + patches + index;
2282
+ if (!result.startsWith(index + "=")) body = index + "=" + body;
2283
+ body = "(" + body + ")";
2284
+ }
2285
+ return "(" + createFunction(ctx.state.vars, body) + ")()";
2286
+ }
2287
+ if (tree.t === 10) return "(" + result + ")";
2288
+ return result;
2289
+ }
2290
+ function serializeTopCross(ctx, tree) {
2291
+ const result = serialize$1(ctx, tree);
2292
+ const id = tree.i;
2293
+ if (id == null) return result;
2294
+ const patches = resolvePatches(ctx.base);
2295
+ const ref = getRefParam(ctx, id);
2296
+ const scopeId = ctx.state.scopeId;
2297
+ const params = scopeId == null ? "" : "$R";
2298
+ const body = patches ? "(" + result + "," + patches + ref + ")" : result;
2299
+ if (params === "") {
2300
+ if (tree.t === 10 && !patches) return "(" + body + ")";
2301
+ return body;
2302
+ }
2303
+ const args = scopeId == null ? "()" : "($R[\"" + serializeString(scopeId) + "\"])";
2304
+ return "(" + createFunction([params], body) + ")" + args;
2305
+ }
2306
+ //#endregion
2307
+ //#region src/core/context/sync-parser.ts
2308
+ function createSyncParserContext(mode, options) {
2309
+ return {
2310
+ type: 1,
2311
+ base: createBaseParserContext(mode, options),
2312
+ child: void 0
2313
+ };
2314
+ }
2315
+ var SyncParsePluginContext = class {
2316
+ constructor(_p, depth) {
2317
+ this._p = _p;
2318
+ this.depth = depth;
2319
+ }
2320
+ parse(current) {
2321
+ return parseSOS(this._p, this.depth, current);
2322
+ }
2323
+ };
2324
+ var StreamParsePluginContext = class {
2325
+ constructor(_p, depth) {
2326
+ this._p = _p;
2327
+ this.depth = depth;
2328
+ }
2329
+ parse(current) {
2330
+ return parseSOS(this._p, this.depth, current);
2331
+ }
2332
+ parseWithError(current) {
2333
+ return parseWithError(this._p, this.depth, current);
2334
+ }
2335
+ isAlive() {
2336
+ return this._p.state.alive;
2337
+ }
2338
+ pushPendingState() {
2339
+ pushPendingState(this._p);
2340
+ }
2341
+ popPendingState() {
2342
+ popPendingState(this._p);
2343
+ }
2344
+ onParse(node) {
2345
+ onParse(this._p, node);
2346
+ }
2347
+ onError(error) {
2348
+ onError(this._p, error);
2349
+ }
2350
+ addCleanup(callback) {
2351
+ this._p.state.cleanups.push(callback);
2352
+ }
2353
+ };
2354
+ function createStreamParserState(options) {
2355
+ return {
2356
+ alive: true,
2357
+ pending: 0,
2358
+ initial: true,
2359
+ buffer: [],
2360
+ onParse: options.onParse,
2361
+ onError: options.onError,
2362
+ onDone: options.onDone,
2363
+ cleanups: []
2364
+ };
2365
+ }
2366
+ function createStreamParserContext(options) {
2367
+ return {
2368
+ type: 2,
2369
+ base: createBaseParserContext(2, options),
2370
+ state: createStreamParserState(options)
2371
+ };
2372
+ }
2373
+ function parseItems(ctx, depth, current) {
2374
+ const nodes = [];
2375
+ for (let i = 0, len = current.length; i < len; i++) if (i in current) nodes[i] = parseSOS(ctx, depth, current[i]);
2376
+ else nodes[i] = 0;
2377
+ return nodes;
2378
+ }
2379
+ function parseArray(ctx, depth, id, current) {
2380
+ return createArrayNode(id, current, parseItems(ctx, depth, current));
2381
+ }
2382
+ function parseProperties(ctx, depth, properties) {
2383
+ const entries = Object.entries(properties);
2384
+ const keyNodes = [];
2385
+ const valueNodes = [];
2386
+ for (let i = 0, len = entries.length; i < len; i++) {
2387
+ keyNodes.push(serializeString(entries[i][0]));
2388
+ valueNodes.push(parseSOS(ctx, depth, entries[i][1]));
2389
+ }
2390
+ if (SYM_ITERATOR in properties) {
2391
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
2392
+ valueNodes.push(createIteratorFactoryInstanceNode(parseIteratorFactory(ctx.base), parseSOS(ctx, depth, createSequenceFromIterable(properties))));
2393
+ }
2394
+ if (SYM_ASYNC_ITERATOR in properties) {
2395
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
2396
+ valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), parseSOS(ctx, depth, ctx.type === 1 ? createStream() : createStreamFromAsyncIterable(properties))));
2397
+ }
2398
+ if (SYM_TO_STRING_TAG in properties) {
2399
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
2400
+ valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
2401
+ }
2402
+ if (SYM_IS_CONCAT_SPREADABLE in properties) {
2403
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
2404
+ valueNodes.push(properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE);
2405
+ }
2406
+ return {
2407
+ k: keyNodes,
2408
+ v: valueNodes
2409
+ };
2410
+ }
2411
+ function parsePlainObject(ctx, depth, id, current, empty) {
2412
+ return createObjectNode(id, current, empty, parseProperties(ctx, depth, current));
2413
+ }
2414
+ function parseBoxed(ctx, depth, id, current) {
2415
+ return createBoxedNode(id, parseSOS(ctx, depth, current.valueOf()));
2416
+ }
2417
+ function parseTypedArray(ctx, depth, id, current) {
2418
+ return createTypedArrayNode(id, current, parseSOS(ctx, depth, current.buffer));
2419
+ }
2420
+ function parseBigIntTypedArray(ctx, depth, id, current) {
2421
+ return createBigIntTypedArrayNode(id, current, parseSOS(ctx, depth, current.buffer));
2422
+ }
2423
+ function parseDataView(ctx, depth, id, current) {
2424
+ return createDataViewNode(id, current, parseSOS(ctx, depth, current.buffer));
2425
+ }
2426
+ function parseError(ctx, depth, id, current) {
2427
+ const options = getErrorOptions(current, ctx.base.features);
2428
+ return createErrorNode(id, current, options ? parseProperties(ctx, depth, options) : void 0);
2429
+ }
2430
+ function parseAggregateError(ctx, depth, id, current) {
2431
+ const options = getErrorOptions(current, ctx.base.features);
2432
+ return createAggregateErrorNode(id, current, options ? parseProperties(ctx, depth, options) : void 0);
2433
+ }
2434
+ function parseMap(ctx, depth, id, current) {
2435
+ const keyNodes = [];
2436
+ const valueNodes = [];
2437
+ for (const [key, value] of current.entries()) {
2438
+ keyNodes.push(parseSOS(ctx, depth, key));
2439
+ valueNodes.push(parseSOS(ctx, depth, value));
2440
+ }
2441
+ return createMapNode(ctx.base, id, keyNodes, valueNodes);
2442
+ }
2443
+ function parseSet(ctx, depth, id, current) {
2444
+ const items = [];
2445
+ for (const item of current.keys()) items.push(parseSOS(ctx, depth, item));
2446
+ return createSetNode(id, items);
2447
+ }
2448
+ function parseStream(ctx, depth, id, current) {
2449
+ const result = createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), []);
2450
+ if (ctx.type === 1) return result;
2451
+ pushPendingState(ctx);
2452
+ current.on({
2453
+ next: (value) => {
2454
+ if (ctx.state.alive) {
2455
+ const parsed = parseWithError(ctx, depth, value);
2456
+ if (parsed) onParse(ctx, createStreamNextNode(id, parsed));
2457
+ }
2458
+ },
2459
+ throw: (value) => {
2460
+ if (ctx.state.alive) {
2461
+ const parsed = parseWithError(ctx, depth, value);
2462
+ if (parsed) onParse(ctx, createStreamThrowNode(id, parsed));
2463
+ }
2464
+ popPendingState(ctx);
2465
+ },
2466
+ return: (value) => {
2467
+ if (ctx.state.alive) {
2468
+ const parsed = parseWithError(ctx, depth, value);
2469
+ if (parsed) onParse(ctx, createStreamReturnNode(id, parsed));
2470
+ }
2471
+ popPendingState(ctx);
2472
+ }
2473
+ });
2474
+ return result;
2475
+ }
2476
+ function handlePromiseSuccess(id, depth, data) {
2477
+ if (this.state.alive) {
2478
+ const parsed = parseWithError(this, depth, data);
2479
+ 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));
2480
+ popPendingState(this);
2481
+ }
2482
+ }
2483
+ function handlePromiseFailure(id, depth, data) {
2484
+ if (this.state.alive) {
2485
+ const parsed = parseWithError(this, depth, data);
2486
+ 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));
2487
+ }
2488
+ popPendingState(this);
2489
+ }
2490
+ function parsePromise(ctx, depth, id, current) {
2491
+ const resolver = createIndexForValue(ctx.base, {});
2492
+ if (ctx.type === 2) {
2493
+ pushPendingState(ctx);
2494
+ current.then(handlePromiseSuccess.bind(ctx, resolver, depth), handlePromiseFailure.bind(ctx, resolver, depth));
2495
+ }
2496
+ return createPromiseConstructorNode(ctx.base, id, resolver);
2497
+ }
2498
+ function parsePluginSync(ctx, depth, id, current, currentPlugins) {
2499
+ for (let i = 0, len = currentPlugins.length; i < len; i++) {
2500
+ const plugin = currentPlugins[i];
2501
+ if (plugin.parse.sync && plugin.test(current)) return createPluginNode(id, plugin.tag, plugin.parse.sync(current, new SyncParsePluginContext(ctx, depth), { id }));
2502
+ }
2503
+ }
2504
+ function parsePluginStream(ctx, depth, id, current, currentPlugins) {
2505
+ for (let i = 0, len = currentPlugins.length; i < len; i++) {
2506
+ const plugin = currentPlugins[i];
2507
+ if (plugin.parse.stream && plugin.test(current)) return createPluginNode(id, plugin.tag, plugin.parse.stream(current, new StreamParsePluginContext(ctx, depth), { id }));
2508
+ }
2509
+ }
2510
+ function parsePlugin(ctx, depth, id, current) {
2511
+ const currentPlugins = ctx.base.plugins;
2512
+ if (currentPlugins) return ctx.type === 1 ? parsePluginSync(ctx, depth, id, current, currentPlugins) : parsePluginStream(ctx, depth, id, current, currentPlugins);
2513
+ }
2514
+ function parseSequence(ctx, depth, id, current) {
2515
+ const nodes = [];
2516
+ for (let i = 0, len = current.v.length; i < len; i++) nodes[i] = parseSOS(ctx, depth, current.v[i]);
2517
+ return createSequenceNode(id, nodes, current.t, current.d);
2518
+ }
2519
+ function parseObjectPhase2(ctx, depth, id, current, currentClass) {
2520
+ switch (currentClass) {
2521
+ case Object: return parsePlainObject(ctx, depth, id, current, false);
2522
+ case void 0: return parsePlainObject(ctx, depth, id, current, true);
2523
+ case Date: return createDateNode(id, current);
2524
+ case Error:
2525
+ case EvalError:
2526
+ case RangeError:
2527
+ case ReferenceError:
2528
+ case SyntaxError:
2529
+ case TypeError:
2530
+ case URIError: return parseError(ctx, depth, id, current);
2531
+ case Number:
2532
+ case Boolean:
2533
+ case String:
2534
+ case BigInt: return parseBoxed(ctx, depth, id, current);
2535
+ case ArrayBuffer: return createArrayBufferNode(ctx.base, id, current);
2536
+ case Int8Array:
2537
+ case Int16Array:
2538
+ case Int32Array:
2539
+ case Uint8Array:
2540
+ case Uint16Array:
2541
+ case Uint32Array:
2542
+ case Uint8ClampedArray:
2543
+ case Float32Array:
2544
+ case Float64Array: return parseTypedArray(ctx, depth, id, current);
2545
+ case DataView: return parseDataView(ctx, depth, id, current);
2546
+ case Map: return parseMap(ctx, depth, id, current);
2547
+ case Set: return parseSet(ctx, depth, id, current);
2548
+ default: break;
2549
+ }
2550
+ if (currentClass === Promise || current instanceof Promise) return parsePromise(ctx, depth, id, current);
2551
+ const currentFeatures = ctx.base.features;
2552
+ if (currentFeatures & 32 && currentClass === RegExp) return createRegExpNode(id, current);
2553
+ if (currentFeatures & 16) switch (currentClass) {
2554
+ case BigInt64Array:
2555
+ case BigUint64Array: return parseBigIntTypedArray(ctx, depth, id, current);
2556
+ default: break;
2557
+ }
2558
+ if (currentFeatures & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) return parseAggregateError(ctx, depth, id, current);
2559
+ if (currentFeatures & 64 && typeof Temporal !== "undefined") switch (currentClass) {
2560
+ case Temporal.Instant: return createTemporalNode(id, 0, current);
2561
+ case Temporal.Duration: return createTemporalNode(id, 1, current);
2562
+ case Temporal.PlainDate: return createTemporalNode(id, 2, current);
2563
+ case Temporal.PlainDateTime: return createTemporalNode(id, 3, current);
2564
+ case Temporal.PlainMonthDay: return createTemporalNode(id, 4, current);
2565
+ case Temporal.PlainTime: return createTemporalNode(id, 5, current);
2566
+ case Temporal.PlainYearMonth: return createTemporalNode(id, 6, current);
2567
+ case Temporal.ZonedDateTime: return createTemporalNode(id, 7, current);
2568
+ default: break;
2569
+ }
2570
+ if (current instanceof Error) return parseError(ctx, depth, id, current);
2571
+ if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) return parsePlainObject(ctx, depth, id, current, !!currentClass);
2572
+ throw new SerovalUnsupportedTypeError(current);
2573
+ }
2574
+ function parseObject(ctx, depth, id, current) {
2575
+ if (Array.isArray(current)) return parseArray(ctx, depth, id, current);
2576
+ if (isStream(current)) return parseStream(ctx, depth, id, current);
2577
+ if (isSequence(current)) return parseSequence(ctx, depth, id, current);
2578
+ let currentClass = current.constructor;
2579
+ if (currentClass !== void 0 && typeof currentClass !== "function") {
2580
+ const proto = Object.getPrototypeOf(current);
2581
+ currentClass = proto === null ? void 0 : proto.constructor;
2582
+ }
2583
+ if (currentClass === OpaqueReference) return parseSOS(ctx, depth, current.replacement);
2584
+ const parsed = parsePlugin(ctx, depth, id, current);
2585
+ if (parsed) return parsed;
2586
+ return parseObjectPhase2(ctx, depth, id, current, currentClass);
2587
+ }
2588
+ function parseFunction(ctx, depth, current) {
2589
+ const ref = getReferenceNode(ctx.base, current);
2590
+ if (ref.type !== 0) return ref.value;
2591
+ const plugin = parsePlugin(ctx, depth, ref.value, current);
2592
+ if (plugin) return plugin;
2593
+ throw new SerovalUnsupportedTypeError(current);
2594
+ }
2595
+ function parseSOS(ctx, depth, current) {
2596
+ if (depth >= ctx.base.depthLimit) throw new SerovalDepthLimitError(ctx.base.depthLimit);
2597
+ switch (typeof current) {
2598
+ case "boolean": return current ? TRUE_NODE : FALSE_NODE;
2599
+ case "undefined": return UNDEFINED_NODE;
2600
+ case "string": return createStringNode(current);
2601
+ case "number": return createNumberNode(current);
2602
+ case "bigint": return createBigIntNode(current);
2603
+ case "object":
2604
+ if (current) {
2605
+ const ref = getReferenceNode(ctx.base, current);
2606
+ return ref.type === 0 ? parseObject(ctx, depth + 1, ref.value, current) : ref.value;
2607
+ }
2608
+ return NULL_NODE;
2609
+ case "symbol": return parseWellKnownSymbol(ctx.base, current);
2610
+ case "function": return parseFunction(ctx, depth, current);
2611
+ default: throw new SerovalUnsupportedTypeError(current);
2612
+ }
2613
+ }
2614
+ function parseTop(ctx, current) {
2615
+ try {
2616
+ return parseSOS(ctx, 0, current);
2617
+ } catch (error) {
2618
+ throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
2619
+ }
2620
+ }
2621
+ function onParse(ctx, node) {
2622
+ if (ctx.state.initial) ctx.state.buffer.push(node);
2623
+ else onParseInternal(ctx, node, false);
2624
+ }
2625
+ function onError(ctx, error) {
2626
+ if (ctx.state.onError) ctx.state.onError(error);
2627
+ else throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
2628
+ }
2629
+ function onDone(ctx) {
2630
+ if (ctx.state.onDone) ctx.state.onDone();
2631
+ for (let i = 0, len = ctx.state.cleanups.length; i < len; i++) ctx.state.cleanups[i]();
2632
+ }
2633
+ function onParseInternal(ctx, node, initial) {
2634
+ try {
2635
+ ctx.state.onParse(node, initial);
2636
+ } catch (error) {
2637
+ onError(ctx, error);
2638
+ }
2639
+ }
2640
+ function pushPendingState(ctx) {
2641
+ ctx.state.pending++;
2642
+ }
2643
+ function popPendingState(ctx) {
2644
+ if (--ctx.state.pending <= 0) onDone(ctx);
2645
+ }
2646
+ function parseWithError(ctx, depth, current) {
2647
+ try {
2648
+ return parseSOS(ctx, depth, current);
2649
+ } catch (err) {
2650
+ onError(ctx, err);
2651
+ return;
2652
+ }
2653
+ }
2654
+ function startStreamParse(ctx, current) {
2655
+ const parsed = parseWithError(ctx, 0, current);
2656
+ if (parsed) {
2657
+ onParseInternal(ctx, parsed, true);
2658
+ ctx.state.initial = false;
2659
+ flushStreamParse(ctx, ctx.state);
2660
+ if (ctx.state.pending <= 0) destroyStreamParse(ctx);
2661
+ }
2662
+ }
2663
+ function flushStreamParse(ctx, state) {
2664
+ for (let i = 0, len = state.buffer.length; i < len; i++) onParseInternal(ctx, state.buffer[i], false);
2665
+ }
2666
+ function destroyStreamParse(ctx) {
2667
+ if (ctx.state.alive) {
2668
+ onDone(ctx);
2669
+ ctx.state.alive = false;
2670
+ }
2671
+ }
2672
+ //#endregion
2673
+ //#region src/core/cross/index.ts
2674
+ function crossSerialize(source, options = {}) {
2675
+ const plugins = resolvePlugins(options.plugins);
2676
+ const ctx = createSyncParserContext(2, {
2677
+ plugins,
2678
+ disabledFeatures: options.disabledFeatures,
2679
+ refs: options.refs
2680
+ });
2681
+ const tree = parseTop(ctx, source);
2682
+ return serializeTopCross(createCrossSerializerContext({
2683
+ plugins,
2684
+ features: ctx.base.features,
2685
+ scopeId: options.scopeId,
2686
+ markedRefs: ctx.base.marked
2687
+ }), tree);
2688
+ }
2689
+ async function crossSerializeAsync(source, options = {}) {
2690
+ const plugins = resolvePlugins(options.plugins);
2691
+ const ctx = createAsyncParserContext(2, {
2692
+ plugins,
2693
+ disabledFeatures: options.disabledFeatures,
2694
+ refs: options.refs
2695
+ });
2696
+ const tree = await parseTopAsync(ctx, source);
2697
+ return serializeTopCross(createCrossSerializerContext({
2698
+ plugins,
2699
+ features: ctx.base.features,
2700
+ scopeId: options.scopeId,
2701
+ markedRefs: ctx.base.marked
2702
+ }), tree);
2703
+ }
2704
+ function toCrossJSON(source, options = {}) {
2705
+ return parseTop(createSyncParserContext(2, {
2706
+ plugins: resolvePlugins(options.plugins),
2707
+ disabledFeatures: options.disabledFeatures,
2708
+ refs: options.refs
2709
+ }), source);
2710
+ }
2711
+ async function toCrossJSONAsync(source, options = {}) {
2712
+ return await parseTopAsync(createAsyncParserContext(2, {
2713
+ plugins: resolvePlugins(options.plugins),
2714
+ disabledFeatures: options.disabledFeatures,
2715
+ refs: options.refs
2716
+ }), source);
2717
+ }
2718
+ function crossSerializeStream(source, options) {
2719
+ const plugins = resolvePlugins(options.plugins);
2720
+ const ctx = createStreamParserContext({
2721
+ plugins,
2722
+ refs: options.refs,
2723
+ disabledFeatures: options.disabledFeatures,
2724
+ onParse(node, initial) {
2725
+ const serial = createCrossSerializerContext({
2726
+ plugins,
2727
+ features: ctx.base.features,
2728
+ scopeId: options.scopeId,
2729
+ markedRefs: ctx.base.marked
2730
+ });
2731
+ let serialized;
2732
+ try {
2733
+ serialized = serializeTopCross(serial, node);
2734
+ } catch (err) {
2735
+ if (options.onError) options.onError(err);
2736
+ return;
2737
+ }
2738
+ options.onSerialize(serialized, initial);
2739
+ },
2740
+ onError: options.onError,
2741
+ onDone: options.onDone
2742
+ });
2743
+ startStreamParse(ctx, source);
2744
+ return destroyStreamParse.bind(null, ctx);
2745
+ }
2746
+ function toCrossJSONStream(source, options) {
2747
+ const ctx = createStreamParserContext({
2748
+ plugins: resolvePlugins(options.plugins),
2749
+ refs: options.refs,
2750
+ disabledFeatures: options.disabledFeatures,
2751
+ depthLimit: options.depthLimit,
2752
+ onParse: options.onParse,
2753
+ onError: options.onError,
2754
+ onDone: options.onDone
2755
+ });
2756
+ startStreamParse(ctx, source);
2757
+ return destroyStreamParse.bind(null, ctx);
2758
+ }
2759
+ function fromCrossJSON(source, options) {
2760
+ return deserializeTop(createCrossDeserializerContext({
2761
+ plugins: resolvePlugins(options.plugins),
2762
+ refs: options.refs,
2763
+ features: options.features,
2764
+ disabledFeatures: options.disabledFeatures,
2765
+ depthLimit: options.depthLimit
2766
+ }), source);
2767
+ }
2768
+ //#endregion
2769
+ //#region src/core/Serializer.ts
2770
+ var Serializer = class {
2771
+ constructor(options) {
2772
+ this.options = options;
2773
+ this.alive = true;
2774
+ this.flushed = false;
2775
+ this.done = false;
2776
+ this.pending = 0;
2777
+ this.cleanups = [];
2778
+ this.refs = /* @__PURE__ */ new Map();
2779
+ this.keys = /* @__PURE__ */ new Set();
2780
+ this.ids = 0;
2781
+ this.plugins = resolvePlugins(options.plugins);
2782
+ }
2783
+ write(key, value) {
2784
+ if (this.alive && !this.flushed) {
2785
+ this.pending++;
2786
+ this.keys.add(key);
2787
+ this.cleanups.push(crossSerializeStream(value, {
2788
+ plugins: this.plugins,
2789
+ scopeId: this.options.scopeId,
2790
+ refs: this.refs,
2791
+ disabledFeatures: this.options.disabledFeatures,
2792
+ onError: this.options.onError,
2793
+ onSerialize: (data, initial) => {
2794
+ if (this.alive) this.options.onData(initial ? this.options.globalIdentifier + "[\"" + serializeString(key) + "\"]=" + data : data);
2795
+ },
2796
+ onDone: () => {
2797
+ if (this.alive) {
2798
+ this.pending--;
2799
+ if (this.pending <= 0 && this.flushed && !this.done && this.options.onDone) {
2800
+ this.options.onDone();
2801
+ this.done = true;
2802
+ }
2803
+ }
2804
+ }
2805
+ }));
2806
+ }
2807
+ }
2808
+ getNextID() {
2809
+ while (this.keys.has("" + this.ids)) this.ids++;
2810
+ return "" + this.ids;
2811
+ }
2812
+ push(value) {
2813
+ const newID = this.getNextID();
2814
+ this.write(newID, value);
2815
+ return newID;
2816
+ }
2817
+ flush() {
2818
+ if (this.alive) {
2819
+ this.flushed = true;
2820
+ if (this.pending <= 0 && !this.done && this.options.onDone) {
2821
+ this.options.onDone();
2822
+ this.done = true;
2823
+ }
2824
+ }
2825
+ }
2826
+ close() {
2827
+ if (this.alive) {
2828
+ for (let i = 0, len = this.cleanups.length; i < len; i++) this.cleanups[i]();
2829
+ if (!this.done && this.options.onDone) {
2830
+ this.options.onDone();
2831
+ this.done = true;
2832
+ }
2833
+ this.alive = false;
2834
+ }
2835
+ }
2836
+ };
2837
+ //#endregion
2838
+ //#region src/core/tree/index.ts
2839
+ function serialize(source, options = {}) {
2840
+ const plugins = resolvePlugins(options.plugins);
2841
+ const ctx = createSyncParserContext(1, {
2842
+ plugins,
2843
+ disabledFeatures: options.disabledFeatures
2844
+ });
2845
+ const tree = parseTop(ctx, source);
2846
+ return serializeTopVanilla(createVanillaSerializerContext({
2847
+ plugins,
2848
+ features: ctx.base.features,
2849
+ markedRefs: ctx.base.marked
2850
+ }), tree);
2851
+ }
2852
+ async function serializeAsync(source, options = {}) {
2853
+ const plugins = resolvePlugins(options.plugins);
2854
+ const ctx = createAsyncParserContext(1, {
2855
+ plugins,
2856
+ disabledFeatures: options.disabledFeatures
2857
+ });
2858
+ const tree = await parseTopAsync(ctx, source);
2859
+ return serializeTopVanilla(createVanillaSerializerContext({
2860
+ plugins,
2861
+ features: ctx.base.features,
2862
+ markedRefs: ctx.base.marked
2863
+ }), tree);
2864
+ }
2865
+ function deserialize(source) {
2866
+ return (0, eval)(source);
2867
+ }
2868
+ function toJSON(source, options = {}) {
2869
+ const ctx = createSyncParserContext(1, {
2870
+ plugins: resolvePlugins(options.plugins),
2871
+ disabledFeatures: options.disabledFeatures
2872
+ });
2873
+ return {
2874
+ t: parseTop(ctx, source),
2875
+ f: ctx.base.features,
2876
+ m: Array.from(ctx.base.marked)
2877
+ };
2878
+ }
2879
+ async function toJSONAsync(source, options = {}) {
2880
+ const ctx = createAsyncParserContext(1, {
2881
+ plugins: resolvePlugins(options.plugins),
2882
+ disabledFeatures: options.disabledFeatures
2883
+ });
2884
+ return {
2885
+ t: await parseTopAsync(ctx, source),
2886
+ f: ctx.base.features,
2887
+ m: Array.from(ctx.base.marked)
2888
+ };
2889
+ }
2890
+ function compileJSON(source, options = {}) {
2891
+ return serializeTopVanilla(createVanillaSerializerContext({
2892
+ plugins: resolvePlugins(options.plugins),
2893
+ features: source.f,
2894
+ markedRefs: source.m
2895
+ }), source.t);
2896
+ }
2897
+ function fromJSON(source, options = {}) {
2898
+ var _source$f;
2899
+ const plugins = resolvePlugins(options.plugins);
2900
+ const disabledFeatures = options.disabledFeatures || 0;
2901
+ const sourceFeatures = (_source$f = source.f) !== null && _source$f !== void 0 ? _source$f : 127;
2902
+ return deserializeTop(createVanillaDeserializerContext({
2903
+ plugins,
2904
+ markedRefs: source.m,
2905
+ features: sourceFeatures & ~disabledFeatures,
2906
+ disabledFeatures
2907
+ }), source.t);
2908
+ }
2909
+ //#endregion
2910
+ export { Feature, OpaqueReference, Serializer, SerovalConflictedNodeIdError, SerovalDepthLimitError, SerovalDeserializationError, SerovalError, SerovalMalformedNodeError, SerovalMissingInstanceError, SerovalMissingPluginError, SerovalMissingReferenceError, SerovalMissingReferenceForIdError, SerovalMode, SerovalParserError, SerovalSerializationError, SerovalUnknownTypedArrayError, SerovalUnsupportedNodeError, SerovalUnsupportedTypeError, compileJSON, createPlugin, createReference, createStream, crossSerialize, crossSerializeAsync, crossSerializeStream, deserialize, fromCrossJSON, fromJSON, getCrossReferenceHeader, resolvePlugins, serialize, serializeAsync, toCrossJSON, toCrossJSONAsync, toCrossJSONStream, toJSON, toJSONAsync };