msgpackr 1.6.1 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.cjs CHANGED
@@ -5,1975 +5,1985 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var stream = require('stream');
6
6
  var module$1 = require('module');
7
7
 
8
- var decoder;
9
- try {
10
- decoder = new TextDecoder();
11
- } catch(error) {}
12
- var src;
13
- var srcEnd;
14
- var position = 0;
15
- const EMPTY_ARRAY = [];
16
- var strings = EMPTY_ARRAY;
17
- var stringPosition = 0;
18
- var currentUnpackr = {};
19
- var currentStructures;
20
- var srcString;
21
- var srcStringStart = 0;
22
- var srcStringEnd = 0;
23
- var bundledStrings;
24
- var referenceMap;
25
- var currentExtensions = [];
26
- var dataView;
27
- var defaultOptions = {
28
- useRecords: false,
29
- mapsAsObjects: true
30
- };
31
- class C1Type {}
32
- const C1 = new C1Type();
33
- C1.name = 'MessagePack 0xC1';
34
- var sequentialMode = false;
35
- var inlineObjectReadThreshold = 2;
36
- try {
37
- new Function('');
38
- } catch(error) {
39
- // if eval variants are not supported, do not create inline object readers ever
40
- inlineObjectReadThreshold = Infinity;
41
- }
42
-
43
- class Unpackr {
44
- constructor(options) {
45
- if (options) {
46
- if (options.useRecords === false && options.mapsAsObjects === undefined)
47
- options.mapsAsObjects = true;
48
- if (options.structures)
49
- options.structures.sharedLength = options.structures.length;
50
- else if (options.getStructures) {
51
- (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
52
- options.structures.sharedLength = 0;
53
- }
54
- }
55
- Object.assign(this, options);
56
- }
57
- unpack(source, end) {
58
- if (src) {
59
- // re-entrant execution, save the state and restore it after we do this unpack
60
- return saveState(() => {
61
- clearSource();
62
- return this ? this.unpack(source, end) : Unpackr.prototype.unpack.call(defaultOptions, source, end)
63
- })
64
- }
65
- srcEnd = end > -1 ? end : source.length;
66
- position = 0;
67
- stringPosition = 0;
68
- srcStringEnd = 0;
69
- srcString = null;
70
- strings = EMPTY_ARRAY;
71
- bundledStrings = null;
72
- src = source;
73
- // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
74
- // technique for getting data from a database where it can be copied into an existing buffer instead of creating
75
- // new ones
76
- try {
77
- dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
78
- } catch(error) {
79
- // if it doesn't have a buffer, maybe it is the wrong type of object
80
- src = null;
81
- if (source instanceof Uint8Array)
82
- throw error
83
- throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
84
- }
85
- if (this instanceof Unpackr) {
86
- currentUnpackr = this;
87
- if (this.structures) {
88
- currentStructures = this.structures;
89
- return checkedRead()
90
- } else if (!currentStructures || currentStructures.length > 0) {
91
- currentStructures = [];
92
- }
93
- } else {
94
- currentUnpackr = defaultOptions;
95
- if (!currentStructures || currentStructures.length > 0)
96
- currentStructures = [];
97
- }
98
- return checkedRead()
99
- }
100
- unpackMultiple(source, forEach) {
101
- let values, lastPosition = 0;
102
- try {
103
- sequentialMode = true;
104
- let size = source.length;
105
- let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
106
- if (forEach) {
107
- forEach(value);
108
- while(position < size) {
109
- lastPosition = position;
110
- if (forEach(checkedRead()) === false) {
111
- return
112
- }
113
- }
114
- }
115
- else {
116
- values = [ value ];
117
- while(position < size) {
118
- lastPosition = position;
119
- values.push(checkedRead());
120
- }
121
- return values
122
- }
123
- } catch(error) {
124
- error.lastPosition = lastPosition;
125
- error.values = values;
126
- throw error
127
- } finally {
128
- sequentialMode = false;
129
- clearSource();
130
- }
131
- }
132
- _mergeStructures(loadedStructures, existingStructures) {
133
- loadedStructures = loadedStructures || [];
134
- for (let i = 0, l = loadedStructures.length; i < l; i++) {
135
- let structure = loadedStructures[i];
136
- if (structure) {
137
- structure.isShared = true;
138
- if (i >= 32)
139
- structure.highByte = (i - 32) >> 5;
140
- }
141
- }
142
- loadedStructures.sharedLength = loadedStructures.length;
143
- for (let id in existingStructures || []) {
144
- if (id >= 0) {
145
- let structure = loadedStructures[id];
146
- let existing = existingStructures[id];
147
- if (existing) {
148
- if (structure)
149
- (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
150
- loadedStructures[id] = existing;
151
- }
152
- }
153
- }
154
- return this.structures = loadedStructures
155
- }
156
- decode(source, end) {
157
- return this.unpack(source, end)
158
- }
159
- }
160
- function checkedRead() {
161
- try {
162
- if (!currentUnpackr.trusted && !sequentialMode) {
163
- let sharedLength = currentStructures.sharedLength || 0;
164
- if (sharedLength < currentStructures.length)
165
- currentStructures.length = sharedLength;
166
- }
167
- let result = read();
168
- if (bundledStrings) // bundled strings to skip past
169
- position = bundledStrings.postBundlePosition;
170
-
171
- if (position == srcEnd) {
172
- // finished reading this source, cleanup references
173
- if (currentStructures.restoreStructures)
174
- restoreStructures();
175
- currentStructures = null;
176
- src = null;
177
- if (referenceMap)
178
- referenceMap = null;
179
- } else if (position > srcEnd) {
180
- // over read
181
- throw new Error('Unexpected end of MessagePack data')
182
- } else if (!sequentialMode) {
183
- throw new Error('Data read, but end of buffer not reached ' + JSON.stringify(result).slice(0, 100))
184
- }
185
- // else more to read, but we are reading sequentially, so don't clear source yet
186
- return result
187
- } catch(error) {
188
- if (currentStructures.restoreStructures)
189
- restoreStructures();
190
- clearSource();
191
- if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position > srcEnd) {
192
- error.incomplete = true;
193
- }
194
- throw error
195
- }
196
- }
197
-
198
- function restoreStructures() {
199
- for (let id in currentStructures.restoreStructures) {
200
- currentStructures[id] = currentStructures.restoreStructures[id];
201
- }
202
- currentStructures.restoreStructures = null;
203
- }
204
-
205
- function read() {
206
- let token = src[position++];
207
- if (token < 0xa0) {
208
- if (token < 0x80) {
209
- if (token < 0x40)
210
- return token
211
- else {
212
- let structure = currentStructures[token & 0x3f] ||
213
- currentUnpackr.getStructures && loadStructures()[token & 0x3f];
214
- if (structure) {
215
- if (!structure.read) {
216
- structure.read = createStructureReader(structure, token & 0x3f);
217
- }
218
- return structure.read()
219
- } else
220
- return token
221
- }
222
- } else if (token < 0x90) {
223
- // map
224
- token -= 0x80;
225
- if (currentUnpackr.mapsAsObjects) {
226
- let object = {};
227
- for (let i = 0; i < token; i++) {
228
- object[readKey()] = read();
229
- }
230
- return object
231
- } else {
232
- let map = new Map();
233
- for (let i = 0; i < token; i++) {
234
- map.set(read(), read());
235
- }
236
- return map
237
- }
238
- } else {
239
- token -= 0x90;
240
- let array = new Array(token);
241
- for (let i = 0; i < token; i++) {
242
- array[i] = read();
243
- }
244
- return array
245
- }
246
- } else if (token < 0xc0) {
247
- // fixstr
248
- let length = token - 0xa0;
249
- if (srcStringEnd >= position) {
250
- return srcString.slice(position - srcStringStart, (position += length) - srcStringStart)
251
- }
252
- if (srcStringEnd == 0 && srcEnd < 140) {
253
- // for small blocks, avoiding the overhead of the extract call is helpful
254
- let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
255
- if (string != null)
256
- return string
257
- }
258
- return readFixedString(length)
259
- } else {
260
- let value;
261
- switch (token) {
262
- case 0xc0: return null
263
- case 0xc1:
264
- if (bundledStrings) {
265
- value = read(); // followed by the length of the string in characters (not bytes!)
266
- if (value > 0)
267
- return bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value)
268
- else
269
- return bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 -= value)
270
- }
271
- return C1; // "never-used", return special object to denote that
272
- case 0xc2: return false
273
- case 0xc3: return true
274
- case 0xc4:
275
- // bin 8
276
- value = src[position++];
277
- if (value === undefined)
278
- throw new Error('Unexpected end of buffer')
279
- return readBin(value)
280
- case 0xc5:
281
- // bin 16
282
- value = dataView.getUint16(position);
283
- position += 2;
284
- return readBin(value)
285
- case 0xc6:
286
- // bin 32
287
- value = dataView.getUint32(position);
288
- position += 4;
289
- return readBin(value)
290
- case 0xc7:
291
- // ext 8
292
- return readExt(src[position++])
293
- case 0xc8:
294
- // ext 16
295
- value = dataView.getUint16(position);
296
- position += 2;
297
- return readExt(value)
298
- case 0xc9:
299
- // ext 32
300
- value = dataView.getUint32(position);
301
- position += 4;
302
- return readExt(value)
303
- case 0xca:
304
- value = dataView.getFloat32(position);
305
- if (currentUnpackr.useFloat32 > 2) {
306
- // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
307
- let multiplier = mult10[((src[position] & 0x7f) << 1) | (src[position + 1] >> 7)];
308
- position += 4;
309
- return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
310
- }
311
- position += 4;
312
- return value
313
- case 0xcb:
314
- value = dataView.getFloat64(position);
315
- position += 8;
316
- return value
317
- // uint handlers
318
- case 0xcc:
319
- return src[position++]
320
- case 0xcd:
321
- value = dataView.getUint16(position);
322
- position += 2;
323
- return value
324
- case 0xce:
325
- value = dataView.getUint32(position);
326
- position += 4;
327
- return value
328
- case 0xcf:
329
- if (currentUnpackr.int64AsNumber) {
330
- value = dataView.getUint32(position) * 0x100000000;
331
- value += dataView.getUint32(position + 4);
332
- } else
333
- value = dataView.getBigUint64(position);
334
- position += 8;
335
- return value
336
-
337
- // int handlers
338
- case 0xd0:
339
- return dataView.getInt8(position++)
340
- case 0xd1:
341
- value = dataView.getInt16(position);
342
- position += 2;
343
- return value
344
- case 0xd2:
345
- value = dataView.getInt32(position);
346
- position += 4;
347
- return value
348
- case 0xd3:
349
- if (currentUnpackr.int64AsNumber) {
350
- value = dataView.getInt32(position) * 0x100000000;
351
- value += dataView.getUint32(position + 4);
352
- } else
353
- value = dataView.getBigInt64(position);
354
- position += 8;
355
- return value
356
-
357
- case 0xd4:
358
- // fixext 1
359
- value = src[position++];
360
- if (value == 0x72) {
361
- return recordDefinition(src[position++] & 0x3f)
362
- } else {
363
- let extension = currentExtensions[value];
364
- if (extension) {
365
- if (extension.read) {
366
- position++; // skip filler byte
367
- return extension.read(read())
368
- } else if (extension.noBuffer) {
369
- position++; // skip filler byte
370
- return extension()
371
- } else
372
- return extension(src.subarray(position, ++position))
373
- } else
374
- throw new Error('Unknown extension ' + value)
375
- }
376
- case 0xd5:
377
- // fixext 2
378
- value = src[position];
379
- if (value == 0x72) {
380
- position++;
381
- return recordDefinition(src[position++] & 0x3f, src[position++])
382
- } else
383
- return readExt(2)
384
- case 0xd6:
385
- // fixext 4
386
- return readExt(4)
387
- case 0xd7:
388
- // fixext 8
389
- return readExt(8)
390
- case 0xd8:
391
- // fixext 16
392
- return readExt(16)
393
- case 0xd9:
394
- // str 8
395
- value = src[position++];
396
- if (srcStringEnd >= position) {
397
- return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
398
- }
399
- return readString8(value)
400
- case 0xda:
401
- // str 16
402
- value = dataView.getUint16(position);
403
- position += 2;
404
- if (srcStringEnd >= position) {
405
- return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
406
- }
407
- return readString16(value)
408
- case 0xdb:
409
- // str 32
410
- value = dataView.getUint32(position);
411
- position += 4;
412
- if (srcStringEnd >= position) {
413
- return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
414
- }
415
- return readString32(value)
416
- case 0xdc:
417
- // array 16
418
- value = dataView.getUint16(position);
419
- position += 2;
420
- return readArray(value)
421
- case 0xdd:
422
- // array 32
423
- value = dataView.getUint32(position);
424
- position += 4;
425
- return readArray(value)
426
- case 0xde:
427
- // map 16
428
- value = dataView.getUint16(position);
429
- position += 2;
430
- return readMap(value)
431
- case 0xdf:
432
- // map 32
433
- value = dataView.getUint32(position);
434
- position += 4;
435
- return readMap(value)
436
- default: // negative int
437
- if (token >= 0xe0)
438
- return token - 0x100
439
- if (token === undefined) {
440
- let error = new Error('Unexpected end of MessagePack data');
441
- error.incomplete = true;
442
- throw error
443
- }
444
- throw new Error('Unknown MessagePack token ' + token)
445
-
446
- }
447
- }
448
- }
449
- const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
450
- function createStructureReader(structure, firstId) {
451
- function readObject() {
452
- // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
453
- if (readObject.count++ > inlineObjectReadThreshold) {
454
- let readObject = structure.read = (new Function('r', 'return function(){return {' + structure.map(key => validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}}'))(read);
455
- if (structure.highByte === 0)
456
- structure.read = createSecondByteReader(firstId, structure.read);
457
- return readObject() // second byte is already read, if there is one so immediately read object
458
- }
459
- let object = {};
460
- for (let i = 0, l = structure.length; i < l; i++) {
461
- let key = structure[i];
462
- object[key] = read();
463
- }
464
- return object
465
- }
466
- readObject.count = 0;
467
- if (structure.highByte === 0) {
468
- return createSecondByteReader(firstId, readObject)
469
- }
470
- return readObject
471
- }
472
-
473
- const createSecondByteReader = (firstId, read0) => {
474
- return function() {
475
- let highByte = src[position++];
476
- if (highByte === 0)
477
- return read0()
478
- let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
479
- let structure = currentStructures[id] || loadStructures()[id];
480
- if (!structure) {
481
- throw new Error('Record id is not defined for ' + id)
482
- }
483
- if (!structure.read)
484
- structure.read = createStructureReader(structure, firstId);
485
- return structure.read()
486
- }
487
- };
488
-
489
- function loadStructures() {
490
- let loadedStructures = saveState(() => {
491
- // save the state in case getStructures modifies our buffer
492
- src = null;
493
- return currentUnpackr.getStructures()
494
- });
495
- return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
496
- }
497
-
498
- var readFixedString = readStringJS;
499
- var readString8 = readStringJS;
500
- var readString16 = readStringJS;
501
- var readString32 = readStringJS;
502
- exports.isNativeAccelerationEnabled = false;
503
-
504
- function setExtractor(extractStrings) {
505
- exports.isNativeAccelerationEnabled = true;
506
- readFixedString = readString(1);
507
- readString8 = readString(2);
508
- readString16 = readString(3);
509
- readString32 = readString(5);
510
- function readString(headerLength) {
511
- return function readString(length) {
512
- let string = strings[stringPosition++];
513
- if (string == null) {
514
- if (bundledStrings)
515
- return readStringJS(length)
516
- let extraction = extractStrings(position - headerLength, srcEnd, src);
517
- if (typeof extraction == 'string') {
518
- string = extraction;
519
- strings = EMPTY_ARRAY;
520
- } else {
521
- strings = extraction;
522
- stringPosition = 1;
523
- srcStringEnd = 1; // even if a utf-8 string was decoded, must indicate we are in the midst of extracted strings and can't skip strings
524
- string = strings[0];
525
- if (string === undefined)
526
- throw new Error('Unexpected end of buffer')
527
- }
528
- }
529
- let srcStringLength = string.length;
530
- if (srcStringLength <= length) {
531
- position += length;
532
- return string
533
- }
534
- srcString = string;
535
- srcStringStart = position;
536
- srcStringEnd = position + srcStringLength;
537
- position += length;
538
- return string.slice(0, length) // we know we just want the beginning
539
- }
540
- }
541
- }
542
- function readStringJS(length) {
543
- let result;
544
- if (length < 16) {
545
- if (result = shortStringInJS(length))
546
- return result
547
- }
548
- if (length > 64 && decoder)
549
- return decoder.decode(src.subarray(position, position += length))
550
- const end = position + length;
551
- const units = [];
552
- result = '';
553
- while (position < end) {
554
- const byte1 = src[position++];
555
- if ((byte1 & 0x80) === 0) {
556
- // 1 byte
557
- units.push(byte1);
558
- } else if ((byte1 & 0xe0) === 0xc0) {
559
- // 2 bytes
560
- const byte2 = src[position++] & 0x3f;
561
- units.push(((byte1 & 0x1f) << 6) | byte2);
562
- } else if ((byte1 & 0xf0) === 0xe0) {
563
- // 3 bytes
564
- const byte2 = src[position++] & 0x3f;
565
- const byte3 = src[position++] & 0x3f;
566
- units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
567
- } else if ((byte1 & 0xf8) === 0xf0) {
568
- // 4 bytes
569
- const byte2 = src[position++] & 0x3f;
570
- const byte3 = src[position++] & 0x3f;
571
- const byte4 = src[position++] & 0x3f;
572
- let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
573
- if (unit > 0xffff) {
574
- unit -= 0x10000;
575
- units.push(((unit >>> 10) & 0x3ff) | 0xd800);
576
- unit = 0xdc00 | (unit & 0x3ff);
577
- }
578
- units.push(unit);
579
- } else {
580
- units.push(byte1);
581
- }
582
-
583
- if (units.length >= 0x1000) {
584
- result += fromCharCode.apply(String, units);
585
- units.length = 0;
586
- }
587
- }
588
-
589
- if (units.length > 0) {
590
- result += fromCharCode.apply(String, units);
591
- }
592
-
593
- return result
594
- }
595
-
596
- function readArray(length) {
597
- let array = new Array(length);
598
- for (let i = 0; i < length; i++) {
599
- array[i] = read();
600
- }
601
- return array
602
- }
603
-
604
- function readMap(length) {
605
- if (currentUnpackr.mapsAsObjects) {
606
- let object = {};
607
- for (let i = 0; i < length; i++) {
608
- object[readKey()] = read();
609
- }
610
- return object
611
- } else {
612
- let map = new Map();
613
- for (let i = 0; i < length; i++) {
614
- map.set(read(), read());
615
- }
616
- return map
617
- }
618
- }
619
-
620
- var fromCharCode = String.fromCharCode;
621
- function longStringInJS(length) {
622
- let start = position;
623
- let bytes = new Array(length);
624
- for (let i = 0; i < length; i++) {
625
- const byte = src[position++];
626
- if ((byte & 0x80) > 0) {
627
- position = start;
628
- return
629
- }
630
- bytes[i] = byte;
631
- }
632
- return fromCharCode.apply(String, bytes)
633
- }
634
- function shortStringInJS(length) {
635
- if (length < 4) {
636
- if (length < 2) {
637
- if (length === 0)
638
- return ''
639
- else {
640
- let a = src[position++];
641
- if ((a & 0x80) > 1) {
642
- position -= 1;
643
- return
644
- }
645
- return fromCharCode(a)
646
- }
647
- } else {
648
- let a = src[position++];
649
- let b = src[position++];
650
- if ((a & 0x80) > 0 || (b & 0x80) > 0) {
651
- position -= 2;
652
- return
653
- }
654
- if (length < 3)
655
- return fromCharCode(a, b)
656
- let c = src[position++];
657
- if ((c & 0x80) > 0) {
658
- position -= 3;
659
- return
660
- }
661
- return fromCharCode(a, b, c)
662
- }
663
- } else {
664
- let a = src[position++];
665
- let b = src[position++];
666
- let c = src[position++];
667
- let d = src[position++];
668
- if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
669
- position -= 4;
670
- return
671
- }
672
- if (length < 6) {
673
- if (length === 4)
674
- return fromCharCode(a, b, c, d)
675
- else {
676
- let e = src[position++];
677
- if ((e & 0x80) > 0) {
678
- position -= 5;
679
- return
680
- }
681
- return fromCharCode(a, b, c, d, e)
682
- }
683
- } else if (length < 8) {
684
- let e = src[position++];
685
- let f = src[position++];
686
- if ((e & 0x80) > 0 || (f & 0x80) > 0) {
687
- position -= 6;
688
- return
689
- }
690
- if (length < 7)
691
- return fromCharCode(a, b, c, d, e, f)
692
- let g = src[position++];
693
- if ((g & 0x80) > 0) {
694
- position -= 7;
695
- return
696
- }
697
- return fromCharCode(a, b, c, d, e, f, g)
698
- } else {
699
- let e = src[position++];
700
- let f = src[position++];
701
- let g = src[position++];
702
- let h = src[position++];
703
- if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
704
- position -= 8;
705
- return
706
- }
707
- if (length < 10) {
708
- if (length === 8)
709
- return fromCharCode(a, b, c, d, e, f, g, h)
710
- else {
711
- let i = src[position++];
712
- if ((i & 0x80) > 0) {
713
- position -= 9;
714
- return
715
- }
716
- return fromCharCode(a, b, c, d, e, f, g, h, i)
717
- }
718
- } else if (length < 12) {
719
- let i = src[position++];
720
- let j = src[position++];
721
- if ((i & 0x80) > 0 || (j & 0x80) > 0) {
722
- position -= 10;
723
- return
724
- }
725
- if (length < 11)
726
- return fromCharCode(a, b, c, d, e, f, g, h, i, j)
727
- let k = src[position++];
728
- if ((k & 0x80) > 0) {
729
- position -= 11;
730
- return
731
- }
732
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
733
- } else {
734
- let i = src[position++];
735
- let j = src[position++];
736
- let k = src[position++];
737
- let l = src[position++];
738
- if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
739
- position -= 12;
740
- return
741
- }
742
- if (length < 14) {
743
- if (length === 12)
744
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
745
- else {
746
- let m = src[position++];
747
- if ((m & 0x80) > 0) {
748
- position -= 13;
749
- return
750
- }
751
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
752
- }
753
- } else {
754
- let m = src[position++];
755
- let n = src[position++];
756
- if ((m & 0x80) > 0 || (n & 0x80) > 0) {
757
- position -= 14;
758
- return
759
- }
760
- if (length < 15)
761
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
762
- let o = src[position++];
763
- if ((o & 0x80) > 0) {
764
- position -= 15;
765
- return
766
- }
767
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
768
- }
769
- }
770
- }
771
- }
772
- }
773
-
774
- function readOnlyJSString() {
775
- let token = src[position++];
776
- let length;
777
- if (token < 0xc0) {
778
- // fixstr
779
- length = token - 0xa0;
780
- } else {
781
- switch(token) {
782
- case 0xd9:
783
- // str 8
784
- length = src[position++];
785
- break
786
- case 0xda:
787
- // str 16
788
- length = dataView.getUint16(position);
789
- position += 2;
790
- break
791
- case 0xdb:
792
- // str 32
793
- length = dataView.getUint32(position);
794
- position += 4;
795
- break
796
- default:
797
- throw new Error('Expected string')
798
- }
799
- }
800
- return readStringJS(length)
801
- }
802
-
803
-
804
- function readBin(length) {
805
- return currentUnpackr.copyBuffers ?
806
- // specifically use the copying slice (not the node one)
807
- Uint8Array.prototype.slice.call(src, position, position += length) :
808
- src.subarray(position, position += length)
809
- }
810
- function readExt(length) {
811
- let type = src[position++];
812
- if (currentExtensions[type]) {
813
- return currentExtensions[type](src.subarray(position, position += length))
814
- }
815
- else
816
- throw new Error('Unknown extension type ' + type)
817
- }
818
-
819
- var keyCache = new Array(4096);
820
- function readKey() {
821
- let length = src[position++];
822
- if (length >= 0xa0 && length < 0xc0) {
823
- // fixstr, potentially use key cache
824
- length = length - 0xa0;
825
- if (srcStringEnd >= position) // if it has been extracted, must use it (and faster anyway)
826
- return srcString.slice(position - srcStringStart, (position += length) - srcStringStart)
827
- else if (!(srcStringEnd == 0 && srcEnd < 180))
828
- return readFixedString(length)
829
- } else { // not cacheable, go back and do a standard read
830
- position--;
831
- return read()
832
- }
833
- let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 0xfff;
834
- let entry = keyCache[key];
835
- let checkPosition = position;
836
- let end = position + length - 3;
837
- let chunk;
838
- let i = 0;
839
- if (entry && entry.bytes == length) {
840
- while (checkPosition < end) {
841
- chunk = dataView.getUint32(checkPosition);
842
- if (chunk != entry[i++]) {
843
- checkPosition = 0x70000000;
844
- break
845
- }
846
- checkPosition += 4;
847
- }
848
- end += 3;
849
- while (checkPosition < end) {
850
- chunk = src[checkPosition++];
851
- if (chunk != entry[i++]) {
852
- checkPosition = 0x70000000;
853
- break
854
- }
855
- }
856
- if (checkPosition === end) {
857
- position = checkPosition;
858
- return entry.string
859
- }
860
- end -= 3;
861
- checkPosition = position;
862
- }
863
- entry = [];
864
- keyCache[key] = entry;
865
- entry.bytes = length;
866
- while (checkPosition < end) {
867
- chunk = dataView.getUint32(checkPosition);
868
- entry.push(chunk);
869
- checkPosition += 4;
870
- }
871
- end += 3;
872
- while (checkPosition < end) {
873
- chunk = src[checkPosition++];
874
- entry.push(chunk);
875
- }
876
- // for small blocks, avoiding the overhead of the extract call is helpful
877
- let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
878
- if (string != null)
879
- return entry.string = string
880
- return entry.string = readFixedString(length)
881
- }
882
-
883
- // the registration of the record definition extension (as "r")
884
- const recordDefinition = (id, highByte) => {
885
- var structure = read();
886
- let firstByte = id;
887
- if (highByte !== undefined) {
888
- id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
889
- structure.highByte = highByte;
890
- }
891
- let existingStructure = currentStructures[id];
892
- if (existingStructure && existingStructure.isShared) {
893
- (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
894
- }
895
- currentStructures[id] = structure;
896
- structure.read = createStructureReader(structure, firstByte);
897
- return structure.read()
898
- };
899
- currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
900
- currentExtensions[0].noBuffer = true;
901
-
902
- currentExtensions[0x65] = () => {
903
- let data = read();
904
- return (globalThis[data[0]] || Error)(data[1])
905
- };
906
-
907
- currentExtensions[0x69] = (data) => {
908
- // id extension (for structured clones)
909
- let id = dataView.getUint32(position - 4);
910
- if (!referenceMap)
911
- referenceMap = new Map();
912
- let token = src[position];
913
- let target;
914
- // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
915
- // ahead past references to record structure definitions
916
- if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
917
- target = [];
918
- else
919
- target = {};
920
-
921
- let refEntry = { target }; // a placeholder object
922
- referenceMap.set(id, refEntry);
923
- let targetProperties = read(); // read the next value as the target object to id
924
- if (refEntry.used) // there is a cycle, so we have to assign properties to original target
925
- return Object.assign(target, targetProperties)
926
- refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
927
- return targetProperties // no cycle, can just use the returned read object
928
- };
929
-
930
- currentExtensions[0x70] = (data) => {
931
- // pointer extension (for structured clones)
932
- let id = dataView.getUint32(position - 4);
933
- let refEntry = referenceMap.get(id);
934
- refEntry.used = true;
935
- return refEntry.target
936
- };
937
-
938
- currentExtensions[0x73] = () => new Set(read());
939
-
940
- const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
941
-
942
- currentExtensions[0x74] = (data) => {
943
- let typeCode = data[0];
944
- let typedArrayName = typedArrays[typeCode];
945
- if (!typedArrayName)
946
- throw new Error('Could not find typed array for code ' + typeCode)
947
- // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
948
- return new globalThis[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer)
949
- };
950
- currentExtensions[0x78] = () => {
951
- let data = read();
952
- return new RegExp(data[0], data[1])
953
- };
954
- const TEMP_BUNDLE = [];
955
- currentExtensions[0x62] = (data) => {
956
- let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
957
- let dataPosition = position;
958
- position += dataSize - data.length;
959
- bundledStrings = TEMP_BUNDLE;
960
- bundledStrings = [readOnlyJSString(), readOnlyJSString()];
961
- bundledStrings.position0 = 0;
962
- bundledStrings.position1 = 0;
963
- bundledStrings.postBundlePosition = position;
964
- position = dataPosition;
965
- return read()
966
- };
967
-
968
- currentExtensions[0xff] = (data) => {
969
- // 32-bit date extension
970
- if (data.length == 4)
971
- return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
972
- else if (data.length == 8)
973
- return new Date(
974
- ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
975
- ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
976
- else if (data.length == 12)// TODO: Implement support for negative
977
- return new Date(
978
- ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
979
- (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
980
- else
981
- return new Date('invalid')
982
- }; // notepack defines extension 0 to mean undefined, so use that as the default here
983
- // registration of bulk record definition?
984
- // currentExtensions[0x52] = () =>
985
-
986
- function saveState(callback) {
987
- let savedSrcEnd = srcEnd;
988
- let savedPosition = position;
989
- let savedStringPosition = stringPosition;
990
- let savedSrcStringStart = srcStringStart;
991
- let savedSrcStringEnd = srcStringEnd;
992
- let savedSrcString = srcString;
993
- let savedStrings = strings;
994
- let savedReferenceMap = referenceMap;
995
- let savedBundledStrings = bundledStrings;
996
-
997
- // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
998
- let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
999
- let savedStructures = currentStructures;
1000
- let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
1001
- let savedPackr = currentUnpackr;
1002
- let savedSequentialMode = sequentialMode;
1003
- let value = callback();
1004
- srcEnd = savedSrcEnd;
1005
- position = savedPosition;
1006
- stringPosition = savedStringPosition;
1007
- srcStringStart = savedSrcStringStart;
1008
- srcStringEnd = savedSrcStringEnd;
1009
- srcString = savedSrcString;
1010
- strings = savedStrings;
1011
- referenceMap = savedReferenceMap;
1012
- bundledStrings = savedBundledStrings;
1013
- src = savedSrc;
1014
- sequentialMode = savedSequentialMode;
1015
- currentStructures = savedStructures;
1016
- currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
1017
- currentUnpackr = savedPackr;
1018
- dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
1019
- return value
1020
- }
1021
- function clearSource() {
1022
- src = null;
1023
- referenceMap = null;
1024
- currentStructures = null;
1025
- }
1026
-
1027
- function addExtension(extension) {
1028
- if (extension.unpack)
1029
- currentExtensions[extension.type] = extension.unpack;
1030
- else
1031
- currentExtensions[extension.type] = extension;
1032
- }
1033
-
1034
- const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
1035
- for (let i = 0; i < 256; i++) {
1036
- mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
1037
- }
1038
- const Decoder = Unpackr;
1039
- var defaultUnpackr = new Unpackr({ useRecords: false });
1040
- const unpack = defaultUnpackr.unpack;
1041
- const unpackMultiple = defaultUnpackr.unpackMultiple;
1042
- const decode = defaultUnpackr.unpack;
1043
- const FLOAT32_OPTIONS = {
1044
- NEVER: 0,
1045
- ALWAYS: 1,
1046
- DECIMAL_ROUND: 3,
1047
- DECIMAL_FIT: 4
1048
- };
1049
- let f32Array = new Float32Array(1);
1050
- let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
1051
- function roundFloat32(float32Number) {
1052
- f32Array[0] = float32Number;
1053
- let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
1054
- return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
8
+ var decoder;
9
+ try {
10
+ decoder = new TextDecoder();
11
+ } catch(error) {}
12
+ var src;
13
+ var srcEnd;
14
+ var position = 0;
15
+ const EMPTY_ARRAY = [];
16
+ var strings = EMPTY_ARRAY;
17
+ var stringPosition = 0;
18
+ var currentUnpackr = {};
19
+ var currentStructures;
20
+ var srcString;
21
+ var srcStringStart = 0;
22
+ var srcStringEnd = 0;
23
+ var bundledStrings;
24
+ var referenceMap;
25
+ var currentExtensions = [];
26
+ var dataView;
27
+ var defaultOptions = {
28
+ useRecords: false,
29
+ mapsAsObjects: true
30
+ };
31
+ class C1Type {}
32
+ const C1 = new C1Type();
33
+ C1.name = 'MessagePack 0xC1';
34
+ var sequentialMode = false;
35
+ var inlineObjectReadThreshold = 2;
36
+ try {
37
+ new Function('');
38
+ } catch(error) {
39
+ // if eval variants are not supported, do not create inline object readers ever
40
+ inlineObjectReadThreshold = Infinity;
1055
41
  }
1056
42
 
1057
- let textEncoder;
1058
- try {
1059
- textEncoder = new TextEncoder();
1060
- } catch (error) {}
1061
- let extensions, extensionClasses;
1062
- const hasNodeBuffer = typeof Buffer !== 'undefined';
1063
- const ByteArrayAllocate = hasNodeBuffer ?
1064
- function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
1065
- const ByteArray = hasNodeBuffer ? Buffer : Uint8Array;
1066
- const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;
1067
- let target, keysTarget;
1068
- let targetView;
1069
- let position$1 = 0;
1070
- let safeEnd;
1071
- let bundledStrings$1 = null;
1072
- const MAX_BUNDLE_SIZE = 0xf000;
1073
- const hasNonLatin = /[\u0080-\uFFFF]/;
1074
- const RECORD_SYMBOL = Symbol('record-id');
1075
- class Packr extends Unpackr {
1076
- constructor(options) {
1077
- super(options);
1078
- this.offset = 0;
1079
- let start;
1080
- let hasSharedUpdate;
1081
- let structures;
1082
- let referenceMap;
1083
- let lastSharedStructuresLength = 0;
1084
- let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
1085
- return target.utf8Write(string, position, 0xffffffff)
1086
- } : (textEncoder && textEncoder.encodeInto) ?
1087
- function(string, position) {
1088
- return textEncoder.encodeInto(string, target.subarray(position)).written
1089
- } : false;
1090
-
1091
- let packr = this;
1092
- if (!options)
1093
- options = {};
1094
- let isSequential = options && options.sequential;
1095
- let hasSharedStructures = options.structures || options.saveStructures;
1096
- let maxSharedStructures = options.maxSharedStructures;
1097
- if (maxSharedStructures == null)
1098
- maxSharedStructures = hasSharedStructures ? 32 : 0;
1099
- if (maxSharedStructures > 8160)
1100
- throw new Error('Maximum maxSharedStructure is 8160')
1101
- if (options.structuredClone && options.moreTypes == undefined) {
1102
- options.moreTypes = true;
1103
- }
1104
- let maxOwnStructures = options.maxOwnStructures;
1105
- if (maxOwnStructures == null)
1106
- maxOwnStructures = hasSharedStructures ? 32 : 64;
1107
- if (!this.structures && options.useRecords != false)
1108
- this.structures = [];
1109
- // two byte record ids for shared structures
1110
- let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);
1111
- let sharedLimitId = maxSharedStructures + 0x40;
1112
- let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
1113
- if (maxStructureId > 8256) {
1114
- throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
1115
- }
1116
- let recordIdsToRemove = [];
1117
- let transitionsCount = 0;
1118
- let serializationsSinceTransitionRebuild = 0;
1119
-
1120
- this.pack = this.encode = function(value, encodeOptions) {
1121
- if (!target) {
1122
- target = new ByteArrayAllocate(8192);
1123
- targetView = new DataView(target.buffer, 0, 8192);
1124
- position$1 = 0;
1125
- }
1126
- safeEnd = target.length - 10;
1127
- if (safeEnd - position$1 < 0x800) {
1128
- // don't start too close to the end,
1129
- target = new ByteArrayAllocate(target.length);
1130
- targetView = new DataView(target.buffer, 0, target.length);
1131
- safeEnd = target.length - 10;
1132
- position$1 = 0;
1133
- } else
1134
- position$1 = (position$1 + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
1135
- start = position$1;
1136
- referenceMap = packr.structuredClone ? new Map() : null;
1137
- if (packr.bundleStrings && typeof value !== 'string') {
1138
- bundledStrings$1 = [];
1139
- bundledStrings$1.size = Infinity; // force a new bundle start on first string
1140
- } else
1141
- bundledStrings$1 = null;
1142
- structures = packr.structures;
1143
- if (structures) {
1144
- if (structures.uninitialized)
1145
- structures = packr._mergeStructures(packr.getStructures());
1146
- let sharedLength = structures.sharedLength || 0;
1147
- if (sharedLength > maxSharedStructures) {
1148
- //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
1149
- throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
1150
- }
1151
- if (!structures.transitions) {
1152
- // rebuild our structure transitions
1153
- structures.transitions = Object.create(null);
1154
- for (let i = 0; i < sharedLength; i++) {
1155
- let keys = structures[i];
1156
- if (!keys)
1157
- continue
1158
- let nextTransition, transition = structures.transitions;
1159
- for (let j = 0, l = keys.length; j < l; j++) {
1160
- let key = keys[j];
1161
- nextTransition = transition[key];
1162
- if (!nextTransition) {
1163
- nextTransition = transition[key] = Object.create(null);
1164
- }
1165
- transition = nextTransition;
1166
- }
1167
- transition[RECORD_SYMBOL] = i + 0x40;
1168
- }
1169
- lastSharedStructuresLength = sharedLength;
1170
- }
1171
- if (!isSequential) {
1172
- structures.nextId = sharedLength + 0x40;
1173
- }
1174
- }
1175
- if (hasSharedUpdate)
1176
- hasSharedUpdate = false;
1177
- try {
1178
- pack(value);
1179
- if (bundledStrings$1) {
1180
- writeBundles(start, pack);
1181
- }
1182
- packr.offset = position$1; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
1183
- if (referenceMap && referenceMap.idsToInsert) {
1184
- position$1 += referenceMap.idsToInsert.length * 6;
1185
- if (position$1 > safeEnd)
1186
- makeRoom(position$1);
1187
- packr.offset = position$1;
1188
- let serialized = insertIds(target.subarray(start, position$1), referenceMap.idsToInsert);
1189
- referenceMap = null;
1190
- return serialized
1191
- }
1192
- if (encodeOptions & REUSE_BUFFER_MODE) {
1193
- target.start = start;
1194
- target.end = position$1;
1195
- return target
1196
- }
1197
- return target.subarray(start, position$1) // position can change if we call pack again in saveStructures, so we get the buffer now
1198
- } finally {
1199
- if (structures) {
1200
- if (serializationsSinceTransitionRebuild < 10)
1201
- serializationsSinceTransitionRebuild++;
1202
- let sharedLength = structures.sharedLength || maxSharedStructures;
1203
- if (structures.length > sharedLength)
1204
- structures.length = sharedLength;
1205
- if (transitionsCount > 10000) {
1206
- // force a rebuild occasionally after a lot of transitions so it can get cleaned up
1207
- structures.transitions = null;
1208
- serializationsSinceTransitionRebuild = 0;
1209
- transitionsCount = 0;
1210
- if (recordIdsToRemove.length > 0)
1211
- recordIdsToRemove = [];
1212
- } else if (recordIdsToRemove.length > 0 && !isSequential) {
1213
- for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
1214
- recordIdsToRemove[i][RECORD_SYMBOL] = 0;
1215
- }
1216
- recordIdsToRemove = [];
1217
- }
1218
- if (hasSharedUpdate && packr.saveStructures) {
1219
- // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
1220
- let returnBuffer = target.subarray(start, position$1);
1221
- if (packr.saveStructures(structures, lastSharedStructuresLength) === false) {
1222
- // get updated structures and try again if the update failed
1223
- packr._mergeStructures(packr.getStructures());
1224
- return packr.pack(value)
1225
- }
1226
- lastSharedStructuresLength = sharedLength;
1227
- return returnBuffer
1228
- }
1229
- }
1230
- if (encodeOptions & RESET_BUFFER_MODE)
1231
- position$1 = start;
1232
- }
1233
- };
1234
- const pack = (value) => {
1235
- if (position$1 > safeEnd)
1236
- target = makeRoom(position$1);
1237
-
1238
- var type = typeof value;
1239
- var length;
1240
- if (type === 'string') {
1241
- let strLength = value.length;
1242
- if (bundledStrings$1 && strLength >= 4 && strLength < 0x1000) {
1243
- if ((bundledStrings$1.size += strLength) > MAX_BUNDLE_SIZE) {
1244
- let extStart;
1245
- let maxBytes = (bundledStrings$1[0] ? bundledStrings$1[0].length * 3 + bundledStrings$1[1].length : 0) + 10;
1246
- if (position$1 + maxBytes > safeEnd)
1247
- target = makeRoom(position$1 + maxBytes);
1248
- if (bundledStrings$1.position) { // here we use the 0x62 extension to write the last bundle and reserve sapce for the reference pointer to the next/current bundle
1249
- target[position$1] = 0xc8; // ext 16
1250
- position$1 += 3; // reserve for the writing bundle size
1251
- target[position$1++] = 0x62; // 'b'
1252
- extStart = position$1 - start;
1253
- position$1 += 4; // reserve for writing bundle reference
1254
- writeBundles(start, pack); // write the last bundles
1255
- targetView.setUint16(extStart + start - 3, position$1 - start - extStart);
1256
- } else { // here we use the 0x62 extension just to reserve the space for the reference pointer to the bundle (will be updated once the bundle is written)
1257
- target[position$1++] = 0xd6; // fixext 4
1258
- target[position$1++] = 0x62; // 'b'
1259
- extStart = position$1 - start;
1260
- position$1 += 4; // reserve for writing bundle reference
1261
- }
1262
- bundledStrings$1 = ['', '']; // create new ones
1263
- bundledStrings$1.size = 0;
1264
- bundledStrings$1.position = extStart;
1265
- }
1266
- let twoByte = hasNonLatin.test(value);
1267
- bundledStrings$1[twoByte ? 0 : 1] += value;
1268
- target[position$1++] = 0xc1;
1269
- pack(twoByte ? -strLength : strLength);
1270
- return
1271
- }
1272
- let headerSize;
1273
- // first we estimate the header size, so we can write to the correct location
1274
- if (strLength < 0x20) {
1275
- headerSize = 1;
1276
- } else if (strLength < 0x100) {
1277
- headerSize = 2;
1278
- } else if (strLength < 0x10000) {
1279
- headerSize = 3;
1280
- } else {
1281
- headerSize = 5;
1282
- }
1283
- let maxBytes = strLength * 3;
1284
- if (position$1 + maxBytes > safeEnd)
1285
- target = makeRoom(position$1 + maxBytes);
1286
-
1287
- if (strLength < 0x40 || !encodeUtf8) {
1288
- let i, c1, c2, strPosition = position$1 + headerSize;
1289
- for (i = 0; i < strLength; i++) {
1290
- c1 = value.charCodeAt(i);
1291
- if (c1 < 0x80) {
1292
- target[strPosition++] = c1;
1293
- } else if (c1 < 0x800) {
1294
- target[strPosition++] = c1 >> 6 | 0xc0;
1295
- target[strPosition++] = c1 & 0x3f | 0x80;
1296
- } else if (
1297
- (c1 & 0xfc00) === 0xd800 &&
1298
- ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
1299
- ) {
1300
- c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
1301
- i++;
1302
- target[strPosition++] = c1 >> 18 | 0xf0;
1303
- target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
1304
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1305
- target[strPosition++] = c1 & 0x3f | 0x80;
1306
- } else {
1307
- target[strPosition++] = c1 >> 12 | 0xe0;
1308
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1309
- target[strPosition++] = c1 & 0x3f | 0x80;
1310
- }
1311
- }
1312
- length = strPosition - position$1 - headerSize;
1313
- } else {
1314
- length = encodeUtf8(value, position$1 + headerSize);
1315
- }
1316
-
1317
- if (length < 0x20) {
1318
- target[position$1++] = 0xa0 | length;
1319
- } else if (length < 0x100) {
1320
- if (headerSize < 2) {
1321
- target.copyWithin(position$1 + 2, position$1 + 1, position$1 + 1 + length);
1322
- }
1323
- target[position$1++] = 0xd9;
1324
- target[position$1++] = length;
1325
- } else if (length < 0x10000) {
1326
- if (headerSize < 3) {
1327
- target.copyWithin(position$1 + 3, position$1 + 2, position$1 + 2 + length);
1328
- }
1329
- target[position$1++] = 0xda;
1330
- target[position$1++] = length >> 8;
1331
- target[position$1++] = length & 0xff;
1332
- } else {
1333
- if (headerSize < 5) {
1334
- target.copyWithin(position$1 + 5, position$1 + 3, position$1 + 3 + length);
1335
- }
1336
- target[position$1++] = 0xdb;
1337
- targetView.setUint32(position$1, length);
1338
- position$1 += 4;
1339
- }
1340
- position$1 += length;
1341
- } else if (type === 'number') {
1342
- if (value >>> 0 === value) {// positive integer, 32-bit or less
1343
- // positive uint
1344
- if (value < 0x40) {
1345
- target[position$1++] = value;
1346
- } else if (value < 0x100) {
1347
- target[position$1++] = 0xcc;
1348
- target[position$1++] = value;
1349
- } else if (value < 0x10000) {
1350
- target[position$1++] = 0xcd;
1351
- target[position$1++] = value >> 8;
1352
- target[position$1++] = value & 0xff;
1353
- } else {
1354
- target[position$1++] = 0xce;
1355
- targetView.setUint32(position$1, value);
1356
- position$1 += 4;
1357
- }
1358
- } else if (value >> 0 === value) { // negative integer
1359
- if (value >= -0x20) {
1360
- target[position$1++] = 0x100 + value;
1361
- } else if (value >= -0x80) {
1362
- target[position$1++] = 0xd0;
1363
- target[position$1++] = value + 0x100;
1364
- } else if (value >= -0x8000) {
1365
- target[position$1++] = 0xd1;
1366
- targetView.setInt16(position$1, value);
1367
- position$1 += 2;
1368
- } else {
1369
- target[position$1++] = 0xd2;
1370
- targetView.setInt32(position$1, value);
1371
- position$1 += 4;
1372
- }
1373
- } else {
1374
- let useFloat32;
1375
- if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
1376
- target[position$1++] = 0xca;
1377
- targetView.setFloat32(position$1, value);
1378
- let xShifted;
1379
- if (useFloat32 < 4 ||
1380
- // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
1381
- ((xShifted = value * mult10[((target[position$1] & 0x7f) << 1) | (target[position$1 + 1] >> 7)]) >> 0) === xShifted) {
1382
- position$1 += 4;
1383
- return
1384
- } else
1385
- position$1--; // move back into position for writing a double
1386
- }
1387
- target[position$1++] = 0xcb;
1388
- targetView.setFloat64(position$1, value);
1389
- position$1 += 8;
1390
- }
1391
- } else if (type === 'object') {
1392
- if (!value)
1393
- target[position$1++] = 0xc0;
1394
- else {
1395
- if (referenceMap) {
1396
- let referee = referenceMap.get(value);
1397
- if (referee) {
1398
- if (!referee.id) {
1399
- let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
1400
- referee.id = idsToInsert.push(referee);
1401
- }
1402
- target[position$1++] = 0xd6; // fixext 4
1403
- target[position$1++] = 0x70; // "p" for pointer
1404
- targetView.setUint32(position$1, referee.id);
1405
- position$1 += 4;
1406
- return
1407
- } else
1408
- referenceMap.set(value, { offset: position$1 - start });
1409
- }
1410
- let constructor = value.constructor;
1411
- if (constructor === Object) {
1412
- writeObject(value, true);
1413
- } else if (constructor === Array) {
1414
- length = value.length;
1415
- if (length < 0x10) {
1416
- target[position$1++] = 0x90 | length;
1417
- } else if (length < 0x10000) {
1418
- target[position$1++] = 0xdc;
1419
- target[position$1++] = length >> 8;
1420
- target[position$1++] = length & 0xff;
1421
- } else {
1422
- target[position$1++] = 0xdd;
1423
- targetView.setUint32(position$1, length);
1424
- position$1 += 4;
1425
- }
1426
- for (let i = 0; i < length; i++) {
1427
- pack(value[i]);
1428
- }
1429
- } else if (constructor === Map) {
1430
- length = value.size;
1431
- if (length < 0x10) {
1432
- target[position$1++] = 0x80 | length;
1433
- } else if (length < 0x10000) {
1434
- target[position$1++] = 0xde;
1435
- target[position$1++] = length >> 8;
1436
- target[position$1++] = length & 0xff;
1437
- } else {
1438
- target[position$1++] = 0xdf;
1439
- targetView.setUint32(position$1, length);
1440
- position$1 += 4;
1441
- }
1442
- for (let [ key, entryValue ] of value) {
1443
- pack(key);
1444
- pack(entryValue);
1445
- }
1446
- } else {
1447
- for (let i = 0, l = extensions.length; i < l; i++) {
1448
- let extensionClass = extensionClasses[i];
1449
- if (value instanceof extensionClass) {
1450
- let extension = extensions[i];
1451
- if (extension.write) {
1452
- if (extension.type) {
1453
- target[position$1++] = 0xd4; // one byte "tag" extension
1454
- target[position$1++] = extension.type;
1455
- target[position$1++] = 0;
1456
- }
1457
- pack(extension.write.call(this, value));
1458
- return
1459
- }
1460
- let currentTarget = target;
1461
- let currentTargetView = targetView;
1462
- let currentPosition = position$1;
1463
- target = null;
1464
- let result;
1465
- try {
1466
- result = extension.pack.call(this, value, (size) => {
1467
- // restore target and use it
1468
- target = currentTarget;
1469
- currentTarget = null;
1470
- position$1 += size;
1471
- if (position$1 > safeEnd)
1472
- makeRoom(position$1);
1473
- return {
1474
- target, targetView, position: position$1 - size
1475
- }
1476
- }, pack);
1477
- } finally {
1478
- // restore current target information (unless already restored)
1479
- if (currentTarget) {
1480
- target = currentTarget;
1481
- targetView = currentTargetView;
1482
- position$1 = currentPosition;
1483
- safeEnd = target.length - 10;
1484
- }
1485
- }
1486
- if (result) {
1487
- if (result.length + position$1 > safeEnd)
1488
- makeRoom(result.length + position$1);
1489
- position$1 = writeExtensionData(result, target, position$1, extension.type);
1490
- }
1491
- return
1492
- }
1493
- }
1494
- // no extension found, write as object
1495
- writeObject(value, !value.hasOwnProperty); // if it doesn't have hasOwnProperty, don't do hasOwnProperty checks
1496
- }
1497
- }
1498
- } else if (type === 'boolean') {
1499
- target[position$1++] = value ? 0xc3 : 0xc2;
1500
- } else if (type === 'bigint') {
1501
- if (value < (BigInt(1)<<BigInt(63)) && value >= -(BigInt(1)<<BigInt(63))) {
1502
- // use a signed int as long as it fits
1503
- target[position$1++] = 0xd3;
1504
- targetView.setBigInt64(position$1, value);
1505
- } else if (value < (BigInt(1)<<BigInt(64)) && value > 0) {
1506
- // if we can fit an unsigned int, use that
1507
- target[position$1++] = 0xcf;
1508
- targetView.setBigUint64(position$1, value);
1509
- } else {
1510
- // overflow
1511
- if (this.largeBigIntToFloat) {
1512
- target[position$1++] = 0xcb;
1513
- targetView.setFloat64(position$1, Number(value));
1514
- } else {
1515
- throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, set largeBigIntToFloat to convert to float-64')
1516
- }
1517
- }
1518
- position$1 += 8;
1519
- } else if (type === 'undefined') {
1520
- if (this.encodeUndefinedAsNil)
1521
- target[position$1++] = 0xc0;
1522
- else {
1523
- target[position$1++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
1524
- target[position$1++] = 0;
1525
- target[position$1++] = 0;
1526
- }
1527
- } else if (type === 'function') {
1528
- pack(this.writeFunction && this.writeFunction()); // if there is a writeFunction, use it, otherwise just encode as undefined
1529
- } else {
1530
- throw new Error('Unknown type: ' + type)
1531
- }
1532
- };
1533
-
1534
- const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {
1535
- // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
1536
- let keys = Object.keys(object);
1537
- let length = keys.length;
1538
- if (length < 0x10) {
1539
- target[position$1++] = 0x80 | length;
1540
- } else if (length < 0x10000) {
1541
- target[position$1++] = 0xde;
1542
- target[position$1++] = length >> 8;
1543
- target[position$1++] = length & 0xff;
1544
- } else {
1545
- target[position$1++] = 0xdf;
1546
- targetView.setUint32(position$1, length);
1547
- position$1 += 4;
1548
- }
1549
- let key;
1550
- for (let i = 0; i < length; i++) {
1551
- pack(key = keys[i]);
1552
- pack(object[key]);
1553
- }
1554
- } :
1555
- (object, safePrototype) => {
1556
- target[position$1++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
1557
- let objectOffset = position$1 - start;
1558
- position$1 += 2;
1559
- let size = 0;
1560
- for (let key in object) {
1561
- if (safePrototype || object.hasOwnProperty(key)) {
1562
- pack(key);
1563
- pack(object[key]);
1564
- size++;
1565
- }
1566
- }
1567
- target[objectOffset++ + start] = size >> 8;
1568
- target[objectOffset + start] = size & 0xff;
1569
- } :
1570
- (options.progressiveRecords && !useTwoByteRecords) ? // this is about 2% faster for highly stable structures, since it only requires one for-in loop (but much more expensive when new structure needs to be written)
1571
- (object, safePrototype) => {
1572
- let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1573
- let objectOffset = position$1++ - start;
1574
- let wroteKeys;
1575
- for (let key in object) {
1576
- if (safePrototype || object.hasOwnProperty(key)) {
1577
- nextTransition = transition[key];
1578
- if (nextTransition)
1579
- transition = nextTransition;
1580
- else {
1581
- // record doesn't exist, create full new record and insert it
1582
- let keys = Object.keys(object);
1583
- let lastTransition = transition;
1584
- transition = structures.transitions;
1585
- let newTransitions = 0;
1586
- for (let i = 0, l = keys.length; i < l; i++) {
1587
- let key = keys[i];
1588
- nextTransition = transition[key];
1589
- if (!nextTransition) {
1590
- nextTransition = transition[key] = Object.create(null);
1591
- newTransitions++;
1592
- }
1593
- transition = nextTransition;
1594
- }
1595
- if (objectOffset + start + 1 == position$1) {
1596
- // first key, so we don't need to insert, we can just write record directly
1597
- position$1--;
1598
- newRecord(transition, keys, newTransitions);
1599
- } else // otherwise we need to insert the record, moving existing data after the record
1600
- insertNewRecord(transition, keys, objectOffset, newTransitions);
1601
- wroteKeys = true;
1602
- transition = lastTransition[key];
1603
- }
1604
- pack(object[key]);
1605
- }
1606
- }
1607
- if (!wroteKeys) {
1608
- let recordId = transition[RECORD_SYMBOL];
1609
- if (recordId)
1610
- target[objectOffset + start] = recordId;
1611
- else
1612
- insertNewRecord(transition, Object.keys(object), objectOffset, 0);
1613
- }
1614
- } :
1615
- (object, safePrototype) => {
1616
- let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1617
- let newTransitions = 0;
1618
- for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
1619
- nextTransition = transition[key];
1620
- if (!nextTransition) {
1621
- nextTransition = transition[key] = Object.create(null);
1622
- newTransitions++;
1623
- }
1624
- transition = nextTransition;
1625
- }
1626
- let recordId = transition[RECORD_SYMBOL];
1627
- if (recordId) {
1628
- if (recordId >= 0x60 && useTwoByteRecords) {
1629
- target[position$1++] = ((recordId -= 0x60) & 0x1f) + 0x60;
1630
- target[position$1++] = recordId >> 5;
1631
- } else
1632
- target[position$1++] = recordId;
1633
- } else {
1634
- newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
1635
- }
1636
- // now write the values
1637
- for (let key in object)
1638
- if (safePrototype || object.hasOwnProperty(key))
1639
- pack(object[key]);
1640
- };
1641
- const makeRoom = (end) => {
1642
- let newSize;
1643
- if (end > 0x1000000) {
1644
- // special handling for really large buffers
1645
- if ((end - start) > MAX_BUFFER_SIZE)
1646
- throw new Error('Packed buffer would be larger than maximum buffer size')
1647
- newSize = Math.min(MAX_BUFFER_SIZE,
1648
- Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
1649
- } else // faster handling for smaller buffers
1650
- newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
1651
- let newBuffer = new ByteArrayAllocate(newSize);
1652
- targetView = new DataView(newBuffer.buffer, 0, newSize);
1653
- end = Math.min(end, target.length);
1654
- if (target.copy)
1655
- target.copy(newBuffer, 0, start, end);
1656
- else
1657
- newBuffer.set(target.slice(start, end));
1658
- position$1 -= start;
1659
- start = 0;
1660
- safeEnd = newBuffer.length - 10;
1661
- return target = newBuffer
1662
- };
1663
- const newRecord = (transition, keys, newTransitions) => {
1664
- let recordId = structures.nextId;
1665
- if (!recordId)
1666
- recordId = 0x40;
1667
- if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
1668
- recordId = structures.nextOwnId;
1669
- if (!(recordId < maxStructureId))
1670
- recordId = sharedLimitId;
1671
- structures.nextOwnId = recordId + 1;
1672
- } else {
1673
- if (recordId >= maxStructureId)// cycle back around
1674
- recordId = sharedLimitId;
1675
- structures.nextId = recordId + 1;
1676
- }
1677
- let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
1678
- transition[RECORD_SYMBOL] = recordId;
1679
- transition.__keys__ = keys;
1680
- structures[recordId - 0x40] = keys;
1681
-
1682
- if (recordId < sharedLimitId) {
1683
- keys.isShared = true;
1684
- structures.sharedLength = recordId - 0x3f;
1685
- hasSharedUpdate = true;
1686
- if (highByte >= 0) {
1687
- target[position$1++] = (recordId & 0x1f) + 0x60;
1688
- target[position$1++] = highByte;
1689
- } else {
1690
- target[position$1++] = recordId;
1691
- }
1692
- } else {
1693
- if (highByte >= 0) {
1694
- target[position$1++] = 0xd5; // fixext 2
1695
- target[position$1++] = 0x72; // "r" record defintion extension type
1696
- target[position$1++] = (recordId & 0x1f) + 0x60;
1697
- target[position$1++] = highByte;
1698
- } else {
1699
- target[position$1++] = 0xd4; // fixext 1
1700
- target[position$1++] = 0x72; // "r" record defintion extension type
1701
- target[position$1++] = recordId;
1702
- }
1703
-
1704
- if (newTransitions)
1705
- transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
1706
- // record the removal of the id, we can maintain our shared structure
1707
- if (recordIdsToRemove.length >= maxOwnStructures)
1708
- recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
1709
- recordIdsToRemove.push(transition);
1710
- pack(keys);
1711
- }
1712
- };
1713
- const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
1714
- let mainTarget = target;
1715
- let mainPosition = position$1;
1716
- let mainSafeEnd = safeEnd;
1717
- let mainStart = start;
1718
- target = keysTarget;
1719
- position$1 = 0;
1720
- start = 0;
1721
- if (!target)
1722
- keysTarget = target = new ByteArrayAllocate(8192);
1723
- safeEnd = target.length - 10;
1724
- newRecord(transition, keys, newTransitions);
1725
- keysTarget = target;
1726
- let keysPosition = position$1;
1727
- target = mainTarget;
1728
- position$1 = mainPosition;
1729
- safeEnd = mainSafeEnd;
1730
- start = mainStart;
1731
- if (keysPosition > 1) {
1732
- let newEnd = position$1 + keysPosition - 1;
1733
- if (newEnd > safeEnd)
1734
- makeRoom(newEnd);
1735
- let insertionPosition = insertionOffset + start;
1736
- target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position$1);
1737
- target.set(keysTarget.slice(0, keysPosition), insertionPosition);
1738
- position$1 = newEnd;
1739
- } else {
1740
- target[insertionOffset + start] = keysTarget[0];
1741
- }
1742
- };
1743
- }
1744
- useBuffer(buffer) {
1745
- // this means we are finished using our own buffer and we can write over it safely
1746
- target = buffer;
1747
- targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
1748
- position$1 = 0;
1749
- }
1750
- clearSharedData() {
1751
- if (this.structures)
1752
- this.structures = [];
1753
- }
1754
- }
1755
-
1756
- extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, C1Type ];
1757
- extensions = [{
1758
- pack(date, allocateForWrite, pack) {
1759
- let seconds = date.getTime() / 1000;
1760
- if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
1761
- // Timestamp 32
1762
- let { target, targetView, position} = allocateForWrite(6);
1763
- target[position++] = 0xd6;
1764
- target[position++] = 0xff;
1765
- targetView.setUint32(position, seconds);
1766
- } else if (seconds > 0 && seconds < 0x100000000) {
1767
- // Timestamp 64
1768
- let { target, targetView, position} = allocateForWrite(10);
1769
- target[position++] = 0xd7;
1770
- target[position++] = 0xff;
1771
- targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
1772
- targetView.setUint32(position + 4, seconds);
1773
- } else if (isNaN(seconds)) {
1774
- if (this.onInvalidDate) {
1775
- allocateForWrite(0);
1776
- return pack(this.onInvalidDate())
1777
- }
1778
- // Intentionally invalid timestamp
1779
- let { target, targetView, position} = allocateForWrite(3);
1780
- target[position++] = 0xd4;
1781
- target[position++] = 0xff;
1782
- target[position++] = 0xff;
1783
- } else {
1784
- // Timestamp 96
1785
- let { target, targetView, position} = allocateForWrite(15);
1786
- target[position++] = 0xc7;
1787
- target[position++] = 12;
1788
- target[position++] = 0xff;
1789
- targetView.setUint32(position, date.getMilliseconds() * 1000000);
1790
- targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
1791
- }
1792
- }
1793
- }, {
1794
- pack(set, allocateForWrite, pack) {
1795
- let array = Array.from(set);
1796
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1797
- if (this.moreTypes) {
1798
- target[position++] = 0xd4;
1799
- target[position++] = 0x73; // 's' for Set
1800
- target[position++] = 0;
1801
- }
1802
- pack(array);
1803
- }
1804
- }, {
1805
- pack(error, allocateForWrite, pack) {
1806
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1807
- if (this.moreTypes) {
1808
- target[position++] = 0xd4;
1809
- target[position++] = 0x65; // 'e' for error
1810
- target[position++] = 0;
1811
- }
1812
- pack([ error.name, error.message ]);
1813
- }
1814
- }, {
1815
- pack(regex, allocateForWrite, pack) {
1816
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1817
- if (this.moreTypes) {
1818
- target[position++] = 0xd4;
1819
- target[position++] = 0x78; // 'x' for regeXp
1820
- target[position++] = 0;
1821
- }
1822
- pack([ regex.source, regex.flags ]);
1823
- }
1824
- }, {
1825
- pack(arrayBuffer, allocateForWrite) {
1826
- if (this.moreTypes)
1827
- writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
1828
- else
1829
- writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
1830
- }
1831
- }, {
1832
- pack(typedArray, allocateForWrite) {
1833
- let constructor = typedArray.constructor;
1834
- if (constructor !== ByteArray && this.moreTypes)
1835
- writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
1836
- else
1837
- writeBuffer(typedArray, allocateForWrite);
1838
- }
1839
- }, {
1840
- pack(c1, allocateForWrite) { // specific 0xC1 object
1841
- let { target, position} = allocateForWrite(1);
1842
- target[position] = 0xc1;
1843
- }
1844
- }];
1845
-
1846
- function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
1847
- let length = typedArray.byteLength;
1848
- if (length + 1 < 0x100) {
1849
- var { target, position } = allocateForWrite(4 + length);
1850
- target[position++] = 0xc7;
1851
- target[position++] = length + 1;
1852
- } else if (length + 1 < 0x10000) {
1853
- var { target, position } = allocateForWrite(5 + length);
1854
- target[position++] = 0xc8;
1855
- target[position++] = (length + 1) >> 8;
1856
- target[position++] = (length + 1) & 0xff;
1857
- } else {
1858
- var { target, position, targetView } = allocateForWrite(7 + length);
1859
- target[position++] = 0xc9;
1860
- targetView.setUint32(position, length + 1); // plus one for the type byte
1861
- position += 4;
1862
- }
1863
- target[position++] = 0x74; // "t" for typed array
1864
- target[position++] = type;
1865
- target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
1866
- }
1867
- function writeBuffer(buffer, allocateForWrite) {
1868
- let length = buffer.byteLength;
1869
- var target, position;
1870
- if (length < 0x100) {
1871
- var { target, position } = allocateForWrite(length + 2);
1872
- target[position++] = 0xc4;
1873
- target[position++] = length;
1874
- } else if (length < 0x10000) {
1875
- var { target, position } = allocateForWrite(length + 3);
1876
- target[position++] = 0xc5;
1877
- target[position++] = length >> 8;
1878
- target[position++] = length & 0xff;
1879
- } else {
1880
- var { target, position, targetView } = allocateForWrite(length + 5);
1881
- target[position++] = 0xc6;
1882
- targetView.setUint32(position, length);
1883
- position += 4;
1884
- }
1885
- target.set(buffer, position);
1886
- }
1887
-
1888
- function writeExtensionData(result, target, position, type) {
1889
- let length = result.length;
1890
- switch (length) {
1891
- case 1:
1892
- target[position++] = 0xd4;
1893
- break
1894
- case 2:
1895
- target[position++] = 0xd5;
1896
- break
1897
- case 4:
1898
- target[position++] = 0xd6;
1899
- break
1900
- case 8:
1901
- target[position++] = 0xd7;
1902
- break
1903
- case 16:
1904
- target[position++] = 0xd8;
1905
- break
1906
- default:
1907
- if (length < 0x100) {
1908
- target[position++] = 0xc7;
1909
- target[position++] = length;
1910
- } else if (length < 0x10000) {
1911
- target[position++] = 0xc8;
1912
- target[position++] = length >> 8;
1913
- target[position++] = length & 0xff;
1914
- } else {
1915
- target[position++] = 0xc9;
1916
- target[position++] = length >> 24;
1917
- target[position++] = (length >> 16) & 0xff;
1918
- target[position++] = (length >> 8) & 0xff;
1919
- target[position++] = length & 0xff;
1920
- }
1921
- }
1922
- target[position++] = type;
1923
- target.set(result, position);
1924
- position += length;
1925
- return position
1926
- }
1927
-
1928
- function insertIds(serialized, idsToInsert) {
1929
- // insert the ids that need to be referenced for structured clones
1930
- let nextId;
1931
- let distanceToMove = idsToInsert.length * 6;
1932
- let lastEnd = serialized.length - distanceToMove;
1933
- idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
1934
- while (nextId = idsToInsert.pop()) {
1935
- let offset = nextId.offset;
1936
- let id = nextId.id;
1937
- serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
1938
- distanceToMove -= 6;
1939
- let position = offset + distanceToMove;
1940
- serialized[position++] = 0xd6;
1941
- serialized[position++] = 0x69; // 'i'
1942
- serialized[position++] = id >> 24;
1943
- serialized[position++] = (id >> 16) & 0xff;
1944
- serialized[position++] = (id >> 8) & 0xff;
1945
- serialized[position++] = id & 0xff;
1946
- lastEnd = offset;
1947
- }
1948
- return serialized
1949
- }
1950
-
1951
- function writeBundles(start, pack) {
1952
- targetView.setUint32(bundledStrings$1.position + start, position$1 - bundledStrings$1.position - start);
1953
- let writeStrings = bundledStrings$1;
1954
- bundledStrings$1 = null;
1955
- pack(writeStrings[0]);
1956
- pack(writeStrings[1]);
1957
- }
1958
-
1959
- function addExtension$1(extension) {
1960
- if (extension.Class) {
1961
- if (!extension.pack && !extension.write)
1962
- throw new Error('Extension has no pack or write function')
1963
- if (extension.pack && !extension.type)
1964
- throw new Error('Extension has no type (numeric code to identify the extension)')
1965
- extensionClasses.unshift(extension.Class);
1966
- extensions.unshift(extension);
1967
- }
1968
- addExtension(extension);
1969
- }
1970
-
1971
- let defaultPackr = new Packr({ useRecords: false });
1972
- const pack = defaultPackr.pack;
1973
- const encode = defaultPackr.pack;
1974
- const Encoder = Packr;
1975
- const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
1976
- const REUSE_BUFFER_MODE = 512;
43
+ class Unpackr {
44
+ constructor(options) {
45
+ if (options) {
46
+ if (options.useRecords === false && options.mapsAsObjects === undefined)
47
+ options.mapsAsObjects = true;
48
+ if (options.sequential && options.trusted !== false) {
49
+ options.trusted = true;
50
+ if (!options.structures && options.useRecords != false) {
51
+ options.structures = [];
52
+ if (!options.maxSharedStructures)
53
+ options.maxSharedStructures = 0;
54
+ }
55
+ }
56
+ if (options.structures)
57
+ options.structures.sharedLength = options.structures.length;
58
+ else if (options.getStructures) {
59
+ (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
60
+ options.structures.sharedLength = 0;
61
+ }
62
+ }
63
+ Object.assign(this, options);
64
+ }
65
+ unpack(source, end) {
66
+ if (src) {
67
+ // re-entrant execution, save the state and restore it after we do this unpack
68
+ return saveState(() => {
69
+ clearSource();
70
+ return this ? this.unpack(source, end) : Unpackr.prototype.unpack.call(defaultOptions, source, end)
71
+ })
72
+ }
73
+ srcEnd = end > -1 ? end : source.length;
74
+ position = 0;
75
+ stringPosition = 0;
76
+ srcStringEnd = 0;
77
+ srcString = null;
78
+ strings = EMPTY_ARRAY;
79
+ bundledStrings = null;
80
+ src = source;
81
+ // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
82
+ // technique for getting data from a database where it can be copied into an existing buffer instead of creating
83
+ // new ones
84
+ try {
85
+ dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
86
+ } catch(error) {
87
+ // if it doesn't have a buffer, maybe it is the wrong type of object
88
+ src = null;
89
+ if (source instanceof Uint8Array)
90
+ throw error
91
+ throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
92
+ }
93
+ if (this instanceof Unpackr) {
94
+ currentUnpackr = this;
95
+ if (this.structures) {
96
+ currentStructures = this.structures;
97
+ return checkedRead()
98
+ } else if (!currentStructures || currentStructures.length > 0) {
99
+ currentStructures = [];
100
+ }
101
+ } else {
102
+ currentUnpackr = defaultOptions;
103
+ if (!currentStructures || currentStructures.length > 0)
104
+ currentStructures = [];
105
+ }
106
+ return checkedRead()
107
+ }
108
+ unpackMultiple(source, forEach) {
109
+ let values, lastPosition = 0;
110
+ try {
111
+ sequentialMode = true;
112
+ let size = source.length;
113
+ let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
114
+ if (forEach) {
115
+ forEach(value);
116
+ while(position < size) {
117
+ lastPosition = position;
118
+ if (forEach(checkedRead()) === false) {
119
+ return
120
+ }
121
+ }
122
+ }
123
+ else {
124
+ values = [ value ];
125
+ while(position < size) {
126
+ lastPosition = position;
127
+ values.push(checkedRead());
128
+ }
129
+ return values
130
+ }
131
+ } catch(error) {
132
+ error.lastPosition = lastPosition;
133
+ error.values = values;
134
+ throw error
135
+ } finally {
136
+ sequentialMode = false;
137
+ clearSource();
138
+ }
139
+ }
140
+ _mergeStructures(loadedStructures, existingStructures) {
141
+ loadedStructures = loadedStructures || [];
142
+ for (let i = 0, l = loadedStructures.length; i < l; i++) {
143
+ let structure = loadedStructures[i];
144
+ if (structure) {
145
+ structure.isShared = true;
146
+ if (i >= 32)
147
+ structure.highByte = (i - 32) >> 5;
148
+ }
149
+ }
150
+ loadedStructures.sharedLength = loadedStructures.length;
151
+ for (let id in existingStructures || []) {
152
+ if (id >= 0) {
153
+ let structure = loadedStructures[id];
154
+ let existing = existingStructures[id];
155
+ if (existing) {
156
+ if (structure)
157
+ (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
158
+ loadedStructures[id] = existing;
159
+ }
160
+ }
161
+ }
162
+ return this.structures = loadedStructures
163
+ }
164
+ decode(source, end) {
165
+ return this.unpack(source, end)
166
+ }
167
+ }
168
+ function checkedRead() {
169
+ try {
170
+ if (!currentUnpackr.trusted && !sequentialMode) {
171
+ let sharedLength = currentStructures.sharedLength || 0;
172
+ if (sharedLength < currentStructures.length)
173
+ currentStructures.length = sharedLength;
174
+ }
175
+ let result = read();
176
+ if (bundledStrings) // bundled strings to skip past
177
+ position = bundledStrings.postBundlePosition;
178
+
179
+ if (position == srcEnd) {
180
+ // finished reading this source, cleanup references
181
+ if (currentStructures.restoreStructures)
182
+ restoreStructures();
183
+ currentStructures = null;
184
+ src = null;
185
+ if (referenceMap)
186
+ referenceMap = null;
187
+ } else if (position > srcEnd) {
188
+ // over read
189
+ throw new Error('Unexpected end of MessagePack data')
190
+ } else if (!sequentialMode) {
191
+ throw new Error('Data read, but end of buffer not reached ' + JSON.stringify(result).slice(0, 100))
192
+ }
193
+ // else more to read, but we are reading sequentially, so don't clear source yet
194
+ return result
195
+ } catch(error) {
196
+ if (currentStructures.restoreStructures)
197
+ restoreStructures();
198
+ clearSource();
199
+ if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position > srcEnd) {
200
+ error.incomplete = true;
201
+ }
202
+ throw error
203
+ }
204
+ }
205
+
206
+ function restoreStructures() {
207
+ for (let id in currentStructures.restoreStructures) {
208
+ currentStructures[id] = currentStructures.restoreStructures[id];
209
+ }
210
+ currentStructures.restoreStructures = null;
211
+ }
212
+
213
+ function read() {
214
+ let token = src[position++];
215
+ if (token < 0xa0) {
216
+ if (token < 0x80) {
217
+ if (token < 0x40)
218
+ return token
219
+ else {
220
+ let structure = currentStructures[token & 0x3f] ||
221
+ currentUnpackr.getStructures && loadStructures()[token & 0x3f];
222
+ if (structure) {
223
+ if (!structure.read) {
224
+ structure.read = createStructureReader(structure, token & 0x3f);
225
+ }
226
+ return structure.read()
227
+ } else
228
+ return token
229
+ }
230
+ } else if (token < 0x90) {
231
+ // map
232
+ token -= 0x80;
233
+ if (currentUnpackr.mapsAsObjects) {
234
+ let object = {};
235
+ for (let i = 0; i < token; i++) {
236
+ object[readKey()] = read();
237
+ }
238
+ return object
239
+ } else {
240
+ let map = new Map();
241
+ for (let i = 0; i < token; i++) {
242
+ map.set(read(), read());
243
+ }
244
+ return map
245
+ }
246
+ } else {
247
+ token -= 0x90;
248
+ let array = new Array(token);
249
+ for (let i = 0; i < token; i++) {
250
+ array[i] = read();
251
+ }
252
+ return array
253
+ }
254
+ } else if (token < 0xc0) {
255
+ // fixstr
256
+ let length = token - 0xa0;
257
+ if (srcStringEnd >= position) {
258
+ return srcString.slice(position - srcStringStart, (position += length) - srcStringStart)
259
+ }
260
+ if (srcStringEnd == 0 && srcEnd < 140) {
261
+ // for small blocks, avoiding the overhead of the extract call is helpful
262
+ let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
263
+ if (string != null)
264
+ return string
265
+ }
266
+ return readFixedString(length)
267
+ } else {
268
+ let value;
269
+ switch (token) {
270
+ case 0xc0: return null
271
+ case 0xc1:
272
+ if (bundledStrings) {
273
+ value = read(); // followed by the length of the string in characters (not bytes!)
274
+ if (value > 0)
275
+ return bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value)
276
+ else
277
+ return bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 -= value)
278
+ }
279
+ return C1; // "never-used", return special object to denote that
280
+ case 0xc2: return false
281
+ case 0xc3: return true
282
+ case 0xc4:
283
+ // bin 8
284
+ value = src[position++];
285
+ if (value === undefined)
286
+ throw new Error('Unexpected end of buffer')
287
+ return readBin(value)
288
+ case 0xc5:
289
+ // bin 16
290
+ value = dataView.getUint16(position);
291
+ position += 2;
292
+ return readBin(value)
293
+ case 0xc6:
294
+ // bin 32
295
+ value = dataView.getUint32(position);
296
+ position += 4;
297
+ return readBin(value)
298
+ case 0xc7:
299
+ // ext 8
300
+ return readExt(src[position++])
301
+ case 0xc8:
302
+ // ext 16
303
+ value = dataView.getUint16(position);
304
+ position += 2;
305
+ return readExt(value)
306
+ case 0xc9:
307
+ // ext 32
308
+ value = dataView.getUint32(position);
309
+ position += 4;
310
+ return readExt(value)
311
+ case 0xca:
312
+ value = dataView.getFloat32(position);
313
+ if (currentUnpackr.useFloat32 > 2) {
314
+ // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
315
+ let multiplier = mult10[((src[position] & 0x7f) << 1) | (src[position + 1] >> 7)];
316
+ position += 4;
317
+ return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
318
+ }
319
+ position += 4;
320
+ return value
321
+ case 0xcb:
322
+ value = dataView.getFloat64(position);
323
+ position += 8;
324
+ return value
325
+ // uint handlers
326
+ case 0xcc:
327
+ return src[position++]
328
+ case 0xcd:
329
+ value = dataView.getUint16(position);
330
+ position += 2;
331
+ return value
332
+ case 0xce:
333
+ value = dataView.getUint32(position);
334
+ position += 4;
335
+ return value
336
+ case 0xcf:
337
+ if (currentUnpackr.int64AsNumber) {
338
+ value = dataView.getUint32(position) * 0x100000000;
339
+ value += dataView.getUint32(position + 4);
340
+ } else
341
+ value = dataView.getBigUint64(position);
342
+ position += 8;
343
+ return value
344
+
345
+ // int handlers
346
+ case 0xd0:
347
+ return dataView.getInt8(position++)
348
+ case 0xd1:
349
+ value = dataView.getInt16(position);
350
+ position += 2;
351
+ return value
352
+ case 0xd2:
353
+ value = dataView.getInt32(position);
354
+ position += 4;
355
+ return value
356
+ case 0xd3:
357
+ if (currentUnpackr.int64AsNumber) {
358
+ value = dataView.getInt32(position) * 0x100000000;
359
+ value += dataView.getUint32(position + 4);
360
+ } else
361
+ value = dataView.getBigInt64(position);
362
+ position += 8;
363
+ return value
364
+
365
+ case 0xd4:
366
+ // fixext 1
367
+ value = src[position++];
368
+ if (value == 0x72) {
369
+ return recordDefinition(src[position++] & 0x3f)
370
+ } else {
371
+ let extension = currentExtensions[value];
372
+ if (extension) {
373
+ if (extension.read) {
374
+ position++; // skip filler byte
375
+ return extension.read(read())
376
+ } else if (extension.noBuffer) {
377
+ position++; // skip filler byte
378
+ return extension()
379
+ } else
380
+ return extension(src.subarray(position, ++position))
381
+ } else
382
+ throw new Error('Unknown extension ' + value)
383
+ }
384
+ case 0xd5:
385
+ // fixext 2
386
+ value = src[position];
387
+ if (value == 0x72) {
388
+ position++;
389
+ return recordDefinition(src[position++] & 0x3f, src[position++])
390
+ } else
391
+ return readExt(2)
392
+ case 0xd6:
393
+ // fixext 4
394
+ return readExt(4)
395
+ case 0xd7:
396
+ // fixext 8
397
+ return readExt(8)
398
+ case 0xd8:
399
+ // fixext 16
400
+ return readExt(16)
401
+ case 0xd9:
402
+ // str 8
403
+ value = src[position++];
404
+ if (srcStringEnd >= position) {
405
+ return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
406
+ }
407
+ return readString8(value)
408
+ case 0xda:
409
+ // str 16
410
+ value = dataView.getUint16(position);
411
+ position += 2;
412
+ if (srcStringEnd >= position) {
413
+ return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
414
+ }
415
+ return readString16(value)
416
+ case 0xdb:
417
+ // str 32
418
+ value = dataView.getUint32(position);
419
+ position += 4;
420
+ if (srcStringEnd >= position) {
421
+ return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
422
+ }
423
+ return readString32(value)
424
+ case 0xdc:
425
+ // array 16
426
+ value = dataView.getUint16(position);
427
+ position += 2;
428
+ return readArray(value)
429
+ case 0xdd:
430
+ // array 32
431
+ value = dataView.getUint32(position);
432
+ position += 4;
433
+ return readArray(value)
434
+ case 0xde:
435
+ // map 16
436
+ value = dataView.getUint16(position);
437
+ position += 2;
438
+ return readMap(value)
439
+ case 0xdf:
440
+ // map 32
441
+ value = dataView.getUint32(position);
442
+ position += 4;
443
+ return readMap(value)
444
+ default: // negative int
445
+ if (token >= 0xe0)
446
+ return token - 0x100
447
+ if (token === undefined) {
448
+ let error = new Error('Unexpected end of MessagePack data');
449
+ error.incomplete = true;
450
+ throw error
451
+ }
452
+ throw new Error('Unknown MessagePack token ' + token)
453
+
454
+ }
455
+ }
456
+ }
457
+ const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
458
+ function createStructureReader(structure, firstId) {
459
+ function readObject() {
460
+ // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
461
+ if (readObject.count++ > inlineObjectReadThreshold) {
462
+ let readObject = structure.read = (new Function('r', 'return function(){return {' + structure.map(key => validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}}'))(read);
463
+ if (structure.highByte === 0)
464
+ structure.read = createSecondByteReader(firstId, structure.read);
465
+ return readObject() // second byte is already read, if there is one so immediately read object
466
+ }
467
+ let object = {};
468
+ for (let i = 0, l = structure.length; i < l; i++) {
469
+ let key = structure[i];
470
+ object[key] = read();
471
+ }
472
+ return object
473
+ }
474
+ readObject.count = 0;
475
+ if (structure.highByte === 0) {
476
+ return createSecondByteReader(firstId, readObject)
477
+ }
478
+ return readObject
479
+ }
480
+
481
+ const createSecondByteReader = (firstId, read0) => {
482
+ return function() {
483
+ let highByte = src[position++];
484
+ if (highByte === 0)
485
+ return read0()
486
+ let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
487
+ let structure = currentStructures[id] || loadStructures()[id];
488
+ if (!structure) {
489
+ throw new Error('Record id is not defined for ' + id)
490
+ }
491
+ if (!structure.read)
492
+ structure.read = createStructureReader(structure, firstId);
493
+ return structure.read()
494
+ }
495
+ };
496
+
497
+ function loadStructures() {
498
+ let loadedStructures = saveState(() => {
499
+ // save the state in case getStructures modifies our buffer
500
+ src = null;
501
+ return currentUnpackr.getStructures()
502
+ });
503
+ return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
504
+ }
505
+
506
+ var readFixedString = readStringJS;
507
+ var readString8 = readStringJS;
508
+ var readString16 = readStringJS;
509
+ var readString32 = readStringJS;
510
+ exports.isNativeAccelerationEnabled = false;
511
+
512
+ function setExtractor(extractStrings) {
513
+ exports.isNativeAccelerationEnabled = true;
514
+ readFixedString = readString(1);
515
+ readString8 = readString(2);
516
+ readString16 = readString(3);
517
+ readString32 = readString(5);
518
+ function readString(headerLength) {
519
+ return function readString(length) {
520
+ let string = strings[stringPosition++];
521
+ if (string == null) {
522
+ if (bundledStrings)
523
+ return readStringJS(length)
524
+ let extraction = extractStrings(position - headerLength, srcEnd, src);
525
+ if (typeof extraction == 'string') {
526
+ string = extraction;
527
+ strings = EMPTY_ARRAY;
528
+ } else {
529
+ strings = extraction;
530
+ stringPosition = 1;
531
+ srcStringEnd = 1; // even if a utf-8 string was decoded, must indicate we are in the midst of extracted strings and can't skip strings
532
+ string = strings[0];
533
+ if (string === undefined)
534
+ throw new Error('Unexpected end of buffer')
535
+ }
536
+ }
537
+ let srcStringLength = string.length;
538
+ if (srcStringLength <= length) {
539
+ position += length;
540
+ return string
541
+ }
542
+ srcString = string;
543
+ srcStringStart = position;
544
+ srcStringEnd = position + srcStringLength;
545
+ position += length;
546
+ return string.slice(0, length) // we know we just want the beginning
547
+ }
548
+ }
549
+ }
550
+ function readStringJS(length) {
551
+ let result;
552
+ if (length < 16) {
553
+ if (result = shortStringInJS(length))
554
+ return result
555
+ }
556
+ if (length > 64 && decoder)
557
+ return decoder.decode(src.subarray(position, position += length))
558
+ const end = position + length;
559
+ const units = [];
560
+ result = '';
561
+ while (position < end) {
562
+ const byte1 = src[position++];
563
+ if ((byte1 & 0x80) === 0) {
564
+ // 1 byte
565
+ units.push(byte1);
566
+ } else if ((byte1 & 0xe0) === 0xc0) {
567
+ // 2 bytes
568
+ const byte2 = src[position++] & 0x3f;
569
+ units.push(((byte1 & 0x1f) << 6) | byte2);
570
+ } else if ((byte1 & 0xf0) === 0xe0) {
571
+ // 3 bytes
572
+ const byte2 = src[position++] & 0x3f;
573
+ const byte3 = src[position++] & 0x3f;
574
+ units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
575
+ } else if ((byte1 & 0xf8) === 0xf0) {
576
+ // 4 bytes
577
+ const byte2 = src[position++] & 0x3f;
578
+ const byte3 = src[position++] & 0x3f;
579
+ const byte4 = src[position++] & 0x3f;
580
+ let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
581
+ if (unit > 0xffff) {
582
+ unit -= 0x10000;
583
+ units.push(((unit >>> 10) & 0x3ff) | 0xd800);
584
+ unit = 0xdc00 | (unit & 0x3ff);
585
+ }
586
+ units.push(unit);
587
+ } else {
588
+ units.push(byte1);
589
+ }
590
+
591
+ if (units.length >= 0x1000) {
592
+ result += fromCharCode.apply(String, units);
593
+ units.length = 0;
594
+ }
595
+ }
596
+
597
+ if (units.length > 0) {
598
+ result += fromCharCode.apply(String, units);
599
+ }
600
+
601
+ return result
602
+ }
603
+
604
+ function readArray(length) {
605
+ let array = new Array(length);
606
+ for (let i = 0; i < length; i++) {
607
+ array[i] = read();
608
+ }
609
+ return array
610
+ }
611
+
612
+ function readMap(length) {
613
+ if (currentUnpackr.mapsAsObjects) {
614
+ let object = {};
615
+ for (let i = 0; i < length; i++) {
616
+ object[readKey()] = read();
617
+ }
618
+ return object
619
+ } else {
620
+ let map = new Map();
621
+ for (let i = 0; i < length; i++) {
622
+ map.set(read(), read());
623
+ }
624
+ return map
625
+ }
626
+ }
627
+
628
+ var fromCharCode = String.fromCharCode;
629
+ function longStringInJS(length) {
630
+ let start = position;
631
+ let bytes = new Array(length);
632
+ for (let i = 0; i < length; i++) {
633
+ const byte = src[position++];
634
+ if ((byte & 0x80) > 0) {
635
+ position = start;
636
+ return
637
+ }
638
+ bytes[i] = byte;
639
+ }
640
+ return fromCharCode.apply(String, bytes)
641
+ }
642
+ function shortStringInJS(length) {
643
+ if (length < 4) {
644
+ if (length < 2) {
645
+ if (length === 0)
646
+ return ''
647
+ else {
648
+ let a = src[position++];
649
+ if ((a & 0x80) > 1) {
650
+ position -= 1;
651
+ return
652
+ }
653
+ return fromCharCode(a)
654
+ }
655
+ } else {
656
+ let a = src[position++];
657
+ let b = src[position++];
658
+ if ((a & 0x80) > 0 || (b & 0x80) > 0) {
659
+ position -= 2;
660
+ return
661
+ }
662
+ if (length < 3)
663
+ return fromCharCode(a, b)
664
+ let c = src[position++];
665
+ if ((c & 0x80) > 0) {
666
+ position -= 3;
667
+ return
668
+ }
669
+ return fromCharCode(a, b, c)
670
+ }
671
+ } else {
672
+ let a = src[position++];
673
+ let b = src[position++];
674
+ let c = src[position++];
675
+ let d = src[position++];
676
+ if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
677
+ position -= 4;
678
+ return
679
+ }
680
+ if (length < 6) {
681
+ if (length === 4)
682
+ return fromCharCode(a, b, c, d)
683
+ else {
684
+ let e = src[position++];
685
+ if ((e & 0x80) > 0) {
686
+ position -= 5;
687
+ return
688
+ }
689
+ return fromCharCode(a, b, c, d, e)
690
+ }
691
+ } else if (length < 8) {
692
+ let e = src[position++];
693
+ let f = src[position++];
694
+ if ((e & 0x80) > 0 || (f & 0x80) > 0) {
695
+ position -= 6;
696
+ return
697
+ }
698
+ if (length < 7)
699
+ return fromCharCode(a, b, c, d, e, f)
700
+ let g = src[position++];
701
+ if ((g & 0x80) > 0) {
702
+ position -= 7;
703
+ return
704
+ }
705
+ return fromCharCode(a, b, c, d, e, f, g)
706
+ } else {
707
+ let e = src[position++];
708
+ let f = src[position++];
709
+ let g = src[position++];
710
+ let h = src[position++];
711
+ if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
712
+ position -= 8;
713
+ return
714
+ }
715
+ if (length < 10) {
716
+ if (length === 8)
717
+ return fromCharCode(a, b, c, d, e, f, g, h)
718
+ else {
719
+ let i = src[position++];
720
+ if ((i & 0x80) > 0) {
721
+ position -= 9;
722
+ return
723
+ }
724
+ return fromCharCode(a, b, c, d, e, f, g, h, i)
725
+ }
726
+ } else if (length < 12) {
727
+ let i = src[position++];
728
+ let j = src[position++];
729
+ if ((i & 0x80) > 0 || (j & 0x80) > 0) {
730
+ position -= 10;
731
+ return
732
+ }
733
+ if (length < 11)
734
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j)
735
+ let k = src[position++];
736
+ if ((k & 0x80) > 0) {
737
+ position -= 11;
738
+ return
739
+ }
740
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
741
+ } else {
742
+ let i = src[position++];
743
+ let j = src[position++];
744
+ let k = src[position++];
745
+ let l = src[position++];
746
+ if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
747
+ position -= 12;
748
+ return
749
+ }
750
+ if (length < 14) {
751
+ if (length === 12)
752
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
753
+ else {
754
+ let m = src[position++];
755
+ if ((m & 0x80) > 0) {
756
+ position -= 13;
757
+ return
758
+ }
759
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
760
+ }
761
+ } else {
762
+ let m = src[position++];
763
+ let n = src[position++];
764
+ if ((m & 0x80) > 0 || (n & 0x80) > 0) {
765
+ position -= 14;
766
+ return
767
+ }
768
+ if (length < 15)
769
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
770
+ let o = src[position++];
771
+ if ((o & 0x80) > 0) {
772
+ position -= 15;
773
+ return
774
+ }
775
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
776
+ }
777
+ }
778
+ }
779
+ }
780
+ }
781
+
782
+ function readOnlyJSString() {
783
+ let token = src[position++];
784
+ let length;
785
+ if (token < 0xc0) {
786
+ // fixstr
787
+ length = token - 0xa0;
788
+ } else {
789
+ switch(token) {
790
+ case 0xd9:
791
+ // str 8
792
+ length = src[position++];
793
+ break
794
+ case 0xda:
795
+ // str 16
796
+ length = dataView.getUint16(position);
797
+ position += 2;
798
+ break
799
+ case 0xdb:
800
+ // str 32
801
+ length = dataView.getUint32(position);
802
+ position += 4;
803
+ break
804
+ default:
805
+ throw new Error('Expected string')
806
+ }
807
+ }
808
+ return readStringJS(length)
809
+ }
810
+
811
+
812
+ function readBin(length) {
813
+ return currentUnpackr.copyBuffers ?
814
+ // specifically use the copying slice (not the node one)
815
+ Uint8Array.prototype.slice.call(src, position, position += length) :
816
+ src.subarray(position, position += length)
817
+ }
818
+ function readExt(length) {
819
+ let type = src[position++];
820
+ if (currentExtensions[type]) {
821
+ return currentExtensions[type](src.subarray(position, position += length))
822
+ }
823
+ else
824
+ throw new Error('Unknown extension type ' + type)
825
+ }
826
+
827
+ var keyCache = new Array(4096);
828
+ function readKey() {
829
+ let length = src[position++];
830
+ if (length >= 0xa0 && length < 0xc0) {
831
+ // fixstr, potentially use key cache
832
+ length = length - 0xa0;
833
+ if (srcStringEnd >= position) // if it has been extracted, must use it (and faster anyway)
834
+ return srcString.slice(position - srcStringStart, (position += length) - srcStringStart)
835
+ else if (!(srcStringEnd == 0 && srcEnd < 180))
836
+ return readFixedString(length)
837
+ } else { // not cacheable, go back and do a standard read
838
+ position--;
839
+ return read()
840
+ }
841
+ let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 0xfff;
842
+ let entry = keyCache[key];
843
+ let checkPosition = position;
844
+ let end = position + length - 3;
845
+ let chunk;
846
+ let i = 0;
847
+ if (entry && entry.bytes == length) {
848
+ while (checkPosition < end) {
849
+ chunk = dataView.getUint32(checkPosition);
850
+ if (chunk != entry[i++]) {
851
+ checkPosition = 0x70000000;
852
+ break
853
+ }
854
+ checkPosition += 4;
855
+ }
856
+ end += 3;
857
+ while (checkPosition < end) {
858
+ chunk = src[checkPosition++];
859
+ if (chunk != entry[i++]) {
860
+ checkPosition = 0x70000000;
861
+ break
862
+ }
863
+ }
864
+ if (checkPosition === end) {
865
+ position = checkPosition;
866
+ return entry.string
867
+ }
868
+ end -= 3;
869
+ checkPosition = position;
870
+ }
871
+ entry = [];
872
+ keyCache[key] = entry;
873
+ entry.bytes = length;
874
+ while (checkPosition < end) {
875
+ chunk = dataView.getUint32(checkPosition);
876
+ entry.push(chunk);
877
+ checkPosition += 4;
878
+ }
879
+ end += 3;
880
+ while (checkPosition < end) {
881
+ chunk = src[checkPosition++];
882
+ entry.push(chunk);
883
+ }
884
+ // for small blocks, avoiding the overhead of the extract call is helpful
885
+ let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
886
+ if (string != null)
887
+ return entry.string = string
888
+ return entry.string = readFixedString(length)
889
+ }
890
+
891
+ // the registration of the record definition extension (as "r")
892
+ const recordDefinition = (id, highByte) => {
893
+ var structure = read();
894
+ let firstByte = id;
895
+ if (highByte !== undefined) {
896
+ id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
897
+ structure.highByte = highByte;
898
+ }
899
+ let existingStructure = currentStructures[id];
900
+ if (existingStructure && existingStructure.isShared) {
901
+ (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
902
+ }
903
+ currentStructures[id] = structure;
904
+ structure.read = createStructureReader(structure, firstByte);
905
+ return structure.read()
906
+ };
907
+ currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
908
+ currentExtensions[0].noBuffer = true;
909
+
910
+ currentExtensions[0x65] = () => {
911
+ let data = read();
912
+ return (globalThis[data[0]] || Error)(data[1])
913
+ };
914
+
915
+ currentExtensions[0x69] = (data) => {
916
+ // id extension (for structured clones)
917
+ let id = dataView.getUint32(position - 4);
918
+ if (!referenceMap)
919
+ referenceMap = new Map();
920
+ let token = src[position];
921
+ let target;
922
+ // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
923
+ // ahead past references to record structure definitions
924
+ if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
925
+ target = [];
926
+ else
927
+ target = {};
928
+
929
+ let refEntry = { target }; // a placeholder object
930
+ referenceMap.set(id, refEntry);
931
+ let targetProperties = read(); // read the next value as the target object to id
932
+ if (refEntry.used) // there is a cycle, so we have to assign properties to original target
933
+ return Object.assign(target, targetProperties)
934
+ refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
935
+ return targetProperties // no cycle, can just use the returned read object
936
+ };
937
+
938
+ currentExtensions[0x70] = (data) => {
939
+ // pointer extension (for structured clones)
940
+ let id = dataView.getUint32(position - 4);
941
+ let refEntry = referenceMap.get(id);
942
+ refEntry.used = true;
943
+ return refEntry.target
944
+ };
945
+
946
+ currentExtensions[0x73] = () => new Set(read());
947
+
948
+ const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
949
+
950
+ currentExtensions[0x74] = (data) => {
951
+ let typeCode = data[0];
952
+ let typedArrayName = typedArrays[typeCode];
953
+ if (!typedArrayName)
954
+ throw new Error('Could not find typed array for code ' + typeCode)
955
+ // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
956
+ return new globalThis[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer)
957
+ };
958
+ currentExtensions[0x78] = () => {
959
+ let data = read();
960
+ return new RegExp(data[0], data[1])
961
+ };
962
+ const TEMP_BUNDLE = [];
963
+ currentExtensions[0x62] = (data) => {
964
+ let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
965
+ let dataPosition = position;
966
+ position += dataSize - data.length;
967
+ bundledStrings = TEMP_BUNDLE;
968
+ bundledStrings = [readOnlyJSString(), readOnlyJSString()];
969
+ bundledStrings.position0 = 0;
970
+ bundledStrings.position1 = 0;
971
+ bundledStrings.postBundlePosition = position;
972
+ position = dataPosition;
973
+ return read()
974
+ };
975
+
976
+ currentExtensions[0xff] = (data) => {
977
+ // 32-bit date extension
978
+ if (data.length == 4)
979
+ return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
980
+ else if (data.length == 8)
981
+ return new Date(
982
+ ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
983
+ ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
984
+ else if (data.length == 12)// TODO: Implement support for negative
985
+ return new Date(
986
+ ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
987
+ (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
988
+ else
989
+ return new Date('invalid')
990
+ }; // notepack defines extension 0 to mean undefined, so use that as the default here
991
+ // registration of bulk record definition?
992
+ // currentExtensions[0x52] = () =>
993
+
994
+ function saveState(callback) {
995
+ let savedSrcEnd = srcEnd;
996
+ let savedPosition = position;
997
+ let savedStringPosition = stringPosition;
998
+ let savedSrcStringStart = srcStringStart;
999
+ let savedSrcStringEnd = srcStringEnd;
1000
+ let savedSrcString = srcString;
1001
+ let savedStrings = strings;
1002
+ let savedReferenceMap = referenceMap;
1003
+ let savedBundledStrings = bundledStrings;
1004
+
1005
+ // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
1006
+ let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
1007
+ let savedStructures = currentStructures;
1008
+ let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
1009
+ let savedPackr = currentUnpackr;
1010
+ let savedSequentialMode = sequentialMode;
1011
+ let value = callback();
1012
+ srcEnd = savedSrcEnd;
1013
+ position = savedPosition;
1014
+ stringPosition = savedStringPosition;
1015
+ srcStringStart = savedSrcStringStart;
1016
+ srcStringEnd = savedSrcStringEnd;
1017
+ srcString = savedSrcString;
1018
+ strings = savedStrings;
1019
+ referenceMap = savedReferenceMap;
1020
+ bundledStrings = savedBundledStrings;
1021
+ src = savedSrc;
1022
+ sequentialMode = savedSequentialMode;
1023
+ currentStructures = savedStructures;
1024
+ currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
1025
+ currentUnpackr = savedPackr;
1026
+ dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
1027
+ return value
1028
+ }
1029
+ function clearSource() {
1030
+ src = null;
1031
+ referenceMap = null;
1032
+ currentStructures = null;
1033
+ }
1034
+
1035
+ function addExtension(extension) {
1036
+ if (extension.unpack)
1037
+ currentExtensions[extension.type] = extension.unpack;
1038
+ else
1039
+ currentExtensions[extension.type] = extension;
1040
+ }
1041
+
1042
+ const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
1043
+ for (let i = 0; i < 256; i++) {
1044
+ mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
1045
+ }
1046
+ const Decoder = Unpackr;
1047
+ var defaultUnpackr = new Unpackr({ useRecords: false });
1048
+ const unpack = defaultUnpackr.unpack;
1049
+ const unpackMultiple = defaultUnpackr.unpackMultiple;
1050
+ const decode = defaultUnpackr.unpack;
1051
+ const FLOAT32_OPTIONS = {
1052
+ NEVER: 0,
1053
+ ALWAYS: 1,
1054
+ DECIMAL_ROUND: 3,
1055
+ DECIMAL_FIT: 4
1056
+ };
1057
+ let f32Array = new Float32Array(1);
1058
+ let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
1059
+ function roundFloat32(float32Number) {
1060
+ f32Array[0] = float32Number;
1061
+ let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
1062
+ return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
1063
+ }
1064
+
1065
+ let textEncoder;
1066
+ try {
1067
+ textEncoder = new TextEncoder();
1068
+ } catch (error) {}
1069
+ let extensions, extensionClasses;
1070
+ const hasNodeBuffer = typeof Buffer !== 'undefined';
1071
+ const ByteArrayAllocate = hasNodeBuffer ?
1072
+ function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
1073
+ const ByteArray = hasNodeBuffer ? Buffer : Uint8Array;
1074
+ const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;
1075
+ let target, keysTarget;
1076
+ let targetView;
1077
+ let position$1 = 0;
1078
+ let safeEnd;
1079
+ let bundledStrings$1 = null;
1080
+ const MAX_BUNDLE_SIZE = 0xf000;
1081
+ const hasNonLatin = /[\u0080-\uFFFF]/;
1082
+ const RECORD_SYMBOL = Symbol('record-id');
1083
+ class Packr extends Unpackr {
1084
+ constructor(options) {
1085
+ super(options);
1086
+ this.offset = 0;
1087
+ let start;
1088
+ let hasSharedUpdate;
1089
+ let structures;
1090
+ let referenceMap;
1091
+ let lastSharedStructuresLength = 0;
1092
+ let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
1093
+ return target.utf8Write(string, position, 0xffffffff)
1094
+ } : (textEncoder && textEncoder.encodeInto) ?
1095
+ function(string, position) {
1096
+ return textEncoder.encodeInto(string, target.subarray(position)).written
1097
+ } : false;
1098
+
1099
+ let packr = this;
1100
+ if (!options)
1101
+ options = {};
1102
+ let isSequential = options && options.sequential;
1103
+ let hasSharedStructures = options.structures || options.saveStructures;
1104
+ let maxSharedStructures = options.maxSharedStructures;
1105
+ if (maxSharedStructures == null)
1106
+ maxSharedStructures = hasSharedStructures ? 32 : 0;
1107
+ if (maxSharedStructures > 8160)
1108
+ throw new Error('Maximum maxSharedStructure is 8160')
1109
+ if (options.structuredClone && options.moreTypes == undefined) {
1110
+ options.moreTypes = true;
1111
+ }
1112
+ let maxOwnStructures = options.maxOwnStructures;
1113
+ if (maxOwnStructures == null)
1114
+ maxOwnStructures = hasSharedStructures ? 32 : 64;
1115
+ if (!this.structures && options.useRecords != false)
1116
+ this.structures = [];
1117
+ // two byte record ids for shared structures
1118
+ let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);
1119
+ let sharedLimitId = maxSharedStructures + 0x40;
1120
+ let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
1121
+ if (maxStructureId > 8256) {
1122
+ throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
1123
+ }
1124
+ let recordIdsToRemove = [];
1125
+ let transitionsCount = 0;
1126
+ let serializationsSinceTransitionRebuild = 0;
1127
+
1128
+ this.pack = this.encode = function(value, encodeOptions) {
1129
+ if (!target) {
1130
+ target = new ByteArrayAllocate(8192);
1131
+ targetView = new DataView(target.buffer, 0, 8192);
1132
+ position$1 = 0;
1133
+ }
1134
+ safeEnd = target.length - 10;
1135
+ if (safeEnd - position$1 < 0x800) {
1136
+ // don't start too close to the end,
1137
+ target = new ByteArrayAllocate(target.length);
1138
+ targetView = new DataView(target.buffer, 0, target.length);
1139
+ safeEnd = target.length - 10;
1140
+ position$1 = 0;
1141
+ } else
1142
+ position$1 = (position$1 + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
1143
+ start = position$1;
1144
+ referenceMap = packr.structuredClone ? new Map() : null;
1145
+ if (packr.bundleStrings && typeof value !== 'string') {
1146
+ bundledStrings$1 = [];
1147
+ bundledStrings$1.size = Infinity; // force a new bundle start on first string
1148
+ } else
1149
+ bundledStrings$1 = null;
1150
+ structures = packr.structures;
1151
+ if (structures) {
1152
+ if (structures.uninitialized)
1153
+ structures = packr._mergeStructures(packr.getStructures());
1154
+ let sharedLength = structures.sharedLength || 0;
1155
+ if (sharedLength > maxSharedStructures) {
1156
+ //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
1157
+ throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
1158
+ }
1159
+ if (!structures.transitions) {
1160
+ // rebuild our structure transitions
1161
+ structures.transitions = Object.create(null);
1162
+ for (let i = 0; i < sharedLength; i++) {
1163
+ let keys = structures[i];
1164
+ if (!keys)
1165
+ continue
1166
+ let nextTransition, transition = structures.transitions;
1167
+ for (let j = 0, l = keys.length; j < l; j++) {
1168
+ let key = keys[j];
1169
+ nextTransition = transition[key];
1170
+ if (!nextTransition) {
1171
+ nextTransition = transition[key] = Object.create(null);
1172
+ }
1173
+ transition = nextTransition;
1174
+ }
1175
+ transition[RECORD_SYMBOL] = i + 0x40;
1176
+ }
1177
+ lastSharedStructuresLength = sharedLength;
1178
+ }
1179
+ if (!isSequential) {
1180
+ structures.nextId = sharedLength + 0x40;
1181
+ }
1182
+ }
1183
+ if (hasSharedUpdate)
1184
+ hasSharedUpdate = false;
1185
+ try {
1186
+ pack(value);
1187
+ if (bundledStrings$1) {
1188
+ writeBundles(start, pack);
1189
+ }
1190
+ packr.offset = position$1; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
1191
+ if (referenceMap && referenceMap.idsToInsert) {
1192
+ position$1 += referenceMap.idsToInsert.length * 6;
1193
+ if (position$1 > safeEnd)
1194
+ makeRoom(position$1);
1195
+ packr.offset = position$1;
1196
+ let serialized = insertIds(target.subarray(start, position$1), referenceMap.idsToInsert);
1197
+ referenceMap = null;
1198
+ return serialized
1199
+ }
1200
+ if (encodeOptions & REUSE_BUFFER_MODE) {
1201
+ target.start = start;
1202
+ target.end = position$1;
1203
+ return target
1204
+ }
1205
+ return target.subarray(start, position$1) // position can change if we call pack again in saveStructures, so we get the buffer now
1206
+ } finally {
1207
+ if (structures) {
1208
+ if (serializationsSinceTransitionRebuild < 10)
1209
+ serializationsSinceTransitionRebuild++;
1210
+ let sharedLength = structures.sharedLength || maxSharedStructures;
1211
+ if (structures.length > sharedLength)
1212
+ structures.length = sharedLength;
1213
+ if (transitionsCount > 10000) {
1214
+ // force a rebuild occasionally after a lot of transitions so it can get cleaned up
1215
+ structures.transitions = null;
1216
+ serializationsSinceTransitionRebuild = 0;
1217
+ transitionsCount = 0;
1218
+ if (recordIdsToRemove.length > 0)
1219
+ recordIdsToRemove = [];
1220
+ } else if (recordIdsToRemove.length > 0 && !isSequential) {
1221
+ for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
1222
+ recordIdsToRemove[i][RECORD_SYMBOL] = 0;
1223
+ }
1224
+ recordIdsToRemove = [];
1225
+ }
1226
+ if (hasSharedUpdate && packr.saveStructures) {
1227
+ // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
1228
+ let returnBuffer = target.subarray(start, position$1);
1229
+ if (packr.saveStructures(structures, lastSharedStructuresLength) === false) {
1230
+ // get updated structures and try again if the update failed
1231
+ packr._mergeStructures(packr.getStructures());
1232
+ return packr.pack(value)
1233
+ }
1234
+ lastSharedStructuresLength = sharedLength;
1235
+ return returnBuffer
1236
+ }
1237
+ }
1238
+ if (encodeOptions & RESET_BUFFER_MODE)
1239
+ position$1 = start;
1240
+ }
1241
+ };
1242
+ const pack = (value) => {
1243
+ if (position$1 > safeEnd)
1244
+ target = makeRoom(position$1);
1245
+
1246
+ var type = typeof value;
1247
+ var length;
1248
+ if (type === 'string') {
1249
+ let strLength = value.length;
1250
+ if (bundledStrings$1 && strLength >= 4 && strLength < 0x1000) {
1251
+ if ((bundledStrings$1.size += strLength) > MAX_BUNDLE_SIZE) {
1252
+ let extStart;
1253
+ let maxBytes = (bundledStrings$1[0] ? bundledStrings$1[0].length * 3 + bundledStrings$1[1].length : 0) + 10;
1254
+ if (position$1 + maxBytes > safeEnd)
1255
+ target = makeRoom(position$1 + maxBytes);
1256
+ if (bundledStrings$1.position) { // here we use the 0x62 extension to write the last bundle and reserve sapce for the reference pointer to the next/current bundle
1257
+ target[position$1] = 0xc8; // ext 16
1258
+ position$1 += 3; // reserve for the writing bundle size
1259
+ target[position$1++] = 0x62; // 'b'
1260
+ extStart = position$1 - start;
1261
+ position$1 += 4; // reserve for writing bundle reference
1262
+ writeBundles(start, pack); // write the last bundles
1263
+ targetView.setUint16(extStart + start - 3, position$1 - start - extStart);
1264
+ } else { // here we use the 0x62 extension just to reserve the space for the reference pointer to the bundle (will be updated once the bundle is written)
1265
+ target[position$1++] = 0xd6; // fixext 4
1266
+ target[position$1++] = 0x62; // 'b'
1267
+ extStart = position$1 - start;
1268
+ position$1 += 4; // reserve for writing bundle reference
1269
+ }
1270
+ bundledStrings$1 = ['', '']; // create new ones
1271
+ bundledStrings$1.size = 0;
1272
+ bundledStrings$1.position = extStart;
1273
+ }
1274
+ let twoByte = hasNonLatin.test(value);
1275
+ bundledStrings$1[twoByte ? 0 : 1] += value;
1276
+ target[position$1++] = 0xc1;
1277
+ pack(twoByte ? -strLength : strLength);
1278
+ return
1279
+ }
1280
+ let headerSize;
1281
+ // first we estimate the header size, so we can write to the correct location
1282
+ if (strLength < 0x20) {
1283
+ headerSize = 1;
1284
+ } else if (strLength < 0x100) {
1285
+ headerSize = 2;
1286
+ } else if (strLength < 0x10000) {
1287
+ headerSize = 3;
1288
+ } else {
1289
+ headerSize = 5;
1290
+ }
1291
+ let maxBytes = strLength * 3;
1292
+ if (position$1 + maxBytes > safeEnd)
1293
+ target = makeRoom(position$1 + maxBytes);
1294
+
1295
+ if (strLength < 0x40 || !encodeUtf8) {
1296
+ let i, c1, c2, strPosition = position$1 + headerSize;
1297
+ for (i = 0; i < strLength; i++) {
1298
+ c1 = value.charCodeAt(i);
1299
+ if (c1 < 0x80) {
1300
+ target[strPosition++] = c1;
1301
+ } else if (c1 < 0x800) {
1302
+ target[strPosition++] = c1 >> 6 | 0xc0;
1303
+ target[strPosition++] = c1 & 0x3f | 0x80;
1304
+ } else if (
1305
+ (c1 & 0xfc00) === 0xd800 &&
1306
+ ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
1307
+ ) {
1308
+ c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
1309
+ i++;
1310
+ target[strPosition++] = c1 >> 18 | 0xf0;
1311
+ target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
1312
+ target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1313
+ target[strPosition++] = c1 & 0x3f | 0x80;
1314
+ } else {
1315
+ target[strPosition++] = c1 >> 12 | 0xe0;
1316
+ target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1317
+ target[strPosition++] = c1 & 0x3f | 0x80;
1318
+ }
1319
+ }
1320
+ length = strPosition - position$1 - headerSize;
1321
+ } else {
1322
+ length = encodeUtf8(value, position$1 + headerSize);
1323
+ }
1324
+
1325
+ if (length < 0x20) {
1326
+ target[position$1++] = 0xa0 | length;
1327
+ } else if (length < 0x100) {
1328
+ if (headerSize < 2) {
1329
+ target.copyWithin(position$1 + 2, position$1 + 1, position$1 + 1 + length);
1330
+ }
1331
+ target[position$1++] = 0xd9;
1332
+ target[position$1++] = length;
1333
+ } else if (length < 0x10000) {
1334
+ if (headerSize < 3) {
1335
+ target.copyWithin(position$1 + 3, position$1 + 2, position$1 + 2 + length);
1336
+ }
1337
+ target[position$1++] = 0xda;
1338
+ target[position$1++] = length >> 8;
1339
+ target[position$1++] = length & 0xff;
1340
+ } else {
1341
+ if (headerSize < 5) {
1342
+ target.copyWithin(position$1 + 5, position$1 + 3, position$1 + 3 + length);
1343
+ }
1344
+ target[position$1++] = 0xdb;
1345
+ targetView.setUint32(position$1, length);
1346
+ position$1 += 4;
1347
+ }
1348
+ position$1 += length;
1349
+ } else if (type === 'number') {
1350
+ if (value >>> 0 === value) {// positive integer, 32-bit or less
1351
+ // positive uint
1352
+ if (value < 0x40 || (value < 0x80 && this.useRecords === false)) {
1353
+ target[position$1++] = value;
1354
+ } else if (value < 0x100) {
1355
+ target[position$1++] = 0xcc;
1356
+ target[position$1++] = value;
1357
+ } else if (value < 0x10000) {
1358
+ target[position$1++] = 0xcd;
1359
+ target[position$1++] = value >> 8;
1360
+ target[position$1++] = value & 0xff;
1361
+ } else {
1362
+ target[position$1++] = 0xce;
1363
+ targetView.setUint32(position$1, value);
1364
+ position$1 += 4;
1365
+ }
1366
+ } else if (value >> 0 === value) { // negative integer
1367
+ if (value >= -0x20) {
1368
+ target[position$1++] = 0x100 + value;
1369
+ } else if (value >= -0x80) {
1370
+ target[position$1++] = 0xd0;
1371
+ target[position$1++] = value + 0x100;
1372
+ } else if (value >= -0x8000) {
1373
+ target[position$1++] = 0xd1;
1374
+ targetView.setInt16(position$1, value);
1375
+ position$1 += 2;
1376
+ } else {
1377
+ target[position$1++] = 0xd2;
1378
+ targetView.setInt32(position$1, value);
1379
+ position$1 += 4;
1380
+ }
1381
+ } else {
1382
+ let useFloat32;
1383
+ if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
1384
+ target[position$1++] = 0xca;
1385
+ targetView.setFloat32(position$1, value);
1386
+ let xShifted;
1387
+ if (useFloat32 < 4 ||
1388
+ // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
1389
+ ((xShifted = value * mult10[((target[position$1] & 0x7f) << 1) | (target[position$1 + 1] >> 7)]) >> 0) === xShifted) {
1390
+ position$1 += 4;
1391
+ return
1392
+ } else
1393
+ position$1--; // move back into position for writing a double
1394
+ }
1395
+ target[position$1++] = 0xcb;
1396
+ targetView.setFloat64(position$1, value);
1397
+ position$1 += 8;
1398
+ }
1399
+ } else if (type === 'object') {
1400
+ if (!value)
1401
+ target[position$1++] = 0xc0;
1402
+ else {
1403
+ if (referenceMap) {
1404
+ let referee = referenceMap.get(value);
1405
+ if (referee) {
1406
+ if (!referee.id) {
1407
+ let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
1408
+ referee.id = idsToInsert.push(referee);
1409
+ }
1410
+ target[position$1++] = 0xd6; // fixext 4
1411
+ target[position$1++] = 0x70; // "p" for pointer
1412
+ targetView.setUint32(position$1, referee.id);
1413
+ position$1 += 4;
1414
+ return
1415
+ } else
1416
+ referenceMap.set(value, { offset: position$1 - start });
1417
+ }
1418
+ let constructor = value.constructor;
1419
+ if (constructor === Object) {
1420
+ writeObject(value, true);
1421
+ } else if (constructor === Array) {
1422
+ length = value.length;
1423
+ if (length < 0x10) {
1424
+ target[position$1++] = 0x90 | length;
1425
+ } else if (length < 0x10000) {
1426
+ target[position$1++] = 0xdc;
1427
+ target[position$1++] = length >> 8;
1428
+ target[position$1++] = length & 0xff;
1429
+ } else {
1430
+ target[position$1++] = 0xdd;
1431
+ targetView.setUint32(position$1, length);
1432
+ position$1 += 4;
1433
+ }
1434
+ for (let i = 0; i < length; i++) {
1435
+ pack(value[i]);
1436
+ }
1437
+ } else if (constructor === Map) {
1438
+ length = value.size;
1439
+ if (length < 0x10) {
1440
+ target[position$1++] = 0x80 | length;
1441
+ } else if (length < 0x10000) {
1442
+ target[position$1++] = 0xde;
1443
+ target[position$1++] = length >> 8;
1444
+ target[position$1++] = length & 0xff;
1445
+ } else {
1446
+ target[position$1++] = 0xdf;
1447
+ targetView.setUint32(position$1, length);
1448
+ position$1 += 4;
1449
+ }
1450
+ for (let [ key, entryValue ] of value) {
1451
+ pack(key);
1452
+ pack(entryValue);
1453
+ }
1454
+ } else {
1455
+ for (let i = 0, l = extensions.length; i < l; i++) {
1456
+ let extensionClass = extensionClasses[i];
1457
+ if (value instanceof extensionClass) {
1458
+ let extension = extensions[i];
1459
+ if (extension.write) {
1460
+ if (extension.type) {
1461
+ target[position$1++] = 0xd4; // one byte "tag" extension
1462
+ target[position$1++] = extension.type;
1463
+ target[position$1++] = 0;
1464
+ }
1465
+ pack(extension.write.call(this, value));
1466
+ return
1467
+ }
1468
+ let currentTarget = target;
1469
+ let currentTargetView = targetView;
1470
+ let currentPosition = position$1;
1471
+ target = null;
1472
+ let result;
1473
+ try {
1474
+ result = extension.pack.call(this, value, (size) => {
1475
+ // restore target and use it
1476
+ target = currentTarget;
1477
+ currentTarget = null;
1478
+ position$1 += size;
1479
+ if (position$1 > safeEnd)
1480
+ makeRoom(position$1);
1481
+ return {
1482
+ target, targetView, position: position$1 - size
1483
+ }
1484
+ }, pack);
1485
+ } finally {
1486
+ // restore current target information (unless already restored)
1487
+ if (currentTarget) {
1488
+ target = currentTarget;
1489
+ targetView = currentTargetView;
1490
+ position$1 = currentPosition;
1491
+ safeEnd = target.length - 10;
1492
+ }
1493
+ }
1494
+ if (result) {
1495
+ if (result.length + position$1 > safeEnd)
1496
+ makeRoom(result.length + position$1);
1497
+ position$1 = writeExtensionData(result, target, position$1, extension.type);
1498
+ }
1499
+ return
1500
+ }
1501
+ }
1502
+ // no extension found, write as object
1503
+ writeObject(value, !value.hasOwnProperty); // if it doesn't have hasOwnProperty, don't do hasOwnProperty checks
1504
+ }
1505
+ }
1506
+ } else if (type === 'boolean') {
1507
+ target[position$1++] = value ? 0xc3 : 0xc2;
1508
+ } else if (type === 'bigint') {
1509
+ if (value < (BigInt(1)<<BigInt(63)) && value >= -(BigInt(1)<<BigInt(63))) {
1510
+ // use a signed int as long as it fits
1511
+ target[position$1++] = 0xd3;
1512
+ targetView.setBigInt64(position$1, value);
1513
+ } else if (value < (BigInt(1)<<BigInt(64)) && value > 0) {
1514
+ // if we can fit an unsigned int, use that
1515
+ target[position$1++] = 0xcf;
1516
+ targetView.setBigUint64(position$1, value);
1517
+ } else {
1518
+ // overflow
1519
+ if (this.largeBigIntToFloat) {
1520
+ target[position$1++] = 0xcb;
1521
+ targetView.setFloat64(position$1, Number(value));
1522
+ } else {
1523
+ throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, set largeBigIntToFloat to convert to float-64')
1524
+ }
1525
+ }
1526
+ position$1 += 8;
1527
+ } else if (type === 'undefined') {
1528
+ if (this.encodeUndefinedAsNil)
1529
+ target[position$1++] = 0xc0;
1530
+ else {
1531
+ target[position$1++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
1532
+ target[position$1++] = 0;
1533
+ target[position$1++] = 0;
1534
+ }
1535
+ } else if (type === 'function') {
1536
+ pack(this.writeFunction && this.writeFunction()); // if there is a writeFunction, use it, otherwise just encode as undefined
1537
+ } else {
1538
+ throw new Error('Unknown type: ' + type)
1539
+ }
1540
+ };
1541
+
1542
+ const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {
1543
+ // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
1544
+ let keys = Object.keys(object);
1545
+ let length = keys.length;
1546
+ if (length < 0x10) {
1547
+ target[position$1++] = 0x80 | length;
1548
+ } else if (length < 0x10000) {
1549
+ target[position$1++] = 0xde;
1550
+ target[position$1++] = length >> 8;
1551
+ target[position$1++] = length & 0xff;
1552
+ } else {
1553
+ target[position$1++] = 0xdf;
1554
+ targetView.setUint32(position$1, length);
1555
+ position$1 += 4;
1556
+ }
1557
+ let key;
1558
+ for (let i = 0; i < length; i++) {
1559
+ pack(key = keys[i]);
1560
+ pack(object[key]);
1561
+ }
1562
+ } :
1563
+ (object, safePrototype) => {
1564
+ target[position$1++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
1565
+ let objectOffset = position$1 - start;
1566
+ position$1 += 2;
1567
+ let size = 0;
1568
+ for (let key in object) {
1569
+ if (safePrototype || object.hasOwnProperty(key)) {
1570
+ pack(key);
1571
+ pack(object[key]);
1572
+ size++;
1573
+ }
1574
+ }
1575
+ target[objectOffset++ + start] = size >> 8;
1576
+ target[objectOffset + start] = size & 0xff;
1577
+ } :
1578
+ (options.progressiveRecords && !useTwoByteRecords) ? // this is about 2% faster for highly stable structures, since it only requires one for-in loop (but much more expensive when new structure needs to be written)
1579
+ (object, safePrototype) => {
1580
+ let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1581
+ let objectOffset = position$1++ - start;
1582
+ let wroteKeys;
1583
+ for (let key in object) {
1584
+ if (safePrototype || object.hasOwnProperty(key)) {
1585
+ nextTransition = transition[key];
1586
+ if (nextTransition)
1587
+ transition = nextTransition;
1588
+ else {
1589
+ // record doesn't exist, create full new record and insert it
1590
+ let keys = Object.keys(object);
1591
+ let lastTransition = transition;
1592
+ transition = structures.transitions;
1593
+ let newTransitions = 0;
1594
+ for (let i = 0, l = keys.length; i < l; i++) {
1595
+ let key = keys[i];
1596
+ nextTransition = transition[key];
1597
+ if (!nextTransition) {
1598
+ nextTransition = transition[key] = Object.create(null);
1599
+ newTransitions++;
1600
+ }
1601
+ transition = nextTransition;
1602
+ }
1603
+ if (objectOffset + start + 1 == position$1) {
1604
+ // first key, so we don't need to insert, we can just write record directly
1605
+ position$1--;
1606
+ newRecord(transition, keys, newTransitions);
1607
+ } else // otherwise we need to insert the record, moving existing data after the record
1608
+ insertNewRecord(transition, keys, objectOffset, newTransitions);
1609
+ wroteKeys = true;
1610
+ transition = lastTransition[key];
1611
+ }
1612
+ pack(object[key]);
1613
+ }
1614
+ }
1615
+ if (!wroteKeys) {
1616
+ let recordId = transition[RECORD_SYMBOL];
1617
+ if (recordId)
1618
+ target[objectOffset + start] = recordId;
1619
+ else
1620
+ insertNewRecord(transition, Object.keys(object), objectOffset, 0);
1621
+ }
1622
+ } :
1623
+ (object, safePrototype) => {
1624
+ let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1625
+ let newTransitions = 0;
1626
+ for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
1627
+ nextTransition = transition[key];
1628
+ if (!nextTransition) {
1629
+ nextTransition = transition[key] = Object.create(null);
1630
+ newTransitions++;
1631
+ }
1632
+ transition = nextTransition;
1633
+ }
1634
+ let recordId = transition[RECORD_SYMBOL];
1635
+ if (recordId) {
1636
+ if (recordId >= 0x60 && useTwoByteRecords) {
1637
+ target[position$1++] = ((recordId -= 0x60) & 0x1f) + 0x60;
1638
+ target[position$1++] = recordId >> 5;
1639
+ } else
1640
+ target[position$1++] = recordId;
1641
+ } else {
1642
+ newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
1643
+ }
1644
+ // now write the values
1645
+ for (let key in object)
1646
+ if (safePrototype || object.hasOwnProperty(key))
1647
+ pack(object[key]);
1648
+ };
1649
+ const makeRoom = (end) => {
1650
+ let newSize;
1651
+ if (end > 0x1000000) {
1652
+ // special handling for really large buffers
1653
+ if ((end - start) > MAX_BUFFER_SIZE)
1654
+ throw new Error('Packed buffer would be larger than maximum buffer size')
1655
+ newSize = Math.min(MAX_BUFFER_SIZE,
1656
+ Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
1657
+ } else // faster handling for smaller buffers
1658
+ newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
1659
+ let newBuffer = new ByteArrayAllocate(newSize);
1660
+ targetView = new DataView(newBuffer.buffer, 0, newSize);
1661
+ end = Math.min(end, target.length);
1662
+ if (target.copy)
1663
+ target.copy(newBuffer, 0, start, end);
1664
+ else
1665
+ newBuffer.set(target.slice(start, end));
1666
+ position$1 -= start;
1667
+ start = 0;
1668
+ safeEnd = newBuffer.length - 10;
1669
+ return target = newBuffer
1670
+ };
1671
+ const newRecord = (transition, keys, newTransitions) => {
1672
+ let recordId = structures.nextId;
1673
+ if (!recordId)
1674
+ recordId = 0x40;
1675
+ if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
1676
+ recordId = structures.nextOwnId;
1677
+ if (!(recordId < maxStructureId))
1678
+ recordId = sharedLimitId;
1679
+ structures.nextOwnId = recordId + 1;
1680
+ } else {
1681
+ if (recordId >= maxStructureId)// cycle back around
1682
+ recordId = sharedLimitId;
1683
+ structures.nextId = recordId + 1;
1684
+ }
1685
+ let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
1686
+ transition[RECORD_SYMBOL] = recordId;
1687
+ transition.__keys__ = keys;
1688
+ structures[recordId - 0x40] = keys;
1689
+
1690
+ if (recordId < sharedLimitId) {
1691
+ keys.isShared = true;
1692
+ structures.sharedLength = recordId - 0x3f;
1693
+ hasSharedUpdate = true;
1694
+ if (highByte >= 0) {
1695
+ target[position$1++] = (recordId & 0x1f) + 0x60;
1696
+ target[position$1++] = highByte;
1697
+ } else {
1698
+ target[position$1++] = recordId;
1699
+ }
1700
+ } else {
1701
+ if (highByte >= 0) {
1702
+ target[position$1++] = 0xd5; // fixext 2
1703
+ target[position$1++] = 0x72; // "r" record defintion extension type
1704
+ target[position$1++] = (recordId & 0x1f) + 0x60;
1705
+ target[position$1++] = highByte;
1706
+ } else {
1707
+ target[position$1++] = 0xd4; // fixext 1
1708
+ target[position$1++] = 0x72; // "r" record defintion extension type
1709
+ target[position$1++] = recordId;
1710
+ }
1711
+
1712
+ if (newTransitions)
1713
+ transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
1714
+ // record the removal of the id, we can maintain our shared structure
1715
+ if (recordIdsToRemove.length >= maxOwnStructures)
1716
+ recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
1717
+ recordIdsToRemove.push(transition);
1718
+ pack(keys);
1719
+ }
1720
+ };
1721
+ const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
1722
+ let mainTarget = target;
1723
+ let mainPosition = position$1;
1724
+ let mainSafeEnd = safeEnd;
1725
+ let mainStart = start;
1726
+ target = keysTarget;
1727
+ position$1 = 0;
1728
+ start = 0;
1729
+ if (!target)
1730
+ keysTarget = target = new ByteArrayAllocate(8192);
1731
+ safeEnd = target.length - 10;
1732
+ newRecord(transition, keys, newTransitions);
1733
+ keysTarget = target;
1734
+ let keysPosition = position$1;
1735
+ target = mainTarget;
1736
+ position$1 = mainPosition;
1737
+ safeEnd = mainSafeEnd;
1738
+ start = mainStart;
1739
+ if (keysPosition > 1) {
1740
+ let newEnd = position$1 + keysPosition - 1;
1741
+ if (newEnd > safeEnd)
1742
+ makeRoom(newEnd);
1743
+ let insertionPosition = insertionOffset + start;
1744
+ target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position$1);
1745
+ target.set(keysTarget.slice(0, keysPosition), insertionPosition);
1746
+ position$1 = newEnd;
1747
+ } else {
1748
+ target[insertionOffset + start] = keysTarget[0];
1749
+ }
1750
+ };
1751
+ }
1752
+ useBuffer(buffer) {
1753
+ // this means we are finished using our own buffer and we can write over it safely
1754
+ target = buffer;
1755
+ targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
1756
+ position$1 = 0;
1757
+ }
1758
+ clearSharedData() {
1759
+ if (this.structures)
1760
+ this.structures = [];
1761
+ }
1762
+ }
1763
+
1764
+ extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, C1Type ];
1765
+ extensions = [{
1766
+ pack(date, allocateForWrite, pack) {
1767
+ let seconds = date.getTime() / 1000;
1768
+ if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
1769
+ // Timestamp 32
1770
+ let { target, targetView, position} = allocateForWrite(6);
1771
+ target[position++] = 0xd6;
1772
+ target[position++] = 0xff;
1773
+ targetView.setUint32(position, seconds);
1774
+ } else if (seconds > 0 && seconds < 0x100000000) {
1775
+ // Timestamp 64
1776
+ let { target, targetView, position} = allocateForWrite(10);
1777
+ target[position++] = 0xd7;
1778
+ target[position++] = 0xff;
1779
+ targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
1780
+ targetView.setUint32(position + 4, seconds);
1781
+ } else if (isNaN(seconds)) {
1782
+ if (this.onInvalidDate) {
1783
+ allocateForWrite(0);
1784
+ return pack(this.onInvalidDate())
1785
+ }
1786
+ // Intentionally invalid timestamp
1787
+ let { target, targetView, position} = allocateForWrite(3);
1788
+ target[position++] = 0xd4;
1789
+ target[position++] = 0xff;
1790
+ target[position++] = 0xff;
1791
+ } else {
1792
+ // Timestamp 96
1793
+ let { target, targetView, position} = allocateForWrite(15);
1794
+ target[position++] = 0xc7;
1795
+ target[position++] = 12;
1796
+ target[position++] = 0xff;
1797
+ targetView.setUint32(position, date.getMilliseconds() * 1000000);
1798
+ targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
1799
+ }
1800
+ }
1801
+ }, {
1802
+ pack(set, allocateForWrite, pack) {
1803
+ let array = Array.from(set);
1804
+ let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1805
+ if (this.moreTypes) {
1806
+ target[position++] = 0xd4;
1807
+ target[position++] = 0x73; // 's' for Set
1808
+ target[position++] = 0;
1809
+ }
1810
+ pack(array);
1811
+ }
1812
+ }, {
1813
+ pack(error, allocateForWrite, pack) {
1814
+ let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1815
+ if (this.moreTypes) {
1816
+ target[position++] = 0xd4;
1817
+ target[position++] = 0x65; // 'e' for error
1818
+ target[position++] = 0;
1819
+ }
1820
+ pack([ error.name, error.message ]);
1821
+ }
1822
+ }, {
1823
+ pack(regex, allocateForWrite, pack) {
1824
+ let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1825
+ if (this.moreTypes) {
1826
+ target[position++] = 0xd4;
1827
+ target[position++] = 0x78; // 'x' for regeXp
1828
+ target[position++] = 0;
1829
+ }
1830
+ pack([ regex.source, regex.flags ]);
1831
+ }
1832
+ }, {
1833
+ pack(arrayBuffer, allocateForWrite) {
1834
+ if (this.moreTypes)
1835
+ writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
1836
+ else
1837
+ writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
1838
+ }
1839
+ }, {
1840
+ pack(typedArray, allocateForWrite) {
1841
+ let constructor = typedArray.constructor;
1842
+ if (constructor !== ByteArray && this.moreTypes)
1843
+ writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
1844
+ else
1845
+ writeBuffer(typedArray, allocateForWrite);
1846
+ }
1847
+ }, {
1848
+ pack(c1, allocateForWrite) { // specific 0xC1 object
1849
+ let { target, position} = allocateForWrite(1);
1850
+ target[position] = 0xc1;
1851
+ }
1852
+ }];
1853
+
1854
+ function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
1855
+ let length = typedArray.byteLength;
1856
+ if (length + 1 < 0x100) {
1857
+ var { target, position } = allocateForWrite(4 + length);
1858
+ target[position++] = 0xc7;
1859
+ target[position++] = length + 1;
1860
+ } else if (length + 1 < 0x10000) {
1861
+ var { target, position } = allocateForWrite(5 + length);
1862
+ target[position++] = 0xc8;
1863
+ target[position++] = (length + 1) >> 8;
1864
+ target[position++] = (length + 1) & 0xff;
1865
+ } else {
1866
+ var { target, position, targetView } = allocateForWrite(7 + length);
1867
+ target[position++] = 0xc9;
1868
+ targetView.setUint32(position, length + 1); // plus one for the type byte
1869
+ position += 4;
1870
+ }
1871
+ target[position++] = 0x74; // "t" for typed array
1872
+ target[position++] = type;
1873
+ target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
1874
+ }
1875
+ function writeBuffer(buffer, allocateForWrite) {
1876
+ let length = buffer.byteLength;
1877
+ var target, position;
1878
+ if (length < 0x100) {
1879
+ var { target, position } = allocateForWrite(length + 2);
1880
+ target[position++] = 0xc4;
1881
+ target[position++] = length;
1882
+ } else if (length < 0x10000) {
1883
+ var { target, position } = allocateForWrite(length + 3);
1884
+ target[position++] = 0xc5;
1885
+ target[position++] = length >> 8;
1886
+ target[position++] = length & 0xff;
1887
+ } else {
1888
+ var { target, position, targetView } = allocateForWrite(length + 5);
1889
+ target[position++] = 0xc6;
1890
+ targetView.setUint32(position, length);
1891
+ position += 4;
1892
+ }
1893
+ target.set(buffer, position);
1894
+ }
1895
+
1896
+ function writeExtensionData(result, target, position, type) {
1897
+ let length = result.length;
1898
+ switch (length) {
1899
+ case 1:
1900
+ target[position++] = 0xd4;
1901
+ break
1902
+ case 2:
1903
+ target[position++] = 0xd5;
1904
+ break
1905
+ case 4:
1906
+ target[position++] = 0xd6;
1907
+ break
1908
+ case 8:
1909
+ target[position++] = 0xd7;
1910
+ break
1911
+ case 16:
1912
+ target[position++] = 0xd8;
1913
+ break
1914
+ default:
1915
+ if (length < 0x100) {
1916
+ target[position++] = 0xc7;
1917
+ target[position++] = length;
1918
+ } else if (length < 0x10000) {
1919
+ target[position++] = 0xc8;
1920
+ target[position++] = length >> 8;
1921
+ target[position++] = length & 0xff;
1922
+ } else {
1923
+ target[position++] = 0xc9;
1924
+ target[position++] = length >> 24;
1925
+ target[position++] = (length >> 16) & 0xff;
1926
+ target[position++] = (length >> 8) & 0xff;
1927
+ target[position++] = length & 0xff;
1928
+ }
1929
+ }
1930
+ target[position++] = type;
1931
+ target.set(result, position);
1932
+ position += length;
1933
+ return position
1934
+ }
1935
+
1936
+ function insertIds(serialized, idsToInsert) {
1937
+ // insert the ids that need to be referenced for structured clones
1938
+ let nextId;
1939
+ let distanceToMove = idsToInsert.length * 6;
1940
+ let lastEnd = serialized.length - distanceToMove;
1941
+ idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
1942
+ while (nextId = idsToInsert.pop()) {
1943
+ let offset = nextId.offset;
1944
+ let id = nextId.id;
1945
+ serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
1946
+ distanceToMove -= 6;
1947
+ let position = offset + distanceToMove;
1948
+ serialized[position++] = 0xd6;
1949
+ serialized[position++] = 0x69; // 'i'
1950
+ serialized[position++] = id >> 24;
1951
+ serialized[position++] = (id >> 16) & 0xff;
1952
+ serialized[position++] = (id >> 8) & 0xff;
1953
+ serialized[position++] = id & 0xff;
1954
+ lastEnd = offset;
1955
+ }
1956
+ return serialized
1957
+ }
1958
+
1959
+ function writeBundles(start, pack) {
1960
+ if (bundledStrings$1.length > 0) {
1961
+ targetView.setUint32(bundledStrings$1.position + start, position$1 - bundledStrings$1.position - start);
1962
+ let writeStrings = bundledStrings$1;
1963
+ bundledStrings$1 = null;
1964
+ pack(writeStrings[0]);
1965
+ pack(writeStrings[1]);
1966
+ }
1967
+ }
1968
+
1969
+ function addExtension$1(extension) {
1970
+ if (extension.Class) {
1971
+ if (!extension.pack && !extension.write)
1972
+ throw new Error('Extension has no pack or write function')
1973
+ if (extension.pack && !extension.type)
1974
+ throw new Error('Extension has no type (numeric code to identify the extension)')
1975
+ extensionClasses.unshift(extension.Class);
1976
+ extensions.unshift(extension);
1977
+ }
1978
+ addExtension(extension);
1979
+ }
1980
+
1981
+ let defaultPackr = new Packr({ useRecords: false });
1982
+ const pack = defaultPackr.pack;
1983
+ const encode = defaultPackr.pack;
1984
+ const Encoder = Packr;
1985
+ const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
1986
+ const REUSE_BUFFER_MODE = 512;
1977
1987
  const RESET_BUFFER_MODE = 1024;
