seroval 1.5.5 → 1.6.0

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 (111) hide show
  1. package/dist/index.d.ts +761 -0
  2. package/dist/index.js +2928 -0
  3. package/package.json +14 -23
  4. package/dist/cjs/development/index.cjs +0 -4230
  5. package/dist/cjs/development/index.cjs.map +0 -7
  6. package/dist/cjs/production/index.cjs +0 -3
  7. package/dist/esm/development/index.mjs +0 -4207
  8. package/dist/esm/development/index.mjs.map +0 -7
  9. package/dist/esm/production/index.mjs +0 -3
  10. package/dist/types/core/Serializer.d.ts +0 -28
  11. package/dist/types/core/Serializer.d.ts.map +0 -1
  12. package/dist/types/core/base-primitives.d.ts +0 -28
  13. package/dist/types/core/base-primitives.d.ts.map +0 -1
  14. package/dist/types/core/compat.d.ts +0 -15
  15. package/dist/types/core/compat.d.ts.map +0 -1
  16. package/dist/types/core/constants.d.ts +0 -105
  17. package/dist/types/core/constants.d.ts.map +0 -1
  18. package/dist/types/core/constructors.d.ts +0 -50
  19. package/dist/types/core/constructors.d.ts.map +0 -1
  20. package/dist/types/core/context/async-parser.d.ts +0 -20
  21. package/dist/types/core/context/async-parser.d.ts.map +0 -1
  22. package/dist/types/core/context/deserializer.d.ts +0 -52
  23. package/dist/types/core/context/deserializer.d.ts.map +0 -1
  24. package/dist/types/core/context/parser.d.ts +0 -62
  25. package/dist/types/core/context/parser.d.ts.map +0 -1
  26. package/dist/types/core/context/serializer.d.ts +0 -103
  27. package/dist/types/core/context/serializer.d.ts.map +0 -1
  28. package/dist/types/core/context/sync-parser.d.ts +0 -61
  29. package/dist/types/core/context/sync-parser.d.ts.map +0 -1
  30. package/dist/types/core/cross/index.d.ts +0 -24
  31. package/dist/types/core/cross/index.d.ts.map +0 -1
  32. package/dist/types/core/errors.d.ts +0 -47
  33. package/dist/types/core/errors.d.ts.map +0 -1
  34. package/dist/types/core/function-string.d.ts +0 -3
  35. package/dist/types/core/function-string.d.ts.map +0 -1
  36. package/dist/types/core/keys.d.ts +0 -4
  37. package/dist/types/core/keys.d.ts.map +0 -1
  38. package/dist/types/core/literals.d.ts +0 -10
  39. package/dist/types/core/literals.d.ts.map +0 -1
  40. package/dist/types/core/node.d.ts +0 -8
  41. package/dist/types/core/node.d.ts.map +0 -1
  42. package/dist/types/core/opaque-reference.d.ts +0 -9
  43. package/dist/types/core/opaque-reference.d.ts.map +0 -1
  44. package/dist/types/core/plugin.d.ts +0 -52
  45. package/dist/types/core/plugin.d.ts.map +0 -1
  46. package/dist/types/core/reference.d.ts +0 -6
  47. package/dist/types/core/reference.d.ts.map +0 -1
  48. package/dist/types/core/sequence.d.ts +0 -11
  49. package/dist/types/core/sequence.d.ts.map +0 -1
  50. package/dist/types/core/special-reference.d.ts +0 -16
  51. package/dist/types/core/special-reference.d.ts.map +0 -1
  52. package/dist/types/core/stream.d.ts +0 -17
  53. package/dist/types/core/stream.d.ts.map +0 -1
  54. package/dist/types/core/string.d.ts +0 -4
  55. package/dist/types/core/string.d.ts.map +0 -1
  56. package/dist/types/core/symbols.d.ts +0 -14
  57. package/dist/types/core/symbols.d.ts.map +0 -1
  58. package/dist/types/core/tree/index.d.ts +0 -21
  59. package/dist/types/core/tree/index.d.ts.map +0 -1
  60. package/dist/types/core/types.d.ts +0 -233
  61. package/dist/types/core/types.d.ts.map +0 -1
  62. package/dist/types/core/utils/error.d.ts +0 -6
  63. package/dist/types/core/utils/error.d.ts.map +0 -1
  64. package/dist/types/core/utils/get-identifier.d.ts +0 -2
  65. package/dist/types/core/utils/get-identifier.d.ts.map +0 -1
  66. package/dist/types/core/utils/get-object-flag.d.ts +0 -3
  67. package/dist/types/core/utils/get-object-flag.d.ts.map +0 -1
  68. package/dist/types/core/utils/is-valid-identifier.d.ts +0 -2
  69. package/dist/types/core/utils/is-valid-identifier.d.ts.map +0 -1
  70. package/dist/types/core/utils/promise-to-result.d.ts +0 -2
  71. package/dist/types/core/utils/promise-to-result.d.ts.map +0 -1
  72. package/dist/types/core/utils/typed-array.d.ts +0 -6
  73. package/dist/types/core/utils/typed-array.d.ts.map +0 -1
  74. package/dist/types/core/utils/valid-properties.d.ts +0 -3
  75. package/dist/types/core/utils/valid-properties.d.ts.map +0 -1
  76. package/dist/types/index.d.ts +0 -18
  77. package/dist/types/index.d.ts.map +0 -1
  78. package/src/core/Serializer.ts +0 -119
  79. package/src/core/base-primitives.ts +0 -537
  80. package/src/core/compat.ts +0 -23
  81. package/src/core/constants.ts +0 -202
  82. package/src/core/constructors.ts +0 -265
  83. package/src/core/context/async-parser.ts +0 -663
  84. package/src/core/context/deserializer.ts +0 -832
  85. package/src/core/context/parser.ts +0 -335
  86. package/src/core/context/serializer.ts +0 -1524
  87. package/src/core/context/sync-parser.ts +0 -943
  88. package/src/core/cross/index.ts +0 -190
  89. package/src/core/errors.ts +0 -196
  90. package/src/core/function-string.ts +0 -31
  91. package/src/core/keys.ts +0 -17
  92. package/src/core/literals.ts +0 -43
  93. package/src/core/node.ts +0 -40
  94. package/src/core/opaque-reference.ts +0 -9
  95. package/src/core/plugin.ts +0 -105
  96. package/src/core/reference.ts +0 -66
  97. package/src/core/sequence.ts +0 -59
  98. package/src/core/special-reference.ts +0 -42
  99. package/src/core/stream.ts +0 -71
  100. package/src/core/string.ts +0 -86
  101. package/src/core/symbols.ts +0 -20
  102. package/src/core/tree/index.ts +0 -134
  103. package/src/core/types.ts +0 -377
  104. package/src/core/utils/error.ts +0 -73
  105. package/src/core/utils/get-identifier.ts +0 -18
  106. package/src/core/utils/get-object-flag.ts +0 -14
  107. package/src/core/utils/is-valid-identifier.ts +0 -12
  108. package/src/core/utils/promise-to-result.ts +0 -9
  109. package/src/core/utils/typed-array.ts +0 -56
  110. package/src/core/utils/valid-properties.ts +0 -34
  111. package/src/index.ts +0 -36
