msgpackr 1.6.0 → 1.7.0-alpha1

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