1978
1988
 
1979
1989
  class PackrStream extends stream.Transform {
@@ -2114,23 +2124,23 @@ function unpackIter (bufferIterator, options = {}) {
2114
2124
  const decodeIter = unpackIter;
2115
2125
  const encodeIter = packIter;
2116
2126
 
2117
- const useRecords = false;
2118
- const mapsAsObjects = true;
2119
-
2120
- const nativeAccelerationDisabled = process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED !== undefined && process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === 'true';
2121
-
2122
- if (!nativeAccelerationDisabled) {
2123
- let extractor;
2124
- try {
2125
- if (typeof require == 'function')
2126
- extractor = require('msgpackr-extract');
2127
- else
2128
- extractor = module$1.createRequire((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('node.cjs', document.baseURI).href)))('msgpackr-extract');
2129
- if (extractor)
2130
- setExtractor(extractor.extractStrings);
2131
- } catch (error) {
2132
- // native module is optional
2133
- }
2127
+ const useRecords = false;
2128
+ const mapsAsObjects = true;
2129
+
2130
+ const nativeAccelerationDisabled = process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED !== undefined && process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === 'true';
2131
+
2132
+ if (!nativeAccelerationDisabled) {
2133
+ let extractor;
2134
+ try {
2135
+ if (typeof require == 'function')
2136
+ extractor = require('msgpackr-extract');
2137
+ else
2138
+ extractor = module$1.createRequire((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('node.cjs', document.baseURI).href)))('msgpackr-extract');
2139
+ if (extractor)
2140
+ setExtractor(extractor.extractStrings);
2141
+ } catch (error) {
2142
+ // native module is optional
2143
+ }
2134
2144
  }
2135
2145
 
2136
2146
  exports.ALWAYS = ALWAYS;