msgpackr 1.7.2 → 1.8.0

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