msgpackr 1.7.2 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2181 @@
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 packArray = (value) => {
1273
+ var length = value.length;
1274
+ if (length < 0x10) {
1275
+ target[position++] = 0x90 | length;
1276
+ } else if (length < 0x10000) {
1277
+ target[position++] = 0xdc;
1278
+ target[position++] = length >> 8;
1279
+ target[position++] = length & 0xff;
1280
+ } else {
1281
+ target[position++] = 0xdd;
1282
+ targetView.setUint32(position, length);
1283
+ position += 4;
1284
+ }
1285
+ for (let i = 0; i < length; i++) {
1286
+ pack(value[i]);
1287
+ }
1288
+ };
1289
+ const pack = (value) => {
1290
+ if (position > safeEnd)
1291
+ target = makeRoom(position);
1292
+
1293
+ var type = typeof value;
1294
+ var length;
1295
+ if (type === 'string') {
1296
+ let strLength = value.length;
1297
+ if (bundledStrings && strLength >= 4 && strLength < 0x1000) {
1298
+ if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
1299
+ let extStart;
1300
+ let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
1301
+ if (position + maxBytes > safeEnd)
1302
+ target = makeRoom(position + maxBytes);
1303
+ let lastBundle;
1304
+ 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
1305
+ lastBundle = bundledStrings;
1306
+ target[position] = 0xc8; // ext 16
1307
+ position += 3; // reserve for the writing bundle size
1308
+ target[position++] = 0x62; // 'b'
1309
+ extStart = position - start;
1310
+ position += 4; // reserve for writing bundle reference
1311
+ writeBundles(start, pack, 0); // write the last bundles
1312
+ targetView.setUint16(extStart + start - 3, position - start - extStart);
1313
+ } 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)
1314
+ target[position++] = 0xd6; // fixext 4
1315
+ target[position++] = 0x62; // 'b'
1316
+ extStart = position - start;
1317
+ position += 4; // reserve for writing bundle reference
1318
+ }
1319
+ bundledStrings = ['', '']; // create new ones
1320
+ bundledStrings.previous = lastBundle;
1321
+ bundledStrings.size = 0;
1322
+ bundledStrings.position = extStart;
1323
+ }
1324
+ let twoByte = hasNonLatin.test(value);
1325
+ bundledStrings[twoByte ? 0 : 1] += value;
1326
+ target[position++] = 0xc1;
1327
+ pack(twoByte ? -strLength : strLength);
1328
+ return
1329
+ }
1330
+ let headerSize;
1331
+ // first we estimate the header size, so we can write to the correct location
1332
+ if (strLength < 0x20) {
1333
+ headerSize = 1;
1334
+ } else if (strLength < 0x100) {
1335
+ headerSize = 2;
1336
+ } else if (strLength < 0x10000) {
1337
+ headerSize = 3;
1338
+ } else {
1339
+ headerSize = 5;
1340
+ }
1341
+ let maxBytes = strLength * 3;
1342
+ if (position + maxBytes > safeEnd)
1343
+ target = makeRoom(position + maxBytes);
1344
+
1345
+ if (strLength < 0x40 || !encodeUtf8) {
1346
+ let i, c1, c2, strPosition = position + headerSize;
1347
+ for (i = 0; i < strLength; i++) {
1348
+ c1 = value.charCodeAt(i);
1349
+ if (c1 < 0x80) {
1350
+ target[strPosition++] = c1;
1351
+ } else if (c1 < 0x800) {
1352
+ target[strPosition++] = c1 >> 6 | 0xc0;
1353
+ target[strPosition++] = c1 & 0x3f | 0x80;
1354
+ } else if (
1355
+ (c1 & 0xfc00) === 0xd800 &&
1356
+ ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
1357
+ ) {
1358
+ c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
1359
+ i++;
1360
+ target[strPosition++] = c1 >> 18 | 0xf0;
1361
+ target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
1362
+ target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1363
+ target[strPosition++] = c1 & 0x3f | 0x80;
1364
+ } else {
1365
+ target[strPosition++] = c1 >> 12 | 0xe0;
1366
+ target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1367
+ target[strPosition++] = c1 & 0x3f | 0x80;
1368
+ }
1369
+ }
1370
+ length = strPosition - position - headerSize;
1371
+ } else {
1372
+ length = encodeUtf8(value, position + headerSize);
1373
+ }
1374
+
1375
+ if (length < 0x20) {
1376
+ target[position++] = 0xa0 | length;
1377
+ } else if (length < 0x100) {
1378
+ if (headerSize < 2) {
1379
+ target.copyWithin(position + 2, position + 1, position + 1 + length);
1380
+ }
1381
+ target[position++] = 0xd9;
1382
+ target[position++] = length;
1383
+ } else if (length < 0x10000) {
1384
+ if (headerSize < 3) {
1385
+ target.copyWithin(position + 3, position + 2, position + 2 + length);
1386
+ }
1387
+ target[position++] = 0xda;
1388
+ target[position++] = length >> 8;
1389
+ target[position++] = length & 0xff;
1390
+ } else {
1391
+ if (headerSize < 5) {
1392
+ target.copyWithin(position + 5, position + 3, position + 3 + length);
1393
+ }
1394
+ target[position++] = 0xdb;
1395
+ targetView.setUint32(position, length);
1396
+ position += 4;
1397
+ }
1398
+ position += length;
1399
+ } else if (type === 'number') {
1400
+ if (value >>> 0 === value) {// positive integer, 32-bit or less
1401
+ // positive uint
1402
+ if (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this.randomAccessStructure)) {
1403
+ target[position++] = value;
1404
+ } else if (value < 0x100) {
1405
+ target[position++] = 0xcc;
1406
+ target[position++] = value;
1407
+ } else if (value < 0x10000) {
1408
+ target[position++] = 0xcd;
1409
+ target[position++] = value >> 8;
1410
+ target[position++] = value & 0xff;
1411
+ } else {
1412
+ target[position++] = 0xce;
1413
+ targetView.setUint32(position, value);
1414
+ position += 4;
1415
+ }
1416
+ } else if (value >> 0 === value) { // negative integer
1417
+ if (value >= -0x20) {
1418
+ target[position++] = 0x100 + value;
1419
+ } else if (value >= -0x80) {
1420
+ target[position++] = 0xd0;
1421
+ target[position++] = value + 0x100;
1422
+ } else if (value >= -0x8000) {
1423
+ target[position++] = 0xd1;
1424
+ targetView.setInt16(position, value);
1425
+ position += 2;
1426
+ } else {
1427
+ target[position++] = 0xd2;
1428
+ targetView.setInt32(position, value);
1429
+ position += 4;
1430
+ }
1431
+ } else {
1432
+ let useFloat32;
1433
+ if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
1434
+ target[position++] = 0xca;
1435
+ targetView.setFloat32(position, value);
1436
+ let xShifted;
1437
+ if (useFloat32 < 4 ||
1438
+ // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
1439
+ ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
1440
+ position += 4;
1441
+ return
1442
+ } else
1443
+ position--; // move back into position for writing a double
1444
+ }
1445
+ target[position++] = 0xcb;
1446
+ targetView.setFloat64(position, value);
1447
+ position += 8;
1448
+ }
1449
+ } else if (type === 'object') {
1450
+ if (!value)
1451
+ target[position++] = 0xc0;
1452
+ else {
1453
+ if (referenceMap) {
1454
+ let referee = referenceMap.get(value);
1455
+ if (referee) {
1456
+ if (!referee.id) {
1457
+ let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
1458
+ referee.id = idsToInsert.push(referee);
1459
+ }
1460
+ target[position++] = 0xd6; // fixext 4
1461
+ target[position++] = 0x70; // "p" for pointer
1462
+ targetView.setUint32(position, referee.id);
1463
+ position += 4;
1464
+ return
1465
+ } else
1466
+ referenceMap.set(value, { offset: position - start });
1467
+ }
1468
+ let constructor = value.constructor;
1469
+ if (constructor === Object) {
1470
+ writeObject(value, true);
1471
+ } else if (constructor === Array) {
1472
+ packArray(value);
1473
+ } else if (constructor === Map) {
1474
+ length = value.size;
1475
+ if (length < 0x10) {
1476
+ target[position++] = 0x80 | length;
1477
+ } else if (length < 0x10000) {
1478
+ target[position++] = 0xde;
1479
+ target[position++] = length >> 8;
1480
+ target[position++] = length & 0xff;
1481
+ } else {
1482
+ target[position++] = 0xdf;
1483
+ targetView.setUint32(position, length);
1484
+ position += 4;
1485
+ }
1486
+ for (let [ key, entryValue ] of value) {
1487
+ pack(key);
1488
+ pack(entryValue);
1489
+ }
1490
+ } else {
1491
+ for (let i = 0, l = extensions.length; i < l; i++) {
1492
+ let extensionClass = extensionClasses[i];
1493
+ if (value instanceof extensionClass) {
1494
+ let extension = extensions[i];
1495
+ if (extension.write) {
1496
+ if (extension.type) {
1497
+ target[position++] = 0xd4; // one byte "tag" extension
1498
+ target[position++] = extension.type;
1499
+ target[position++] = 0;
1500
+ }
1501
+ let writeResult = extension.write.call(this, value);
1502
+ if (writeResult === value) { // avoid infinite recursion
1503
+ if (Array.isArray(value)) {
1504
+ packArray(value);
1505
+ } else {
1506
+ writeObject(value);
1507
+ }
1508
+ } else {
1509
+ pack(writeResult);
1510
+ }
1511
+ return
1512
+ }
1513
+ let currentTarget = target;
1514
+ let currentTargetView = targetView;
1515
+ let currentPosition = position;
1516
+ target = null;
1517
+ let result;
1518
+ try {
1519
+ result = extension.pack.call(this, value, (size) => {
1520
+ // restore target and use it
1521
+ target = currentTarget;
1522
+ currentTarget = null;
1523
+ position += size;
1524
+ if (position > safeEnd)
1525
+ makeRoom(position);
1526
+ return {
1527
+ target, targetView, position: position - size
1528
+ }
1529
+ }, pack);
1530
+ } finally {
1531
+ // restore current target information (unless already restored)
1532
+ if (currentTarget) {
1533
+ target = currentTarget;
1534
+ targetView = currentTargetView;
1535
+ position = currentPosition;
1536
+ safeEnd = target.length - 10;
1537
+ }
1538
+ }
1539
+ if (result) {
1540
+ if (result.length + position > safeEnd)
1541
+ makeRoom(result.length + position);
1542
+ position = writeExtensionData(result, target, position, extension.type);
1543
+ }
1544
+ return
1545
+ }
1546
+ }
1547
+ // check isArray after extensions, because extensions can extend Array
1548
+ if (Array.isArray(value)) {
1549
+ packArray(value);
1550
+ } else {
1551
+ // no extension found, write as object
1552
+ writeObject(value, !value.hasOwnProperty); // if it doesn't have hasOwnProperty, don't do hasOwnProperty checks
1553
+ }
1554
+ }
1555
+ }
1556
+ } else if (type === 'boolean') {
1557
+ target[position++] = value ? 0xc3 : 0xc2;
1558
+ } else if (type === 'bigint') {
1559
+ if (value < (BigInt(1)<<BigInt(63)) && value >= -(BigInt(1)<<BigInt(63))) {
1560
+ // use a signed int as long as it fits
1561
+ target[position++] = 0xd3;
1562
+ targetView.setBigInt64(position, value);
1563
+ } else if (value < (BigInt(1)<<BigInt(64)) && value > 0) {
1564
+ // if we can fit an unsigned int, use that
1565
+ target[position++] = 0xcf;
1566
+ targetView.setBigUint64(position, value);
1567
+ } else {
1568
+ // overflow
1569
+ if (this.largeBigIntToFloat) {
1570
+ target[position++] = 0xcb;
1571
+ targetView.setFloat64(position, Number(value));
1572
+ } else {
1573
+ throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, set largeBigIntToFloat to convert to float-64')
1574
+ }
1575
+ }
1576
+ position += 8;
1577
+ } else if (type === 'undefined') {
1578
+ if (this.encodeUndefinedAsNil)
1579
+ target[position++] = 0xc0;
1580
+ else {
1581
+ target[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
1582
+ target[position++] = 0;
1583
+ target[position++] = 0;
1584
+ }
1585
+ } else if (type === 'function') {
1586
+ pack(this.writeFunction && this.writeFunction()); // if there is a writeFunction, use it, otherwise just encode as undefined
1587
+ } else {
1588
+ throw new Error('Unknown type: ' + type)
1589
+ }
1590
+ };
1591
+
1592
+ const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {
1593
+ // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
1594
+ let keys = Object.keys(object);
1595
+ let length = keys.length;
1596
+ if (length < 0x10) {
1597
+ target[position++] = 0x80 | length;
1598
+ } else if (length < 0x10000) {
1599
+ target[position++] = 0xde;
1600
+ target[position++] = length >> 8;
1601
+ target[position++] = length & 0xff;
1602
+ } else {
1603
+ target[position++] = 0xdf;
1604
+ targetView.setUint32(position, length);
1605
+ position += 4;
1606
+ }
1607
+ let key;
1608
+ for (let i = 0; i < length; i++) {
1609
+ pack(key = keys[i]);
1610
+ pack(object[key]);
1611
+ }
1612
+ } :
1613
+ (object, safePrototype) => {
1614
+ target[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
1615
+ let objectOffset = position - start;
1616
+ position += 2;
1617
+ let size = 0;
1618
+ for (let key in object) {
1619
+ if (safePrototype || object.hasOwnProperty(key)) {
1620
+ pack(key);
1621
+ pack(object[key]);
1622
+ size++;
1623
+ }
1624
+ }
1625
+ target[objectOffset++ + start] = size >> 8;
1626
+ target[objectOffset + start] = size & 0xff;
1627
+ } :
1628
+ (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)
1629
+ (object, safePrototype) => {
1630
+ let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1631
+ let objectOffset = position++ - start;
1632
+ let wroteKeys;
1633
+ for (let key in object) {
1634
+ if (safePrototype || object.hasOwnProperty(key)) {
1635
+ nextTransition = transition[key];
1636
+ if (nextTransition)
1637
+ transition = nextTransition;
1638
+ else {
1639
+ // record doesn't exist, create full new record and insert it
1640
+ let keys = Object.keys(object);
1641
+ let lastTransition = transition;
1642
+ transition = structures.transitions;
1643
+ let newTransitions = 0;
1644
+ for (let i = 0, l = keys.length; i < l; i++) {
1645
+ let key = keys[i];
1646
+ nextTransition = transition[key];
1647
+ if (!nextTransition) {
1648
+ nextTransition = transition[key] = Object.create(null);
1649
+ newTransitions++;
1650
+ }
1651
+ transition = nextTransition;
1652
+ }
1653
+ if (objectOffset + start + 1 == position) {
1654
+ // first key, so we don't need to insert, we can just write record directly
1655
+ position--;
1656
+ newRecord(transition, keys, newTransitions);
1657
+ } else // otherwise we need to insert the record, moving existing data after the record
1658
+ insertNewRecord(transition, keys, objectOffset, newTransitions);
1659
+ wroteKeys = true;
1660
+ transition = lastTransition[key];
1661
+ }
1662
+ pack(object[key]);
1663
+ }
1664
+ }
1665
+ if (!wroteKeys) {
1666
+ let recordId = transition[RECORD_SYMBOL];
1667
+ if (recordId)
1668
+ target[objectOffset + start] = recordId;
1669
+ else
1670
+ insertNewRecord(transition, Object.keys(object), objectOffset, 0);
1671
+ }
1672
+ } :
1673
+ (object, safePrototype) => {
1674
+ let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1675
+ let newTransitions = 0;
1676
+ for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
1677
+ nextTransition = transition[key];
1678
+ if (!nextTransition) {
1679
+ nextTransition = transition[key] = Object.create(null);
1680
+ newTransitions++;
1681
+ }
1682
+ transition = nextTransition;
1683
+ }
1684
+ let recordId = transition[RECORD_SYMBOL];
1685
+ if (recordId) {
1686
+ if (recordId >= 0x60 && useTwoByteRecords) {
1687
+ target[position++] = ((recordId -= 0x60) & 0x1f) + 0x60;
1688
+ target[position++] = recordId >> 5;
1689
+ } else
1690
+ target[position++] = recordId;
1691
+ } else {
1692
+ newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
1693
+ }
1694
+ // now write the values
1695
+ for (let key in object)
1696
+ if (safePrototype || object.hasOwnProperty(key))
1697
+ pack(object[key]);
1698
+ };
1699
+ const makeRoom = (end) => {
1700
+ let newSize;
1701
+ if (end > 0x1000000) {
1702
+ // special handling for really large buffers
1703
+ if ((end - start) > MAX_BUFFER_SIZE)
1704
+ throw new Error('Packed buffer would be larger than maximum buffer size')
1705
+ newSize = Math.min(MAX_BUFFER_SIZE,
1706
+ Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
1707
+ } else // faster handling for smaller buffers
1708
+ newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
1709
+ let newBuffer = new ByteArrayAllocate(newSize);
1710
+ targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize));
1711
+ end = Math.min(end, target.length);
1712
+ if (target.copy)
1713
+ target.copy(newBuffer, 0, start, end);
1714
+ else
1715
+ newBuffer.set(target.slice(start, end));
1716
+ position -= start;
1717
+ start = 0;
1718
+ safeEnd = newBuffer.length - 10;
1719
+ return target = newBuffer
1720
+ };
1721
+ const newRecord = (transition, keys, newTransitions) => {
1722
+ let recordId = structures.nextId;
1723
+ if (!recordId)
1724
+ recordId = 0x40;
1725
+ if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
1726
+ recordId = structures.nextOwnId;
1727
+ if (!(recordId < maxStructureId))
1728
+ recordId = sharedLimitId;
1729
+ structures.nextOwnId = recordId + 1;
1730
+ } else {
1731
+ if (recordId >= maxStructureId)// cycle back around
1732
+ recordId = sharedLimitId;
1733
+ structures.nextId = recordId + 1;
1734
+ }
1735
+ let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
1736
+ transition[RECORD_SYMBOL] = recordId;
1737
+ transition.__keys__ = keys;
1738
+ structures[recordId - 0x40] = keys;
1739
+
1740
+ if (recordId < sharedLimitId) {
1741
+ keys.isShared = true;
1742
+ structures.sharedLength = recordId - 0x3f;
1743
+ hasSharedUpdate = true;
1744
+ if (highByte >= 0) {
1745
+ target[position++] = (recordId & 0x1f) + 0x60;
1746
+ target[position++] = highByte;
1747
+ } else {
1748
+ target[position++] = recordId;
1749
+ }
1750
+ } else {
1751
+ if (highByte >= 0) {
1752
+ target[position++] = 0xd5; // fixext 2
1753
+ target[position++] = 0x72; // "r" record defintion extension type
1754
+ target[position++] = (recordId & 0x1f) + 0x60;
1755
+ target[position++] = highByte;
1756
+ } else {
1757
+ target[position++] = 0xd4; // fixext 1
1758
+ target[position++] = 0x72; // "r" record defintion extension type
1759
+ target[position++] = recordId;
1760
+ }
1761
+
1762
+ if (newTransitions)
1763
+ transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
1764
+ // record the removal of the id, we can maintain our shared structure
1765
+ if (recordIdsToRemove.length >= maxOwnStructures)
1766
+ recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
1767
+ recordIdsToRemove.push(transition);
1768
+ pack(keys);
1769
+ }
1770
+ };
1771
+ const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
1772
+ let mainTarget = target;
1773
+ let mainPosition = position;
1774
+ let mainSafeEnd = safeEnd;
1775
+ let mainStart = start;
1776
+ target = keysTarget;
1777
+ position = 0;
1778
+ start = 0;
1779
+ if (!target)
1780
+ keysTarget = target = new ByteArrayAllocate(8192);
1781
+ safeEnd = target.length - 10;
1782
+ newRecord(transition, keys, newTransitions);
1783
+ keysTarget = target;
1784
+ let keysPosition = position;
1785
+ target = mainTarget;
1786
+ position = mainPosition;
1787
+ safeEnd = mainSafeEnd;
1788
+ start = mainStart;
1789
+ if (keysPosition > 1) {
1790
+ let newEnd = position + keysPosition - 1;
1791
+ if (newEnd > safeEnd)
1792
+ makeRoom(newEnd);
1793
+ let insertionPosition = insertionOffset + start;
1794
+ target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position);
1795
+ target.set(keysTarget.slice(0, keysPosition), insertionPosition);
1796
+ position = newEnd;
1797
+ } else {
1798
+ target[insertionOffset + start] = keysTarget[0];
1799
+ }
1800
+ };
1801
+ const writeStruct = (object, safePrototype) => {
1802
+ let newPosition = writeStructSlots(object, target, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {
1803
+ if (notifySharedUpdate)
1804
+ return hasSharedUpdate = true;
1805
+ position = newPosition;
1806
+ if (start > 0) {
1807
+ pack(value);
1808
+ if (start == 0)
1809
+ return { position, targetView, target }; // indicate the buffer was re-allocated
1810
+ } else
1811
+ pack(value);
1812
+ return position;
1813
+ }, this);
1814
+ if (newPosition === 0) // bail and go to a msgpack object
1815
+ return writeObject(object, true);
1816
+ position = newPosition;
1817
+ };
1818
+ }
1819
+ useBuffer(buffer) {
1820
+ // this means we are finished using our own buffer and we can write over it safely
1821
+ target = buffer;
1822
+ targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
1823
+ position = 0;
1824
+ }
1825
+ clearSharedData() {
1826
+ if (this.structures)
1827
+ this.structures = [];
1828
+ if (this.typedStructs)
1829
+ this.typedStructs = [];
1830
+ }
1831
+ }
1832
+
1833
+ extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, C1Type ];
1834
+ extensions = [{
1835
+ pack(date, allocateForWrite, pack) {
1836
+ let seconds = date.getTime() / 1000;
1837
+ if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
1838
+ // Timestamp 32
1839
+ let { target, targetView, position} = allocateForWrite(6);
1840
+ target[position++] = 0xd6;
1841
+ target[position++] = 0xff;
1842
+ targetView.setUint32(position, seconds);
1843
+ } else if (seconds > 0 && seconds < 0x100000000) {
1844
+ // Timestamp 64
1845
+ let { target, targetView, position} = allocateForWrite(10);
1846
+ target[position++] = 0xd7;
1847
+ target[position++] = 0xff;
1848
+ targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
1849
+ targetView.setUint32(position + 4, seconds);
1850
+ } else if (isNaN(seconds)) {
1851
+ if (this.onInvalidDate) {
1852
+ allocateForWrite(0);
1853
+ return pack(this.onInvalidDate())
1854
+ }
1855
+ // Intentionally invalid timestamp
1856
+ let { target, targetView, position} = allocateForWrite(3);
1857
+ target[position++] = 0xd4;
1858
+ target[position++] = 0xff;
1859
+ target[position++] = 0xff;
1860
+ } else {
1861
+ // Timestamp 96
1862
+ let { target, targetView, position} = allocateForWrite(15);
1863
+ target[position++] = 0xc7;
1864
+ target[position++] = 12;
1865
+ target[position++] = 0xff;
1866
+ targetView.setUint32(position, date.getMilliseconds() * 1000000);
1867
+ targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
1868
+ }
1869
+ }
1870
+ }, {
1871
+ pack(set, allocateForWrite, pack) {
1872
+ let array = Array.from(set);
1873
+ let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1874
+ if (this.moreTypes) {
1875
+ target[position++] = 0xd4;
1876
+ target[position++] = 0x73; // 's' for Set
1877
+ target[position++] = 0;
1878
+ }
1879
+ pack(array);
1880
+ }
1881
+ }, {
1882
+ pack(error, allocateForWrite, pack) {
1883
+ let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1884
+ if (this.moreTypes) {
1885
+ target[position++] = 0xd4;
1886
+ target[position++] = 0x65; // 'e' for error
1887
+ target[position++] = 0;
1888
+ }
1889
+ pack([ error.name, error.message ]);
1890
+ }
1891
+ }, {
1892
+ pack(regex, allocateForWrite, pack) {
1893
+ let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1894
+ if (this.moreTypes) {
1895
+ target[position++] = 0xd4;
1896
+ target[position++] = 0x78; // 'x' for regeXp
1897
+ target[position++] = 0;
1898
+ }
1899
+ pack([ regex.source, regex.flags ]);
1900
+ }
1901
+ }, {
1902
+ pack(arrayBuffer, allocateForWrite) {
1903
+ if (this.moreTypes)
1904
+ writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
1905
+ else
1906
+ writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
1907
+ }
1908
+ }, {
1909
+ pack(typedArray, allocateForWrite) {
1910
+ let constructor = typedArray.constructor;
1911
+ if (constructor !== ByteArray && this.moreTypes)
1912
+ writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
1913
+ else
1914
+ writeBuffer(typedArray, allocateForWrite);
1915
+ }
1916
+ }, {
1917
+ pack(c1, allocateForWrite) { // specific 0xC1 object
1918
+ let { target, position} = allocateForWrite(1);
1919
+ target[position] = 0xc1;
1920
+ }
1921
+ }];
1922
+
1923
+ function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
1924
+ let length = typedArray.byteLength;
1925
+ if (length + 1 < 0x100) {
1926
+ var { target, position } = allocateForWrite(4 + length);
1927
+ target[position++] = 0xc7;
1928
+ target[position++] = length + 1;
1929
+ } else if (length + 1 < 0x10000) {
1930
+ var { target, position } = allocateForWrite(5 + length);
1931
+ target[position++] = 0xc8;
1932
+ target[position++] = (length + 1) >> 8;
1933
+ target[position++] = (length + 1) & 0xff;
1934
+ } else {
1935
+ var { target, position, targetView } = allocateForWrite(7 + length);
1936
+ target[position++] = 0xc9;
1937
+ targetView.setUint32(position, length + 1); // plus one for the type byte
1938
+ position += 4;
1939
+ }
1940
+ target[position++] = 0x74; // "t" for typed array
1941
+ target[position++] = type;
1942
+ target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
1943
+ }
1944
+ function writeBuffer(buffer, allocateForWrite) {
1945
+ let length = buffer.byteLength;
1946
+ var target, position;
1947
+ if (length < 0x100) {
1948
+ var { target, position } = allocateForWrite(length + 2);
1949
+ target[position++] = 0xc4;
1950
+ target[position++] = length;
1951
+ } else if (length < 0x10000) {
1952
+ var { target, position } = allocateForWrite(length + 3);
1953
+ target[position++] = 0xc5;
1954
+ target[position++] = length >> 8;
1955
+ target[position++] = length & 0xff;
1956
+ } else {
1957
+ var { target, position, targetView } = allocateForWrite(length + 5);
1958
+ target[position++] = 0xc6;
1959
+ targetView.setUint32(position, length);
1960
+ position += 4;
1961
+ }
1962
+ target.set(buffer, position);
1963
+ }
1964
+
1965
+ function writeExtensionData(result, target, position, type) {
1966
+ let length = result.length;
1967
+ switch (length) {
1968
+ case 1:
1969
+ target[position++] = 0xd4;
1970
+ break
1971
+ case 2:
1972
+ target[position++] = 0xd5;
1973
+ break
1974
+ case 4:
1975
+ target[position++] = 0xd6;
1976
+ break
1977
+ case 8:
1978
+ target[position++] = 0xd7;
1979
+ break
1980
+ case 16:
1981
+ target[position++] = 0xd8;
1982
+ break
1983
+ default:
1984
+ if (length < 0x100) {
1985
+ target[position++] = 0xc7;
1986
+ target[position++] = length;
1987
+ } else if (length < 0x10000) {
1988
+ target[position++] = 0xc8;
1989
+ target[position++] = length >> 8;
1990
+ target[position++] = length & 0xff;
1991
+ } else {
1992
+ target[position++] = 0xc9;
1993
+ target[position++] = length >> 24;
1994
+ target[position++] = (length >> 16) & 0xff;
1995
+ target[position++] = (length >> 8) & 0xff;
1996
+ target[position++] = length & 0xff;
1997
+ }
1998
+ }
1999
+ target[position++] = type;
2000
+ target.set(result, position);
2001
+ position += length;
2002
+ return position
2003
+ }
2004
+
2005
+ function insertIds(serialized, idsToInsert) {
2006
+ // insert the ids that need to be referenced for structured clones
2007
+ let nextId;
2008
+ let distanceToMove = idsToInsert.length * 6;
2009
+ let lastEnd = serialized.length - distanceToMove;
2010
+ while (nextId = idsToInsert.pop()) {
2011
+ let offset = nextId.offset;
2012
+ let id = nextId.id;
2013
+ serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
2014
+ distanceToMove -= 6;
2015
+ let position = offset + distanceToMove;
2016
+ serialized[position++] = 0xd6;
2017
+ serialized[position++] = 0x69; // 'i'
2018
+ serialized[position++] = id >> 24;
2019
+ serialized[position++] = (id >> 16) & 0xff;
2020
+ serialized[position++] = (id >> 8) & 0xff;
2021
+ serialized[position++] = id & 0xff;
2022
+ lastEnd = offset;
2023
+ }
2024
+ return serialized
2025
+ }
2026
+
2027
+ function writeBundles(start, pack, incrementPosition) {
2028
+ if (bundledStrings.length > 0) {
2029
+ targetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start);
2030
+ bundledStrings.stringsPosition = position - start;
2031
+ let writeStrings = bundledStrings;
2032
+ bundledStrings = null;
2033
+ pack(writeStrings[0]);
2034
+ pack(writeStrings[1]);
2035
+ }
2036
+ }
2037
+
2038
+ function addExtension(extension) {
2039
+ if (extension.Class) {
2040
+ if (!extension.pack && !extension.write)
2041
+ throw new Error('Extension has no pack or write function')
2042
+ if (extension.pack && !extension.type)
2043
+ throw new Error('Extension has no type (numeric code to identify the extension)')
2044
+ extensionClasses.unshift(extension.Class);
2045
+ extensions.unshift(extension);
2046
+ }
2047
+ addExtension$1(extension);
2048
+ }
2049
+ function prepareStructures(structures, packr) {
2050
+ structures.isCompatible = (existingStructures) => {
2051
+ let compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length);
2052
+ if (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction
2053
+ packr._mergeStructures(existingStructures);
2054
+ return compatible;
2055
+ };
2056
+ return structures
2057
+ }
2058
+
2059
+ let defaultPackr = new Packr({ useRecords: false });
2060
+ const pack = defaultPackr.pack;
2061
+ const encode = defaultPackr.pack;
2062
+ const Encoder = Packr;
2063
+ const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
2064
+ const REUSE_BUFFER_MODE = 512;
2065
+ const RESET_BUFFER_MODE = 1024;
2066
+
2067
+ /**
2068
+ * Given an Iterable first argument, returns an Iterable where each value is packed as a Buffer
2069
+ * If the argument is only Async Iterable, the return value will be an Async Iterable.
2070
+ * @param {Iterable|Iterator|AsyncIterable|AsyncIterator} objectIterator - iterable source, like a Readable object stream, an array, Set, or custom object
2071
+ * @param {options} [options] - msgpackr pack options
2072
+ * @returns {IterableIterator|Promise.<AsyncIterableIterator>}
2073
+ */
2074
+ function packIter (objectIterator, options = {}) {
2075
+ if (!objectIterator || typeof objectIterator !== 'object') {
2076
+ throw new Error('first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable')
2077
+ } else if (typeof objectIterator[Symbol.iterator] === 'function') {
2078
+ return packIterSync(objectIterator, options)
2079
+ } else if (typeof objectIterator.then === 'function' || typeof objectIterator[Symbol.asyncIterator] === 'function') {
2080
+ return packIterAsync(objectIterator, options)
2081
+ } else {
2082
+ throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise')
2083
+ }
2084
+ }
2085
+
2086
+ function * packIterSync (objectIterator, options) {
2087
+ const packr = new Packr(options);
2088
+ for (const value of objectIterator) {
2089
+ yield packr.pack(value);
2090
+ }
2091
+ }
2092
+
2093
+ async function * packIterAsync (objectIterator, options) {
2094
+ const packr = new Packr(options);
2095
+ for await (const value of objectIterator) {
2096
+ yield packr.pack(value);
2097
+ }
2098
+ }
2099
+
2100
+ /**
2101
+ * Given an Iterable/Iterator input which yields buffers, returns an IterableIterator which yields sync decoded objects
2102
+ * Or, given an Async Iterable/Iterator which yields promises resolving in buffers, returns an AsyncIterableIterator.
2103
+ * @param {Iterable|Iterator|AsyncIterable|AsyncIterableIterator} bufferIterator
2104
+ * @param {object} [options] - unpackr options
2105
+ * @returns {IterableIterator|Promise.<AsyncIterableIterator}
2106
+ */
2107
+ function unpackIter (bufferIterator, options = {}) {
2108
+ if (!bufferIterator || typeof bufferIterator !== 'object') {
2109
+ throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise')
2110
+ }
2111
+
2112
+ const unpackr = new Unpackr(options);
2113
+ let incomplete;
2114
+ const parser = (chunk) => {
2115
+ let yields;
2116
+ // if there's incomplete data from previous chunk, concatinate and try again
2117
+ if (incomplete) {
2118
+ chunk = Buffer.concat([incomplete, chunk]);
2119
+ incomplete = undefined;
2120
+ }
2121
+
2122
+ try {
2123
+ yields = unpackr.unpackMultiple(chunk);
2124
+ } catch (err) {
2125
+ if (err.incomplete) {
2126
+ incomplete = chunk.slice(err.lastPosition);
2127
+ yields = err.values;
2128
+ } else {
2129
+ throw err
2130
+ }
2131
+ }
2132
+ return yields
2133
+ };
2134
+
2135
+ if (typeof bufferIterator[Symbol.iterator] === 'function') {
2136
+ return (function * iter () {
2137
+ for (const value of bufferIterator) {
2138
+ yield * parser(value);
2139
+ }
2140
+ })()
2141
+ } else if (typeof bufferIterator[Symbol.asyncIterator] === 'function') {
2142
+ return (async function * iter () {
2143
+ for await (const value of bufferIterator) {
2144
+ yield * parser(value);
2145
+ }
2146
+ })()
2147
+ }
2148
+ }
2149
+ const decodeIter = unpackIter;
2150
+ const encodeIter = packIter;
2151
+
2152
+ const useRecords = false;
2153
+ const mapsAsObjects = true;
2154
+
2155
+ exports.ALWAYS = ALWAYS;
2156
+ exports.C1 = C1;
2157
+ exports.DECIMAL_FIT = DECIMAL_FIT;
2158
+ exports.DECIMAL_ROUND = DECIMAL_ROUND;
2159
+ exports.Decoder = Decoder;
2160
+ exports.Encoder = Encoder;
2161
+ exports.FLOAT32_OPTIONS = FLOAT32_OPTIONS;
2162
+ exports.NEVER = NEVER;
2163
+ exports.Packr = Packr;
2164
+ exports.REUSE_BUFFER_MODE = REUSE_BUFFER_MODE;
2165
+ exports.Unpackr = Unpackr;
2166
+ exports.addExtension = addExtension;
2167
+ exports.clearSource = clearSource;
2168
+ exports.decode = decode;
2169
+ exports.decodeIter = decodeIter;
2170
+ exports.encode = encode;
2171
+ exports.encodeIter = encodeIter;
2172
+ exports.isNativeAccelerationEnabled = isNativeAccelerationEnabled;
2173
+ exports.mapsAsObjects = mapsAsObjects;
2174
+ exports.pack = pack;
2175
+ exports.roundFloat32 = roundFloat32;
2176
+ exports.unpack = unpack;
2177
+ exports.unpackMultiple = unpackMultiple;
2178
+ exports.useRecords = useRecords;
2179
+
2180
+ }));
2181
+ //# sourceMappingURL=index-no-eval.cjs.map