@@ -1,4230 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var src_exports = {};
22
- __export(src_exports, {
23
- Feature: () => Feature,
24
- OpaqueReference: () => OpaqueReference,
25
- Serializer: () => Serializer,
26
- SerovalConflictedNodeIdError: () => SerovalConflictedNodeIdError,
27
- SerovalDepthLimitError: () => SerovalDepthLimitError,
28
- SerovalDeserializationError: () => SerovalDeserializationError,
29
- SerovalError: () => SerovalError,
30
- SerovalMalformedNodeError: () => SerovalMalformedNodeError,
31
- SerovalMissingInstanceError: () => SerovalMissingInstanceError,
32
- SerovalMissingPluginError: () => SerovalMissingPluginError,
33
- SerovalMissingReferenceError: () => SerovalMissingReferenceError,
34
- SerovalMissingReferenceForIdError: () => SerovalMissingReferenceForIdError,
35
- SerovalMode: () => SerovalMode,
36
- SerovalParserError: () => SerovalParserError,
37
- SerovalSerializationError: () => SerovalSerializationError,
38
- SerovalUnknownTypedArrayError: () => SerovalUnknownTypedArrayError,
39
- SerovalUnsupportedNodeError: () => SerovalUnsupportedNodeError,
40
- SerovalUnsupportedTypeError: () => SerovalUnsupportedTypeError,
41
- compileJSON: () => compileJSON,
42
- createPlugin: () => createPlugin,
43
- createReference: () => createReference,
44
- createStream: () => createStream,
45
- crossSerialize: () => crossSerialize,
46
- crossSerializeAsync: () => crossSerializeAsync,
47
- crossSerializeStream: () => crossSerializeStream,
48
- deserialize: () => deserialize2,
49
- fromCrossJSON: () => fromCrossJSON,
50
- fromJSON: () => fromJSON,
51
- getCrossReferenceHeader: () => getCrossReferenceHeader,
52
- resolvePlugins: () => resolvePlugins,
53
- serialize: () => serialize2,
54
- serializeAsync: () => serializeAsync,
55
- toCrossJSON: () => toCrossJSON,
56
- toCrossJSONAsync: () => toCrossJSONAsync,
57
- toCrossJSONStream: () => toCrossJSONStream,
58
- toJSON: () => toJSON,
59
- toJSONAsync: () => toJSONAsync
60
- });
61
- module.exports = __toCommonJS(src_exports);
62
-
63
- // src/core/compat.ts
64
- var Feature = /* @__PURE__ */ ((Feature2) => {
65
- Feature2[Feature2["AggregateError"] = 1] = "AggregateError";
66
- Feature2[Feature2["ArrowFunction"] = 2] = "ArrowFunction";
67
- Feature2[Feature2["ErrorPrototypeStack"] = 4] = "ErrorPrototypeStack";
68
- Feature2[Feature2["ObjectAssign"] = 8] = "ObjectAssign";
69
- Feature2[Feature2["BigIntTypedArray"] = 16] = "BigIntTypedArray";
70
- Feature2[Feature2["RegExp"] = 32] = "RegExp";
71
- return Feature2;
72
- })(Feature || {});
73
- var ALL_ENABLED = 1 /* AggregateError */ | 2 /* ArrowFunction */ | 4 /* ErrorPrototypeStack */ | 8 /* ObjectAssign */ | 16 /* BigIntTypedArray */ | 32 /* RegExp */;
74
-
75
- // src/core/symbols.ts
76
- var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
77
- var SYM_HAS_INSTANCE = Symbol.hasInstance;
78
- var SYM_IS_CONCAT_SPREADABLE = Symbol.isConcatSpreadable;
79
- var SYM_ITERATOR = Symbol.iterator;
80
- var SYM_MATCH = Symbol.match;
81
- var SYM_MATCH_ALL = Symbol.matchAll;
82
- var SYM_REPLACE = Symbol.replace;
83
- var SYM_SEARCH = Symbol.search;
84
- var SYM_SPECIES = Symbol.species;
85
- var SYM_SPLIT = Symbol.split;
86
- var SYM_TO_PRIMITIVE = Symbol.toPrimitive;
87
- var SYM_TO_STRING_TAG = Symbol.toStringTag;
88
- var SYM_UNSCOPABLES = Symbol.unscopables;
89
-
90
- // src/core/constants.ts
91
- var SYMBOL_STRING = {
92
- [0 /* AsyncIterator */]: "Symbol.asyncIterator",
93
- [1 /* HasInstance */]: "Symbol.hasInstance",
94
- [2 /* IsConcatSpreadable */]: "Symbol.isConcatSpreadable",
95
- [3 /* Iterator */]: "Symbol.iterator",
96
- [4 /* Match */]: "Symbol.match",
97
- [5 /* MatchAll */]: "Symbol.matchAll",
98
- [6 /* Replace */]: "Symbol.replace",
99
- [7 /* Search */]: "Symbol.search",
100
- [8 /* Species */]: "Symbol.species",
101
- [9 /* Split */]: "Symbol.split",
102
- [10 /* ToPrimitive */]: "Symbol.toPrimitive",
103
- [11 /* ToStringTag */]: "Symbol.toStringTag",
104
- [12 /* Unscopables */]: "Symbol.unscopables"
105
- };
106
- var INV_SYMBOL_REF = {
107
- [SYM_ASYNC_ITERATOR]: 0 /* AsyncIterator */,
108
- [SYM_HAS_INSTANCE]: 1 /* HasInstance */,
109
- [SYM_IS_CONCAT_SPREADABLE]: 2 /* IsConcatSpreadable */,
110
- [SYM_ITERATOR]: 3 /* Iterator */,
111
- [SYM_MATCH]: 4 /* Match */,
112
- [SYM_MATCH_ALL]: 5 /* MatchAll */,
113
- [SYM_REPLACE]: 6 /* Replace */,
114
- [SYM_SEARCH]: 7 /* Search */,
115
- [SYM_SPECIES]: 8 /* Species */,
116
- [SYM_SPLIT]: 9 /* Split */,
117
- [SYM_TO_PRIMITIVE]: 10 /* ToPrimitive */,
118
- [SYM_TO_STRING_TAG]: 11 /* ToStringTag */,
119
- [SYM_UNSCOPABLES]: 12 /* Unscopables */
120
- };
121
- var SYMBOL_REF = {
122
- [0 /* AsyncIterator */]: SYM_ASYNC_ITERATOR,
123
- [1 /* HasInstance */]: SYM_HAS_INSTANCE,
124
- [2 /* IsConcatSpreadable */]: SYM_IS_CONCAT_SPREADABLE,
125
- [3 /* Iterator */]: SYM_ITERATOR,
126
- [4 /* Match */]: SYM_MATCH,
127
- [5 /* MatchAll */]: SYM_MATCH_ALL,
128
- [6 /* Replace */]: SYM_REPLACE,
129
- [7 /* Search */]: SYM_SEARCH,
130
- [8 /* Species */]: SYM_SPECIES,
131
- [9 /* Split */]: SYM_SPLIT,
132
- [10 /* ToPrimitive */]: SYM_TO_PRIMITIVE,
133
- [11 /* ToStringTag */]: SYM_TO_STRING_TAG,
134
- [12 /* Unscopables */]: SYM_UNSCOPABLES
135
- };
136
- var CONSTANT_STRING = {
137
- [2 /* True */]: "!0",
138
- [3 /* False */]: "!1",
139
- [1 /* Undefined */]: "void 0",
140
- [0 /* Null */]: "null",
141
- [4 /* NegZero */]: "-0",
142
- [5 /* Inf */]: "1/0",
143
- [6 /* NegInf */]: "-1/0",
144
- [7 /* Nan */]: "0/0"
145
- };
146
- var NIL = void 0;
147
- var CONSTANT_VAL = {
148
- [2 /* True */]: true,
149
- [3 /* False */]: false,
150
- [1 /* Undefined */]: NIL,
151
- [0 /* Null */]: null,
152
- [4 /* NegZero */]: -0,
153
- [5 /* Inf */]: Number.POSITIVE_INFINITY,
154
- [6 /* NegInf */]: Number.NEGATIVE_INFINITY,
155
- [7 /* Nan */]: Number.NaN
156
- };
157
- var ERROR_CONSTRUCTOR_STRING = {
158
- [0 /* Error */]: "Error",
159
- [1 /* EvalError */]: "EvalError",
160
- [2 /* RangeError */]: "RangeError",
161
- [3 /* ReferenceError */]: "ReferenceError",
162
- [4 /* SyntaxError */]: "SyntaxError",
163
- [5 /* TypeError */]: "TypeError",
164
- [6 /* URIError */]: "URIError"
165
- };
166
- var ERROR_CONSTRUCTOR = {
167
- [0 /* Error */]: Error,
168
- [1 /* EvalError */]: EvalError,
169
- [2 /* RangeError */]: RangeError,
170
- [3 /* ReferenceError */]: ReferenceError,
171
- [4 /* SyntaxError */]: SyntaxError,
172
- [5 /* TypeError */]: TypeError,
173
- [6 /* URIError */]: URIError
174
- };
175
-
176
- // src/core/node.ts
177
- function createSerovalNode(t, i, s, c, m, p, e, a, f, b, o, l) {
178
- return {
179
- t,
180
- i,
181
- s,
182
- c,
183
- m,
184
- p,
185
- e,
186
- a,
187
- f,
188
- b,
189
- o,
190
- l
191
- };
192
- }
193
-
194
- // src/core/literals.ts
195
- function createConstantNode(value) {
196
- return createSerovalNode(
197
- 2 /* Constant */,
198
- NIL,
199
- value,
200
- NIL,
201
- NIL,
202
- NIL,
203
- NIL,
204
- NIL,
205
- NIL,
206
- NIL,
207
- NIL,
208
- NIL
209
- );
210
- }
211
- var TRUE_NODE = /* @__PURE__ */ createConstantNode(
212
- 2 /* True */
213
- );
214
- var FALSE_NODE = /* @__PURE__ */ createConstantNode(
215
- 3 /* False */
216
- );
217
- var UNDEFINED_NODE = /* @__PURE__ */ createConstantNode(
218
- 1 /* Undefined */
219
- );
220
- var NULL_NODE = /* @__PURE__ */ createConstantNode(
221
- 0 /* Null */
222
- );
223
- var NEG_ZERO_NODE = /* @__PURE__ */ createConstantNode(
224
- 4 /* NegZero */
225
- );
226
- var INFINITY_NODE = /* @__PURE__ */ createConstantNode(
227
- 5 /* Inf */
228
- );
229
- var NEG_INFINITY_NODE = /* @__PURE__ */ createConstantNode(
230
- 6 /* NegInf */
231
- );
232
- var NAN_NODE = /* @__PURE__ */ createConstantNode(7 /* Nan */);
233
-
234
- // src/core/string.ts
235
- function serializeChar(str) {
236
- switch (str) {
237
- case '"':
238
- return '\\"';
239
- case "\\":
240
- return "\\\\";
241
- case "\n":
242
- return "\\n";
243
- case "\r":
244
- return "\\r";
245
- case "\b":
246
- return "\\b";
247
- case " ":
248
- return "\\t";
249
- case "\f":
250
- return "\\f";
251
- case "<":
252
- return "\\x3C";
253
- case "\u2028":
254
- return "\\u2028";
255
- case "\u2029":
256
- return "\\u2029";
257
- default:
258
- return NIL;
259
- }
260
- }
261
- function serializeString(str) {
262
- let result = "";
263
- let lastPos = 0;
264
- let replacement;
265
- for (let i = 0, len = str.length; i < len; i++) {
266
- replacement = serializeChar(str[i]);
267
- if (replacement) {
268
- result += str.slice(lastPos, i) + replacement;
269
- lastPos = i + 1;
270
- }
271
- }
272
- if (lastPos === 0) {
273
- result = str;
274
- } else {
275
- result += str.slice(lastPos);
276
- }
277
- return result;
278
- }
279
- function deserializeReplacer(str) {
280
- switch (str) {
281
- case "\\\\":
282
- return "\\";
283
- case '\\"':
284
- return '"';
285
- case "\\n":
286
- return "\n";
287
- case "\\r":
288
- return "\r";
289
- case "\\b":
290
- return "\b";
291
- case "\\t":
292
- return " ";
293
- case "\\f":
294
- return "\f";
295
- case "\\x3C":
296
- return "<";
297
- case "\\u2028":
298
- return "\u2028";
299
- case "\\u2029":
300
- return "\u2029";
301
- default:
302
- return str;
303
- }
304
- }
305
- function deserializeString(str) {
306
- return str.replace(
307
- /(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g,
308
- deserializeReplacer
309
- );
310
- }
311
-
312
- // src/core/keys.ts
313
- var REFERENCES_KEY = "__SEROVAL_REFS__";
314
- var GLOBAL_CONTEXT_REFERENCES = "$R";
315
- var GLOBAL_CONTEXT_R = `self.${GLOBAL_CONTEXT_REFERENCES}`;
316
- function getCrossReferenceHeader(id) {
317
- if (id == null) {
318
- return `${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||[]`;
319
- }
320
- return `(${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||{})["${serializeString(
321
- id
322
- )}"]=[]`;
323
- }
324
-
325
- // src/core/reference.ts
326
- var REFERENCE = /* @__PURE__ */ new Map();
327
- var INV_REFERENCE = /* @__PURE__ */ new Map();
328
- function createReference(id, value) {
329
- REFERENCE.set(value, id);
330
- INV_REFERENCE.set(id, value);
331
- return value;
332
- }
333
- function hasReferenceID(value) {
334
- return REFERENCE.has(value);
335
- }
336
- function hasReference(id) {
337
- return INV_REFERENCE.has(id);
338
- }
339
- function getReferenceID(value) {
340
- if (hasReferenceID(value)) {
341
- return REFERENCE.get(value);
342
- }
343
- throw new SerovalMissingReferenceError(value);
344
- }
345
- function getReference(id) {
346
- if (hasReference(id)) {
347
- return INV_REFERENCE.get(id);
348
- }
349
- throw new SerovalMissingReferenceForIdError(id);
350
- }
351
- if (typeof globalThis !== "undefined") {
352
- Object.defineProperty(globalThis, REFERENCES_KEY, {
353
- value: INV_REFERENCE,
354
- configurable: true,
355
- writable: false,
356
- enumerable: false
357
- });
358
- } else if (typeof window !== "undefined") {
359
- Object.defineProperty(window, REFERENCES_KEY, {
360
- value: INV_REFERENCE,
361
- configurable: true,
362
- writable: false,
363
- enumerable: false
364
- });
365
- } else if (typeof self !== "undefined") {
366
- Object.defineProperty(self, REFERENCES_KEY, {
367
- value: INV_REFERENCE,
368
- configurable: true,
369
- writable: false,
370
- enumerable: false
371
- });
372
- } else if (typeof global !== "undefined") {
373
- Object.defineProperty(global, REFERENCES_KEY, {
374
- value: INV_REFERENCE,
375
- configurable: true,
376
- writable: false,
377
- enumerable: false
378
- });
379
- }
380
-
381
- // src/core/utils/error.ts
382
- function getErrorConstructor(error) {
383
- if (error instanceof EvalError) {
384
- return 1 /* EvalError */;
385
- }
386
- if (error instanceof RangeError) {
387
- return 2 /* RangeError */;
388
- }
389
- if (error instanceof ReferenceError) {
390
- return 3 /* ReferenceError */;
391
- }
392
- if (error instanceof SyntaxError) {
393
- return 4 /* SyntaxError */;
394
- }
395
- if (error instanceof TypeError) {
396
- return 5 /* TypeError */;
397
- }
398
- if (error instanceof URIError) {
399
- return 6 /* URIError */;
400
- }
401
- return 0 /* Error */;
402
- }
403
- function getInitialErrorOptions(error) {
404
- const construct = ERROR_CONSTRUCTOR_STRING[getErrorConstructor(error)];
405
- if (error.name !== construct) {
406
- return { name: error.name };
407
- }
408
- if (error.constructor.name !== construct) {
409
- return { name: error.constructor.name };
410
- }
411
- return {};
412
- }
413
- function getErrorOptions(error, features) {
414
- let options = getInitialErrorOptions(error);
415
- const names = Object.getOwnPropertyNames(error);
416
- for (let i = 0, len = names.length, name; i < len; i++) {
417
- name = names[i];
418
- if (name !== "name" && name !== "message") {
419
- if (name === "stack") {
420
- if (features & 4 /* ErrorPrototypeStack */) {
421
- options = options || {};
422
- options[name] = error[name];
423
- }
424
- } else {
425
- options = options || {};
426
- options[name] = error[name];
427
- }
428
- }
429
- }
430
- return options;
431
- }
432
-
433
- // src/core/utils/get-object-flag.ts
434
- function getObjectFlag(obj) {
435
- if (Object.isFrozen(obj)) {
436
- return 3 /* Frozen */;
437
- }
438
- if (Object.isSealed(obj)) {
439
- return 2 /* Sealed */;
440
- }
441
- if (Object.isExtensible(obj)) {
442
- return 0 /* None */;
443
- }
444
- return 1 /* NonExtensible */;
445
- }
446
-
447
- // src/core/base-primitives.ts
448
- function createNumberNode(value) {
449
- switch (value) {
450
- case Number.POSITIVE_INFINITY:
451
- return INFINITY_NODE;
452
- case Number.NEGATIVE_INFINITY:
453
- return NEG_INFINITY_NODE;
454
- }
455
- if (value !== value) {
456
- return NAN_NODE;
457
- }
458
- if (Object.is(value, -0)) {
459
- return NEG_ZERO_NODE;
460
- }
461
- return createSerovalNode(
462
- 0 /* Number */,
463
- NIL,
464
- value,
465
- NIL,
466
- NIL,
467
- NIL,
468
- NIL,
469
- NIL,
470
- NIL,
471
- NIL,
472
- NIL,
473
- NIL
474
- );
475
- }
476
- function createStringNode(value) {
477
- return createSerovalNode(
478
- 1 /* String */,
479
- NIL,
480
- serializeString(value),
481
- NIL,
482
- NIL,
483
- NIL,
484
- NIL,
485
- NIL,
486
- NIL,
487
- NIL,
488
- NIL,
489
- NIL
490
- );
491
- }
492
- function createBigIntNode(current) {
493
- return createSerovalNode(
494
- 3 /* BigInt */,
495
- NIL,
496
- "" + current,
497
- NIL,
498
- NIL,
499
- NIL,
500
- NIL,
501
- NIL,
502
- NIL,
503
- NIL,
504
- NIL,
505
- NIL
506
- );
507
- }
508
- function createIndexedValueNode(id) {
509
- return createSerovalNode(
510
- 4 /* IndexedValue */,
511
- id,
512
- NIL,
513
- NIL,
514
- NIL,
515
- NIL,
516
- NIL,
517
- NIL,
518
- NIL,
519
- NIL,
520
- NIL,
521
- NIL
522
- );
523
- }
524
- function createDateNode(id, current) {
525
- const timestamp = current.valueOf();
526
- return createSerovalNode(
527
- 5 /* Date */,
528
- id,
529
- timestamp !== timestamp ? "" : current.toISOString(),
530
- NIL,
531
- NIL,
532
- NIL,
533
- NIL,
534
- NIL,
535
- NIL,
536
- NIL,
537
- NIL,
538
- NIL
539
- );
540
- }
541
- function createRegExpNode(id, current) {
542
- return createSerovalNode(
543
- 6 /* RegExp */,
544
- id,
545
- NIL,
546
- serializeString(current.source),
547
- current.flags,
548
- NIL,
549
- NIL,
550
- NIL,
551
- NIL,
552
- NIL,
553
- NIL,
554
- NIL
555
- );
556
- }
557
- function createWKSymbolNode(id, current) {
558
- return createSerovalNode(
559
- 17 /* WKSymbol */,
560
- id,
561
- INV_SYMBOL_REF[current],
562
- NIL,
563
- NIL,
564
- NIL,
565
- NIL,
566
- NIL,
567
- NIL,
568
- NIL,
569
- NIL,
570
- NIL
571
- );
572
- }
573
- function createReferenceNode(id, ref) {
574
- return createSerovalNode(
575
- 18 /* Reference */,
576
- id,
577
- serializeString(getReferenceID(ref)),
578
- NIL,
579
- NIL,
580
- NIL,
581
- NIL,
582
- NIL,
583
- NIL,
584
- NIL,
585
- NIL,
586
- NIL
587
- );
588
- }
589
- function createPluginNode(id, tag, value) {
590
- return createSerovalNode(
591
- 25 /* Plugin */,
592
- id,
593
- value,
594
- serializeString(tag),
595
- NIL,
596
- NIL,
597
- NIL,
598
- NIL,
599
- NIL,
600
- NIL,
601
- NIL,
602
- NIL
603
- );
604
- }
605
- function createArrayNode(id, current, parsedItems) {
606
- return createSerovalNode(
607
- 9 /* Array */,
608
- id,
609
- NIL,
610
- NIL,
611
- NIL,
612
- NIL,
613
- NIL,
614
- parsedItems,
615
- NIL,
616
- NIL,
617
- getObjectFlag(current),
618
- NIL
619
- );
620
- }
621
- function createBoxedNode(id, boxed) {
622
- return createSerovalNode(
623
- 21 /* Boxed */,
624
- id,
625
- NIL,
626
- NIL,
627
- NIL,
628
- NIL,
629
- NIL,
630
- NIL,
631
- boxed,
632
- NIL,
633
- NIL,
634
- NIL
635
- );
636
- }
637
- function createTypedArrayNode(id, current, buffer) {
638
- return createSerovalNode(
639
- 15 /* TypedArray */,
640
- id,
641
- NIL,
642
- current.constructor.name,
643
- NIL,
644
- NIL,
645
- NIL,
646
- NIL,
647
- buffer,
648
- current.byteOffset,
649
- NIL,
650
- current.length
651
- );
652
- }
653
- function createBigIntTypedArrayNode(id, current, buffer) {
654
- return createSerovalNode(
655
- 16 /* BigIntTypedArray */,
656
- id,
657
- NIL,
658
- current.constructor.name,
659
- NIL,
660
- NIL,
661
- NIL,
662
- NIL,
663
- buffer,
664
- current.byteOffset,
665
- NIL,
666
- current.length
667
- );
668
- }
669
- function createDataViewNode(id, current, buffer) {
670
- return createSerovalNode(
671
- 20 /* DataView */,
672
- id,
673
- NIL,
674
- NIL,
675
- NIL,
676
- NIL,
677
- NIL,
678
- NIL,
679
- buffer,
680
- current.byteOffset,
681
- NIL,
682
- current.byteLength
683
- );
684
- }
685
- function createErrorNode(id, current, options) {
686
- return createSerovalNode(
687
- 13 /* Error */,
688
- id,
689
- getErrorConstructor(current),
690
- NIL,
691
- serializeString(current.message),
692
- options,
693
- NIL,
694
- NIL,
695
- NIL,
696
- NIL,
697
- NIL,
698
- NIL
699
- );
700
- }
701
- function createAggregateErrorNode(id, current, options) {
702
- return createSerovalNode(
703
- 14 /* AggregateError */,
704
- id,
705
- getErrorConstructor(current),
706
- NIL,
707
- serializeString(current.message),
708
- options,
709
- NIL,
710
- NIL,
711
- NIL,
712
- NIL,
713
- NIL,
714
- NIL
715
- );
716
- }
717
- function createSetNode(id, items) {
718
- return createSerovalNode(
719
- 7 /* Set */,
720
- id,
721
- NIL,
722
- NIL,
723
- NIL,
724
- NIL,
725
- NIL,
726
- items,
727
- NIL,
728
- NIL,
729
- NIL,
730
- NIL
731
- );
732
- }
733
- function createIteratorFactoryInstanceNode(factory, items) {
734
- return createSerovalNode(
735
- 28 /* IteratorFactoryInstance */,
736
- NIL,
737
- NIL,
738
- NIL,
739
- NIL,
740
- NIL,
741
- NIL,
742
- [factory, items],
743
- NIL,
744
- NIL,
745
- NIL,
746
- NIL
747
- );
748
- }
749
- function createAsyncIteratorFactoryInstanceNode(factory, items) {
750
- return createSerovalNode(
751
- 30 /* AsyncIteratorFactoryInstance */,
752
- NIL,
753
- NIL,
754
- NIL,
755
- NIL,
756
- NIL,
757
- NIL,
758
- [factory, items],
759
- NIL,
760
- NIL,
761
- NIL,
762
- NIL
763
- );
764
- }
765
- function createStreamConstructorNode(id, factory, sequence) {
766
- return createSerovalNode(
767
- 31 /* StreamConstructor */,
768
- id,
769
- NIL,
770
- NIL,
771
- NIL,
772
- NIL,
773
- NIL,
774
- sequence,
775
- factory,
776
- NIL,
777
- NIL,
778
- NIL
779
- );
780
- }
781
- function createStreamNextNode(id, parsed) {
782
- return createSerovalNode(
783
- 32 /* StreamNext */,
784
- id,
785
- NIL,
786
- NIL,
787
- NIL,
788
- NIL,
789
- NIL,
790
- NIL,
791
- parsed,
792
- NIL,
793
- NIL,
794
- NIL
795
- );
796
- }
797
- function createStreamThrowNode(id, parsed) {
798
- return createSerovalNode(
799
- 33 /* StreamThrow */,
800
- id,
801
- NIL,
802
- NIL,
803
- NIL,
804
- NIL,
805
- NIL,
806
- NIL,
807
- parsed,
808
- NIL,
809
- NIL,
810
- NIL
811
- );
812
- }
813
- function createStreamReturnNode(id, parsed) {
814
- return createSerovalNode(
815
- 34 /* StreamReturn */,
816
- id,
817
- NIL,
818
- NIL,
819
- NIL,
820
- NIL,
821
- NIL,
822
- NIL,
823
- parsed,
824
- NIL,
825
- NIL,
826
- NIL
827
- );
828
- }
829
- function createSequenceNode(id, sequence, throwAt, doneAt) {
830
- return createSerovalNode(
831
- 35 /* Sequence */,
832
- id,
833
- throwAt,
834
- NIL,
835
- NIL,
836
- NIL,
837
- NIL,
838
- sequence,
839
- NIL,
840
- NIL,
841
- NIL,
842
- doneAt
843
- );
844
- }
845
-
846
- // src/core/errors.ts
847
- var { toString: objectToString } = Object.prototype;
848
- function getErrorMessageDev(type, cause) {
849
- if (cause instanceof Error) {
850
- return `Seroval caught an error during the ${type} process.
851
-
852
- ${cause.name}
853
- ${cause.message}
854
-
855
- - For more information, please check the "cause" property of this error.
856
- - If you believe this is an error in Seroval, please submit an issue at https://github.com/lxsmnsyc/seroval/issues/new`;
857
- }
858
- return `Seroval caught an error during the ${type} process.
859
-
860
- "${objectToString.call(cause)}"
861
-
862
- For more information, please check the "cause" property of this error.`;
863
- }
864
- var getErrorMessage = (type, cause) => false ? getErrorMessageProd(type) : getErrorMessageDev(type, cause);
865
- var SerovalError = class extends Error {
866
- constructor(type, cause) {
867
- super(getErrorMessage(type, cause));
868
- this.cause = cause;
869
- }
870
- };
871
- var SerovalParserError = class extends SerovalError {
872
- constructor(cause) {
873
- super("parsing", cause);
874
- }
875
- };
876
- var SerovalSerializationError = class extends SerovalError {
877
- constructor(cause) {
878
- super("serialization", cause);
879
- }
880
- };
881
- var SerovalDeserializationError = class extends SerovalError {
882
- constructor(cause) {
883
- super("deserialization", cause);
884
- }
885
- };
886
- var SerovalUnsupportedTypeError = class extends Error {
887
- constructor(value) {
888
- super(
889
- false ? getSpecificErrorMessage(1 /* UnsupportedType */) : `The value ${objectToString.call(value)} of type "${typeof value}" cannot be parsed/serialized.
890
-
891
- There are few workarounds for this problem:
892
- - Transform the value in a way that it can be serialized.
893
- - If the reference is present on multiple runtimes (isomorphic), you can use the Reference API to map the references.`
894
- );
895
- this.value = value;
896
- }
897
- };
898
- var SerovalUnsupportedNodeError = class extends Error {
899
- constructor(node) {
900
- super(
901
- false ? getSpecificErrorMessage(2 /* UnsupportedNode */) : 'Unsupported node type "' + node.t + '".'
902
- );
903
- }
904
- };
905
- var SerovalMissingPluginError = class extends Error {
906
- constructor(tag) {
907
- super(
908
- false ? getSpecificErrorMessage(3 /* MissingPlugin */) : 'Missing plugin for tag "' + tag + '".'
909
- );
910
- }
911
- };
912
- var SerovalMissingInstanceError = class extends Error {
913
- constructor(tag) {
914
- super(
915
- false ? getSpecificErrorMessage(4 /* MissingInstance */) : 'Missing "' + tag + '" instance.'
916
- );
917
- }
918
- };
919
- var SerovalMissingReferenceError = class extends Error {
920
- constructor(value) {
921
- super(
922
- false ? getSpecificErrorMessage(5 /* MissingReference */) : 'Missing reference for the value "' + objectToString.call(value) + '" of type "' + typeof value + '"'
923
- );
924
- this.value = value;
925
- }
926
- };
927
- var SerovalMissingReferenceForIdError = class extends Error {
928
- constructor(id) {
929
- super(
930
- false ? getSpecificErrorMessage(6 /* MissingReferenceForId */) : 'Missing reference for id "' + serializeString(id) + '"'
931
- );
932
- }
933
- };
934
- var SerovalUnknownTypedArrayError = class extends Error {
935
- constructor(name) {
936
- super(
937
- false ? getSpecificErrorMessage(7 /* UnknownTypedArray */) : 'Unknown TypedArray "' + name + '"'
938
- );
939
- }
940
- };
941
- var SerovalMalformedNodeError = class extends Error {
942
- constructor(node) {
943
- super(
944
- false ? getSpecificErrorMessage(8 /* MalformedNode */) : 'Malformed node type "' + node.t + '".'
945
- );
946
- }
947
- };
948
- var SerovalConflictedNodeIdError = class extends Error {
949
- constructor(node) {
950
- super(
951
- false ? getSpecificErrorMessage(9 /* ConflictedNodeId */) : 'Conflicted node id "' + node.i + '".'
952
- );
953
- }
954
- };
955
- var SerovalDepthLimitError = class extends Error {
956
- constructor(limit) {
957
- super(
958
- false ? getSpecificErrorMessage(9 /* ConflictedNodeId */) : "Depth limit of " + limit + " reached"
959
- );
960
- }
961
- };
962
-
963
- // src/core/opaque-reference.ts
964
- var OpaqueReference = class {
965
- constructor(value, replacement) {
966
- this.value = value;
967
- this.replacement = replacement;
968
- }
969
- };
970
-
971
- // src/core/constructors.ts
972
- var PROMISE_CONSTRUCTOR = () => {
973
- const resolver = {
974
- p: 0,
975
- s: 0,
976
- f: 0
977
- };
978
- resolver.p = new Promise((resolve, reject) => {
979
- resolver.s = resolve;
980
- resolver.f = reject;
981
- });
982
- return resolver;
983
- };
984
- var PROMISE_SUCCESS = (resolver, data) => {
985
- resolver.s(data);
986
- resolver.p.s = 1;
987
- resolver.p.v = data;
988
- };
989
- var PROMISE_FAILURE = (resolver, data) => {
990
- resolver.f(data);
991
- resolver.p.s = 2;
992
- resolver.p.v = data;
993
- };
994
- var SERIALIZED_PROMISE_CONSTRUCTOR = /* @__PURE__ */ PROMISE_CONSTRUCTOR.toString();
995
- var SERIALIZED_PROMISE_SUCCESS = /* @__PURE__ */ PROMISE_SUCCESS.toString();
996
- var SERIALIZED_PROMISE_FAILURE = /* @__PURE__ */ PROMISE_FAILURE.toString();
997
- var STREAM_CONSTRUCTOR = () => {
998
- const buffer = [];
999
- const listeners = [];
1000
- let alive = true;
1001
- let success = false;
1002
- let count = 0;
1003
- const flush = (value, mode, x) => {
1004
- for (x = 0; x < count; x++) {
1005
- if (listeners[x]) {
1006
- listeners[x][mode](value);
1007
- }
1008
- }
1009
- };
1010
- const up = (listener, x, z, current) => {
1011
- for (x = 0, z = buffer.length; x < z; x++) {
1012
- current = buffer[x];
1013
- if (!alive && x === z - 1) {
1014
- listener[success ? "return" : "throw"](current);
1015
- } else {
1016
- listener.next(current);
1017
- }
1018
- }
1019
- };
1020
- const on = (listener, temp) => {
1021
- if (alive) {
1022
- temp = count++;
1023
- listeners[temp] = listener;
1024
- }
1025
- up(listener);
1026
- return () => {
1027
- if (alive) {
1028
- listeners[temp] = listeners[count];
1029
- listeners[count--] = void 0;
1030
- }
1031
- };
1032
- };
1033
- return {
1034
- __SEROVAL_STREAM__: true,
1035
- on: (listener) => on(listener),
1036
- next: (value) => {
1037
- if (alive) {
1038
- buffer.push(value);
1039
- flush(value, "next");
1040
- }
1041
- },
1042
- throw: (value) => {
1043
- if (alive) {
1044
- buffer.push(value);
1045
- flush(value, "throw");
1046
- alive = false;
1047
- success = false;
1048
- listeners.length = 0;
1049
- }
1050
- },
1051
- return: (value) => {
1052
- if (alive) {
1053
- buffer.push(value);
1054
- flush(value, "return");
1055
- alive = false;
1056
- success = true;
1057
- listeners.length = 0;
1058
- }
1059
- }
1060
- };
1061
- };
1062
- var SERIALIZED_STREAM_CONSTRUCTOR = /* @__PURE__ */ STREAM_CONSTRUCTOR.toString();
1063
- var ITERATOR_CONSTRUCTOR = (symbol) => (sequence) => () => {
1064
- let index = 0;
1065
- const instance = {
1066
- [symbol]: () => instance,
1067
- next: () => {
1068
- if (index > sequence.d) {
1069
- return {
1070
- done: true,
1071
- value: void 0
1072
- };
1073
- }
1074
- const currentIndex = index++;
1075
- const data = sequence.v[currentIndex];
1076
- if (currentIndex === sequence.t) {
1077
- throw data;
1078
- }
1079
- return {
1080
- done: currentIndex === sequence.d,
1081
- value: data
1082
- };
1083
- }
1084
- };
1085
- return instance;
1086
- };
1087
- var SERIALIZED_ITERATOR_CONSTRUCTOR = /* @__PURE__ */ ITERATOR_CONSTRUCTOR.toString();
1088
- var ASYNC_ITERATOR_CONSTRUCTOR = (symbol, createPromise) => (stream) => () => {
1089
- let count = 0;
1090
- let doneAt = -1;
1091
- let isThrow = false;
1092
- const buffer = [];
1093
- const pending = [];
1094
- const finalize = (i = 0, len = pending.length) => {
1095
- for (; i < len; i++) {
1096
- pending[i].s({
1097
- done: true,
1098
- value: void 0
1099
- });
1100
- }
1101
- };
1102
- stream.on({
1103
- next: (value) => {
1104
- const temp = pending.shift();
1105
- if (temp) {
1106
- temp.s({ done: false, value });
1107
- }
1108
- buffer.push(value);
1109
- },
1110
- throw: (value) => {
1111
- const temp = pending.shift();
1112
- if (temp) {
1113
- temp.f(value);
1114
- }
1115
- finalize();
1116
- doneAt = buffer.length;
1117
- isThrow = true;
1118
- buffer.push(value);
1119
- },
1120
- return: (value) => {
1121
- const temp = pending.shift();
1122
- if (temp) {
1123
- temp.s({ done: true, value });
1124
- }
1125
- finalize();
1126
- doneAt = buffer.length;
1127
- buffer.push(value);
1128
- }
1129
- });
1130
- const instance = {
1131
- [symbol]: () => instance,
1132
- next: () => {
1133
- if (doneAt === -1) {
1134
- const index2 = count++;
1135
- if (index2 >= buffer.length) {
1136
- const temp = createPromise();
1137
- pending.push(temp);
1138
- return temp.p;
1139
- }
1140
- return {
1141
- done: false,
1142
- value: buffer[index2]
1143
- };
1144
- }
1145
- if (count > doneAt) {
1146
- return {
1147
- done: true,
1148
- value: void 0
1149
- };
1150
- }
1151
- const index = count++;
1152
- const value = buffer[index];
1153
- if (index !== doneAt) {
1154
- return {
1155
- done: false,
1156
- value
1157
- };
1158
- }
1159
- if (isThrow) {
1160
- throw value;
1161
- }
1162
- return {
1163
- done: true,
1164
- value
1165
- };
1166
- }
1167
- };
1168
- return instance;
1169
- };
1170
- var SERIALIZED_ASYNC_ITERATOR_CONSTRUCTOR = /* @__PURE__ */ ASYNC_ITERATOR_CONSTRUCTOR.toString();
1171
- var ARRAY_BUFFER_CONSTRUCTOR = (b64) => {
1172
- const decoded = atob(b64);
1173
- const length = decoded.length;
1174
- const arr = new Uint8Array(length);
1175
- for (let i = 0; i < length; i++) {
1176
- arr[i] = decoded.charCodeAt(i);
1177
- }
1178
- return arr.buffer;
1179
- };
1180
- var SERIALIZED_ARRAY_BUFFER_CONSTRUCTOR = /* @__PURE__ */ ARRAY_BUFFER_CONSTRUCTOR.toString();
1181
-
1182
- // src/core/sequence.ts
1183
- function isSequence(value) {
1184
- return "__SEROVAL_SEQUENCE__" in value;
1185
- }
1186
- function createSequence(values, throwAt, doneAt) {
1187
- return {
1188
- __SEROVAL_SEQUENCE__: true,
1189
- v: values,
1190
- t: throwAt,
1191
- d: doneAt
1192
- };
1193
- }
1194
- function createSequenceFromIterable(source) {
1195
- const values = [];
1196
- let throwsAt = -1;
1197
- let doneAt = -1;
1198
- const iterator = source[SYM_ITERATOR]();
1199
- while (true) {
1200
- try {
1201
- const value = iterator.next();
1202
- values.push(value.value);
1203
- if (value.done) {
1204
- doneAt = values.length - 1;
1205
- break;
1206
- }
1207
- } catch (error) {
1208
- throwsAt = values.length;
1209
- values.push(error);
1210
- }
1211
- }
1212
- return createSequence(values, throwsAt, doneAt);
1213
- }
1214
- var createIterator = ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
1215
- function sequenceToIterator(sequence) {
1216
- return createIterator(sequence);
1217
- }
1218
-
1219
- // src/core/special-reference.ts
1220
- var ITERATOR = {};
1221
- var ASYNC_ITERATOR = {};
1222
- var SPECIAL_REFS = {
1223
- [0 /* MapSentinel */]: {},
1224
- [1 /* PromiseConstructor */]: {},
1225
- [2 /* PromiseSuccess */]: {},
1226
- [3 /* PromiseFailure */]: {},
1227
- [4 /* StreamConstructor */]: {},
1228
- [5 /* ArrayBufferConstructor */]: {}
1229
- };
1230
- var SPECIAL_REF_STRING = {
1231
- [0 /* MapSentinel */]: "[]",
1232
- [1 /* PromiseConstructor */]: SERIALIZED_PROMISE_CONSTRUCTOR,
1233
- [2 /* PromiseSuccess */]: SERIALIZED_PROMISE_SUCCESS,
1234
- [3 /* PromiseFailure */]: SERIALIZED_PROMISE_FAILURE,
1235
- [4 /* StreamConstructor */]: SERIALIZED_STREAM_CONSTRUCTOR,
1236
- [5 /* ArrayBufferConstructor */]: SERIALIZED_ARRAY_BUFFER_CONSTRUCTOR
1237
- };
1238
-
1239
- // src/core/stream.ts
1240
- function isStream(value) {
1241
- return "__SEROVAL_STREAM__" in value;
1242
- }
1243
- function createStream() {
1244
- return STREAM_CONSTRUCTOR();
1245
- }
1246
- function createStreamFromAsyncIterable(iterable) {
1247
- const stream = createStream();
1248
- const iterator = iterable[SYM_ASYNC_ITERATOR]();
1249
- async function push() {
1250
- try {
1251
- const value = await iterator.next();
1252
- if (value.done) {
1253
- stream.return(value.value);
1254
- } else {
1255
- stream.next(value.value);
1256
- await push();
1257
- }
1258
- } catch (error) {
1259
- stream.throw(error);
1260
- }
1261
- }
1262
- push().catch(() => {
1263
- });
1264
- return stream;
1265
- }
1266
- var createAsyncIterable = ASYNC_ITERATOR_CONSTRUCTOR(
1267
- SYM_ASYNC_ITERATOR,
1268
- PROMISE_CONSTRUCTOR
1269
- );
1270
- function streamToAsyncIterable(stream) {
1271
- return createAsyncIterable(
1272
- stream
1273
- );
1274
- }
1275
-
1276
- // src/core/utils/promise-to-result.ts
1277
- async function promiseToResult(current) {
1278
- try {
1279
- return [1, await current];
1280
- } catch (e) {
1281
- return [0, e];
1282
- }
1283
- }
1284
-
1285
- // src/core/context/parser.ts
1286
- function createBaseParserContext(mode, options) {
1287
- return {
1288
- plugins: options.plugins,
1289
- mode,
1290
- marked: /* @__PURE__ */ new Set(),
1291
- features: ALL_ENABLED ^ (options.disabledFeatures || 0),
1292
- refs: options.refs || /* @__PURE__ */ new Map(),
1293
- depthLimit: options.depthLimit || 1e3
1294
- };
1295
- }
1296
- function markParserRef(ctx, id) {
1297
- ctx.marked.add(id);
1298
- }
1299
- function createIndexForValue(ctx, current) {
1300
- const id = ctx.refs.size;
1301
- ctx.refs.set(current, id);
1302
- return id;
1303
- }
1304
- function getNodeForIndexedValue(ctx, current) {
1305
- const registeredId = ctx.refs.get(current);
1306
- if (registeredId != null) {
1307
- markParserRef(ctx, registeredId);
1308
- return {
1309
- type: 1 /* Indexed */,
1310
- value: createIndexedValueNode(registeredId)
1311
- };
1312
- }
1313
- return {
1314
- type: 0 /* Fresh */,
1315
- value: createIndexForValue(ctx, current)
1316
- };
1317
- }
1318
- function getReferenceNode(ctx, current) {
1319
- const indexed = getNodeForIndexedValue(ctx, current);
1320
- if (indexed.type === 1 /* Indexed */) {
1321
- return indexed;
1322
- }
1323
- if (hasReferenceID(current)) {
1324
- return {
1325
- type: 2 /* Referenced */,
1326
- value: createReferenceNode(indexed.value, current)
1327
- };
1328
- }
1329
- return indexed;
1330
- }
1331
- function parseWellKnownSymbol(ctx, current) {
1332
- const ref = getReferenceNode(ctx, current);
1333
- if (ref.type !== 0 /* Fresh */) {
1334
- return ref.value;
1335
- }
1336
- if (current in INV_SYMBOL_REF) {
1337
- return createWKSymbolNode(ref.value, current);
1338
- }
1339
- throw new SerovalUnsupportedTypeError(current);
1340
- }
1341
- function parseSpecialReference(ctx, ref) {
1342
- const result = getNodeForIndexedValue(ctx, SPECIAL_REFS[ref]);
1343
- if (result.type === 1 /* Indexed */) {
1344
- return result.value;
1345
- }
1346
- return createSerovalNode(
1347
- 26 /* SpecialReference */,
1348
- result.value,
1349
- ref,
1350
- NIL,
1351
- NIL,
1352
- NIL,
1353
- NIL,
1354
- NIL,
1355
- NIL,
1356
- NIL,
1357
- NIL,
1358
- NIL
1359
- );
1360
- }
1361
- function parseIteratorFactory(ctx) {
1362
- const result = getNodeForIndexedValue(ctx, ITERATOR);
1363
- if (result.type === 1 /* Indexed */) {
1364
- return result.value;
1365
- }
1366
- return createSerovalNode(
1367
- 27 /* IteratorFactory */,
1368
- result.value,
1369
- NIL,
1370
- NIL,
1371
- NIL,
1372
- NIL,
1373
- NIL,
1374
- NIL,
1375
- parseWellKnownSymbol(ctx, SYM_ITERATOR),
1376
- NIL,
1377
- NIL,
1378
- NIL
1379
- );
1380
- }
1381
- function parseAsyncIteratorFactory(ctx) {
1382
- const result = getNodeForIndexedValue(ctx, ASYNC_ITERATOR);
1383
- if (result.type === 1 /* Indexed */) {
1384
- return result.value;
1385
- }
1386
- return createSerovalNode(
1387
- 29 /* AsyncIteratorFactory */,
1388
- result.value,
1389
- NIL,
1390
- NIL,
1391
- NIL,
1392
- NIL,
1393
- NIL,
1394
- [
1395
- parseSpecialReference(ctx, 1 /* PromiseConstructor */),
1396
- parseWellKnownSymbol(ctx, SYM_ASYNC_ITERATOR)
1397
- ],
1398
- NIL,
1399
- NIL,
1400
- NIL,
1401
- NIL
1402
- );
1403
- }
1404
- function createObjectNode(id, current, empty, record) {
1405
- return createSerovalNode(
1406
- empty ? 11 /* NullConstructor */ : 10 /* Object */,
1407
- id,
1408
- NIL,
1409
- NIL,
1410
- NIL,
1411
- record,
1412
- NIL,
1413
- NIL,
1414
- NIL,
1415
- NIL,
1416
- getObjectFlag(current),
1417
- NIL
1418
- );
1419
- }
1420
- function createMapNode(ctx, id, k, v) {
1421
- return createSerovalNode(
1422
- 8 /* Map */,
1423
- id,
1424
- NIL,
1425
- NIL,
1426
- NIL,
1427
- NIL,
1428
- { k, v },
1429
- NIL,
1430
- parseSpecialReference(ctx, 0 /* MapSentinel */),
1431
- NIL,
1432
- NIL,
1433
- NIL
1434
- );
1435
- }
1436
- function createPromiseConstructorNode(ctx, id, resolver) {
1437
- return createSerovalNode(
1438
- 22 /* PromiseConstructor */,
1439
- id,
1440
- resolver,
1441
- NIL,
1442
- NIL,
1443
- NIL,
1444
- NIL,
1445
- NIL,
1446
- parseSpecialReference(ctx, 1 /* PromiseConstructor */),
1447
- NIL,
1448
- NIL,
1449
- NIL
1450
- );
1451
- }
1452
- function createArrayBufferNode(ctx, id, current) {
1453
- const bytes = new Uint8Array(current);
1454
- let result = "";
1455
- for (let i = 0, len = bytes.length; i < len; i++) {
1456
- result += String.fromCharCode(bytes[i]);
1457
- }
1458
- return createSerovalNode(
1459
- 19 /* ArrayBuffer */,
1460
- id,
1461
- serializeString(btoa(result)),
1462
- NIL,
1463
- NIL,
1464
- NIL,
1465
- NIL,
1466
- NIL,
1467
- parseSpecialReference(ctx, 5 /* ArrayBufferConstructor */),
1468
- NIL,
1469
- NIL,
1470
- NIL
1471
- );
1472
- }
1473
-
1474
- // src/core/context/async-parser.ts
1475
- function createAsyncParserContext(mode, options) {
1476
- return {
1477
- base: createBaseParserContext(mode, options),
1478
- child: void 0
1479
- };
1480
- }
1481
- var AsyncParsePluginContext = class {
1482
- constructor(_p, depth) {
1483
- this._p = _p;
1484
- this.depth = depth;
1485
- }
1486
- parse(current) {
1487
- return parseAsync(this._p, this.depth, current);
1488
- }
1489
- };
1490
- async function parseItems(ctx, depth, current) {
1491
- const nodes = [];
1492
- for (let i = 0, len = current.length; i < len; i++) {
1493
- if (i in current) {
1494
- nodes[i] = await parseAsync(ctx, depth, current[i]);
1495
- } else {
1496
- nodes[i] = 0;
1497
- }
1498
- }
1499
- return nodes;
1500
- }
1501
- async function parseArray(ctx, depth, id, current) {
1502
- return createArrayNode(id, current, await parseItems(ctx, depth, current));
1503
- }
1504
- async function parseProperties(ctx, depth, properties) {
1505
- const entries = Object.entries(properties);
1506
- const keyNodes = [];
1507
- const valueNodes = [];
1508
- for (let i = 0, len = entries.length; i < len; i++) {
1509
- keyNodes.push(serializeString(entries[i][0]));
1510
- valueNodes.push(await parseAsync(ctx, depth, entries[i][1]));
1511
- }
1512
- if (SYM_ITERATOR in properties) {
1513
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
1514
- valueNodes.push(
1515
- createIteratorFactoryInstanceNode(
1516
- parseIteratorFactory(ctx.base),
1517
- await parseAsync(
1518
- ctx,
1519
- depth,
1520
- createSequenceFromIterable(
1521
- properties
1522
- )
1523
- )
1524
- )
1525
- );
1526
- }
1527
- if (SYM_ASYNC_ITERATOR in properties) {
1528
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
1529
- valueNodes.push(
1530
- createAsyncIteratorFactoryInstanceNode(
1531
- parseAsyncIteratorFactory(ctx.base),
1532
- await parseAsync(
1533
- ctx,
1534
- depth,
1535
- createStreamFromAsyncIterable(
1536
- properties
1537
- )
1538
- )
1539
- )
1540
- );
1541
- }
1542
- if (SYM_TO_STRING_TAG in properties) {
1543
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
1544
- valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
1545
- }
1546
- if (SYM_IS_CONCAT_SPREADABLE in properties) {
1547
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
1548
- valueNodes.push(
1549
- properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE
1550
- );
1551
- }
1552
- return {
1553
- k: keyNodes,
1554
- v: valueNodes
1555
- };
1556
- }
1557
- async function parsePlainObject(ctx, depth, id, current, empty) {
1558
- return createObjectNode(
1559
- id,
1560
- current,
1561
- empty,
1562
- await parseProperties(ctx, depth, current)
1563
- );
1564
- }
1565
- async function parseBoxed(ctx, depth, id, current) {
1566
- return createBoxedNode(id, await parseAsync(ctx, depth, current.valueOf()));
1567
- }
1568
- async function parseTypedArray(ctx, depth, id, current) {
1569
- return createTypedArrayNode(
1570
- id,
1571
- current,
1572
- await parseAsync(ctx, depth, current.buffer)
1573
- );
1574
- }
1575
- async function parseBigIntTypedArray(ctx, depth, id, current) {
1576
- return createBigIntTypedArrayNode(
1577
- id,
1578
- current,
1579
- await parseAsync(ctx, depth, current.buffer)
1580
- );
1581
- }
1582
- async function parseDataView(ctx, depth, id, current) {
1583
- return createDataViewNode(
1584
- id,
1585
- current,
1586
- await parseAsync(ctx, depth, current.buffer)
1587
- );
1588
- }
1589
- async function parseError(ctx, depth, id, current) {
1590
- const options = getErrorOptions(current, ctx.base.features);
1591
- return createErrorNode(
1592
- id,
1593
- current,
1594
- options ? await parseProperties(ctx, depth, options) : NIL
1595
- );
1596
- }
1597
- async function parseAggregateError(ctx, depth, id, current) {
1598
- const options = getErrorOptions(current, ctx.base.features);
1599
- return createAggregateErrorNode(
1600
- id,
1601
- current,
1602
- options ? await parseProperties(ctx, depth, options) : NIL
1603
- );
1604
- }
1605
- async function parseMap(ctx, depth, id, current) {
1606
- const keyNodes = [];
1607
- const valueNodes = [];
1608
- for (const [key, value] of current.entries()) {
1609
- keyNodes.push(await parseAsync(ctx, depth, key));
1610
- valueNodes.push(await parseAsync(ctx, depth, value));
1611
- }
1612
- return createMapNode(ctx.base, id, keyNodes, valueNodes);
1613
- }
1614
- async function parseSet(ctx, depth, id, current) {
1615
- const items = [];
1616
- for (const item of current.keys()) {
1617
- items.push(await parseAsync(ctx, depth, item));
1618
- }
1619
- return createSetNode(id, items);
1620
- }
1621
- async function parsePlugin(ctx, depth, id, current) {
1622
- const currentPlugins = ctx.base.plugins;
1623
- if (currentPlugins) {
1624
- for (let i = 0, len = currentPlugins.length; i < len; i++) {
1625
- const plugin = currentPlugins[i];
1626
- if (plugin.parse.async && plugin.test(current)) {
1627
- return createPluginNode(
1628
- id,
1629
- plugin.tag,
1630
- await plugin.parse.async(
1631
- current,
1632
- new AsyncParsePluginContext(ctx, depth),
1633
- {
1634
- id
1635
- }
1636
- )
1637
- );
1638
- }
1639
- }
1640
- }
1641
- return NIL;
1642
- }
1643
- async function parsePromise(ctx, depth, id, current) {
1644
- const [status, result] = await promiseToResult(current);
1645
- return createSerovalNode(
1646
- 12 /* Promise */,
1647
- id,
1648
- status,
1649
- NIL,
1650
- NIL,
1651
- NIL,
1652
- NIL,
1653
- NIL,
1654
- await parseAsync(ctx, depth, result),
1655
- NIL,
1656
- NIL,
1657
- NIL
1658
- );
1659
- }
1660
- function parseStreamHandle(depth, id, current, resolve, reject) {
1661
- const sequence = [];
1662
- const cleanup = current.on({
1663
- next: (value) => {
1664
- markParserRef(this.base, id);
1665
- parseAsync(this, depth, value).then(
1666
- (data) => {
1667
- sequence.push(createStreamNextNode(id, data));
1668
- },
1669
- (data) => {
1670
- reject(data);
1671
- cleanup();
1672
- }
1673
- );
1674
- },
1675
- throw: (value) => {
1676
- markParserRef(this.base, id);
1677
- parseAsync(this, depth, value).then(
1678
- (data) => {
1679
- sequence.push(createStreamThrowNode(id, data));
1680
- resolve(sequence);
1681
- cleanup();
1682
- },
1683
- (data) => {
1684
- reject(data);
1685
- cleanup();
1686
- }
1687
- );
1688
- },
1689
- return: (value) => {
1690
- markParserRef(this.base, id);
1691
- parseAsync(this, depth, value).then(
1692
- (data) => {
1693
- sequence.push(createStreamReturnNode(id, data));
1694
- resolve(sequence);
1695
- cleanup();
1696
- },
1697
- (data) => {
1698
- reject(data);
1699
- cleanup();
1700
- }
1701
- );
1702
- }
1703
- });
1704
- }
1705
- async function parseStream(ctx, depth, id, current) {
1706
- return createStreamConstructorNode(
1707
- id,
1708
- parseSpecialReference(ctx.base, 4 /* StreamConstructor */),
1709
- await new Promise(
1710
- parseStreamHandle.bind(ctx, depth, id, current)
1711
- )
1712
- );
1713
- }
1714
- async function parseSequence(ctx, depth, id, current) {
1715
- const nodes = [];
1716
- for (let i = 0, len = current.v.length; i < len; i++) {
1717
- nodes[i] = await parseAsync(ctx, depth, current.v[i]);
1718
- }
1719
- return createSequenceNode(id, nodes, current.t, current.d);
1720
- }
1721
- async function parseObjectAsync(ctx, depth, id, current) {
1722
- if (Array.isArray(current)) {
1723
- return parseArray(ctx, depth, id, current);
1724
- }
1725
- if (isStream(current)) {
1726
- return parseStream(ctx, depth, id, current);
1727
- }
1728
- if (isSequence(current)) {
1729
- return parseSequence(ctx, depth, id, current);
1730
- }
1731
- const currentClass = current.constructor;
1732
- if (currentClass === OpaqueReference) {
1733
- return parseAsync(
1734
- ctx,
1735
- depth,
1736
- current.replacement
1737
- );
1738
- }
1739
- const parsed = await parsePlugin(ctx, depth, id, current);
1740
- if (parsed) {
1741
- return parsed;
1742
- }
1743
- switch (currentClass) {
1744
- case Object:
1745
- return parsePlainObject(
1746
- ctx,
1747
- depth,
1748
- id,
1749
- current,
1750
- false
1751
- );
1752
- case NIL:
1753
- return parsePlainObject(
1754
- ctx,
1755
- depth,
1756
- id,
1757
- current,
1758
- true
1759
- );
1760
- case Date:
1761
- return createDateNode(id, current);
1762
- case Error:
1763
- case EvalError:
1764
- case RangeError:
1765
- case ReferenceError:
1766
- case SyntaxError:
1767
- case TypeError:
1768
- case URIError:
1769
- return parseError(ctx, depth, id, current);
1770
- case Number:
1771
- case Boolean:
1772
- case String:
1773
- case BigInt:
1774
- return parseBoxed(ctx, depth, id, current);
1775
- case ArrayBuffer:
1776
- return createArrayBufferNode(
1777
- ctx.base,
1778
- id,
1779
- current
1780
- );
1781
- case Int8Array:
1782
- case Int16Array:
1783
- case Int32Array:
1784
- case Uint8Array:
1785
- case Uint16Array:
1786
- case Uint32Array:
1787
- case Uint8ClampedArray:
1788
- case Float32Array:
1789
- case Float64Array:
1790
- return parseTypedArray(
1791
- ctx,
1792
- depth,
1793
- id,
1794
- current
1795
- );
1796
- case DataView:
1797
- return parseDataView(ctx, depth, id, current);
1798
- case Map:
1799
- return parseMap(
1800
- ctx,
1801
- depth,
1802
- id,
1803
- current
1804
- );
1805
- case Set:
1806
- return parseSet(ctx, depth, id, current);
1807
- default:
1808
- break;
1809
- }
1810
- if (currentClass === Promise || current instanceof Promise) {
1811
- return parsePromise(ctx, depth, id, current);
1812
- }
1813
- const currentFeatures = ctx.base.features;
1814
- if (currentFeatures & 32 /* RegExp */ && currentClass === RegExp) {
1815
- return createRegExpNode(id, current);
1816
- }
1817
- if (currentFeatures & 16 /* BigIntTypedArray */) {
1818
- switch (currentClass) {
1819
- case BigInt64Array:
1820
- case BigUint64Array:
1821
- return parseBigIntTypedArray(
1822
- ctx,
1823
- depth,
1824
- id,
1825
- current
1826
- );
1827
- default:
1828
- break;
1829
- }
1830
- }
1831
- if (currentFeatures & 1 /* AggregateError */ && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) {
1832
- return parseAggregateError(
1833
- ctx,
1834
- depth,
1835
- id,
1836
- current
1837
- );
1838
- }
1839
- if (current instanceof Error) {
1840
- return parseError(ctx, depth, id, current);
1841
- }
1842
- if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) {
1843
- return parsePlainObject(ctx, depth, id, current, !!currentClass);
1844
- }
1845
- throw new SerovalUnsupportedTypeError(current);
1846
- }
1847
- async function parseFunctionAsync(ctx, depth, current) {
1848
- const ref = getReferenceNode(ctx.base, current);
1849
- if (ref.type !== 0 /* Fresh */) {
1850
- return ref.value;
1851
- }
1852
- const plugin = await parsePlugin(ctx, depth, ref.value, current);
1853
- if (plugin) {
1854
- return plugin;
1855
- }
1856
- throw new SerovalUnsupportedTypeError(current);
1857
- }
1858
- async function parseAsync(ctx, depth, current) {
1859
- switch (typeof current) {
1860
- case "boolean":
1861
- return current ? TRUE_NODE : FALSE_NODE;
1862
- case "undefined":
1863
- return UNDEFINED_NODE;
1864
- case "string":
1865
- return createStringNode(current);
1866
- case "number":
1867
- return createNumberNode(current);
1868
- case "bigint":
1869
- return createBigIntNode(current);
1870
- case "object": {
1871
- if (current) {
1872
- const ref = getReferenceNode(ctx.base, current);
1873
- return ref.type === 0 ? await parseObjectAsync(ctx, depth + 1, ref.value, current) : ref.value;
1874
- }
1875
- return NULL_NODE;
1876
- }
1877
- case "symbol":
1878
- return parseWellKnownSymbol(ctx.base, current);
1879
- case "function":
1880
- return parseFunctionAsync(ctx, depth, current);
1881
- default:
1882
- throw new SerovalUnsupportedTypeError(current);
1883
- }
1884
- }
1885
- async function parseTopAsync(ctx, current) {
1886
- try {
1887
- return await parseAsync(ctx, 0, current);
1888
- } catch (error) {
1889
- throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
1890
- }
1891
- }
1892
-
1893
- // src/core/plugin.ts
1894
- var SerovalMode = /* @__PURE__ */ ((SerovalMode2) => {
1895
- SerovalMode2[SerovalMode2["Vanilla"] = 1] = "Vanilla";
1896
- SerovalMode2[SerovalMode2["Cross"] = 2] = "Cross";
1897
- return SerovalMode2;
1898
- })(SerovalMode || {});
1899
- function createPlugin(plugin) {
1900
- return plugin;
1901
- }
1902
- function dedupePlugins(deduped, plugins) {
1903
- for (let i = 0, len = plugins.length; i < len; i++) {
1904
- const current = plugins[i];
1905
- if (!deduped.has(current)) {
1906
- deduped.add(current);
1907
- if (current.extends) {
1908
- dedupePlugins(deduped, current.extends);
1909
- }
1910
- }
1911
- }
1912
- }
1913
- function resolvePlugins(plugins) {
1914
- if (plugins) {
1915
- const deduped = /* @__PURE__ */ new Set();
1916
- dedupePlugins(deduped, plugins);
1917
- return [...deduped];
1918
- }
1919
- return void 0;
1920
- }
1921
-
1922
- // src/core/utils/typed-array.ts
1923
- function getTypedArrayConstructor(name) {
1924
- switch (name) {
1925
- case "Int8Array":
1926
- return Int8Array;
1927
- case "Int16Array":
1928
- return Int16Array;
1929
- case "Int32Array":
1930
- return Int32Array;
1931
- case "Uint8Array":
1932
- return Uint8Array;
1933
- case "Uint16Array":
1934
- return Uint16Array;
1935
- case "Uint32Array":
1936
- return Uint32Array;
1937
- case "Uint8ClampedArray":
1938
- return Uint8ClampedArray;
1939
- case "Float32Array":
1940
- return Float32Array;
1941
- case "Float64Array":
1942
- return Float64Array;
1943
- case "BigInt64Array":
1944
- return BigInt64Array;
1945
- case "BigUint64Array":
1946
- return BigUint64Array;
1947
- default:
1948
- throw new SerovalUnknownTypedArrayError(name);
1949
- }
1950
- }
1951
-
1952
- // src/core/utils/valid-properties.ts
1953
- function isValidKey(key) {
1954
- switch (key) {
1955
- case "constructor":
1956
- case "__proto__":
1957
- case "prototype":
1958
- case "__defineGetter__":
1959
- case "__defineSetter__":
1960
- case "__lookupGetter__":
1961
- case "__lookupSetter__":
1962
- return false;
1963
- default:
1964
- return true;
1965
- }
1966
- }
1967
- function isValidSymbol(symbol) {
1968
- switch (symbol) {
1969
- case SYM_ASYNC_ITERATOR:
1970
- case SYM_IS_CONCAT_SPREADABLE:
1971
- case SYM_TO_STRING_TAG:
1972
- case SYM_ITERATOR:
1973
- return true;
1974
- default:
1975
- return false;
1976
- }
1977
- }
1978
-
1979
- // src/core/context/deserializer.ts
1980
- var MAX_BASE64_LENGTH = 1e6;
1981
- var MAX_BIGINT_LENGTH = 1e4;
1982
- var MAX_REGEXP_SOURCE_LENGTH = 2e4;
1983
- function applyObjectFlag(obj, flag) {
1984
- switch (flag) {
1985
- case 3 /* Frozen */:
1986
- return Object.freeze(obj);
1987
- case 1 /* NonExtensible */:
1988
- return Object.preventExtensions(obj);
1989
- case 2 /* Sealed */:
1990
- return Object.seal(obj);
1991
- default:
1992
- return obj;
1993
- }
1994
- }
1995
- var DEFAULT_DEPTH_LIMIT = 1e3;
1996
- function createBaseDeserializerContext(mode, options) {
1997
- var _a;
1998
- const refs = options.refs || /* @__PURE__ */ new Map();
1999
- if (!("types" in refs)) {
2000
- Object.assign(refs, {
2001
- types: /* @__PURE__ */ new Map()
2002
- });
2003
- }
2004
- return {
2005
- mode,
2006
- plugins: options.plugins,
2007
- refs,
2008
- features: (_a = options.features) != null ? _a : ALL_ENABLED ^ (options.disabledFeatures || 0),
2009
- depthLimit: options.depthLimit || DEFAULT_DEPTH_LIMIT
2010
- };
2011
- }
2012
- function createVanillaDeserializerContext(options) {
2013
- return {
2014
- mode: 1 /* Vanilla */,
2015
- base: createBaseDeserializerContext(1 /* Vanilla */, options),
2016
- child: NIL,
2017
- state: {
2018
- marked: new Set(options.markedRefs)
2019
- }
2020
- };
2021
- }
2022
- function createCrossDeserializerContext(options) {
2023
- return {
2024
- mode: 2 /* Cross */,
2025
- base: createBaseDeserializerContext(2 /* Cross */, options),
2026
- child: NIL
2027
- };
2028
- }
2029
- var DeserializePluginContext = class {
2030
- constructor(_p, depth) {
2031
- this._p = _p;
2032
- this.depth = depth;
2033
- }
2034
- deserialize(node) {
2035
- return deserialize(this._p, this.depth, node);
2036
- }
2037
- };
2038
- function guardIndexedValue(ctx, id) {
2039
- if (id < 0 || !Number.isFinite(id) || !Number.isInteger(id)) {
2040
- throw new SerovalMalformedNodeError({
2041
- t: 4 /* IndexedValue */,
2042
- i: id
2043
- });
2044
- }
2045
- if (ctx.refs.has(id)) {
2046
- throw new Error("Conflicted ref id: " + id);
2047
- }
2048
- }
2049
- function assignIndexedValueVanilla(ctx, id, value) {
2050
- guardIndexedValue(ctx.base, id);
2051
- if (ctx.state.marked.has(id)) {
2052
- ctx.base.refs.set(id, value);
2053
- }
2054
- return value;
2055
- }
2056
- function assignIndexedValueCross(ctx, id, value) {
2057
- guardIndexedValue(ctx.base, id);
2058
- ctx.base.refs.set(id, value);
2059
- return value;
2060
- }
2061
- function assignIndexedValue(ctx, id, value) {
2062
- return ctx.mode === 1 /* Vanilla */ ? assignIndexedValueVanilla(ctx, id, value) : assignIndexedValueCross(ctx, id, value);
2063
- }
2064
- function deserializeKnownValue(node, record, key) {
2065
- if (Object.hasOwn(record, key)) {
2066
- return record[key];
2067
- }
2068
- throw new SerovalMalformedNodeError(node);
2069
- }
2070
- function deserializeReference(ctx, node) {
2071
- return assignIndexedValue(
2072
- ctx,
2073
- node.i,
2074
- getReference(deserializeString(node.s))
2075
- );
2076
- }
2077
- function deserializeArray(ctx, depth, node) {
2078
- const items = node.a;
2079
- const len = items.length;
2080
- const result = assignIndexedValue(
2081
- ctx,
2082
- node.i,
2083
- new Array(len)
2084
- );
2085
- for (let i = 0, item; i < len; i++) {
2086
- item = items[i];
2087
- if (item) {
2088
- result[i] = deserialize(ctx, depth, item);
2089
- }
2090
- }
2091
- applyObjectFlag(result, node.o);
2092
- return result;
2093
- }
2094
- function assignStringProperty(object, key, value) {
2095
- if (isValidKey(key)) {
2096
- object[key] = value;
2097
- } else {
2098
- Object.defineProperty(object, key, {
2099
- value,
2100
- configurable: true,
2101
- enumerable: true,
2102
- writable: true
2103
- });
2104
- }
2105
- }
2106
- function assignProperty(ctx, depth, object, key, value) {
2107
- if (typeof key === "string") {
2108
- assignStringProperty(
2109
- object,
2110
- deserializeString(key),
2111
- deserialize(ctx, depth, value)
2112
- );
2113
- } else {
2114
- const actual = deserialize(ctx, depth, key);
2115
- switch (typeof actual) {
2116
- case "string":
2117
- assignStringProperty(object, actual, deserialize(ctx, depth, value));
2118
- break;
2119
- case "symbol":
2120
- if (isValidSymbol(actual)) {
2121
- object[actual] = deserialize(ctx, depth, value);
2122
- }
2123
- break;
2124
- default:
2125
- throw new SerovalMalformedNodeError(key);
2126
- }
2127
- }
2128
- }
2129
- function assignNodeType(ctx, id, type) {
2130
- ctx.base.refs.types.set(id, type);
2131
- }
2132
- function validateNodeType(ctx, node, id, type) {
2133
- if (ctx.base.refs.types.get(id) !== type) {
2134
- throw new SerovalMalformedNodeError(node);
2135
- }
2136
- }
2137
- function deserializeProperties(ctx, depth, node, result) {
2138
- const keys = node.k;
2139
- const len = keys.length;
2140
- if (len > 0) {
2141
- for (let i = 0, vals = node.v, len2 = keys.length; i < len2; i++) {
2142
- assignProperty(ctx, depth, result, keys[i], vals[i]);
2143
- }
2144
- }
2145
- return result;
2146
- }
2147
- function deserializeObject(ctx, depth, node) {
2148
- const result = assignIndexedValue(
2149
- ctx,
2150
- node.i,
2151
- node.t === 10 /* Object */ ? {} : /* @__PURE__ */ Object.create(null)
2152
- );
2153
- deserializeProperties(ctx, depth, node.p, result);
2154
- applyObjectFlag(result, node.o);
2155
- return result;
2156
- }
2157
- function deserializeDate(ctx, node) {
2158
- return assignIndexedValue(ctx, node.i, new Date(node.s));
2159
- }
2160
- function deserializeRegExp(ctx, node) {
2161
- if (ctx.base.features & 32 /* RegExp */) {
2162
- const source = deserializeString(node.c);
2163
- if (source.length > MAX_REGEXP_SOURCE_LENGTH) {
2164
- throw new SerovalMalformedNodeError(node);
2165
- }
2166
- return assignIndexedValue(ctx, node.i, new RegExp(source, node.m));
2167
- }
2168
- throw new SerovalUnsupportedNodeError(node);
2169
- }
2170
- function deserializeSet(ctx, depth, node) {
2171
- const result = assignIndexedValue(ctx, node.i, /* @__PURE__ */ new Set());
2172
- for (let i = 0, items = node.a, len = items.length; i < len; i++) {
2173
- result.add(deserialize(ctx, depth, items[i]));
2174
- }
2175
- return result;
2176
- }
2177
- function deserializeMap(ctx, depth, node) {
2178
- const result = assignIndexedValue(ctx, node.i, /* @__PURE__ */ new Map());
2179
- for (let i = 0, keys = node.e.k, vals = node.e.v, len = keys.length; i < len; i++) {
2180
- result.set(
2181
- deserialize(ctx, depth, keys[i]),
2182
- deserialize(ctx, depth, vals[i])
2183
- );
2184
- }
2185
- return result;
2186
- }
2187
- function deserializeArrayBuffer(ctx, node) {
2188
- if (node.s.length > MAX_BASE64_LENGTH) {
2189
- throw new SerovalMalformedNodeError(node);
2190
- }
2191
- const result = assignIndexedValue(
2192
- ctx,
2193
- node.i,
2194
- ARRAY_BUFFER_CONSTRUCTOR(deserializeString(node.s))
2195
- );
2196
- return result;
2197
- }
2198
- function deserializeTypedArray(ctx, depth, node) {
2199
- var _a;
2200
- const construct = getTypedArrayConstructor(node.c);
2201
- const source = deserialize(ctx, depth, node.f);
2202
- const offset = (_a = node.b) != null ? _a : 0;
2203
- if (offset < 0 || offset > source.byteLength) {
2204
- throw new SerovalMalformedNodeError(node);
2205
- }
2206
- const result = assignIndexedValue(
2207
- ctx,
2208
- node.i,
2209
- new construct(source, offset, node.l)
2210
- );
2211
- return result;
2212
- }
2213
- function deserializeDataView(ctx, depth, node) {
2214
- var _a;
2215
- const source = deserialize(ctx, depth, node.f);
2216
- const offset = (_a = node.b) != null ? _a : 0;
2217
- if (offset < 0 || offset > source.byteLength) {
2218
- throw new SerovalMalformedNodeError(node);
2219
- }
2220
- const result = assignIndexedValue(
2221
- ctx,
2222
- node.i,
2223
- new DataView(source, offset, node.l)
2224
- );
2225
- return result;
2226
- }
2227
- function deserializeDictionary(ctx, depth, node, result) {
2228
- if (node.p) {
2229
- const fields = deserializeProperties(ctx, depth, node.p, {});
2230
- Object.defineProperties(result, Object.getOwnPropertyDescriptors(fields));
2231
- }
2232
- return result;
2233
- }
2234
- function deserializeAggregateError(ctx, depth, node) {
2235
- const result = assignIndexedValue(
2236
- ctx,
2237
- node.i,
2238
- new AggregateError([], deserializeString(node.m))
2239
- );
2240
- return deserializeDictionary(ctx, depth, node, result);
2241
- }
2242
- function deserializeError(ctx, depth, node) {
2243
- const construct = deserializeKnownValue(node, ERROR_CONSTRUCTOR, node.s);
2244
- const result = assignIndexedValue(
2245
- ctx,
2246
- node.i,
2247
- new construct(deserializeString(node.m))
2248
- );
2249
- return deserializeDictionary(ctx, depth, node, result);
2250
- }
2251
- function deserializePromise(ctx, depth, node) {
2252
- const deferred = PROMISE_CONSTRUCTOR();
2253
- const result = assignIndexedValue(ctx, node.i, deferred.p);
2254
- const deserialized = deserialize(ctx, depth, node.f);
2255
- if (node.s) {
2256
- deferred.s(deserialized);
2257
- } else {
2258
- deferred.f(deserialized);
2259
- }
2260
- return result;
2261
- }
2262
- function deserializeBoxed(ctx, depth, node) {
2263
- return assignIndexedValue(
2264
- ctx,
2265
- node.i,
2266
- // biome-ignore lint/style/useConsistentBuiltinInstantiation: intended
2267
- Object(deserialize(ctx, depth, node.f))
2268
- );
2269
- }
2270
- function deserializePlugin(ctx, depth, node) {
2271
- const currentPlugins = ctx.base.plugins;
2272
- if (currentPlugins) {
2273
- const tag = deserializeString(node.c);
2274
- for (let i = 0, len = currentPlugins.length; i < len; i++) {
2275
- const plugin = currentPlugins[i];
2276
- if (plugin.tag === tag) {
2277
- return assignIndexedValue(
2278
- ctx,
2279
- node.i,
2280
- plugin.deserialize(node.s, new DeserializePluginContext(ctx, depth), {
2281
- id: node.i
2282
- })
2283
- );
2284
- }
2285
- }
2286
- }
2287
- throw new SerovalMissingPluginError(node.c);
2288
- }
2289
- function deserializePromiseConstructor(ctx, node) {
2290
- const value = assignIndexedValue(
2291
- ctx,
2292
- node.i,
2293
- assignIndexedValue(ctx, node.s, PROMISE_CONSTRUCTOR()).p
2294
- );
2295
- assignNodeType(ctx, node.s, 22 /* PromiseConstructor */);
2296
- return value;
2297
- }
2298
- function deserializePromiseResolve(ctx, depth, node) {
2299
- const deferred = ctx.base.refs.get(node.i);
2300
- if (deferred) {
2301
- validateNodeType(ctx, node, node.i, 22 /* PromiseConstructor */);
2302
- deferred.s(deserialize(ctx, depth, node.a[1]));
2303
- return NIL;
2304
- }
2305
- throw new SerovalMissingInstanceError("Promise");
2306
- }
2307
- function deserializePromiseReject(ctx, depth, node) {
2308
- const deferred = ctx.base.refs.get(node.i);
2309
- if (deferred) {
2310
- validateNodeType(ctx, node, node.i, 22 /* PromiseConstructor */);
2311
- deferred.f(deserialize(ctx, depth, node.a[1]));
2312
- return NIL;
2313
- }
2314
- throw new SerovalMissingInstanceError("Promise");
2315
- }
2316
- function deserializeIteratorFactoryInstance(ctx, depth, node) {
2317
- deserialize(ctx, depth, node.a[0]);
2318
- const source = deserialize(ctx, depth, node.a[1]);
2319
- return sequenceToIterator(source);
2320
- }
2321
- function deserializeAsyncIteratorFactoryInstance(ctx, depth, node) {
2322
- deserialize(ctx, depth, node.a[0]);
2323
- const source = deserialize(ctx, depth, node.a[1]);
2324
- return streamToAsyncIterable(source);
2325
- }
2326
- function deserializeStreamConstructor(ctx, depth, node) {
2327
- const result = assignIndexedValue(ctx, node.i, createStream());
2328
- assignNodeType(ctx, node.i, 31 /* StreamConstructor */);
2329
- const items = node.a;
2330
- const len = items.length;
2331
- if (len) {
2332
- for (let i = 0; i < len; i++) {
2333
- deserialize(ctx, depth, items[i]);
2334
- }
2335
- }
2336
- return result;
2337
- }
2338
- function deserializeStreamNext(ctx, depth, node) {
2339
- const deferred = ctx.base.refs.get(node.i);
2340
- if (deferred) {
2341
- validateNodeType(ctx, node, node.i, 31 /* StreamConstructor */);
2342
- deferred.next(deserialize(ctx, depth, node.f));
2343
- return NIL;
2344
- }
2345
- throw new SerovalMissingInstanceError("Stream");
2346
- }
2347
- function deserializeStreamThrow(ctx, depth, node) {
2348
- const deferred = ctx.base.refs.get(node.i);
2349
- if (deferred) {
2350
- validateNodeType(ctx, node, node.i, 31 /* StreamConstructor */);
2351
- deferred.throw(deserialize(ctx, depth, node.f));
2352
- return NIL;
2353
- }
2354
- throw new SerovalMissingInstanceError("Stream");
2355
- }
2356
- function deserializeStreamReturn(ctx, depth, node) {
2357
- const deferred = ctx.base.refs.get(node.i);
2358
- if (deferred) {
2359
- validateNodeType(ctx, node, node.i, 31 /* StreamConstructor */);
2360
- deferred.return(deserialize(ctx, depth, node.f));
2361
- return NIL;
2362
- }
2363
- throw new SerovalMissingInstanceError("Stream");
2364
- }
2365
- function deserializeIteratorFactory(ctx, depth, node) {
2366
- deserialize(ctx, depth, node.f);
2367
- return NIL;
2368
- }
2369
- function deserializeAsyncIteratorFactory(ctx, depth, node) {
2370
- deserialize(ctx, depth, node.a[1]);
2371
- return NIL;
2372
- }
2373
- function deserializeSequence(ctx, depth, node) {
2374
- const result = assignIndexedValue(
2375
- ctx,
2376
- node.i,
2377
- createSequence([], node.s, node.l)
2378
- );
2379
- for (let i = 0, len = node.a.length; i < len; i++) {
2380
- result.v[i] = deserialize(ctx, depth, node.a[i]);
2381
- }
2382
- return result;
2383
- }
2384
- function deserialize(ctx, depth, node) {
2385
- if (depth > ctx.base.depthLimit) {
2386
- throw new SerovalDepthLimitError(ctx.base.depthLimit);
2387
- }
2388
- depth += 1;
2389
- switch (node.t) {
2390
- case 2 /* Constant */:
2391
- return deserializeKnownValue(node, CONSTANT_VAL, node.s);
2392
- case 0 /* Number */:
2393
- return Number(node.s);
2394
- case 1 /* String */:
2395
- return deserializeString(String(node.s));
2396
- case 3 /* BigInt */:
2397
- if (String(node.s).length > MAX_BIGINT_LENGTH) {
2398
- throw new SerovalMalformedNodeError(node);
2399
- }
2400
- return BigInt(node.s);
2401
- case 4 /* IndexedValue */:
2402
- return ctx.base.refs.get(node.i);
2403
- case 18 /* Reference */:
2404
- return deserializeReference(ctx, node);
2405
- case 9 /* Array */:
2406
- return deserializeArray(ctx, depth, node);
2407
- case 10 /* Object */:
2408
- case 11 /* NullConstructor */:
2409
- return deserializeObject(ctx, depth, node);
2410
- case 5 /* Date */:
2411
- return deserializeDate(ctx, node);
2412
- case 6 /* RegExp */:
2413
- return deserializeRegExp(ctx, node);
2414
- case 7 /* Set */:
2415
- return deserializeSet(ctx, depth, node);
2416
- case 8 /* Map */:
2417
- return deserializeMap(ctx, depth, node);
2418
- case 19 /* ArrayBuffer */:
2419
- return deserializeArrayBuffer(ctx, node);
2420
- case 16 /* BigIntTypedArray */:
2421
- case 15 /* TypedArray */:
2422
- return deserializeTypedArray(ctx, depth, node);
2423
- case 20 /* DataView */:
2424
- return deserializeDataView(ctx, depth, node);
2425
- case 14 /* AggregateError */:
2426
- return deserializeAggregateError(ctx, depth, node);
2427
- case 13 /* Error */:
2428
- return deserializeError(ctx, depth, node);
2429
- case 12 /* Promise */:
2430
- return deserializePromise(ctx, depth, node);
2431
- case 17 /* WKSymbol */:
2432
- return deserializeKnownValue(node, SYMBOL_REF, node.s);
2433
- case 21 /* Boxed */:
2434
- return deserializeBoxed(ctx, depth, node);
2435
- case 25 /* Plugin */:
2436
- return deserializePlugin(ctx, depth, node);
2437
- case 22 /* PromiseConstructor */:
2438
- return deserializePromiseConstructor(ctx, node);
2439
- case 23 /* PromiseSuccess */:
2440
- return deserializePromiseResolve(ctx, depth, node);
2441
- case 24 /* PromiseFailure */:
2442
- return deserializePromiseReject(ctx, depth, node);
2443
- case 28 /* IteratorFactoryInstance */:
2444
- return deserializeIteratorFactoryInstance(ctx, depth, node);
2445
- case 30 /* AsyncIteratorFactoryInstance */:
2446
- return deserializeAsyncIteratorFactoryInstance(ctx, depth, node);
2447
- case 31 /* StreamConstructor */:
2448
- return deserializeStreamConstructor(ctx, depth, node);
2449
- case 32 /* StreamNext */:
2450
- return deserializeStreamNext(ctx, depth, node);
2451
- case 33 /* StreamThrow */:
2452
- return deserializeStreamThrow(ctx, depth, node);
2453
- case 34 /* StreamReturn */:
2454
- return deserializeStreamReturn(ctx, depth, node);
2455
- case 27 /* IteratorFactory */:
2456
- return deserializeIteratorFactory(ctx, depth, node);
2457
- case 29 /* AsyncIteratorFactory */:
2458
- return deserializeAsyncIteratorFactory(ctx, depth, node);
2459
- // case SerovalNodeType.SpecialReference:
2460
- case 35 /* Sequence */:
2461
- return deserializeSequence(ctx, depth, node);
2462
- default:
2463
- throw new SerovalUnsupportedNodeError(node);
2464
- }
2465
- }
2466
- function deserializeTop(ctx, node) {
2467
- try {
2468
- return deserialize(ctx, 0, node);
2469
- } catch (error) {
2470
- throw new SerovalDeserializationError(error);
2471
- }
2472
- }
2473
-
2474
- // src/core/function-string.ts
2475
- var RETURN = () => T;
2476
- var SERIALIZED_RETURN = /* @__PURE__ */ RETURN.toString();
2477
- var IS_MODERN = /* @__PURE__ */ /=>/.test(SERIALIZED_RETURN);
2478
- function createFunction(parameters, body) {
2479
- if (IS_MODERN) {
2480
- const joined = parameters.length === 1 ? parameters[0] : "(" + parameters.join(",") + ")";
2481
- return joined + "=>" + (body.startsWith("{") ? "(" + body + ")" : body);
2482
- }
2483
- return "function(" + parameters.join(",") + "){return " + body + "}";
2484
- }
2485
- function createEffectfulFunction(parameters, body) {
2486
- if (IS_MODERN) {
2487
- const joined = parameters.length === 1 ? parameters[0] : "(" + parameters.join(",") + ")";
2488
- return joined + "=>{" + body + "}";
2489
- }
2490
- return "function(" + parameters.join(",") + "){" + body + "}";
2491
- }
2492
-
2493
- // src/core/utils/get-identifier.ts
2494
- var REF_START_CHARS = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_";
2495
- var REF_START_CHARS_LEN = REF_START_CHARS.length;
2496
- var REF_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
2497
- var REF_CHARS_LEN = REF_CHARS.length;
2498
- function getIdentifier(index) {
2499
- let mod = index % REF_START_CHARS_LEN;
2500
- let ref = REF_START_CHARS[mod];
2501
- index = (index - mod) / REF_START_CHARS_LEN;
2502
- while (index > 0) {
2503
- mod = index % REF_CHARS_LEN;
2504
- ref += REF_CHARS[mod];
2505
- index = (index - mod) / REF_CHARS_LEN;
2506
- }
2507
- return ref;
2508
- }
2509
-
2510
- // src/core/utils/is-valid-identifier.ts
2511
- var IDENTIFIER_CHECK = /^[$A-Z_][0-9A-Z_$]*$/i;
2512
- function isValidIdentifier(name) {
2513
- const char = name[0];
2514
- return (char === "$" || char === "_" || char >= "A" && char <= "Z" || char >= "a" && char <= "z") && IDENTIFIER_CHECK.test(name);
2515
- }
2516
-
2517
- // src/core/context/serializer.ts
2518
- function getAssignmentExpression(assignment) {
2519
- switch (assignment.t) {
2520
- case 0 /* Index */:
2521
- return assignment.s + "=" + assignment.v;
2522
- case 2 /* Set */:
2523
- return assignment.s + ".set(" + assignment.k + "," + assignment.v + ")";
2524
- case 1 /* Add */:
2525
- return assignment.s + ".add(" + assignment.v + ")";
2526
- case 3 /* Delete */:
2527
- return assignment.s + ".delete(" + assignment.k + ")";
2528
- case 4 /* Define */:
2529
- return "Object.defineProperty(" + assignment.s + ',"__proto__",{value:' + assignment.k + ",configurable:!0,enumerable:!0,writable:!0})";
2530
- }
2531
- }
2532
- function mergeAssignments(assignments) {
2533
- const newAssignments = [];
2534
- let current = assignments[0];
2535
- for (let i = 1, len = assignments.length, item, prev = current; i < len; i++) {
2536
- item = assignments[i];
2537
- if (item.t === 0 /* Index */ && item.v === prev.v) {
2538
- current = {
2539
- t: 0 /* Index */,
2540
- s: item.s,
2541
- k: NIL,
2542
- v: getAssignmentExpression(current)
2543
- };
2544
- } else if (item.t === 2 /* Set */ && item.s === prev.s) {
2545
- current = {
2546
- t: 2 /* Set */,
2547
- s: getAssignmentExpression(current),
2548
- k: item.k,
2549
- v: item.v
2550
- };
2551
- } else if (item.t === 1 /* Add */ && item.s === prev.s) {
2552
- current = {
2553
- t: 1 /* Add */,
2554
- s: getAssignmentExpression(current),
2555
- k: NIL,
2556
- v: item.v
2557
- };
2558
- } else if (item.t === 3 /* Delete */ && item.s === prev.s) {
2559
- current = {
2560
- t: 3 /* Delete */,
2561
- s: getAssignmentExpression(current),
2562
- k: item.k,
2563
- v: NIL
2564
- };
2565
- } else {
2566
- newAssignments.push(current);
2567
- current = item;
2568
- }
2569
- prev = item;
2570
- }
2571
- newAssignments.push(current);
2572
- return newAssignments;
2573
- }
2574
- function resolveAssignments(assignments) {
2575
- if (assignments.length) {
2576
- let result = "";
2577
- const merged = mergeAssignments(assignments);
2578
- for (let i = 0, len = merged.length; i < len; i++) {
2579
- result += getAssignmentExpression(merged[i]) + ",";
2580
- }
2581
- return result;
2582
- }
2583
- return NIL;
2584
- }
2585
- var NULL_CONSTRUCTOR = "Object.create(null)";
2586
- var SET_CONSTRUCTOR = "new Set";
2587
- var MAP_CONSTRUCTOR = "new Map";
2588
- var PROMISE_RESOLVE = "Promise.resolve";
2589
- var PROMISE_REJECT = "Promise.reject";
2590
- var OBJECT_FLAG_CONSTRUCTOR = {
2591
- [3 /* Frozen */]: "Object.freeze",
2592
- [2 /* Sealed */]: "Object.seal",
2593
- [1 /* NonExtensible */]: "Object.preventExtensions",
2594
- [0 /* None */]: NIL
2595
- };
2596
- function createBaseSerializerContext(mode, options) {
2597
- return {
2598
- mode,
2599
- plugins: options.plugins,
2600
- features: options.features,
2601
- marked: new Set(options.markedRefs),
2602
- stack: [],
2603
- flags: [],
2604
- assignments: []
2605
- };
2606
- }
2607
- function createVanillaSerializerState() {
2608
- return {
2609
- valid: /* @__PURE__ */ new Map(),
2610
- vars: []
2611
- };
2612
- }
2613
- function createVanillaSerializerContext(options) {
2614
- return {
2615
- mode: 1 /* Vanilla */,
2616
- base: createBaseSerializerContext(1 /* Vanilla */, options),
2617
- state: createVanillaSerializerState(),
2618
- child: NIL
2619
- };
2620
- }
2621
- function createCrossSerializerContext(options) {
2622
- return {
2623
- mode: 2 /* Cross */,
2624
- base: createBaseSerializerContext(2 /* Cross */, options),
2625
- state: options,
2626
- child: NIL
2627
- };
2628
- }
2629
- var SerializePluginContext = class {
2630
- constructor(_p) {
2631
- this._p = _p;
2632
- }
2633
- serialize(node) {
2634
- return serialize(this._p, node);
2635
- }
2636
- };
2637
- function getVanillaRefParam(state, index) {
2638
- let actualIndex = state.valid.get(index);
2639
- if (actualIndex == null) {
2640
- actualIndex = state.valid.size;
2641
- state.valid.set(index, actualIndex);
2642
- }
2643
- let identifier = state.vars[actualIndex];
2644
- if (identifier == null) {
2645
- identifier = getIdentifier(actualIndex);
2646
- state.vars[actualIndex] = identifier;
2647
- }
2648
- return identifier;
2649
- }
2650
- function getCrossRefParam(id) {
2651
- return GLOBAL_CONTEXT_REFERENCES + "[" + id + "]";
2652
- }
2653
- function getRefParam(ctx, id) {
2654
- return ctx.mode === 1 /* Vanilla */ ? getVanillaRefParam(ctx.state, id) : getCrossRefParam(id);
2655
- }
2656
- function markSerializerRef(ctx, id) {
2657
- ctx.marked.add(id);
2658
- }
2659
- function isSerializerRefMarked(ctx, id) {
2660
- return ctx.marked.has(id);
2661
- }
2662
- function pushObjectFlag(ctx, flag, id) {
2663
- if (flag !== 0 /* None */) {
2664
- markSerializerRef(ctx.base, id);
2665
- ctx.base.flags.push({
2666
- type: flag,
2667
- value: getRefParam(ctx, id)
2668
- });
2669
- }
2670
- }
2671
- function resolveFlags(ctx) {
2672
- let result = "";
2673
- for (let i = 0, current = ctx.flags, len = current.length; i < len; i++) {
2674
- const flag = current[i];
2675
- result += OBJECT_FLAG_CONSTRUCTOR[flag.type] + "(" + flag.value + "),";
2676
- }
2677
- return result;
2678
- }
2679
- function resolvePatches(ctx) {
2680
- const assignments = resolveAssignments(ctx.assignments);
2681
- const flags = resolveFlags(ctx);
2682
- if (assignments) {
2683
- if (flags) {
2684
- return assignments + flags;
2685
- }
2686
- return assignments;
2687
- }
2688
- return flags;
2689
- }
2690
- function createAssignment(ctx, source, value) {
2691
- ctx.assignments.push({
2692
- t: 0 /* Index */,
2693
- s: source,
2694
- k: NIL,
2695
- v: value
2696
- });
2697
- }
2698
- function createAddAssignment(ctx, ref, value) {
2699
- ctx.base.assignments.push({
2700
- t: 1 /* Add */,
2701
- s: getRefParam(ctx, ref),
2702
- k: NIL,
2703
- v: value
2704
- });
2705
- }
2706
- function createSetAssignment(ctx, ref, key, value) {
2707
- ctx.base.assignments.push({
2708
- t: 2 /* Set */,
2709
- s: getRefParam(ctx, ref),
2710
- k: key,
2711
- v: value
2712
- });
2713
- }
2714
- function createDeleteAssignment(ctx, ref, key) {
2715
- ctx.base.assignments.push({
2716
- t: 3 /* Delete */,
2717
- s: getRefParam(ctx, ref),
2718
- k: key,
2719
- v: NIL
2720
- });
2721
- }
2722
- function createArrayAssign(ctx, ref, index, value) {
2723
- createAssignment(ctx.base, getRefParam(ctx, ref) + "[" + index + "]", value);
2724
- }
2725
- function createObjectAssign(ctx, ref, key, value) {
2726
- if (!isValidKey(key)) {
2727
- ctx.base.assignments.push({
2728
- t: 4 /* Define */,
2729
- s: getRefParam(ctx, ref),
2730
- k: value,
2731
- v: NIL
2732
- });
2733
- return;
2734
- }
2735
- createAssignment(ctx.base, getRefParam(ctx, ref) + "." + key, value);
2736
- }
2737
- function createSequenceAssign(ctx, ref, index, value) {
2738
- createAssignment(
2739
- ctx.base,
2740
- getRefParam(ctx, ref) + ".v[" + index + "]",
2741
- value
2742
- );
2743
- }
2744
- function isIndexedValueInStack(ctx, node) {
2745
- return node.t === 4 /* IndexedValue */ && ctx.stack.includes(node.i);
2746
- }
2747
- function assignIndexedValue2(ctx, index, value) {
2748
- if (ctx.mode === 1 /* Vanilla */ && !isSerializerRefMarked(ctx.base, index)) {
2749
- return value;
2750
- }
2751
- return getRefParam(ctx, index) + "=" + value;
2752
- }
2753
- function serializeReference(node) {
2754
- return REFERENCES_KEY + '.get("' + node.s + '")';
2755
- }
2756
- function serializeArrayItem(ctx, id, item, index) {
2757
- if (item) {
2758
- if (isIndexedValueInStack(ctx.base, item)) {
2759
- markSerializerRef(ctx.base, id);
2760
- createArrayAssign(
2761
- ctx,
2762
- id,
2763
- index,
2764
- getRefParam(ctx, item.i)
2765
- );
2766
- return "";
2767
- }
2768
- return serialize(ctx, item);
2769
- }
2770
- return "";
2771
- }
2772
- function serializeArray(ctx, node) {
2773
- const id = node.i;
2774
- const list = node.a;
2775
- const len = list.length;
2776
- if (len > 0) {
2777
- ctx.base.stack.push(id);
2778
- let values = serializeArrayItem(ctx, id, list[0], 0);
2779
- let isHoley = values === "";
2780
- for (let i = 1, item; i < len; i++) {
2781
- item = serializeArrayItem(ctx, id, list[i], i);
2782
- values += "," + item;
2783
- isHoley = item === "";
2784
- }
2785
- ctx.base.stack.pop();
2786
- pushObjectFlag(ctx, node.o, node.i);
2787
- return "[" + values + (isHoley ? ",]" : "]");
2788
- }
2789
- return "[]";
2790
- }
2791
- function serializeProperty(ctx, source, key, val) {
2792
- if (typeof key === "string") {
2793
- const check = Number(key);
2794
- const isIdentifier = (
2795
- // Test if key is a valid positive number or JS identifier
2796
- // so that we don't have to serialize the key and wrap with brackets
2797
- check >= 0 && // It's also important to consider that if the key is
2798
- // indeed numeric, we need to make sure that when
2799
- // converted back into a string, it's still the same
2800
- // to the original key. This allows us to differentiate
2801
- // keys that has numeric formats but in a different
2802
- // format, which can cause unintentional key declaration
2803
- // Example: { 0x1: 1 } vs { '0x1': 1 }
2804
- check.toString() === key || isValidIdentifier(key)
2805
- );
2806
- if (isIndexedValueInStack(ctx.base, val)) {
2807
- const refParam = getRefParam(ctx, val.i);
2808
- markSerializerRef(ctx.base, source.i);
2809
- if (isIdentifier && check !== check) {
2810
- createObjectAssign(ctx, source.i, key, refParam);
2811
- } else {
2812
- createArrayAssign(
2813
- ctx,
2814
- source.i,
2815
- isIdentifier ? key : '"' + key + '"',
2816
- refParam
2817
- );
2818
- }
2819
- return "";
2820
- }
2821
- if (isValidKey(key)) {
2822
- return (isIdentifier ? key : '"' + key + '"') + ":" + serialize(ctx, val);
2823
- }
2824
- return '["' + key + '"]:' + serialize(ctx, val);
2825
- }
2826
- return "[" + serialize(ctx, key) + "]:" + serialize(ctx, val);
2827
- }
2828
- function serializeProperties(ctx, source, record) {
2829
- const keys = record.k;
2830
- const len = keys.length;
2831
- if (len > 0) {
2832
- const values = record.v;
2833
- ctx.base.stack.push(source.i);
2834
- let result = serializeProperty(ctx, source, keys[0], values[0]);
2835
- for (let i = 1, item = result; i < len; i++) {
2836
- item = serializeProperty(ctx, source, keys[i], values[i]);
2837
- result += (item && result && ",") + item;
2838
- }
2839
- ctx.base.stack.pop();
2840
- return "{" + result + "}";
2841
- }
2842
- return "{}";
2843
- }
2844
- function serializeObject(ctx, node) {
2845
- pushObjectFlag(ctx, node.o, node.i);
2846
- return serializeProperties(ctx, node, node.p);
2847
- }
2848
- function serializeWithObjectAssign(ctx, source, value, serialized) {
2849
- const fields = serializeProperties(ctx, source, value);
2850
- if (fields !== "{}") {
2851
- return "Object.assign(" + serialized + "," + fields + ")";
2852
- }
2853
- return serialized;
2854
- }
2855
- function serializeStringKeyAssignment(ctx, source, mainAssignments, key, value) {
2856
- const base = ctx.base;
2857
- const serialized = serialize(ctx, value);
2858
- const check = Number(key);
2859
- const isIdentifier = (
2860
- // Test if key is a valid positive number or JS identifier
2861
- // so that we don't have to serialize the key and wrap with brackets
2862
- check >= 0 && // It's also important to consider that if the key is
2863
- // indeed numeric, we need to make sure that when
2864
- // converted back into a string, it's still the same
2865
- // to the original key. This allows us to differentiate
2866
- // keys that has numeric formats but in a different
2867
- // format, which can cause unintentional key declaration
2868
- // Example: { 0x1: 1 } vs { '0x1': 1 }
2869
- check.toString() === key || isValidIdentifier(key)
2870
- );
2871
- if (isIndexedValueInStack(base, value)) {
2872
- if (isIdentifier && check !== check) {
2873
- createObjectAssign(ctx, source.i, key, serialized);
2874
- } else {
2875
- createArrayAssign(
2876
- ctx,
2877
- source.i,
2878
- isIdentifier ? key : '"' + key + '"',
2879
- serialized
2880
- );
2881
- }
2882
- } else {
2883
- const parentAssignment = base.assignments;
2884
- base.assignments = mainAssignments;
2885
- if (isIdentifier && check !== check) {
2886
- createObjectAssign(ctx, source.i, key, serialized);
2887
- } else {
2888
- createArrayAssign(
2889
- ctx,
2890
- source.i,
2891
- isIdentifier ? key : '"' + key + '"',
2892
- serialized
2893
- );
2894
- }
2895
- base.assignments = parentAssignment;
2896
- }
2897
- }
2898
- function serializeAssignment(ctx, source, mainAssignments, key, value) {
2899
- if (typeof key === "string") {
2900
- serializeStringKeyAssignment(ctx, source, mainAssignments, key, value);
2901
- } else {
2902
- const base = ctx.base;
2903
- const parent = base.stack;
2904
- base.stack = [];
2905
- const serialized = serialize(ctx, value);
2906
- base.stack = parent;
2907
- const parentAssignment = base.assignments;
2908
- base.assignments = mainAssignments;
2909
- createArrayAssign(ctx, source.i, serialize(ctx, key), serialized);
2910
- base.assignments = parentAssignment;
2911
- }
2912
- }
2913
- function serializeAssignments(ctx, source, node) {
2914
- const keys = node.k;
2915
- const len = keys.length;
2916
- if (len > 0) {
2917
- const mainAssignments = [];
2918
- const values = node.v;
2919
- ctx.base.stack.push(source.i);
2920
- for (let i = 0; i < len; i++) {
2921
- serializeAssignment(ctx, source, mainAssignments, keys[i], values[i]);
2922
- }
2923
- ctx.base.stack.pop();
2924
- return resolveAssignments(mainAssignments);
2925
- }
2926
- return NIL;
2927
- }
2928
- function serializeDictionary(ctx, node, init) {
2929
- if (node.p) {
2930
- const base = ctx.base;
2931
- if (base.features & 8 /* ObjectAssign */) {
2932
- init = serializeWithObjectAssign(ctx, node, node.p, init);
2933
- } else {
2934
- markSerializerRef(base, node.i);
2935
- const assignments = serializeAssignments(ctx, node, node.p);
2936
- if (assignments) {
2937
- return "(" + assignIndexedValue2(ctx, node.i, init) + "," + assignments + getRefParam(ctx, node.i) + ")";
2938
- }
2939
- }
2940
- }
2941
- return init;
2942
- }
2943
- function serializeNullConstructor(ctx, node) {
2944
- pushObjectFlag(ctx, node.o, node.i);
2945
- return serializeDictionary(ctx, node, NULL_CONSTRUCTOR);
2946
- }
2947
- function serializeDate(node) {
2948
- return 'new Date("' + node.s + '")';
2949
- }
2950
- function serializeRegExp(ctx, node) {
2951
- if (ctx.base.features & 32 /* RegExp */) {
2952
- return "/" + deserializeString(node.c) + "/" + node.m;
2953
- }
2954
- throw new SerovalUnsupportedNodeError(node);
2955
- }
2956
- function serializeSetItem(ctx, id, item) {
2957
- const base = ctx.base;
2958
- if (isIndexedValueInStack(base, item)) {
2959
- markSerializerRef(base, id);
2960
- createAddAssignment(
2961
- ctx,
2962
- id,
2963
- getRefParam(ctx, item.i)
2964
- );
2965
- return "";
2966
- }
2967
- return serialize(ctx, item);
2968
- }
2969
- function serializeSet(ctx, node) {
2970
- let serialized = SET_CONSTRUCTOR;
2971
- const items = node.a;
2972
- const size = items.length;
2973
- const id = node.i;
2974
- if (size > 0) {
2975
- ctx.base.stack.push(id);
2976
- let result = serializeSetItem(ctx, id, items[0]);
2977
- for (let i = 1, item = result; i < size; i++) {
2978
- item = serializeSetItem(ctx, id, items[i]);
2979
- result += (item && result && ",") + item;
2980
- }
2981
- ctx.base.stack.pop();
2982
- if (result) {
2983
- serialized += "([" + result + "])";
2984
- }
2985
- }
2986
- return serialized;
2987
- }
2988
- function serializeMapEntry(ctx, id, key, val, sentinel) {
2989
- const base = ctx.base;
2990
- if (isIndexedValueInStack(base, key)) {
2991
- const keyRef = getRefParam(ctx, key.i);
2992
- markSerializerRef(base, id);
2993
- if (isIndexedValueInStack(base, val)) {
2994
- const valueRef = getRefParam(ctx, val.i);
2995
- createSetAssignment(ctx, id, keyRef, valueRef);
2996
- return "";
2997
- }
2998
- if (val.t !== 4 /* IndexedValue */ && val.i != null && isSerializerRefMarked(base, val.i)) {
2999
- const serialized = "(" + serialize(ctx, val) + ",[" + sentinel + "," + sentinel + "])";
3000
- createSetAssignment(ctx, id, keyRef, getRefParam(ctx, val.i));
3001
- createDeleteAssignment(ctx, id, sentinel);
3002
- return serialized;
3003
- }
3004
- const parent = base.stack;
3005
- base.stack = [];
3006
- createSetAssignment(ctx, id, keyRef, serialize(ctx, val));
3007
- base.stack = parent;
3008
- return "";
3009
- }
3010
- if (isIndexedValueInStack(base, val)) {
3011
- const valueRef = getRefParam(ctx, val.i);
3012
- markSerializerRef(base, id);
3013
- if (key.t !== 4 /* IndexedValue */ && key.i != null && isSerializerRefMarked(base, key.i)) {
3014
- const serialized = "(" + serialize(ctx, key) + ",[" + sentinel + "," + sentinel + "])";
3015
- createSetAssignment(ctx, id, getRefParam(ctx, key.i), valueRef);
3016
- createDeleteAssignment(ctx, id, sentinel);
3017
- return serialized;
3018
- }
3019
- const parent = base.stack;
3020
- base.stack = [];
3021
- createSetAssignment(ctx, id, serialize(ctx, key), valueRef);
3022
- base.stack = parent;
3023
- return "";
3024
- }
3025
- return "[" + serialize(ctx, key) + "," + serialize(ctx, val) + "]";
3026
- }
3027
- function serializeMap(ctx, node) {
3028
- let serialized = MAP_CONSTRUCTOR;
3029
- const keys = node.e.k;
3030
- const size = keys.length;
3031
- const id = node.i;
3032
- const sentinel = node.f;
3033
- const sentinelId = getRefParam(ctx, sentinel.i);
3034
- const base = ctx.base;
3035
- if (size > 0) {
3036
- const vals = node.e.v;
3037
- base.stack.push(id);
3038
- let result = serializeMapEntry(ctx, id, keys[0], vals[0], sentinelId);
3039
- for (let i = 1, item = result; i < size; i++) {
3040
- item = serializeMapEntry(ctx, id, keys[i], vals[i], sentinelId);
3041
- result += (item && result && ",") + item;
3042
- }
3043
- base.stack.pop();
3044
- if (result) {
3045
- serialized += "([" + result + "])";
3046
- }
3047
- }
3048
- if (sentinel.t === 26 /* SpecialReference */) {
3049
- markSerializerRef(base, sentinel.i);
3050
- serialized = "(" + serialize(ctx, sentinel) + "," + serialized + ")";
3051
- }
3052
- return serialized;
3053
- }
3054
- function serializeArrayBuffer(ctx, node) {
3055
- return getConstructor(ctx, node.f) + '("' + node.s + '")';
3056
- }
3057
- function serializeTypedArray(ctx, node) {
3058
- return "new " + node.c + "(" + serialize(ctx, node.f) + "," + node.b + "," + node.l + ")";
3059
- }
3060
- function serializeDataView(ctx, node) {
3061
- return "new DataView(" + serialize(ctx, node.f) + "," + node.b + "," + node.l + ")";
3062
- }
3063
- function serializeAggregateError(ctx, node) {
3064
- const id = node.i;
3065
- ctx.base.stack.push(id);
3066
- const serialized = serializeDictionary(
3067
- ctx,
3068
- node,
3069
- 'new AggregateError([],"' + node.m + '")'
3070
- );
3071
- ctx.base.stack.pop();
3072
- return serialized;
3073
- }
3074
- function serializeError(ctx, node) {
3075
- return serializeDictionary(
3076
- ctx,
3077
- node,
3078
- "new " + ERROR_CONSTRUCTOR_STRING[node.s] + '("' + node.m + '")'
3079
- );
3080
- }
3081
- function serializePromise(ctx, node) {
3082
- let serialized;
3083
- const fulfilled = node.f;
3084
- const id = node.i;
3085
- const promiseConstructor = node.s ? PROMISE_RESOLVE : PROMISE_REJECT;
3086
- const base = ctx.base;
3087
- if (isIndexedValueInStack(base, fulfilled)) {
3088
- const ref = getRefParam(ctx, fulfilled.i);
3089
- serialized = promiseConstructor + (node.s ? "().then(" + createFunction([], ref) + ")" : "().catch(" + createEffectfulFunction([], "throw " + ref) + ")");
3090
- } else {
3091
- base.stack.push(id);
3092
- const result = serialize(ctx, fulfilled);
3093
- base.stack.pop();
3094
- serialized = promiseConstructor + "(" + result + ")";
3095
- }
3096
- return serialized;
3097
- }
3098
- function serializeBoxed(ctx, node) {
3099
- return "Object(" + serialize(ctx, node.f) + ")";
3100
- }
3101
- function getConstructor(ctx, node) {
3102
- const current = serialize(ctx, node);
3103
- return node.t === 4 /* IndexedValue */ ? current : "(" + current + ")";
3104
- }
3105
- function serializePromiseConstructor(ctx, node) {
3106
- if (ctx.mode === 1 /* Vanilla */) {
3107
- throw new SerovalUnsupportedNodeError(node);
3108
- }
3109
- const resolver = assignIndexedValue2(
3110
- ctx,
3111
- node.s,
3112
- getConstructor(ctx, node.f) + "()"
3113
- );
3114
- return "(" + resolver + ").p";
3115
- }
3116
- function serializePromiseResolve(ctx, node) {
3117
- if (ctx.mode === 1 /* Vanilla */) {
3118
- throw new SerovalUnsupportedNodeError(node);
3119
- }
3120
- return getConstructor(ctx, node.a[0]) + "(" + getRefParam(ctx, node.i) + "," + serialize(ctx, node.a[1]) + ")";
3121
- }
3122
- function serializePromiseReject(ctx, node) {
3123
- if (ctx.mode === 1 /* Vanilla */) {
3124
- throw new SerovalUnsupportedNodeError(node);
3125
- }
3126
- return getConstructor(ctx, node.a[0]) + "(" + getRefParam(ctx, node.i) + "," + serialize(ctx, node.a[1]) + ")";
3127
- }
3128
- function serializePlugin(ctx, node) {
3129
- const currentPlugins = ctx.base.plugins;
3130
- if (currentPlugins) {
3131
- for (let i = 0, len = currentPlugins.length; i < len; i++) {
3132
- const plugin = currentPlugins[i];
3133
- if (plugin.tag === node.c) {
3134
- if (ctx.child == null) {
3135
- ctx.child = new SerializePluginContext(ctx);
3136
- }
3137
- return plugin.serialize(node.s, ctx.child, {
3138
- id: node.i
3139
- });
3140
- }
3141
- }
3142
- }
3143
- throw new SerovalMissingPluginError(node.c);
3144
- }
3145
- function serializeIteratorFactory(ctx, node) {
3146
- let result = "";
3147
- let initialized = false;
3148
- if (node.f.t !== 4 /* IndexedValue */) {
3149
- markSerializerRef(ctx.base, node.f.i);
3150
- result = "(" + serialize(ctx, node.f) + ",";
3151
- initialized = true;
3152
- }
3153
- result += assignIndexedValue2(
3154
- ctx,
3155
- node.i,
3156
- "(" + SERIALIZED_ITERATOR_CONSTRUCTOR + ")(" + getRefParam(ctx, node.f.i) + ")"
3157
- );
3158
- if (initialized) {
3159
- result += ")";
3160
- }
3161
- return result;
3162
- }
3163
- function serializeIteratorFactoryInstance(ctx, node) {
3164
- return getConstructor(ctx, node.a[0]) + "(" + serialize(ctx, node.a[1]) + ")";
3165
- }
3166
- function serializeAsyncIteratorFactory(ctx, node) {
3167
- const promise = node.a[0];
3168
- const symbol = node.a[1];
3169
- const base = ctx.base;
3170
- let result = "";
3171
- if (promise.t !== 4 /* IndexedValue */) {
3172
- markSerializerRef(base, promise.i);
3173
- result += "(" + serialize(ctx, promise);
3174
- }
3175
- if (symbol.t !== 4 /* IndexedValue */) {
3176
- markSerializerRef(base, symbol.i);
3177
- result += (result ? "," : "(") + serialize(ctx, symbol);
3178
- }
3179
- if (result) {
3180
- result += ",";
3181
- }
3182
- const iterator = assignIndexedValue2(
3183
- ctx,
3184
- node.i,
3185
- "(" + SERIALIZED_ASYNC_ITERATOR_CONSTRUCTOR + ")(" + getRefParam(ctx, symbol.i) + "," + getRefParam(ctx, promise.i) + ")"
3186
- );
3187
- if (result) {
3188
- return result + iterator + ")";
3189
- }
3190
- return iterator;
3191
- }
3192
- function serializeAsyncIteratorFactoryInstance(ctx, node) {
3193
- return getConstructor(ctx, node.a[0]) + "(" + serialize(ctx, node.a[1]) + ")";
3194
- }
3195
- function serializeStreamConstructor(ctx, node) {
3196
- const result = assignIndexedValue2(
3197
- ctx,
3198
- node.i,
3199
- getConstructor(ctx, node.f) + "()"
3200
- );
3201
- const len = node.a.length;
3202
- if (len) {
3203
- let values = serialize(ctx, node.a[0]);
3204
- for (let i = 1; i < len; i++) {
3205
- values += "," + serialize(ctx, node.a[i]);
3206
- }
3207
- return "(" + result + "," + values + "," + getRefParam(ctx, node.i) + ")";
3208
- }
3209
- return result;
3210
- }
3211
- function serializeStreamNext(ctx, node) {
3212
- return getRefParam(ctx, node.i) + ".next(" + serialize(ctx, node.f) + ")";
3213
- }
3214
- function serializeStreamThrow(ctx, node) {
3215
- return getRefParam(ctx, node.i) + ".throw(" + serialize(ctx, node.f) + ")";
3216
- }
3217
- function serializeStreamReturn(ctx, node) {
3218
- return getRefParam(ctx, node.i) + ".return(" + serialize(ctx, node.f) + ")";
3219
- }
3220
- function serializeSequenceItem(ctx, id, index, item) {
3221
- const base = ctx.base;
3222
- if (isIndexedValueInStack(base, item)) {
3223
- markSerializerRef(base, id);
3224
- createSequenceAssign(
3225
- ctx,
3226
- id,
3227
- index,
3228
- getRefParam(ctx, item.i)
3229
- );
3230
- return "";
3231
- }
3232
- return serialize(ctx, item);
3233
- }
3234
- function serializeSequence(ctx, node) {
3235
- const items = node.a;
3236
- const size = items.length;
3237
- const id = node.i;
3238
- if (size > 0) {
3239
- ctx.base.stack.push(id);
3240
- let result = serializeSequenceItem(ctx, id, 0, items[0]);
3241
- for (let i = 1, item = result; i < size; i++) {
3242
- item = serializeSequenceItem(ctx, id, i, items[i]);
3243
- result += (item && result && ",") + item;
3244
- }
3245
- ctx.base.stack.pop();
3246
- if (result) {
3247
- return "{__SEROVAL_SEQUENCE__:!0,v:[" + result + "],t:" + node.s + ",d:" + node.l + "}";
3248
- }
3249
- }
3250
- return "{__SEROVAL_SEQUENCE__:!0,v:[],t:-1,d:0}";
3251
- }
3252
- function serializeAssignable(ctx, node) {
3253
- switch (node.t) {
3254
- case 17 /* WKSymbol */:
3255
- return SYMBOL_STRING[node.s];
3256
- case 18 /* Reference */:
3257
- return serializeReference(node);
3258
- case 9 /* Array */:
3259
- return serializeArray(ctx, node);
3260
- case 10 /* Object */:
3261
- return serializeObject(ctx, node);
3262
- case 11 /* NullConstructor */:
3263
- return serializeNullConstructor(ctx, node);
3264
- case 5 /* Date */:
3265
- return serializeDate(node);
3266
- case 6 /* RegExp */:
3267
- return serializeRegExp(ctx, node);
3268
- case 7 /* Set */:
3269
- return serializeSet(ctx, node);
3270
- case 8 /* Map */:
3271
- return serializeMap(ctx, node);
3272
- case 19 /* ArrayBuffer */:
3273
- return serializeArrayBuffer(ctx, node);
3274
- case 16 /* BigIntTypedArray */:
3275
- case 15 /* TypedArray */:
3276
- return serializeTypedArray(ctx, node);
3277
- case 20 /* DataView */:
3278
- return serializeDataView(ctx, node);
3279
- case 14 /* AggregateError */:
3280
- return serializeAggregateError(ctx, node);
3281
- case 13 /* Error */:
3282
- return serializeError(ctx, node);
3283
- case 12 /* Promise */:
3284
- return serializePromise(ctx, node);
3285
- case 21 /* Boxed */:
3286
- return serializeBoxed(ctx, node);
3287
- case 22 /* PromiseConstructor */:
3288
- return serializePromiseConstructor(ctx, node);
3289
- case 25 /* Plugin */:
3290
- return serializePlugin(ctx, node);
3291
- case 26 /* SpecialReference */:
3292
- return SPECIAL_REF_STRING[node.s];
3293
- case 35 /* Sequence */:
3294
- return serializeSequence(ctx, node);
3295
- default:
3296
- throw new SerovalUnsupportedNodeError(node);
3297
- }
3298
- }
3299
- function serialize(ctx, node) {
3300
- switch (node.t) {
3301
- case 2 /* Constant */:
3302
- return CONSTANT_STRING[node.s];
3303
- case 0 /* Number */:
3304
- return "" + node.s;
3305
- case 1 /* String */:
3306
- return '"' + node.s + '"';
3307
- case 3 /* BigInt */:
3308
- return node.s + "n";
3309
- case 4 /* IndexedValue */:
3310
- return getRefParam(ctx, node.i);
3311
- case 23 /* PromiseSuccess */:
3312
- return serializePromiseResolve(ctx, node);
3313
- case 24 /* PromiseFailure */:
3314
- return serializePromiseReject(ctx, node);
3315
- case 27 /* IteratorFactory */:
3316
- return serializeIteratorFactory(ctx, node);
3317
- case 28 /* IteratorFactoryInstance */:
3318
- return serializeIteratorFactoryInstance(ctx, node);
3319
- case 29 /* AsyncIteratorFactory */:
3320
- return serializeAsyncIteratorFactory(ctx, node);
3321
- case 30 /* AsyncIteratorFactoryInstance */:
3322
- return serializeAsyncIteratorFactoryInstance(ctx, node);
3323
- case 31 /* StreamConstructor */:
3324
- return serializeStreamConstructor(ctx, node);
3325
- case 32 /* StreamNext */:
3326
- return serializeStreamNext(ctx, node);
3327
- case 33 /* StreamThrow */:
3328
- return serializeStreamThrow(ctx, node);
3329
- case 34 /* StreamReturn */:
3330
- return serializeStreamReturn(ctx, node);
3331
- default:
3332
- return assignIndexedValue2(ctx, node.i, serializeAssignable(ctx, node));
3333
- }
3334
- }
3335
- function serializeTopVanilla(ctx, tree) {
3336
- const result = serialize(ctx, tree);
3337
- if (tree.i != null && ctx.state.vars.length) {
3338
- const patches = resolvePatches(ctx.base);
3339
- let body = result;
3340
- if (patches) {
3341
- const index = getRefParam(ctx, tree.i);
3342
- body = result + "," + patches + index;
3343
- if (!result.startsWith(index + "=")) {
3344
- body = index + "=" + body;
3345
- }
3346
- body = "(" + body + ")";
3347
- }
3348
- return "(" + createFunction(ctx.state.vars, body) + ")()";
3349
- }
3350
- if (tree.t === 10 /* Object */) {
3351
- return "(" + result + ")";
3352
- }
3353
- return result;
3354
- }
3355
- function serializeTopCross(ctx, tree) {
3356
- const result = serialize(ctx, tree);
3357
- const id = tree.i;
3358
- if (id == null) {
3359
- return result;
3360
- }
3361
- const patches = resolvePatches(ctx.base);
3362
- const ref = getRefParam(ctx, id);
3363
- const scopeId = ctx.state.scopeId;
3364
- const params = scopeId == null ? "" : GLOBAL_CONTEXT_REFERENCES;
3365
- const body = patches ? "(" + result + "," + patches + ref + ")" : result;
3366
- if (params === "") {
3367
- if (tree.t === 10 /* Object */ && !patches) {
3368
- return "(" + body + ")";
3369
- }
3370
- return body;
3371
- }
3372
- const args = scopeId == null ? "()" : "(" + GLOBAL_CONTEXT_REFERENCES + '["' + serializeString(scopeId) + '"])';
3373
- return "(" + createFunction([params], body) + ")" + args;
3374
- }
3375
-
3376
- // src/core/context/sync-parser.ts
3377
- function createSyncParserContext(mode, options) {
3378
- return {
3379
- type: 1 /* Sync */,
3380
- base: createBaseParserContext(mode, options),
3381
- child: NIL
3382
- };
3383
- }
3384
- var SyncParsePluginContext = class {
3385
- constructor(_p, depth) {
3386
- this._p = _p;
3387
- this.depth = depth;
3388
- }
3389
- parse(current) {
3390
- return parseSOS(this._p, this.depth, current);
3391
- }
3392
- };
3393
- var StreamParsePluginContext = class {
3394
- constructor(_p, depth) {
3395
- this._p = _p;
3396
- this.depth = depth;
3397
- }
3398
- parse(current) {
3399
- return parseSOS(this._p, this.depth, current);
3400
- }
3401
- parseWithError(current) {
3402
- return parseWithError(this._p, this.depth, current);
3403
- }
3404
- isAlive() {
3405
- return this._p.state.alive;
3406
- }
3407
- pushPendingState() {
3408
- pushPendingState(this._p);
3409
- }
3410
- popPendingState() {
3411
- popPendingState(this._p);
3412
- }
3413
- onParse(node) {
3414
- onParse(this._p, node);
3415
- }
3416
- onError(error) {
3417
- onError(this._p, error);
3418
- }
3419
- addCleanup(callback) {
3420
- this._p.state.cleanups.push(callback);
3421
- }
3422
- };
3423
- function createStreamParserState(options) {
3424
- return {
3425
- alive: true,
3426
- pending: 0,
3427
- initial: true,
3428
- buffer: [],
3429
- onParse: options.onParse,
3430
- onError: options.onError,
3431
- onDone: options.onDone,
3432
- cleanups: []
3433
- };
3434
- }
3435
- function createStreamParserContext(options) {
3436
- return {
3437
- type: 2 /* Stream */,
3438
- base: createBaseParserContext(2 /* Cross */, options),
3439
- state: createStreamParserState(options)
3440
- };
3441
- }
3442
- function parseItems2(ctx, depth, current) {
3443
- const nodes = [];
3444
- for (let i = 0, len = current.length; i < len; i++) {
3445
- if (i in current) {
3446
- nodes[i] = parseSOS(ctx, depth, current[i]);
3447
- } else {
3448
- nodes[i] = 0;
3449
- }
3450
- }
3451
- return nodes;
3452
- }
3453
- function parseArray2(ctx, depth, id, current) {
3454
- return createArrayNode(id, current, parseItems2(ctx, depth, current));
3455
- }
3456
- function parseProperties2(ctx, depth, properties) {
3457
- const entries = Object.entries(properties);
3458
- const keyNodes = [];
3459
- const valueNodes = [];
3460
- for (let i = 0, len = entries.length; i < len; i++) {
3461
- keyNodes.push(serializeString(entries[i][0]));
3462
- valueNodes.push(parseSOS(ctx, depth, entries[i][1]));
3463
- }
3464
- if (SYM_ITERATOR in properties) {
3465
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
3466
- valueNodes.push(
3467
- createIteratorFactoryInstanceNode(
3468
- parseIteratorFactory(ctx.base),
3469
- parseSOS(
3470
- ctx,
3471
- depth,
3472
- createSequenceFromIterable(
3473
- properties
3474
- )
3475
- )
3476
- )
3477
- );
3478
- }
3479
- if (SYM_ASYNC_ITERATOR in properties) {
3480
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
3481
- valueNodes.push(
3482
- createAsyncIteratorFactoryInstanceNode(
3483
- parseAsyncIteratorFactory(ctx.base),
3484
- parseSOS(
3485
- ctx,
3486
- depth,
3487
- ctx.type === 1 /* Sync */ ? createStream() : createStreamFromAsyncIterable(
3488
- properties
3489
- )
3490
- )
3491
- )
3492
- );
3493
- }
3494
- if (SYM_TO_STRING_TAG in properties) {
3495
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
3496
- valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
3497
- }
3498
- if (SYM_IS_CONCAT_SPREADABLE in properties) {
3499
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
3500
- valueNodes.push(
3501
- properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE
3502
- );
3503
- }
3504
- return {
3505
- k: keyNodes,
3506
- v: valueNodes
3507
- };
3508
- }
3509
- function parsePlainObject2(ctx, depth, id, current, empty) {
3510
- return createObjectNode(
3511
- id,
3512
- current,
3513
- empty,
3514
- parseProperties2(ctx, depth, current)
3515
- );
3516
- }
3517
- function parseBoxed2(ctx, depth, id, current) {
3518
- return createBoxedNode(id, parseSOS(ctx, depth, current.valueOf()));
3519
- }
3520
- function parseTypedArray2(ctx, depth, id, current) {
3521
- return createTypedArrayNode(
3522
- id,
3523
- current,
3524
- parseSOS(ctx, depth, current.buffer)
3525
- );
3526
- }
3527
- function parseBigIntTypedArray2(ctx, depth, id, current) {
3528
- return createBigIntTypedArrayNode(
3529
- id,
3530
- current,
3531
- parseSOS(ctx, depth, current.buffer)
3532
- );
3533
- }
3534
- function parseDataView2(ctx, depth, id, current) {
3535
- return createDataViewNode(id, current, parseSOS(ctx, depth, current.buffer));
3536
- }
3537
- function parseError2(ctx, depth, id, current) {
3538
- const options = getErrorOptions(current, ctx.base.features);
3539
- return createErrorNode(
3540
- id,
3541
- current,
3542
- options ? parseProperties2(ctx, depth, options) : NIL
3543
- );
3544
- }
3545
- function parseAggregateError2(ctx, depth, id, current) {
3546
- const options = getErrorOptions(current, ctx.base.features);
3547
- return createAggregateErrorNode(
3548
- id,
3549
- current,
3550
- options ? parseProperties2(ctx, depth, options) : NIL
3551
- );
3552
- }
3553
- function parseMap2(ctx, depth, id, current) {
3554
- const keyNodes = [];
3555
- const valueNodes = [];
3556
- for (const [key, value] of current.entries()) {
3557
- keyNodes.push(parseSOS(ctx, depth, key));
3558
- valueNodes.push(parseSOS(ctx, depth, value));
3559
- }
3560
- return createMapNode(ctx.base, id, keyNodes, valueNodes);
3561
- }
3562
- function parseSet2(ctx, depth, id, current) {
3563
- const items = [];
3564
- for (const item of current.keys()) {
3565
- items.push(parseSOS(ctx, depth, item));
3566
- }
3567
- return createSetNode(id, items);
3568
- }
3569
- function parseStream2(ctx, depth, id, current) {
3570
- const result = createStreamConstructorNode(
3571
- id,
3572
- parseSpecialReference(ctx.base, 4 /* StreamConstructor */),
3573
- []
3574
- );
3575
- if (ctx.type === 1 /* Sync */) {
3576
- return result;
3577
- }
3578
- pushPendingState(ctx);
3579
- current.on({
3580
- next: (value) => {
3581
- if (ctx.state.alive) {
3582
- const parsed = parseWithError(ctx, depth, value);
3583
- if (parsed) {
3584
- onParse(ctx, createStreamNextNode(id, parsed));
3585
- }
3586
- }
3587
- },
3588
- throw: (value) => {
3589
- if (ctx.state.alive) {
3590
- const parsed = parseWithError(ctx, depth, value);
3591
- if (parsed) {
3592
- onParse(ctx, createStreamThrowNode(id, parsed));
3593
- }
3594
- }
3595
- popPendingState(ctx);
3596
- },
3597
- return: (value) => {
3598
- if (ctx.state.alive) {
3599
- const parsed = parseWithError(ctx, depth, value);
3600
- if (parsed) {
3601
- onParse(ctx, createStreamReturnNode(id, parsed));
3602
- }
3603
- }
3604
- popPendingState(ctx);
3605
- }
3606
- });
3607
- return result;
3608
- }
3609
- function handlePromiseSuccess(id, depth, data) {
3610
- if (this.state.alive) {
3611
- const parsed = parseWithError(this, depth, data);
3612
- if (parsed) {
3613
- onParse(
3614
- this,
3615
- createSerovalNode(
3616
- 23 /* PromiseSuccess */,
3617
- id,
3618
- NIL,
3619
- NIL,
3620
- NIL,
3621
- NIL,
3622
- NIL,
3623
- [
3624
- parseSpecialReference(this.base, 2 /* PromiseSuccess */),
3625
- parsed
3626
- ],
3627
- NIL,
3628
- NIL,
3629
- NIL,
3630
- NIL
3631
- )
3632
- );
3633
- }
3634
- popPendingState(this);
3635
- }
3636
- }
3637
- function handlePromiseFailure(id, depth, data) {
3638
- if (this.state.alive) {
3639
- const parsed = parseWithError(this, depth, data);
3640
- if (parsed) {
3641
- onParse(
3642
- this,
3643
- createSerovalNode(
3644
- 24 /* PromiseFailure */,
3645
- id,
3646
- NIL,
3647
- NIL,
3648
- NIL,
3649
- NIL,
3650
- NIL,
3651
- [
3652
- parseSpecialReference(this.base, 3 /* PromiseFailure */),
3653
- parsed
3654
- ],
3655
- NIL,
3656
- NIL,
3657
- NIL,
3658
- NIL
3659
- )
3660
- );
3661
- }
3662
- }
3663
- popPendingState(this);
3664
- }
3665
- function parsePromise2(ctx, depth, id, current) {
3666
- const resolver = createIndexForValue(ctx.base, {});
3667
- if (ctx.type === 2 /* Stream */) {
3668
- pushPendingState(ctx);
3669
- current.then(
3670
- handlePromiseSuccess.bind(ctx, resolver, depth),
3671
- handlePromiseFailure.bind(ctx, resolver, depth)
3672
- );
3673
- }
3674
- return createPromiseConstructorNode(ctx.base, id, resolver);
3675
- }
3676
- function parsePluginSync(ctx, depth, id, current, currentPlugins) {
3677
- for (let i = 0, len = currentPlugins.length; i < len; i++) {
3678
- const plugin = currentPlugins[i];
3679
- if (plugin.parse.sync && plugin.test(current)) {
3680
- return createPluginNode(
3681
- id,
3682
- plugin.tag,
3683
- plugin.parse.sync(current, new SyncParsePluginContext(ctx, depth), {
3684
- id
3685
- })
3686
- );
3687
- }
3688
- }
3689
- return NIL;
3690
- }
3691
- function parsePluginStream(ctx, depth, id, current, currentPlugins) {
3692
- for (let i = 0, len = currentPlugins.length; i < len; i++) {
3693
- const plugin = currentPlugins[i];
3694
- if (plugin.parse.stream && plugin.test(current)) {
3695
- return createPluginNode(
3696
- id,
3697
- plugin.tag,
3698
- plugin.parse.stream(current, new StreamParsePluginContext(ctx, depth), {
3699
- id
3700
- })
3701
- );
3702
- }
3703
- }
3704
- return NIL;
3705
- }
3706
- function parsePlugin2(ctx, depth, id, current) {
3707
- const currentPlugins = ctx.base.plugins;
3708
- if (currentPlugins) {
3709
- return ctx.type === 1 /* Sync */ ? parsePluginSync(ctx, depth, id, current, currentPlugins) : parsePluginStream(ctx, depth, id, current, currentPlugins);
3710
- }
3711
- return NIL;
3712
- }
3713
- function parseSequence2(ctx, depth, id, current) {
3714
- const nodes = [];
3715
- for (let i = 0, len = current.v.length; i < len; i++) {
3716
- nodes[i] = parseSOS(ctx, depth, current.v[i]);
3717
- }
3718
- return createSequenceNode(id, nodes, current.t, current.d);
3719
- }
3720
- function parseObjectPhase2(ctx, depth, id, current, currentClass) {
3721
- switch (currentClass) {
3722
- case Object:
3723
- return parsePlainObject2(
3724
- ctx,
3725
- depth,
3726
- id,
3727
- current,
3728
- false
3729
- );
3730
- case NIL:
3731
- return parsePlainObject2(
3732
- ctx,
3733
- depth,
3734
- id,
3735
- current,
3736
- true
3737
- );
3738
- case Date:
3739
- return createDateNode(id, current);
3740
- case Error:
3741
- case EvalError:
3742
- case RangeError:
3743
- case ReferenceError:
3744
- case SyntaxError:
3745
- case TypeError:
3746
- case URIError:
3747
- return parseError2(ctx, depth, id, current);
3748
- case Number:
3749
- case Boolean:
3750
- case String:
3751
- case BigInt:
3752
- return parseBoxed2(ctx, depth, id, current);
3753
- case ArrayBuffer:
3754
- return createArrayBufferNode(
3755
- ctx.base,
3756
- id,
3757
- current
3758
- );
3759
- case Int8Array:
3760
- case Int16Array:
3761
- case Int32Array:
3762
- case Uint8Array:
3763
- case Uint16Array:
3764
- case Uint32Array:
3765
- case Uint8ClampedArray:
3766
- case Float32Array:
3767
- case Float64Array:
3768
- return parseTypedArray2(
3769
- ctx,
3770
- depth,
3771
- id,
3772
- current
3773
- );
3774
- case DataView:
3775
- return parseDataView2(ctx, depth, id, current);
3776
- case Map:
3777
- return parseMap2(
3778
- ctx,
3779
- depth,
3780
- id,
3781
- current
3782
- );
3783
- case Set:
3784
- return parseSet2(ctx, depth, id, current);
3785
- default:
3786
- break;
3787
- }
3788
- if (currentClass === Promise || current instanceof Promise) {
3789
- return parsePromise2(ctx, depth, id, current);
3790
- }
3791
- const currentFeatures = ctx.base.features;
3792
- if (currentFeatures & 32 /* RegExp */ && currentClass === RegExp) {
3793
- return createRegExpNode(id, current);
3794
- }
3795
- if (currentFeatures & 16 /* BigIntTypedArray */) {
3796
- switch (currentClass) {
3797
- case BigInt64Array:
3798
- case BigUint64Array:
3799
- return parseBigIntTypedArray2(
3800
- ctx,
3801
- depth,
3802
- id,
3803
- current
3804
- );
3805
- default:
3806
- break;
3807
- }
3808
- }
3809
- if (currentFeatures & 1 /* AggregateError */ && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) {
3810
- return parseAggregateError2(
3811
- ctx,
3812
- depth,
3813
- id,
3814
- current
3815
- );
3816
- }
3817
- if (current instanceof Error) {
3818
- return parseError2(ctx, depth, id, current);
3819
- }
3820
- if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) {
3821
- return parsePlainObject2(ctx, depth, id, current, !!currentClass);
3822
- }
3823
- throw new SerovalUnsupportedTypeError(current);
3824
- }
3825
- function parseObject(ctx, depth, id, current) {
3826
- if (Array.isArray(current)) {
3827
- return parseArray2(ctx, depth, id, current);
3828
- }
3829
- if (isStream(current)) {
3830
- return parseStream2(ctx, depth, id, current);
3831
- }
3832
- if (isSequence(current)) {
3833
- return parseSequence2(ctx, depth, id, current);
3834
- }
3835
- const currentClass = current.constructor;
3836
- if (currentClass === OpaqueReference) {
3837
- return parseSOS(
3838
- ctx,
3839
- depth,
3840
- current.replacement
3841
- );
3842
- }
3843
- const parsed = parsePlugin2(ctx, depth, id, current);
3844
- if (parsed) {
3845
- return parsed;
3846
- }
3847
- return parseObjectPhase2(ctx, depth, id, current, currentClass);
3848
- }
3849
- function parseFunction(ctx, depth, current) {
3850
- const ref = getReferenceNode(ctx.base, current);
3851
- if (ref.type !== 0 /* Fresh */) {
3852
- return ref.value;
3853
- }
3854
- const plugin = parsePlugin2(ctx, depth, ref.value, current);
3855
- if (plugin) {
3856
- return plugin;
3857
- }
3858
- throw new SerovalUnsupportedTypeError(current);
3859
- }
3860
- function parseSOS(ctx, depth, current) {
3861
- if (depth >= ctx.base.depthLimit) {
3862
- throw new SerovalDepthLimitError(ctx.base.depthLimit);
3863
- }
3864
- switch (typeof current) {
3865
- case "boolean":
3866
- return current ? TRUE_NODE : FALSE_NODE;
3867
- case "undefined":
3868
- return UNDEFINED_NODE;
3869
- case "string":
3870
- return createStringNode(current);
3871
- case "number":
3872
- return createNumberNode(current);
3873
- case "bigint":
3874
- return createBigIntNode(current);
3875
- case "object": {
3876
- if (current) {
3877
- const ref = getReferenceNode(ctx.base, current);
3878
- return ref.type === 0 /* Fresh */ ? parseObject(ctx, depth + 1, ref.value, current) : ref.value;
3879
- }
3880
- return NULL_NODE;
3881
- }
3882
- case "symbol":
3883
- return parseWellKnownSymbol(ctx.base, current);
3884
- case "function": {
3885
- return parseFunction(ctx, depth, current);
3886
- }
3887
- default:
3888
- throw new SerovalUnsupportedTypeError(current);
3889
- }
3890
- }
3891
- function parseTop(ctx, current) {
3892
- try {
3893
- return parseSOS(ctx, 0, current);
3894
- } catch (error) {
3895
- throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
3896
- }
3897
- }
3898
- function onParse(ctx, node) {
3899
- if (ctx.state.initial) {
3900
- ctx.state.buffer.push(node);
3901
- } else {
3902
- onParseInternal(ctx, node, false);
3903
- }
3904
- }
3905
- function onError(ctx, error) {
3906
- if (ctx.state.onError) {
3907
- ctx.state.onError(error);
3908
- } else {
3909
- throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
3910
- }
3911
- }
3912
- function onDone(ctx) {
3913
- if (ctx.state.onDone) {
3914
- ctx.state.onDone();
3915
- }
3916
- for (let i = 0, len = ctx.state.cleanups.length; i < len; i++) {
3917
- ctx.state.cleanups[i]();
3918
- }
3919
- }
3920
- function onParseInternal(ctx, node, initial) {
3921
- try {
3922
- ctx.state.onParse(node, initial);
3923
- } catch (error) {
3924
- onError(ctx, error);
3925
- }
3926
- }
3927
- function pushPendingState(ctx) {
3928
- ctx.state.pending++;
3929
- }
3930
- function popPendingState(ctx) {
3931
- if (--ctx.state.pending <= 0) {
3932
- onDone(ctx);
3933
- }
3934
- }
3935
- function parseWithError(ctx, depth, current) {
3936
- try {
3937
- return parseSOS(ctx, depth, current);
3938
- } catch (err) {
3939
- onError(ctx, err);
3940
- return NIL;
3941
- }
3942
- }
3943
- function startStreamParse(ctx, current) {
3944
- const parsed = parseWithError(ctx, 0, current);
3945
- if (parsed) {
3946
- onParseInternal(ctx, parsed, true);
3947
- ctx.state.initial = false;
3948
- flushStreamParse(ctx, ctx.state);
3949
- if (ctx.state.pending <= 0) {
3950
- destroyStreamParse(ctx);
3951
- }
3952
- }
3953
- }
3954
- function flushStreamParse(ctx, state) {
3955
- for (let i = 0, len = state.buffer.length; i < len; i++) {
3956
- onParseInternal(ctx, state.buffer[i], false);
3957
- }
3958
- }
3959
- function destroyStreamParse(ctx) {
3960
- if (ctx.state.alive) {
3961
- onDone(ctx);
3962
- ctx.state.alive = false;
3963
- }
3964
- }
3965
-
3966
- // src/core/cross/index.ts
3967
- function crossSerialize(source, options = {}) {
3968
- const plugins = resolvePlugins(options.plugins);
3969
- const ctx = createSyncParserContext(2 /* Cross */, {
3970
- plugins,
3971
- disabledFeatures: options.disabledFeatures,
3972
- refs: options.refs
3973
- });
3974
- const tree = parseTop(ctx, source);
3975
- const serial = createCrossSerializerContext({
3976
- plugins,
3977
- features: ctx.base.features,
3978
- scopeId: options.scopeId,
3979
- markedRefs: ctx.base.marked
3980
- });
3981
- return serializeTopCross(serial, tree);
3982
- }
3983
- async function crossSerializeAsync(source, options = {}) {
3984
- const plugins = resolvePlugins(options.plugins);
3985
- const ctx = createAsyncParserContext(2 /* Cross */, {
3986
- plugins,
3987
- disabledFeatures: options.disabledFeatures,
3988
- refs: options.refs
3989
- });
3990
- const tree = await parseTopAsync(ctx, source);
3991
- const serial = createCrossSerializerContext({
3992
- plugins,
3993
- features: ctx.base.features,
3994
- scopeId: options.scopeId,
3995
- markedRefs: ctx.base.marked
3996
- });
3997
- return serializeTopCross(serial, tree);
3998
- }
3999
- function toCrossJSON(source, options = {}) {
4000
- const plugins = resolvePlugins(options.plugins);
4001
- const ctx = createSyncParserContext(2 /* Cross */, {
4002
- plugins,
4003
- disabledFeatures: options.disabledFeatures,
4004
- refs: options.refs
4005
- });
4006
- return parseTop(ctx, source);
4007
- }
4008
- async function toCrossJSONAsync(source, options = {}) {
4009
- const plugins = resolvePlugins(options.plugins);
4010
- const ctx = createAsyncParserContext(2 /* Cross */, {
4011
- plugins,
4012
- disabledFeatures: options.disabledFeatures,
4013
- refs: options.refs
4014
- });
4015
- return await parseTopAsync(ctx, source);
4016
- }
4017
- function crossSerializeStream(source, options) {
4018
- const plugins = resolvePlugins(options.plugins);
4019
- const ctx = createStreamParserContext({
4020
- plugins,
4021
- refs: options.refs,
4022
- disabledFeatures: options.disabledFeatures,
4023
- onParse(node, initial) {
4024
- const serial = createCrossSerializerContext({
4025
- plugins,
4026
- features: ctx.base.features,
4027
- scopeId: options.scopeId,
4028
- markedRefs: ctx.base.marked
4029
- });
4030
- let serialized;
4031
- try {
4032
- serialized = serializeTopCross(serial, node);
4033
- } catch (err) {
4034
- if (options.onError) {
4035
- options.onError(err);
4036
- }
4037
- return;
4038
- }
4039
- options.onSerialize(serialized, initial);
4040
- },
4041
- onError: options.onError,
4042
- onDone: options.onDone
4043
- });
4044
- startStreamParse(ctx, source);
4045
- return destroyStreamParse.bind(null, ctx);
4046
- }
4047
- function toCrossJSONStream(source, options) {
4048
- const plugins = resolvePlugins(options.plugins);
4049
- const ctx = createStreamParserContext({
4050
- plugins,
4051
- refs: options.refs,
4052
- disabledFeatures: options.disabledFeatures,
4053
- depthLimit: options.depthLimit,
4054
- onParse: options.onParse,
4055
- onError: options.onError,
4056
- onDone: options.onDone
4057
- });
4058
- startStreamParse(ctx, source);
4059
- return destroyStreamParse.bind(null, ctx);
4060
- }
4061
- function fromCrossJSON(source, options) {
4062
- const plugins = resolvePlugins(options.plugins);
4063
- const ctx = createCrossDeserializerContext({
4064
- plugins,
4065
- refs: options.refs,
4066
- features: options.features,
4067
- disabledFeatures: options.disabledFeatures,
4068
- depthLimit: options.depthLimit
4069
- });
4070
- return deserializeTop(ctx, source);
4071
- }
4072
-
4073
- // src/core/Serializer.ts
4074
- var Serializer = class {
4075
- constructor(options) {
4076
- this.options = options;
4077
- this.alive = true;
4078
- this.flushed = false;
4079
- this.done = false;
4080
- this.pending = 0;
4081
- this.cleanups = [];
4082
- this.refs = /* @__PURE__ */ new Map();
4083
- this.keys = /* @__PURE__ */ new Set();
4084
- this.ids = 0;
4085
- this.plugins = resolvePlugins(options.plugins);
4086
- }
4087
- write(key, value) {
4088
- if (this.alive && !this.flushed) {
4089
- this.pending++;
4090
- this.keys.add(key);
4091
- this.cleanups.push(
4092
- crossSerializeStream(value, {
4093
- plugins: this.plugins,
4094
- scopeId: this.options.scopeId,
4095
- refs: this.refs,
4096
- disabledFeatures: this.options.disabledFeatures,
4097
- onError: this.options.onError,
4098
- onSerialize: (data, initial) => {
4099
- if (this.alive) {
4100
- this.options.onData(
4101
- initial ? this.options.globalIdentifier + '["' + serializeString(key) + '"]=' + data : data
4102
- );
4103
- }
4104
- },
4105
- onDone: () => {
4106
- if (this.alive) {
4107
- this.pending--;
4108
- if (this.pending <= 0 && this.flushed && !this.done && this.options.onDone) {
4109
- this.options.onDone();
4110
- this.done = true;
4111
- }
4112
- }
4113
- }
4114
- })
4115
- );
4116
- }
4117
- }
4118
- getNextID() {
4119
- while (this.keys.has("" + this.ids)) {
4120
- this.ids++;
4121
- }
4122
- return "" + this.ids;
4123
- }
4124
- push(value) {
4125
- const newID = this.getNextID();
4126
- this.write(newID, value);
4127
- return newID;
4128
- }
4129
- flush() {
4130
- if (this.alive) {
4131
- this.flushed = true;
4132
- if (this.pending <= 0 && !this.done && this.options.onDone) {
4133
- this.options.onDone();
4134
- this.done = true;
4135
- }
4136
- }
4137
- }
4138
- close() {
4139
- if (this.alive) {
4140
- for (let i = 0, len = this.cleanups.length; i < len; i++) {
4141
- this.cleanups[i]();
4142
- }
4143
- if (!this.done && this.options.onDone) {
4144
- this.options.onDone();
4145
- this.done = true;
4146
- }
4147
- this.alive = false;
4148
- }
4149
- }
4150
- };
4151
-
4152
- // src/core/tree/index.ts
4153
- function serialize2(source, options = {}) {
4154
- const plugins = resolvePlugins(options.plugins);
4155
- const ctx = createSyncParserContext(1 /* Vanilla */, {
4156
- plugins,
4157
- disabledFeatures: options.disabledFeatures
4158
- });
4159
- const tree = parseTop(ctx, source);
4160
- const serial = createVanillaSerializerContext({
4161
- plugins,
4162
- features: ctx.base.features,
4163
- markedRefs: ctx.base.marked
4164
- });
4165
- return serializeTopVanilla(serial, tree);
4166
- }
4167
- async function serializeAsync(source, options = {}) {
4168
- const plugins = resolvePlugins(options.plugins);
4169
- const ctx = createAsyncParserContext(1 /* Vanilla */, {
4170
- plugins,
4171
- disabledFeatures: options.disabledFeatures
4172
- });
4173
- const tree = await parseTopAsync(ctx, source);
4174
- const serial = createVanillaSerializerContext({
4175
- plugins,
4176
- features: ctx.base.features,
4177
- markedRefs: ctx.base.marked
4178
- });
4179
- return serializeTopVanilla(serial, tree);
4180
- }
4181
- function deserialize2(source) {
4182
- return (0, eval)(source);
4183
- }
4184
- function toJSON(source, options = {}) {
4185
- const plugins = resolvePlugins(options.plugins);
4186
- const ctx = createSyncParserContext(1 /* Vanilla */, {
4187
- plugins,
4188
- disabledFeatures: options.disabledFeatures
4189
- });
4190
- return {
4191
- t: parseTop(ctx, source),
4192
- f: ctx.base.features,
4193
- m: Array.from(ctx.base.marked)
4194
- };
4195
- }
4196
- async function toJSONAsync(source, options = {}) {
4197
- const plugins = resolvePlugins(options.plugins);
4198
- const ctx = createAsyncParserContext(1 /* Vanilla */, {
4199
- plugins,
4200
- disabledFeatures: options.disabledFeatures
4201
- });
4202
- return {
4203
- t: await parseTopAsync(ctx, source),
4204
- f: ctx.base.features,
4205
- m: Array.from(ctx.base.marked)
4206
- };
4207
- }
4208
- function compileJSON(source, options = {}) {
4209
- const plugins = resolvePlugins(options.plugins);
4210
- const ctx = createVanillaSerializerContext({
4211
- plugins,
4212
- features: source.f,
4213
- markedRefs: source.m
4214
- });
4215
- return serializeTopVanilla(ctx, source.t);
4216
- }
4217
- function fromJSON(source, options = {}) {
4218
- var _a;
4219
- const plugins = resolvePlugins(options.plugins);
4220
- const disabledFeatures = options.disabledFeatures || 0;
4221
- const sourceFeatures = (_a = source.f) != null ? _a : ALL_ENABLED;
4222
- const ctx = createVanillaDeserializerContext({
4223
- plugins,
4224
- markedRefs: source.m,
4225
- features: sourceFeatures & ~disabledFeatures,
4226
- disabledFeatures
4227
- });
4228
- return deserializeTop(ctx, source.t);
4229
- }
4230
- //# sourceMappingURL=index.cjs.map