cbor-x 1.4.1 → 1.5.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,2398 @@
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.CBOR = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ let decoder;
8
+ try {
9
+ decoder = new TextDecoder();
10
+ } catch(error) {}
11
+ let src;
12
+ let srcEnd;
13
+ let position$1 = 0;
14
+ const LEGACY_RECORD_INLINE_ID = 105;
15
+ const RECORD_DEFINITIONS_ID = 0xdffe;
16
+ const RECORD_INLINE_ID = 0xdfff; // temporary first-come first-serve tag // proposed tag: 0x7265 // 're'
17
+ const BUNDLED_STRINGS_ID = 0xdff9;
18
+ const PACKED_REFERENCE_TAG_ID = 6;
19
+ const STOP_CODE = {};
20
+ let currentDecoder = {};
21
+ let currentStructures;
22
+ let srcString;
23
+ let srcStringStart = 0;
24
+ let srcStringEnd = 0;
25
+ let bundledStrings$1;
26
+ let referenceMap;
27
+ let currentExtensions = [];
28
+ let currentExtensionRanges = [];
29
+ let packedValues;
30
+ let dataView;
31
+ let restoreMapsAsObject;
32
+ let defaultOptions = {
33
+ useRecords: false,
34
+ mapsAsObjects: true
35
+ };
36
+ let sequentialMode = false;
37
+
38
+ class Decoder {
39
+ constructor(options) {
40
+ if (options) {
41
+ if ((options.keyMap || options._keyMap) && !options.useRecords) {
42
+ options.useRecords = false;
43
+ options.mapsAsObjects = true;
44
+ }
45
+ if (options.useRecords === false && options.mapsAsObjects === undefined)
46
+ options.mapsAsObjects = true;
47
+ if (options.getStructures)
48
+ options.getShared = options.getStructures;
49
+ if (options.getShared && !options.structures)
50
+ (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
51
+ if (options.keyMap) {
52
+ this.mapKey = new Map();
53
+ for (let [k,v] of Object.entries(options.keyMap)) this.mapKey.set(v,k);
54
+ }
55
+ }
56
+ Object.assign(this, options);
57
+ }
58
+ /*
59
+ decodeKey(key) {
60
+ return this.keyMap
61
+ ? Object.keys(this.keyMap)[Object.values(this.keyMap).indexOf(key)] || key
62
+ : key
63
+ }
64
+ */
65
+ decodeKey(key) {
66
+ return this.keyMap ? this.mapKey.get(key) || key : key
67
+ }
68
+
69
+ encodeKey(key) {
70
+ return this.keyMap && this.keyMap.hasOwnProperty(key) ? this.keyMap[key] : key
71
+ }
72
+
73
+ encodeKeys(rec) {
74
+ if (!this._keyMap) return rec
75
+ let map = new Map();
76
+ for (let [k,v] of Object.entries(rec)) map.set((this._keyMap.hasOwnProperty(k) ? this._keyMap[k] : k), v);
77
+ return map
78
+ }
79
+
80
+ decodeKeys(map) {
81
+ if (!this._keyMap || map.constructor.name != 'Map') return map
82
+ if (!this._mapKey) {
83
+ this._mapKey = new Map();
84
+ for (let [k,v] of Object.entries(this._keyMap)) this._mapKey.set(v,k);
85
+ }
86
+ let res = {};
87
+ //map.forEach((v,k) => res[Object.keys(this._keyMap)[Object.values(this._keyMap).indexOf(k)] || k] = v)
88
+ map.forEach((v,k) => res[safeKey(this._mapKey.has(k) ? this._mapKey.get(k) : k)] = v);
89
+ return res
90
+ }
91
+
92
+ mapDecode(source, end) {
93
+
94
+ let res = this.decode(source);
95
+ if (this._keyMap) {
96
+ //Experiemntal support for Optimised KeyMap decoding
97
+ switch (res.constructor.name) {
98
+ case 'Array': return res.map(r => this.decodeKeys(r))
99
+ //case 'Map': return this.decodeKeys(res)
100
+ }
101
+ }
102
+ return res
103
+ }
104
+
105
+ decode(source, end) {
106
+ if (src) {
107
+ // re-entrant execution, save the state and restore it after we do this decode
108
+ return saveState(() => {
109
+ clearSource();
110
+ return this ? this.decode(source, end) : Decoder.prototype.decode.call(defaultOptions, source, end)
111
+ })
112
+ }
113
+ srcEnd = end > -1 ? end : source.length;
114
+ position$1 = 0;
115
+ srcStringEnd = 0;
116
+ srcString = null;
117
+ bundledStrings$1 = null;
118
+ src = source;
119
+ // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
120
+ // technique for getting data from a database where it can be copied into an existing buffer instead of creating
121
+ // new ones
122
+ try {
123
+ dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
124
+ } catch(error) {
125
+ // if it doesn't have a buffer, maybe it is the wrong type of object
126
+ src = null;
127
+ if (source instanceof Uint8Array)
128
+ throw error
129
+ throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
130
+ }
131
+ if (this instanceof Decoder) {
132
+ currentDecoder = this;
133
+ packedValues = this.sharedValues &&
134
+ (this.pack ? new Array(this.maxPrivatePackedValues || 16).concat(this.sharedValues) :
135
+ this.sharedValues);
136
+ if (this.structures) {
137
+ currentStructures = this.structures;
138
+ return checkedRead()
139
+ } else if (!currentStructures || currentStructures.length > 0) {
140
+ currentStructures = [];
141
+ }
142
+ } else {
143
+ currentDecoder = defaultOptions;
144
+ if (!currentStructures || currentStructures.length > 0)
145
+ currentStructures = [];
146
+ packedValues = null;
147
+ }
148
+ return checkedRead()
149
+ }
150
+ decodeMultiple(source, forEach) {
151
+ let values, lastPosition = 0;
152
+ try {
153
+ let size = source.length;
154
+ sequentialMode = true;
155
+ let value = this ? this.decode(source, size) : defaultDecoder.decode(source, size);
156
+ if (forEach) {
157
+ if (forEach(value) === false) {
158
+ return
159
+ }
160
+ while(position$1 < size) {
161
+ lastPosition = position$1;
162
+ if (forEach(checkedRead()) === false) {
163
+ return
164
+ }
165
+ }
166
+ }
167
+ else {
168
+ values = [ value ];
169
+ while(position$1 < size) {
170
+ lastPosition = position$1;
171
+ values.push(checkedRead());
172
+ }
173
+ return values
174
+ }
175
+ } catch(error) {
176
+ error.lastPosition = lastPosition;
177
+ error.values = values;
178
+ throw error
179
+ } finally {
180
+ sequentialMode = false;
181
+ clearSource();
182
+ }
183
+ }
184
+ }
185
+ function checkedRead() {
186
+ try {
187
+ let result = read();
188
+ if (bundledStrings$1) {
189
+ if (position$1 >= bundledStrings$1.postBundlePosition) {
190
+ let error = new Error('Unexpected bundle position');
191
+ error.incomplete = true;
192
+ throw error
193
+ }
194
+ // bundled strings to skip past
195
+ position$1 = bundledStrings$1.postBundlePosition;
196
+ bundledStrings$1 = null;
197
+ }
198
+
199
+ if (position$1 == srcEnd) {
200
+ // finished reading this source, cleanup references
201
+ currentStructures = null;
202
+ src = null;
203
+ if (referenceMap)
204
+ referenceMap = null;
205
+ } else if (position$1 > srcEnd) {
206
+ // over read
207
+ let error = new Error('Unexpected end of CBOR data');
208
+ error.incomplete = true;
209
+ throw error
210
+ } else if (!sequentialMode) {
211
+ throw new Error('Data read, but end of buffer not reached')
212
+ }
213
+ // else more to read, but we are reading sequentially, so don't clear source yet
214
+ return result
215
+ } catch(error) {
216
+ clearSource();
217
+ if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer')) {
218
+ error.incomplete = true;
219
+ }
220
+ throw error
221
+ }
222
+ }
223
+
224
+ function read() {
225
+ let token = src[position$1++];
226
+ let majorType = token >> 5;
227
+ token = token & 0x1f;
228
+ if (token > 0x17) {
229
+ switch (token) {
230
+ case 0x18:
231
+ token = src[position$1++];
232
+ break
233
+ case 0x19:
234
+ if (majorType == 7) {
235
+ return getFloat16()
236
+ }
237
+ token = dataView.getUint16(position$1);
238
+ position$1 += 2;
239
+ break
240
+ case 0x1a:
241
+ if (majorType == 7) {
242
+ let value = dataView.getFloat32(position$1);
243
+ if (currentDecoder.useFloat32 > 2) {
244
+ // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
245
+ let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)];
246
+ position$1 += 4;
247
+ return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
248
+ }
249
+ position$1 += 4;
250
+ return value
251
+ }
252
+ token = dataView.getUint32(position$1);
253
+ position$1 += 4;
254
+ break
255
+ case 0x1b:
256
+ if (majorType == 7) {
257
+ let value = dataView.getFloat64(position$1);
258
+ position$1 += 8;
259
+ return value
260
+ }
261
+ if (majorType > 1) {
262
+ if (dataView.getUint32(position$1) > 0)
263
+ throw new Error('JavaScript does not support arrays, maps, or strings with length over 4294967295')
264
+ token = dataView.getUint32(position$1 + 4);
265
+ } else if (currentDecoder.int64AsNumber) {
266
+ token = dataView.getUint32(position$1) * 0x100000000;
267
+ token += dataView.getUint32(position$1 + 4);
268
+ } else
269
+ token = dataView.getBigUint64(position$1);
270
+ position$1 += 8;
271
+ break
272
+ case 0x1f:
273
+ // indefinite length
274
+ switch(majorType) {
275
+ case 2: // byte string
276
+ case 3: // text string
277
+ throw new Error('Indefinite length not supported for byte or text strings')
278
+ case 4: // array
279
+ let array = [];
280
+ let value, i = 0;
281
+ while ((value = read()) != STOP_CODE) {
282
+ array[i++] = value;
283
+ }
284
+ return majorType == 4 ? array : majorType == 3 ? array.join('') : Buffer.concat(array)
285
+ case 5: // map
286
+ let key;
287
+ if (currentDecoder.mapsAsObjects) {
288
+ let object = {};
289
+ if (currentDecoder.keyMap) while((key = read()) != STOP_CODE) object[safeKey(currentDecoder.decodeKey(key))] = read();
290
+ else while ((key = read()) != STOP_CODE) object[safeKey(key)] = read();
291
+ return object
292
+ } else {
293
+ if (restoreMapsAsObject) {
294
+ currentDecoder.mapsAsObjects = true;
295
+ restoreMapsAsObject = false;
296
+ }
297
+ let map = new Map();
298
+ if (currentDecoder.keyMap) while((key = read()) != STOP_CODE) map.set(currentDecoder.decodeKey(key), read());
299
+ else while ((key = read()) != STOP_CODE) map.set(key, read());
300
+ return map
301
+ }
302
+ case 7:
303
+ return STOP_CODE
304
+ default:
305
+ throw new Error('Invalid major type for indefinite length ' + majorType)
306
+ }
307
+ default:
308
+ throw new Error('Unknown token ' + token)
309
+ }
310
+ }
311
+ switch (majorType) {
312
+ case 0: // positive int
313
+ return token
314
+ case 1: // negative int
315
+ return ~token
316
+ case 2: // buffer
317
+ return readBin(token)
318
+ case 3: // string
319
+ if (srcStringEnd >= position$1) {
320
+ return srcString.slice(position$1 - srcStringStart, (position$1 += token) - srcStringStart)
321
+ }
322
+ if (srcStringEnd == 0 && srcEnd < 140 && token < 32) {
323
+ // for small blocks, avoiding the overhead of the extract call is helpful
324
+ let string = token < 16 ? shortStringInJS(token) : longStringInJS(token);
325
+ if (string != null)
326
+ return string
327
+ }
328
+ return readFixedString(token)
329
+ case 4: // array
330
+ let array = new Array(token);
331
+ //if (currentDecoder.keyMap) for (let i = 0; i < token; i++) array[i] = currentDecoder.decodeKey(read())
332
+ //else
333
+ for (let i = 0; i < token; i++) array[i] = read();
334
+ return array
335
+ case 5: // map
336
+ if (currentDecoder.mapsAsObjects) {
337
+ let object = {};
338
+ if (currentDecoder.keyMap) for (let i = 0; i < token; i++) object[safeKey(currentDecoder.decodeKey(read()))] = read();
339
+ else for (let i = 0; i < token; i++) object[safeKey(read())] = read();
340
+ return object
341
+ } else {
342
+ if (restoreMapsAsObject) {
343
+ currentDecoder.mapsAsObjects = true;
344
+ restoreMapsAsObject = false;
345
+ }
346
+ let map = new Map();
347
+ if (currentDecoder.keyMap) for (let i = 0; i < token; i++) map.set(currentDecoder.decodeKey(read()),read());
348
+ else for (let i = 0; i < token; i++) map.set(read(), read());
349
+ return map
350
+ }
351
+ case 6: // extension
352
+ if (token >= BUNDLED_STRINGS_ID) {
353
+ let structure = currentStructures[token & 0x1fff]; // check record structures first
354
+ // At some point we may provide an option for dynamic tag assignment with a range like token >= 8 && (token < 16 || (token > 0x80 && token < 0xc0) || (token > 0x130 && token < 0x4000))
355
+ if (structure) {
356
+ if (!structure.read) structure.read = createStructureReader(structure);
357
+ return structure.read()
358
+ }
359
+ if (token < 0x10000) {
360
+ if (token == RECORD_INLINE_ID) { // we do a special check for this so that we can keep the
361
+ // currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements)
362
+ let length = readJustLength();
363
+ let id = read();
364
+ let structure = read();
365
+ recordDefinition(id, structure);
366
+ let object = {};
367
+ if (currentDecoder.keyMap) for (let i = 2; i < length; i++) {
368
+ let key = currentDecoder.decodeKey(structure[i - 2]);
369
+ object[safeKey(key)] = read();
370
+ }
371
+ else for (let i = 2; i < length; i++) {
372
+ let key = structure[i - 2];
373
+ object[safeKey(key)] = read();
374
+ }
375
+ return object
376
+ }
377
+ else if (token == RECORD_DEFINITIONS_ID) {
378
+ let length = readJustLength();
379
+ let id = read();
380
+ for (let i = 2; i < length; i++) {
381
+ recordDefinition(id++, read());
382
+ }
383
+ return read()
384
+ } else if (token == BUNDLED_STRINGS_ID) {
385
+ return readBundleExt()
386
+ }
387
+ if (currentDecoder.getShared) {
388
+ loadShared();
389
+ structure = currentStructures[token & 0x1fff];
390
+ if (structure) {
391
+ if (!structure.read)
392
+ structure.read = createStructureReader(structure);
393
+ return structure.read()
394
+ }
395
+ }
396
+ }
397
+ }
398
+ let extension = currentExtensions[token];
399
+ if (extension) {
400
+ if (extension.handlesRead)
401
+ return extension(read)
402
+ else
403
+ return extension(read())
404
+ } else {
405
+ let input = read();
406
+ for (let i = 0; i < currentExtensionRanges.length; i++) {
407
+ let value = currentExtensionRanges[i](token, input);
408
+ if (value !== undefined)
409
+ return value
410
+ }
411
+ return new Tag(input, token)
412
+ }
413
+ case 7: // fixed value
414
+ switch (token) {
415
+ case 0x14: return false
416
+ case 0x15: return true
417
+ case 0x16: return null
418
+ case 0x17: return; // undefined
419
+ case 0x1f:
420
+ default:
421
+ let packedValue = (packedValues || getPackedValues())[token];
422
+ if (packedValue !== undefined)
423
+ return packedValue
424
+ throw new Error('Unknown token ' + token)
425
+ }
426
+ default: // negative int
427
+ if (isNaN(token)) {
428
+ let error = new Error('Unexpected end of CBOR data');
429
+ error.incomplete = true;
430
+ throw error
431
+ }
432
+ throw new Error('Unknown CBOR token ' + token)
433
+ }
434
+ }
435
+ const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
436
+ function createStructureReader(structure) {
437
+ function readObject() {
438
+ // get the array size from the header
439
+ let length = src[position$1++];
440
+ //let majorType = token >> 5
441
+ length = length & 0x1f;
442
+ if (length > 0x17) {
443
+ switch (length) {
444
+ case 0x18:
445
+ length = src[position$1++];
446
+ break
447
+ case 0x19:
448
+ length = dataView.getUint16(position$1);
449
+ position$1 += 2;
450
+ break
451
+ case 0x1a:
452
+ length = dataView.getUint32(position$1);
453
+ position$1 += 4;
454
+ break
455
+ default:
456
+ throw new Error('Expected array header, but got ' + src[position$1 - 1])
457
+ }
458
+ }
459
+ // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
460
+ let compiledReader = this.compiledReader; // first look to see if we have the fast compiled function
461
+ while(compiledReader) {
462
+ // we have a fast compiled object literal reader
463
+ if (compiledReader.propertyCount === length)
464
+ return compiledReader(read) // with the right length, so we use it
465
+ compiledReader = compiledReader.next; // see if there is another reader with the right length
466
+ }
467
+ if (this.slowReads++ >= 3) { // create a fast compiled reader
468
+ let array = this.length == length ? this : this.slice(0, length);
469
+ compiledReader = currentDecoder.keyMap
470
+ ? new BlockedFunction ('r', 'return {' + array.map(k => currentDecoder.decodeKey(k)).map(k => validName.test(k) ? safeKey(k) + ':r()' : ('[' + JSON.stringify(k) + ']:r()')).join(',') + '}')
471
+ : new BlockedFunction ('r', 'return {' + array.map(key => validName.test(key) ? safeKey(key) + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}');
472
+ if (this.compiledReader)
473
+ compiledReader.next = this.compiledReader; // if there is an existing one, we store multiple readers as a linked list because it is usually pretty rare to have multiple readers (of different length) for the same structure
474
+ compiledReader.propertyCount = length;
475
+ this.compiledReader = compiledReader;
476
+ return compiledReader(read)
477
+ }
478
+ let object = {};
479
+ if (currentDecoder.keyMap) for (let i = 0; i < length; i++) object[safeKey(currentDecoder.decodeKey(this[i]))] = read();
480
+ else for (let i = 0; i < length; i++) {
481
+ object[safeKey(this[i])] = read();
482
+ }
483
+ return object
484
+ }
485
+ structure.slowReads = 0;
486
+ return readObject
487
+ }
488
+
489
+ function safeKey(key) {
490
+ return key === '__proto__' ? '__proto_' : key
491
+ }
492
+
493
+ let readFixedString = readStringJS;
494
+
495
+ let isNativeAccelerationEnabled = false;
496
+ function readStringJS(length) {
497
+ let result;
498
+ if (length < 16) {
499
+ if (result = shortStringInJS(length))
500
+ return result
501
+ }
502
+ if (length > 64 && decoder)
503
+ return decoder.decode(src.subarray(position$1, position$1 += length))
504
+ const end = position$1 + length;
505
+ const units = [];
506
+ result = '';
507
+ while (position$1 < end) {
508
+ const byte1 = src[position$1++];
509
+ if ((byte1 & 0x80) === 0) {
510
+ // 1 byte
511
+ units.push(byte1);
512
+ } else if ((byte1 & 0xe0) === 0xc0) {
513
+ // 2 bytes
514
+ const byte2 = src[position$1++] & 0x3f;
515
+ units.push(((byte1 & 0x1f) << 6) | byte2);
516
+ } else if ((byte1 & 0xf0) === 0xe0) {
517
+ // 3 bytes
518
+ const byte2 = src[position$1++] & 0x3f;
519
+ const byte3 = src[position$1++] & 0x3f;
520
+ units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
521
+ } else if ((byte1 & 0xf8) === 0xf0) {
522
+ // 4 bytes
523
+ const byte2 = src[position$1++] & 0x3f;
524
+ const byte3 = src[position$1++] & 0x3f;
525
+ const byte4 = src[position$1++] & 0x3f;
526
+ let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
527
+ if (unit > 0xffff) {
528
+ unit -= 0x10000;
529
+ units.push(((unit >>> 10) & 0x3ff) | 0xd800);
530
+ unit = 0xdc00 | (unit & 0x3ff);
531
+ }
532
+ units.push(unit);
533
+ } else {
534
+ units.push(byte1);
535
+ }
536
+
537
+ if (units.length >= 0x1000) {
538
+ result += fromCharCode.apply(String, units);
539
+ units.length = 0;
540
+ }
541
+ }
542
+
543
+ if (units.length > 0) {
544
+ result += fromCharCode.apply(String, units);
545
+ }
546
+
547
+ return result
548
+ }
549
+ let fromCharCode = String.fromCharCode;
550
+ function longStringInJS(length) {
551
+ let start = position$1;
552
+ let bytes = new Array(length);
553
+ for (let i = 0; i < length; i++) {
554
+ const byte = src[position$1++];
555
+ if ((byte & 0x80) > 0) {
556
+ position$1 = start;
557
+ return
558
+ }
559
+ bytes[i] = byte;
560
+ }
561
+ return fromCharCode.apply(String, bytes)
562
+ }
563
+ function shortStringInJS(length) {
564
+ if (length < 4) {
565
+ if (length < 2) {
566
+ if (length === 0)
567
+ return ''
568
+ else {
569
+ let a = src[position$1++];
570
+ if ((a & 0x80) > 1) {
571
+ position$1 -= 1;
572
+ return
573
+ }
574
+ return fromCharCode(a)
575
+ }
576
+ } else {
577
+ let a = src[position$1++];
578
+ let b = src[position$1++];
579
+ if ((a & 0x80) > 0 || (b & 0x80) > 0) {
580
+ position$1 -= 2;
581
+ return
582
+ }
583
+ if (length < 3)
584
+ return fromCharCode(a, b)
585
+ let c = src[position$1++];
586
+ if ((c & 0x80) > 0) {
587
+ position$1 -= 3;
588
+ return
589
+ }
590
+ return fromCharCode(a, b, c)
591
+ }
592
+ } else {
593
+ let a = src[position$1++];
594
+ let b = src[position$1++];
595
+ let c = src[position$1++];
596
+ let d = src[position$1++];
597
+ if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
598
+ position$1 -= 4;
599
+ return
600
+ }
601
+ if (length < 6) {
602
+ if (length === 4)
603
+ return fromCharCode(a, b, c, d)
604
+ else {
605
+ let e = src[position$1++];
606
+ if ((e & 0x80) > 0) {
607
+ position$1 -= 5;
608
+ return
609
+ }
610
+ return fromCharCode(a, b, c, d, e)
611
+ }
612
+ } else if (length < 8) {
613
+ let e = src[position$1++];
614
+ let f = src[position$1++];
615
+ if ((e & 0x80) > 0 || (f & 0x80) > 0) {
616
+ position$1 -= 6;
617
+ return
618
+ }
619
+ if (length < 7)
620
+ return fromCharCode(a, b, c, d, e, f)
621
+ let g = src[position$1++];
622
+ if ((g & 0x80) > 0) {
623
+ position$1 -= 7;
624
+ return
625
+ }
626
+ return fromCharCode(a, b, c, d, e, f, g)
627
+ } else {
628
+ let e = src[position$1++];
629
+ let f = src[position$1++];
630
+ let g = src[position$1++];
631
+ let h = src[position$1++];
632
+ if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
633
+ position$1 -= 8;
634
+ return
635
+ }
636
+ if (length < 10) {
637
+ if (length === 8)
638
+ return fromCharCode(a, b, c, d, e, f, g, h)
639
+ else {
640
+ let i = src[position$1++];
641
+ if ((i & 0x80) > 0) {
642
+ position$1 -= 9;
643
+ return
644
+ }
645
+ return fromCharCode(a, b, c, d, e, f, g, h, i)
646
+ }
647
+ } else if (length < 12) {
648
+ let i = src[position$1++];
649
+ let j = src[position$1++];
650
+ if ((i & 0x80) > 0 || (j & 0x80) > 0) {
651
+ position$1 -= 10;
652
+ return
653
+ }
654
+ if (length < 11)
655
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j)
656
+ let k = src[position$1++];
657
+ if ((k & 0x80) > 0) {
658
+ position$1 -= 11;
659
+ return
660
+ }
661
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
662
+ } else {
663
+ let i = src[position$1++];
664
+ let j = src[position$1++];
665
+ let k = src[position$1++];
666
+ let l = src[position$1++];
667
+ if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
668
+ position$1 -= 12;
669
+ return
670
+ }
671
+ if (length < 14) {
672
+ if (length === 12)
673
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
674
+ else {
675
+ let m = src[position$1++];
676
+ if ((m & 0x80) > 0) {
677
+ position$1 -= 13;
678
+ return
679
+ }
680
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
681
+ }
682
+ } else {
683
+ let m = src[position$1++];
684
+ let n = src[position$1++];
685
+ if ((m & 0x80) > 0 || (n & 0x80) > 0) {
686
+ position$1 -= 14;
687
+ return
688
+ }
689
+ if (length < 15)
690
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
691
+ let o = src[position$1++];
692
+ if ((o & 0x80) > 0) {
693
+ position$1 -= 15;
694
+ return
695
+ }
696
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
697
+ }
698
+ }
699
+ }
700
+ }
701
+ }
702
+
703
+ function readBin(length) {
704
+ return currentDecoder.copyBuffers ?
705
+ // specifically use the copying slice (not the node one)
706
+ Uint8Array.prototype.slice.call(src, position$1, position$1 += length) :
707
+ src.subarray(position$1, position$1 += length)
708
+ }
709
+ let f32Array = new Float32Array(1);
710
+ let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
711
+ function getFloat16() {
712
+ let byte0 = src[position$1++];
713
+ let byte1 = src[position$1++];
714
+ let exponent = (byte0 & 0x7f) >> 2;
715
+ if (exponent === 0x1f) { // specials
716
+ if (byte1 || (byte0 & 3))
717
+ return NaN;
718
+ return (byte0 & 0x80) ? -Infinity : Infinity;
719
+ }
720
+ if (exponent === 0) { // sub-normals
721
+ // significand with 10 fractional bits and divided by 2^14
722
+ let abs = (((byte0 & 3) << 8) | byte1) / (1 << 24);
723
+ return (byte0 & 0x80) ? -abs : abs
724
+ }
725
+
726
+ u8Array[3] = (byte0 & 0x80) | // sign bit
727
+ ((exponent >> 1) + 56); // 4 of 5 of the exponent bits, re-offset-ed
728
+ u8Array[2] = ((byte0 & 7) << 5) | // last exponent bit and first two mantissa bits
729
+ (byte1 >> 3); // next 5 bits of mantissa
730
+ u8Array[1] = byte1 << 5; // last three bits of mantissa
731
+ u8Array[0] = 0;
732
+ return f32Array[0];
733
+ }
734
+
735
+ new Array(4096);
736
+
737
+ class Tag {
738
+ constructor(value, tag) {
739
+ this.value = value;
740
+ this.tag = tag;
741
+ }
742
+ }
743
+
744
+ currentExtensions[0] = (dateString) => {
745
+ // string date extension
746
+ return new Date(dateString)
747
+ };
748
+
749
+ currentExtensions[1] = (epochSec) => {
750
+ // numeric date extension
751
+ return new Date(Math.round(epochSec * 1000))
752
+ };
753
+
754
+ currentExtensions[2] = (buffer) => {
755
+ // bigint extension
756
+ let value = BigInt(0);
757
+ for (let i = 0, l = buffer.byteLength; i < l; i++) {
758
+ value = BigInt(buffer[i]) + value << BigInt(8);
759
+ }
760
+ return value
761
+ };
762
+
763
+ currentExtensions[3] = (buffer) => {
764
+ // negative bigint extension
765
+ return BigInt(-1) - currentExtensions[2](buffer)
766
+ };
767
+ currentExtensions[4] = (fraction) => {
768
+ // best to reparse to maintain accuracy
769
+ return +(fraction[1] + 'e' + fraction[0])
770
+ };
771
+
772
+ currentExtensions[5] = (fraction) => {
773
+ // probably not sufficiently accurate
774
+ return fraction[1] * Math.exp(fraction[0] * Math.log(2))
775
+ };
776
+
777
+ // the registration of the record definition extension
778
+ const recordDefinition = (id, structure) => {
779
+ id = id - 0xe000;
780
+ let existingStructure = currentStructures[id];
781
+ if (existingStructure && existingStructure.isShared) {
782
+ (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
783
+ }
784
+ currentStructures[id] = structure;
785
+
786
+ structure.read = createStructureReader(structure);
787
+ };
788
+ currentExtensions[LEGACY_RECORD_INLINE_ID] = (data) => {
789
+ let length = data.length;
790
+ let structure = data[1];
791
+ recordDefinition(data[0], structure);
792
+ let object = {};
793
+ for (let i = 2; i < length; i++) {
794
+ let key = structure[i - 2];
795
+ object[safeKey(key)] = data[i];
796
+ }
797
+ return object
798
+ };
799
+ currentExtensions[14] = (value) => {
800
+ if (bundledStrings$1)
801
+ return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 += value)
802
+ return new Tag(value, 14)
803
+ };
804
+ currentExtensions[15] = (value) => {
805
+ if (bundledStrings$1)
806
+ return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value)
807
+ return new Tag(value, 15)
808
+ };
809
+ let glbl = { Error, RegExp };
810
+ currentExtensions[27] = (data) => { // http://cbor.schmorp.de/generic-object
811
+ return (glbl[data[0]] || Error)(data[1], data[2])
812
+ };
813
+ const packedTable = (read) => {
814
+ if (src[position$1++] != 0x84)
815
+ throw new Error('Packed values structure must be followed by a 4 element array')
816
+ let newPackedValues = read(); // packed values
817
+ packedValues = packedValues ? newPackedValues.concat(packedValues.slice(newPackedValues.length)) : newPackedValues;
818
+ packedValues.prefixes = read();
819
+ packedValues.suffixes = read();
820
+ return read() // read the rump
821
+ };
822
+ packedTable.handlesRead = true;
823
+ currentExtensions[51] = packedTable;
824
+
825
+ currentExtensions[PACKED_REFERENCE_TAG_ID] = (data) => { // packed reference
826
+ if (!packedValues) {
827
+ if (currentDecoder.getShared)
828
+ loadShared();
829
+ else
830
+ return new Tag(data, PACKED_REFERENCE_TAG_ID)
831
+ }
832
+ if (typeof data == 'number')
833
+ return packedValues[16 + (data >= 0 ? 2 * data : (-2 * data - 1))]
834
+ throw new Error('No support for non-integer packed references yet')
835
+ };
836
+
837
+ // The following code is an incomplete implementation of http://cbor.schmorp.de/stringref
838
+ // the real thing would need to implemennt more logic to populate the stringRefs table and
839
+ // maintain a stack of stringRef "namespaces".
840
+ //
841
+ // currentExtensions[25] = (id) => {
842
+ // return stringRefs[id]
843
+ // }
844
+ // currentExtensions[256] = (read) => {
845
+ // stringRefs = []
846
+ // try {
847
+ // return read()
848
+ // } finally {
849
+ // stringRefs = null
850
+ // }
851
+ // }
852
+ // currentExtensions[256].handlesRead = true
853
+
854
+ currentExtensions[28] = (read) => {
855
+ // shareable http://cbor.schmorp.de/value-sharing (for structured clones)
856
+ if (!referenceMap) {
857
+ referenceMap = new Map();
858
+ referenceMap.id = 0;
859
+ }
860
+ let id = referenceMap.id++;
861
+ let token = src[position$1];
862
+ let target;
863
+ // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
864
+ // ahead past references to record structure definitions
865
+ if ((token >> 5) == 4)
866
+ target = [];
867
+ else
868
+ target = {};
869
+
870
+ let refEntry = { target }; // a placeholder object
871
+ referenceMap.set(id, refEntry);
872
+ let targetProperties = read(); // read the next value as the target object to id
873
+ if (refEntry.used) // there is a cycle, so we have to assign properties to original target
874
+ return Object.assign(target, targetProperties)
875
+ refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
876
+ return targetProperties // no cycle, can just use the returned read object
877
+ };
878
+ currentExtensions[28].handlesRead = true;
879
+
880
+ currentExtensions[29] = (id) => {
881
+ // sharedref http://cbor.schmorp.de/value-sharing (for structured clones)
882
+ let refEntry = referenceMap.get(id);
883
+ refEntry.used = true;
884
+ return refEntry.target
885
+ };
886
+
887
+ currentExtensions[258] = (array) => new Set(array); // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md
888
+ (currentExtensions[259] = (read) => {
889
+ // https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec
890
+ // for decoding as a standard Map
891
+ if (currentDecoder.mapsAsObjects) {
892
+ currentDecoder.mapsAsObjects = false;
893
+ restoreMapsAsObject = true;
894
+ }
895
+ return read()
896
+ }).handlesRead = true;
897
+ function combine(a, b) {
898
+ if (typeof a === 'string')
899
+ return a + b
900
+ if (a instanceof Array)
901
+ return a.concat(b)
902
+ return Object.assign({}, a, b)
903
+ }
904
+ function getPackedValues() {
905
+ if (!packedValues) {
906
+ if (currentDecoder.getShared)
907
+ loadShared();
908
+ else
909
+ throw new Error('No packed values available')
910
+ }
911
+ return packedValues
912
+ }
913
+ const SHARED_DATA_TAG_ID = 0x53687264; // ascii 'Shrd'
914
+ currentExtensionRanges.push((tag, input) => {
915
+ if (tag >= 225 && tag <= 255)
916
+ return combine(getPackedValues().prefixes[tag - 224], input)
917
+ if (tag >= 28704 && tag <= 32767)
918
+ return combine(getPackedValues().prefixes[tag - 28672], input)
919
+ if (tag >= 1879052288 && tag <= 2147483647)
920
+ return combine(getPackedValues().prefixes[tag - 1879048192], input)
921
+ if (tag >= 216 && tag <= 223)
922
+ return combine(input, getPackedValues().suffixes[tag - 216])
923
+ if (tag >= 27647 && tag <= 28671)
924
+ return combine(input, getPackedValues().suffixes[tag - 27639])
925
+ if (tag >= 1811940352 && tag <= 1879048191)
926
+ return combine(input, getPackedValues().suffixes[tag - 1811939328])
927
+ if (tag == SHARED_DATA_TAG_ID) {// we do a special check for this so that we can keep the currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements)
928
+ return {
929
+ packedValues: packedValues,
930
+ structures: currentStructures.slice(0),
931
+ version: input,
932
+ }
933
+ }
934
+ if (tag == 55799) // self-descriptive CBOR tag, just return input value
935
+ return input
936
+ });
937
+
938
+ const isLittleEndianMachine$1 = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
939
+ const typedArrays = [Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,
940
+ typeof BigUint64Array == 'undefined' ? { name:'BigUint64Array' } : BigUint64Array, Int8Array, Int16Array, Int32Array,
941
+ typeof BigInt64Array == 'undefined' ? { name:'BigInt64Array' } : BigInt64Array, Float32Array, Float64Array];
942
+ const typedArrayTags = [64, 68, 69, 70, 71, 72, 77, 78, 79, 85, 86];
943
+ for (let i = 0; i < typedArrays.length; i++) {
944
+ registerTypedArray(typedArrays[i], typedArrayTags[i]);
945
+ }
946
+ function registerTypedArray(TypedArray, tag) {
947
+ let dvMethod = 'get' + TypedArray.name.slice(0, -5);
948
+ if (typeof TypedArray !== 'function')
949
+ TypedArray = null;
950
+ let bytesPerElement = TypedArray.BYTES_PER_ELEMENT;
951
+ for (let littleEndian = 0; littleEndian < 2; littleEndian++) {
952
+ if (!littleEndian && bytesPerElement == 1)
953
+ continue
954
+ let sizeShift = bytesPerElement == 2 ? 1 : bytesPerElement == 4 ? 2 : 3;
955
+ currentExtensions[littleEndian ? tag : (tag - 4)] = (bytesPerElement == 1 || littleEndian == isLittleEndianMachine$1) ? (buffer) => {
956
+ if (!TypedArray)
957
+ throw new Error('Could not find typed array for code ' + tag)
958
+ // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
959
+ return new TypedArray(Uint8Array.prototype.slice.call(buffer, 0).buffer)
960
+ } : buffer => {
961
+ if (!TypedArray)
962
+ throw new Error('Could not find typed array for code ' + tag)
963
+ let dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
964
+ let elements = buffer.length >> sizeShift;
965
+ let ta = new TypedArray(elements);
966
+ let method = dv[dvMethod];
967
+ for (let i = 0; i < elements; i++) {
968
+ ta[i] = method.call(dv, i << sizeShift, littleEndian);
969
+ }
970
+ return ta
971
+ };
972
+ }
973
+ }
974
+
975
+ function readBundleExt() {
976
+ let length = readJustLength();
977
+ let bundlePosition = position$1 + read();
978
+ for (let i = 2; i < length; i++) {
979
+ // skip past bundles that were already read
980
+ let bundleLength = readJustLength(); // this will increment position, so must add to position afterwards
981
+ position$1 += bundleLength;
982
+ }
983
+ let dataPosition = position$1;
984
+ position$1 = bundlePosition;
985
+ bundledStrings$1 = [readStringJS(readJustLength()), readStringJS(readJustLength())];
986
+ bundledStrings$1.position0 = 0;
987
+ bundledStrings$1.position1 = 0;
988
+ bundledStrings$1.postBundlePosition = position$1;
989
+ position$1 = dataPosition;
990
+ return read()
991
+ }
992
+
993
+ function readJustLength() {
994
+ let token = src[position$1++] & 0x1f;
995
+ if (token > 0x17) {
996
+ switch (token) {
997
+ case 0x18:
998
+ token = src[position$1++];
999
+ break
1000
+ case 0x19:
1001
+ token = dataView.getUint16(position$1);
1002
+ position$1 += 2;
1003
+ break
1004
+ case 0x1a:
1005
+ token = dataView.getUint32(position$1);
1006
+ position$1 += 4;
1007
+ break
1008
+ }
1009
+ }
1010
+ return token
1011
+ }
1012
+
1013
+ function loadShared() {
1014
+ if (currentDecoder.getShared) {
1015
+ let sharedData = saveState(() => {
1016
+ // save the state in case getShared modifies our buffer
1017
+ src = null;
1018
+ return currentDecoder.getShared()
1019
+ }) || {};
1020
+ let updatedStructures = sharedData.structures || [];
1021
+ currentDecoder.sharedVersion = sharedData.version;
1022
+ packedValues = currentDecoder.sharedValues = sharedData.packedValues;
1023
+ if (currentStructures === true)
1024
+ currentDecoder.structures = currentStructures = updatedStructures;
1025
+ else
1026
+ currentStructures.splice.apply(currentStructures, [0, updatedStructures.length].concat(updatedStructures));
1027
+ }
1028
+ }
1029
+
1030
+ function saveState(callback) {
1031
+ let savedSrcEnd = srcEnd;
1032
+ let savedPosition = position$1;
1033
+ let savedSrcStringStart = srcStringStart;
1034
+ let savedSrcStringEnd = srcStringEnd;
1035
+ let savedSrcString = srcString;
1036
+ let savedReferenceMap = referenceMap;
1037
+ let savedBundledStrings = bundledStrings$1;
1038
+
1039
+ // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
1040
+ let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
1041
+ let savedStructures = currentStructures;
1042
+ let savedDecoder = currentDecoder;
1043
+ let savedSequentialMode = sequentialMode;
1044
+ let value = callback();
1045
+ srcEnd = savedSrcEnd;
1046
+ position$1 = savedPosition;
1047
+ srcStringStart = savedSrcStringStart;
1048
+ srcStringEnd = savedSrcStringEnd;
1049
+ srcString = savedSrcString;
1050
+ referenceMap = savedReferenceMap;
1051
+ bundledStrings$1 = savedBundledStrings;
1052
+ src = savedSrc;
1053
+ sequentialMode = savedSequentialMode;
1054
+ currentStructures = savedStructures;
1055
+ currentDecoder = savedDecoder;
1056
+ dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
1057
+ return value
1058
+ }
1059
+ function clearSource() {
1060
+ src = null;
1061
+ referenceMap = null;
1062
+ currentStructures = null;
1063
+ }
1064
+
1065
+ function addExtension$1(extension) {
1066
+ currentExtensions[extension.tag] = extension.decode;
1067
+ }
1068
+
1069
+ const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
1070
+ for (let i = 0; i < 256; i++) {
1071
+ mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
1072
+ }
1073
+ let defaultDecoder = new Decoder({ useRecords: false });
1074
+ const decode = defaultDecoder.decode;
1075
+ const decodeMultiple = defaultDecoder.decodeMultiple;
1076
+ const FLOAT32_OPTIONS = {
1077
+ NEVER: 0,
1078
+ ALWAYS: 1,
1079
+ DECIMAL_ROUND: 3,
1080
+ DECIMAL_FIT: 4
1081
+ };
1082
+ function roundFloat32(float32Number) {
1083
+ f32Array[0] = float32Number;
1084
+ let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
1085
+ return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
1086
+ }
1087
+
1088
+ let textEncoder;
1089
+ try {
1090
+ textEncoder = new TextEncoder();
1091
+ } catch (error) {}
1092
+ let extensions, extensionClasses;
1093
+ const Buffer$1 = globalThis.Buffer;
1094
+ const hasNodeBuffer = typeof Buffer$1 !== 'undefined';
1095
+ const ByteArrayAllocate = hasNodeBuffer ? Buffer$1.allocUnsafeSlow : Uint8Array;
1096
+ const ByteArray = hasNodeBuffer ? Buffer$1 : Uint8Array;
1097
+ const MAX_STRUCTURES = 0x100;
1098
+ const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;
1099
+ let throwOnIterable;
1100
+ let target;
1101
+ let targetView;
1102
+ let position = 0;
1103
+ let safeEnd;
1104
+ let bundledStrings = null;
1105
+ const MAX_BUNDLE_SIZE = 0xf000;
1106
+ const hasNonLatin = /[\u0080-\uFFFF]/;
1107
+ const RECORD_SYMBOL = Symbol('record-id');
1108
+ class Encoder extends Decoder {
1109
+ constructor(options) {
1110
+ super(options);
1111
+ this.offset = 0;
1112
+ let start;
1113
+ let sharedStructures;
1114
+ let hasSharedUpdate;
1115
+ let structures;
1116
+ let referenceMap;
1117
+ options = options || {};
1118
+ let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position, maxBytes) {
1119
+ return target.utf8Write(string, position, maxBytes)
1120
+ } : (textEncoder && textEncoder.encodeInto) ?
1121
+ function(string, position) {
1122
+ return textEncoder.encodeInto(string, target.subarray(position)).written
1123
+ } : false;
1124
+
1125
+ let encoder = this;
1126
+ let hasSharedStructures = options.structures || options.saveStructures;
1127
+ let maxSharedStructures = options.maxSharedStructures;
1128
+ if (maxSharedStructures == null)
1129
+ maxSharedStructures = hasSharedStructures ? 128 : 0;
1130
+ if (maxSharedStructures > 8190)
1131
+ throw new Error('Maximum maxSharedStructure is 8190')
1132
+ let isSequential = options.sequential;
1133
+ if (isSequential) {
1134
+ maxSharedStructures = 0;
1135
+ }
1136
+ if (!this.structures)
1137
+ this.structures = [];
1138
+ if (this.saveStructures)
1139
+ this.saveShared = this.saveStructures;
1140
+ let samplingPackedValues, packedObjectMap, sharedValues = options.sharedValues;
1141
+ let sharedPackedObjectMap;
1142
+ if (sharedValues) {
1143
+ sharedPackedObjectMap = Object.create(null);
1144
+ for (let i = 0, l = sharedValues.length; i < l; i++) {
1145
+ sharedPackedObjectMap[sharedValues[i]] = i;
1146
+ }
1147
+ }
1148
+ let recordIdsToRemove = [];
1149
+ let transitionsCount = 0;
1150
+ let serializationsSinceTransitionRebuild = 0;
1151
+
1152
+ this.mapEncode = function(value, encodeOptions) {
1153
+ // Experimental support for premapping keys using _keyMap instad of keyMap - not optiimised yet)
1154
+ if (this._keyMap && !this._mapped) {
1155
+ //console.log('encoding ', value)
1156
+ switch (value.constructor.name) {
1157
+ case 'Array':
1158
+ value = value.map(r => this.encodeKeys(r));
1159
+ break
1160
+ //case 'Map':
1161
+ // value = this.encodeKeys(value)
1162
+ // break
1163
+ }
1164
+ //this._mapped = true
1165
+ }
1166
+ return this.encode(value, encodeOptions)
1167
+ };
1168
+
1169
+ this.encode = function(value, encodeOptions) {
1170
+ if (!target) {
1171
+ target = new ByteArrayAllocate(8192);
1172
+ targetView = new DataView(target.buffer, 0, 8192);
1173
+ position = 0;
1174
+ }
1175
+ safeEnd = target.length - 10;
1176
+ if (safeEnd - position < 0x800) {
1177
+ // don't start too close to the end,
1178
+ target = new ByteArrayAllocate(target.length);
1179
+ targetView = new DataView(target.buffer, 0, target.length);
1180
+ safeEnd = target.length - 10;
1181
+ position = 0;
1182
+ } else if (encodeOptions === REUSE_BUFFER_MODE)
1183
+ position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
1184
+ start = position;
1185
+ if (encoder.useSelfDescribedHeader) {
1186
+ targetView.setUint32(position, 0xd9d9f700); // tag two byte, then self-descriptive tag
1187
+ position += 3;
1188
+ }
1189
+ referenceMap = encoder.structuredClone ? new Map() : null;
1190
+ if (encoder.bundleStrings && typeof value !== 'string') {
1191
+ bundledStrings = [];
1192
+ bundledStrings.size = Infinity; // force a new bundle start on first string
1193
+ } else
1194
+ bundledStrings = null;
1195
+
1196
+ sharedStructures = encoder.structures;
1197
+ if (sharedStructures) {
1198
+ if (sharedStructures.uninitialized) {
1199
+ let sharedData = encoder.getShared() || {};
1200
+ encoder.structures = sharedStructures = sharedData.structures || [];
1201
+ encoder.sharedVersion = sharedData.version;
1202
+ let sharedValues = encoder.sharedValues = sharedData.packedValues;
1203
+ if (sharedValues) {
1204
+ sharedPackedObjectMap = {};
1205
+ for (let i = 0, l = sharedValues.length; i < l; i++)
1206
+ sharedPackedObjectMap[sharedValues[i]] = i;
1207
+ }
1208
+ }
1209
+ let sharedStructuresLength = sharedStructures.length;
1210
+ if (sharedStructuresLength > maxSharedStructures && !isSequential)
1211
+ sharedStructuresLength = maxSharedStructures;
1212
+ if (!sharedStructures.transitions) {
1213
+ // rebuild our structure transitions
1214
+ sharedStructures.transitions = Object.create(null);
1215
+ for (let i = 0; i < sharedStructuresLength; i++) {
1216
+ let keys = sharedStructures[i];
1217
+ //console.log('shared struct keys:', keys)
1218
+ if (!keys)
1219
+ continue
1220
+ let nextTransition, transition = sharedStructures.transitions;
1221
+ for (let j = 0, l = keys.length; j < l; j++) {
1222
+ if (transition[RECORD_SYMBOL] === undefined)
1223
+ transition[RECORD_SYMBOL] = i;
1224
+ let key = keys[j];
1225
+ nextTransition = transition[key];
1226
+ if (!nextTransition) {
1227
+ nextTransition = transition[key] = Object.create(null);
1228
+ }
1229
+ transition = nextTransition;
1230
+ }
1231
+ transition[RECORD_SYMBOL] = i | 0x100000;
1232
+ }
1233
+ }
1234
+ if (!isSequential)
1235
+ sharedStructures.nextId = sharedStructuresLength;
1236
+ }
1237
+ if (hasSharedUpdate)
1238
+ hasSharedUpdate = false;
1239
+ structures = sharedStructures || [];
1240
+ packedObjectMap = sharedPackedObjectMap;
1241
+ if (options.pack) {
1242
+ let packedValues = new Map();
1243
+ packedValues.values = [];
1244
+ packedValues.encoder = encoder;
1245
+ packedValues.maxValues = options.maxPrivatePackedValues || (sharedPackedObjectMap ? 16 : Infinity);
1246
+ packedValues.objectMap = sharedPackedObjectMap || false;
1247
+ packedValues.samplingPackedValues = samplingPackedValues;
1248
+ findRepetitiveStrings(value, packedValues);
1249
+ if (packedValues.values.length > 0) {
1250
+ target[position++] = 0xd8; // one-byte tag
1251
+ target[position++] = 51; // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
1252
+ writeArrayHeader(4);
1253
+ let valuesArray = packedValues.values;
1254
+ encode(valuesArray);
1255
+ writeArrayHeader(0); // prefixes
1256
+ writeArrayHeader(0); // suffixes
1257
+ packedObjectMap = Object.create(sharedPackedObjectMap || null);
1258
+ for (let i = 0, l = valuesArray.length; i < l; i++) {
1259
+ packedObjectMap[valuesArray[i]] = i;
1260
+ }
1261
+ }
1262
+ }
1263
+ throwOnIterable = encodeOptions & THROW_ON_ITERABLE;
1264
+ try {
1265
+ if (throwOnIterable)
1266
+ return;
1267
+ encode(value);
1268
+ if (bundledStrings) {
1269
+ writeBundles(start, encode);
1270
+ }
1271
+ encoder.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
1272
+ if (referenceMap && referenceMap.idsToInsert) {
1273
+ position += referenceMap.idsToInsert.length * 2;
1274
+ if (position > safeEnd)
1275
+ makeRoom(position);
1276
+ encoder.offset = position;
1277
+ let serialized = insertIds(target.subarray(start, position), referenceMap.idsToInsert);
1278
+ referenceMap = null;
1279
+ return serialized
1280
+ }
1281
+ if (encodeOptions & REUSE_BUFFER_MODE) {
1282
+ target.start = start;
1283
+ target.end = position;
1284
+ return target
1285
+ }
1286
+ return target.subarray(start, position) // position can change if we call encode again in saveShared, so we get the buffer now
1287
+ } finally {
1288
+ if (sharedStructures) {
1289
+ if (serializationsSinceTransitionRebuild < 10)
1290
+ serializationsSinceTransitionRebuild++;
1291
+ if (sharedStructures.length > maxSharedStructures)
1292
+ sharedStructures.length = maxSharedStructures;
1293
+ if (transitionsCount > 10000) {
1294
+ // force a rebuild occasionally after a lot of transitions so it can get cleaned up
1295
+ sharedStructures.transitions = null;
1296
+ serializationsSinceTransitionRebuild = 0;
1297
+ transitionsCount = 0;
1298
+ if (recordIdsToRemove.length > 0)
1299
+ recordIdsToRemove = [];
1300
+ } else if (recordIdsToRemove.length > 0 && !isSequential) {
1301
+ for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
1302
+ recordIdsToRemove[i][RECORD_SYMBOL] = undefined;
1303
+ }
1304
+ recordIdsToRemove = [];
1305
+ //sharedStructures.nextId = maxSharedStructures
1306
+ }
1307
+ }
1308
+ if (hasSharedUpdate && encoder.saveShared) {
1309
+ if (encoder.structures.length > maxSharedStructures) {
1310
+ encoder.structures = encoder.structures.slice(0, maxSharedStructures);
1311
+ }
1312
+ // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
1313
+ let returnBuffer = target.subarray(start, position);
1314
+ if (encoder.updateSharedData() === false)
1315
+ return encoder.encode(value) // re-encode if it fails
1316
+ return returnBuffer
1317
+ }
1318
+ if (encodeOptions & RESET_BUFFER_MODE)
1319
+ position = start;
1320
+ }
1321
+ };
1322
+ this.findCommonStringsToPack = () => {
1323
+ samplingPackedValues = new Map();
1324
+ if (!sharedPackedObjectMap)
1325
+ sharedPackedObjectMap = Object.create(null);
1326
+ return (options) => {
1327
+ let threshold = options && options.threshold || 4;
1328
+ let position = this.pack ? options.maxPrivatePackedValues || 16 : 0;
1329
+ if (!sharedValues)
1330
+ sharedValues = this.sharedValues = [];
1331
+ for (let [ key, status ] of samplingPackedValues) {
1332
+ if (status.count > threshold) {
1333
+ sharedPackedObjectMap[key] = position++;
1334
+ sharedValues.push(key);
1335
+ hasSharedUpdate = true;
1336
+ }
1337
+ }
1338
+ while (this.saveShared && this.updateSharedData() === false) {}
1339
+ samplingPackedValues = null;
1340
+ }
1341
+ };
1342
+ const encode = (value) => {
1343
+ if (position > safeEnd)
1344
+ target = makeRoom(position);
1345
+
1346
+ var type = typeof value;
1347
+ var length;
1348
+ if (type === 'string') {
1349
+ if (packedObjectMap) {
1350
+ let packedPosition = packedObjectMap[value];
1351
+ if (packedPosition >= 0) {
1352
+ if (packedPosition < 16)
1353
+ target[position++] = packedPosition + 0xe0; // simple values, defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
1354
+ else {
1355
+ target[position++] = 0xc6; // tag 6 defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
1356
+ if (packedPosition & 1)
1357
+ encode((15 - packedPosition) >> 1);
1358
+ else
1359
+ encode((packedPosition - 16) >> 1);
1360
+ }
1361
+ return
1362
+ /* } else if (packedStatus.serializationId != serializationId) {
1363
+ packedStatus.serializationId = serializationId
1364
+ packedStatus.count = 1
1365
+ if (options.sharedPack) {
1366
+ let sharedCount = packedStatus.sharedCount = (packedStatus.sharedCount || 0) + 1
1367
+ if (shareCount > (options.sharedPack.threshold || 5)) {
1368
+ let sharedPosition = packedStatus.position = packedStatus.nextSharedPosition
1369
+ hasSharedUpdate = true
1370
+ if (sharedPosition < 16)
1371
+ target[position++] = sharedPosition + 0xc0
1372
+
1373
+ }
1374
+ }
1375
+ } // else any in-doc incrementation?*/
1376
+ } else if (samplingPackedValues && !options.pack) {
1377
+ let status = samplingPackedValues.get(value);
1378
+ if (status)
1379
+ status.count++;
1380
+ else
1381
+ samplingPackedValues.set(value, {
1382
+ count: 1,
1383
+ });
1384
+ }
1385
+ }
1386
+ let strLength = value.length;
1387
+ if (bundledStrings && strLength >= 4 && strLength < 0x400) {
1388
+ if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
1389
+ let extStart;
1390
+ let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
1391
+ if (position + maxBytes > safeEnd)
1392
+ target = makeRoom(position + maxBytes);
1393
+ target[position++] = 0xd9; // tag 16-bit
1394
+ target[position++] = 0xdf; // tag 0xdff9
1395
+ target[position++] = 0xf9;
1396
+ // TODO: If we only have one bundle with any string data, only write one string bundle
1397
+ target[position++] = bundledStrings.position ? 0x84 : 0x82; // array of 4 or 2 elements depending on if we write bundles
1398
+ target[position++] = 0x1a; // 32-bit unsigned int
1399
+ extStart = position - start;
1400
+ position += 4; // reserve for writing bundle reference
1401
+ if (bundledStrings.position) {
1402
+ writeBundles(start, encode); // write the last bundles
1403
+ }
1404
+ bundledStrings = ['', '']; // create new ones
1405
+ bundledStrings.size = 0;
1406
+ bundledStrings.position = extStart;
1407
+ }
1408
+ let twoByte = hasNonLatin.test(value);
1409
+ bundledStrings[twoByte ? 0 : 1] += value;
1410
+ target[position++] = twoByte ? 0xce : 0xcf;
1411
+ encode(strLength);
1412
+ return
1413
+ }
1414
+ let headerSize;
1415
+ // first we estimate the header size, so we can write to the correct location
1416
+ if (strLength < 0x20) {
1417
+ headerSize = 1;
1418
+ } else if (strLength < 0x100) {
1419
+ headerSize = 2;
1420
+ } else if (strLength < 0x10000) {
1421
+ headerSize = 3;
1422
+ } else {
1423
+ headerSize = 5;
1424
+ }
1425
+ let maxBytes = strLength * 3;
1426
+ if (position + maxBytes > safeEnd)
1427
+ target = makeRoom(position + maxBytes);
1428
+
1429
+ if (strLength < 0x40 || !encodeUtf8) {
1430
+ let i, c1, c2, strPosition = position + headerSize;
1431
+ for (i = 0; i < strLength; i++) {
1432
+ c1 = value.charCodeAt(i);
1433
+ if (c1 < 0x80) {
1434
+ target[strPosition++] = c1;
1435
+ } else if (c1 < 0x800) {
1436
+ target[strPosition++] = c1 >> 6 | 0xc0;
1437
+ target[strPosition++] = c1 & 0x3f | 0x80;
1438
+ } else if (
1439
+ (c1 & 0xfc00) === 0xd800 &&
1440
+ ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
1441
+ ) {
1442
+ c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
1443
+ i++;
1444
+ target[strPosition++] = c1 >> 18 | 0xf0;
1445
+ target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
1446
+ target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1447
+ target[strPosition++] = c1 & 0x3f | 0x80;
1448
+ } else {
1449
+ target[strPosition++] = c1 >> 12 | 0xe0;
1450
+ target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1451
+ target[strPosition++] = c1 & 0x3f | 0x80;
1452
+ }
1453
+ }
1454
+ length = strPosition - position - headerSize;
1455
+ } else {
1456
+ length = encodeUtf8(value, position + headerSize, maxBytes);
1457
+ }
1458
+
1459
+ if (length < 0x18) {
1460
+ target[position++] = 0x60 | length;
1461
+ } else if (length < 0x100) {
1462
+ if (headerSize < 2) {
1463
+ target.copyWithin(position + 2, position + 1, position + 1 + length);
1464
+ }
1465
+ target[position++] = 0x78;
1466
+ target[position++] = length;
1467
+ } else if (length < 0x10000) {
1468
+ if (headerSize < 3) {
1469
+ target.copyWithin(position + 3, position + 2, position + 2 + length);
1470
+ }
1471
+ target[position++] = 0x79;
1472
+ target[position++] = length >> 8;
1473
+ target[position++] = length & 0xff;
1474
+ } else {
1475
+ if (headerSize < 5) {
1476
+ target.copyWithin(position + 5, position + 3, position + 3 + length);
1477
+ }
1478
+ target[position++] = 0x7a;
1479
+ targetView.setUint32(position, length);
1480
+ position += 4;
1481
+ }
1482
+ position += length;
1483
+ } else if (type === 'number') {
1484
+ if (value >>> 0 === value) {// positive integer, 32-bit or less
1485
+ // positive uint
1486
+ if (value < 0x18) {
1487
+ target[position++] = value;
1488
+ } else if (value < 0x100) {
1489
+ target[position++] = 0x18;
1490
+ target[position++] = value;
1491
+ } else if (value < 0x10000) {
1492
+ target[position++] = 0x19;
1493
+ target[position++] = value >> 8;
1494
+ target[position++] = value & 0xff;
1495
+ } else {
1496
+ target[position++] = 0x1a;
1497
+ targetView.setUint32(position, value);
1498
+ position += 4;
1499
+ }
1500
+ } else if (value >> 0 === value) { // negative integer
1501
+ if (value >= -0x18) {
1502
+ target[position++] = 0x1f - value;
1503
+ } else if (value >= -0x100) {
1504
+ target[position++] = 0x38;
1505
+ target[position++] = ~value;
1506
+ } else if (value >= -0x10000) {
1507
+ target[position++] = 0x39;
1508
+ targetView.setUint16(position, ~value);
1509
+ position += 2;
1510
+ } else {
1511
+ target[position++] = 0x3a;
1512
+ targetView.setUint32(position, ~value);
1513
+ position += 4;
1514
+ }
1515
+ } else {
1516
+ let useFloat32;
1517
+ if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
1518
+ target[position++] = 0xfa;
1519
+ targetView.setFloat32(position, value);
1520
+ let xShifted;
1521
+ if (useFloat32 < 4 ||
1522
+ // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
1523
+ ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
1524
+ position += 4;
1525
+ return
1526
+ } else
1527
+ position--; // move back into position for writing a double
1528
+ }
1529
+ target[position++] = 0xfb;
1530
+ targetView.setFloat64(position, value);
1531
+ position += 8;
1532
+ }
1533
+ } else if (type === 'object') {
1534
+ if (!value)
1535
+ target[position++] = 0xf6;
1536
+ else {
1537
+ if (referenceMap) {
1538
+ let referee = referenceMap.get(value);
1539
+ if (referee) {
1540
+ target[position++] = 0xd8;
1541
+ target[position++] = 29; // http://cbor.schmorp.de/value-sharing
1542
+ target[position++] = 0x19; // 16-bit uint
1543
+ if (!referee.references) {
1544
+ let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
1545
+ referee.references = [];
1546
+ idsToInsert.push(referee);
1547
+ }
1548
+ referee.references.push(position - start);
1549
+ position += 2; // TODO: also support 32-bit
1550
+ return
1551
+ } else
1552
+ referenceMap.set(value, { offset: position - start });
1553
+ }
1554
+ let constructor = value.constructor;
1555
+ if (constructor === Object) {
1556
+ writeObject(value, true);
1557
+ } else if (constructor === Array) {
1558
+ length = value.length;
1559
+ if (length < 0x18) {
1560
+ target[position++] = 0x80 | length;
1561
+ } else {
1562
+ writeArrayHeader(length);
1563
+ }
1564
+ for (let i = 0; i < length; i++) {
1565
+ encode(value[i]);
1566
+ }
1567
+ } else if (constructor === Map) {
1568
+ if (this.mapsAsObjects ? this.useTag259ForMaps !== false : this.useTag259ForMaps) {
1569
+ // use Tag 259 (https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec--explicit-maps.md) for maps if the user wants it that way
1570
+ target[position++] = 0xd9;
1571
+ target[position++] = 1;
1572
+ target[position++] = 3;
1573
+ }
1574
+ length = value.size;
1575
+ if (length < 0x18) {
1576
+ target[position++] = 0xa0 | length;
1577
+ } else if (length < 0x100) {
1578
+ target[position++] = 0xb8;
1579
+ target[position++] = length;
1580
+ } else if (length < 0x10000) {
1581
+ target[position++] = 0xb9;
1582
+ target[position++] = length >> 8;
1583
+ target[position++] = length & 0xff;
1584
+ } else {
1585
+ target[position++] = 0xba;
1586
+ targetView.setUint32(position, length);
1587
+ position += 4;
1588
+ }
1589
+ if (encoder.keyMap) {
1590
+ for (let [ key, entryValue ] of value) {
1591
+ encode(encoder.encodeKey(key));
1592
+ encode(entryValue);
1593
+ }
1594
+ } else {
1595
+ for (let [ key, entryValue ] of value) {
1596
+ encode(key);
1597
+ encode(entryValue);
1598
+ }
1599
+ }
1600
+ } else {
1601
+ for (let i = 0, l = extensions.length; i < l; i++) {
1602
+ let extensionClass = extensionClasses[i];
1603
+ if (value instanceof extensionClass) {
1604
+ let extension = extensions[i];
1605
+ let tag = extension.tag;
1606
+ if (tag == undefined)
1607
+ tag = extension.getTag && extension.getTag.call(this, value);
1608
+ if (tag < 0x18) {
1609
+ target[position++] = 0xc0 | tag;
1610
+ } else if (tag < 0x100) {
1611
+ target[position++] = 0xd8;
1612
+ target[position++] = tag;
1613
+ } else if (tag < 0x10000) {
1614
+ target[position++] = 0xd9;
1615
+ target[position++] = tag >> 8;
1616
+ target[position++] = tag & 0xff;
1617
+ } else if (tag > -1) {
1618
+ target[position++] = 0xda;
1619
+ targetView.setUint32(position, tag);
1620
+ position += 4;
1621
+ } // else undefined, don't write tag
1622
+ extension.encode.call(this, value, encode, makeRoom);
1623
+ return
1624
+ }
1625
+ }
1626
+ if (value[Symbol.iterator]) {
1627
+ if (throwOnIterable) {
1628
+ let error = new Error('Iterable should be serialized as iterator');
1629
+ error.iteratorNotHandled = true;
1630
+ throw error;
1631
+ }
1632
+ target[position++] = 0x9f; // indefinite length array
1633
+ for (let entry of value) {
1634
+ encode(entry);
1635
+ }
1636
+ target[position++] = 0xff; // stop-code
1637
+ return
1638
+ }
1639
+ if (value[Symbol.asyncIterator] || isBlob(value)) {
1640
+ let error = new Error('Iterable/blob should be serialized as iterator');
1641
+ error.iteratorNotHandled = true;
1642
+ throw error;
1643
+ }
1644
+ // no extension found, write as object
1645
+ writeObject(value, !value.hasOwnProperty); // if it doesn't have hasOwnProperty, don't do hasOwnProperty checks
1646
+ }
1647
+ }
1648
+ } else if (type === 'boolean') {
1649
+ target[position++] = value ? 0xf5 : 0xf4;
1650
+ } else if (type === 'bigint') {
1651
+ if (value < (BigInt(1)<<BigInt(64)) && value >= 0) {
1652
+ // use an unsigned int as long as it fits
1653
+ target[position++] = 0x1b;
1654
+ targetView.setBigUint64(position, value);
1655
+ } else if (value > -(BigInt(1)<<BigInt(64)) && value < 0) {
1656
+ // if we can fit an unsigned int, use that
1657
+ target[position++] = 0x3b;
1658
+ targetView.setBigUint64(position, -value - BigInt(1));
1659
+ } else {
1660
+ // overflow
1661
+ if (this.largeBigIntToFloat) {
1662
+ target[position++] = 0xfb;
1663
+ targetView.setFloat64(position, Number(value));
1664
+ } else {
1665
+ throw new RangeError(value + ' was too large to fit in CBOR 64-bit integer format, set largeBigIntToFloat to convert to float-64')
1666
+ }
1667
+ }
1668
+ position += 8;
1669
+ } else if (type === 'undefined') {
1670
+ target[position++] = 0xf7;
1671
+ } else {
1672
+ throw new Error('Unknown type: ' + type)
1673
+ }
1674
+ };
1675
+
1676
+ const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {
1677
+ // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
1678
+ let keys = Object.keys(object);
1679
+ let vals = Object.values(object);
1680
+ let length = keys.length;
1681
+ if (length < 0x18) {
1682
+ target[position++] = 0xa0 | length;
1683
+ } else if (length < 0x100) {
1684
+ target[position++] = 0xb8;
1685
+ target[position++] = length;
1686
+ } else if (length < 0x10000) {
1687
+ target[position++] = 0xb9;
1688
+ target[position++] = length >> 8;
1689
+ target[position++] = length & 0xff;
1690
+ } else {
1691
+ target[position++] = 0xba;
1692
+ targetView.setUint32(position, length);
1693
+ position += 4;
1694
+ }
1695
+ if (encoder.keyMap) {
1696
+ for (let i = 0; i < length; i++) {
1697
+ encode(encodeKey(keys[i]));
1698
+ encode(vals[i]);
1699
+ }
1700
+ } else {
1701
+ for (let i = 0; i < length; i++) {
1702
+ encode(keys[i]);
1703
+ encode(vals[i]);
1704
+ }
1705
+ }
1706
+ } :
1707
+ (object, safePrototype) => {
1708
+ target[position++] = 0xb9; // always use map 16, so we can preallocate and set the length afterwards
1709
+ let objectOffset = position - start;
1710
+ position += 2;
1711
+ let size = 0;
1712
+ if (encoder.keyMap) {
1713
+ for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
1714
+ encode(encoder.encodeKey(key));
1715
+ encode(object[key]);
1716
+ size++;
1717
+ }
1718
+ } else {
1719
+ for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
1720
+ encode(key);
1721
+ encode(object[key]);
1722
+ size++;
1723
+ }
1724
+ }
1725
+ target[objectOffset++ + start] = size >> 8;
1726
+ target[objectOffset + start] = size & 0xff;
1727
+ } :
1728
+ (object, safePrototype) => {
1729
+ let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1730
+ let newTransitions = 0;
1731
+ let length = 0;
1732
+ let parentRecordId;
1733
+ let keys;
1734
+ if (this.keyMap) {
1735
+ keys = Object.keys(object).map(k => this.encodeKey(k));
1736
+ length = keys.length;
1737
+ for (let i = 0; i < length; i++) {
1738
+ let key = keys[i];
1739
+ nextTransition = transition[key];
1740
+ if (!nextTransition) {
1741
+ nextTransition = transition[key] = Object.create(null);
1742
+ newTransitions++;
1743
+ }
1744
+ transition = nextTransition;
1745
+ }
1746
+ } else {
1747
+ for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
1748
+ nextTransition = transition[key];
1749
+ if (!nextTransition) {
1750
+ if (transition[RECORD_SYMBOL] & 0x100000) {// this indicates it is a brancheable/extendable terminal node, so we will use this record id and extend it
1751
+ parentRecordId = transition[RECORD_SYMBOL] & 0xffff;
1752
+ }
1753
+ nextTransition = transition[key] = Object.create(null);
1754
+ newTransitions++;
1755
+ }
1756
+ transition = nextTransition;
1757
+ length++;
1758
+ }
1759
+ }
1760
+ let recordId = transition[RECORD_SYMBOL];
1761
+ if (recordId !== undefined) {
1762
+ recordId &= 0xffff;
1763
+ target[position++] = 0xd9;
1764
+ target[position++] = (recordId >> 8) | 0xe0;
1765
+ target[position++] = recordId & 0xff;
1766
+ } else {
1767
+ if (!keys)
1768
+ keys = transition.__keys__ || (transition.__keys__ = Object.keys(object));
1769
+ if (parentRecordId === undefined) {
1770
+ recordId = structures.nextId++;
1771
+ if (!recordId) {
1772
+ recordId = 0;
1773
+ structures.nextId = 1;
1774
+ }
1775
+ if (recordId >= MAX_STRUCTURES) {// cycle back around
1776
+ structures.nextId = (recordId = maxSharedStructures) + 1;
1777
+ }
1778
+ } else {
1779
+ recordId = parentRecordId;
1780
+ }
1781
+ structures[recordId] = keys;
1782
+ if (recordId < maxSharedStructures) {
1783
+ target[position++] = 0xd9;
1784
+ target[position++] = (recordId >> 8) | 0xe0;
1785
+ target[position++] = recordId & 0xff;
1786
+ transition = structures.transitions;
1787
+ for (let i = 0; i < length; i++) {
1788
+ if (transition[RECORD_SYMBOL] === undefined || (transition[RECORD_SYMBOL] & 0x100000))
1789
+ transition[RECORD_SYMBOL] = recordId;
1790
+ transition = transition[keys[i]];
1791
+ }
1792
+ transition[RECORD_SYMBOL] = recordId | 0x100000; // indicates it is a extendable terminal
1793
+ hasSharedUpdate = true;
1794
+ } else {
1795
+ transition[RECORD_SYMBOL] = recordId;
1796
+ targetView.setUint32(position, 0xd9dfff00); // tag two byte, then record definition id
1797
+ position += 3;
1798
+ if (newTransitions)
1799
+ transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
1800
+ // record the removal of the id, we can maintain our shared structure
1801
+ if (recordIdsToRemove.length >= MAX_STRUCTURES - maxSharedStructures)
1802
+ recordIdsToRemove.shift()[RECORD_SYMBOL] = undefined; // we are cycling back through, and have to remove old ones
1803
+ recordIdsToRemove.push(transition);
1804
+ writeArrayHeader(length + 2);
1805
+ encode(0xe000 + recordId);
1806
+ encode(keys);
1807
+ if (safePrototype === null) return; // special exit for iterator
1808
+ for (let key in object)
1809
+ if (safePrototype || object.hasOwnProperty(key))
1810
+ encode(object[key]);
1811
+ return
1812
+ }
1813
+ }
1814
+ if (length < 0x18) { // write the array header
1815
+ target[position++] = 0x80 | length;
1816
+ } else {
1817
+ writeArrayHeader(length);
1818
+ }
1819
+ if (safePrototype === null) return; // special exit for iterator
1820
+ for (let key in object)
1821
+ if (safePrototype || object.hasOwnProperty(key))
1822
+ encode(object[key]);
1823
+ };
1824
+ const makeRoom = (end) => {
1825
+ let newSize;
1826
+ if (end > 0x1000000) {
1827
+ // special handling for really large buffers
1828
+ if ((end - start) > MAX_BUFFER_SIZE)
1829
+ throw new Error('Encoded buffer would be larger than maximum buffer size')
1830
+ newSize = Math.min(MAX_BUFFER_SIZE,
1831
+ Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
1832
+ } else // faster handling for smaller buffers
1833
+ newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
1834
+ let newBuffer = new ByteArrayAllocate(newSize);
1835
+ targetView = new DataView(newBuffer.buffer, 0, newSize);
1836
+ if (target.copy)
1837
+ target.copy(newBuffer, 0, start, end);
1838
+ else
1839
+ newBuffer.set(target.slice(start, end));
1840
+ position -= start;
1841
+ start = 0;
1842
+ safeEnd = newBuffer.length - 10;
1843
+ return target = newBuffer
1844
+ };
1845
+ let chunkThreshold = 100;
1846
+ let continuedChunkThreshold = 1000;
1847
+ this.encodeAsIterable = function(value, options) {
1848
+ return startEncoding(value, options, encodeObjectAsIterable);
1849
+ };
1850
+ this.encodeAsAsyncIterable = function(value, options) {
1851
+ return startEncoding(value, options, encodeObjectAsAsyncIterable);
1852
+ };
1853
+
1854
+ function* encodeObjectAsIterable(object, iterateProperties, finalIterable) {
1855
+ let constructor = object.constructor;
1856
+ if (constructor === Object) {
1857
+ let useRecords = encoder.useRecords !== false;
1858
+ if (useRecords)
1859
+ writeObject(object, null); // write the record identifier
1860
+ else
1861
+ writeEntityLength(Object.keys(object).length, 0xa0);
1862
+ for (let key in object) {
1863
+ let value = object[key];
1864
+ if (!useRecords) encode(key);
1865
+ if (value && typeof value === 'object') {
1866
+ if (iterateProperties[key])
1867
+ yield* encodeObjectAsIterable(value, iterateProperties[key]);
1868
+ else
1869
+ yield* tryEncode(value, iterateProperties, key);
1870
+ } else encode(value);
1871
+ }
1872
+ } else if (constructor === Array) {
1873
+ let length = object.length;
1874
+ writeArrayHeader(length);
1875
+ for (let i = 0; i < length; i++) {
1876
+ let value = object[i];
1877
+ if (value && (typeof value === 'object' || position - start > chunkThreshold)) {
1878
+ if (iterateProperties.element)
1879
+ yield* encodeObjectAsIterable(value, iterateProperties.element);
1880
+ else
1881
+ yield* tryEncode(value, iterateProperties, 'element');
1882
+ } else encode(value);
1883
+ }
1884
+ } else if (object[Symbol.iterator]) {
1885
+ target[position++] = 0x9f; // start indefinite array
1886
+ for (let value of object) {
1887
+ if (value && (typeof value === 'object' || position - start > chunkThreshold)) {
1888
+ if (iterateProperties.element)
1889
+ yield* encodeObjectAsIterable(value, iterateProperties.element);
1890
+ else
1891
+ yield* tryEncode(value, iterateProperties, 'element');
1892
+ } else encode(value);
1893
+ }
1894
+ target[position++] = 0xff; // stop byte
1895
+ } else if (isBlob(object)){
1896
+ writeEntityLength(object.size, 0x40); // encode as binary data
1897
+ yield target.subarray(start, position);
1898
+ yield object; // directly return blobs, they have to be encoded asynchronously
1899
+ restartEncoding();
1900
+ } else if (object[Symbol.asyncIterator]) {
1901
+ target[position++] = 0x9f; // start indefinite array
1902
+ yield target.subarray(start, position);
1903
+ yield object; // directly return async iterators, they have to be encoded asynchronously
1904
+ restartEncoding();
1905
+ target[position++] = 0xff; // stop byte
1906
+ } else {
1907
+ encode(object);
1908
+ }
1909
+ if (finalIterable && position > start) yield target.subarray(start, position);
1910
+ else if (position - start > chunkThreshold) {
1911
+ yield target.subarray(start, position);
1912
+ restartEncoding();
1913
+ }
1914
+ }
1915
+ function* tryEncode(value, iterateProperties, key) {
1916
+ let restart = position - start;
1917
+ try {
1918
+ encode(value);
1919
+ if (position - start > chunkThreshold) {
1920
+ yield target.subarray(start, position);
1921
+ restartEncoding();
1922
+ }
1923
+ } catch (error) {
1924
+ if (error.iteratorNotHandled) {
1925
+ iterateProperties[key] = {};
1926
+ position = start + restart; // restart our position so we don't have partial data from last encode
1927
+ yield* encodeObjectAsIterable.call(this, value, iterateProperties[key]);
1928
+ } else throw error;
1929
+ }
1930
+ }
1931
+ function restartEncoding() {
1932
+ chunkThreshold = continuedChunkThreshold;
1933
+ encoder.encode(null, THROW_ON_ITERABLE); // restart encoding
1934
+ }
1935
+ function startEncoding(value, options, encodeIterable) {
1936
+ if (options && options.chunkThreshold) // explicitly specified chunk sizes
1937
+ chunkThreshold = continuedChunkThreshold = options.chunkThreshold;
1938
+ else // we start with a smaller threshold to get initial bytes sent quickly
1939
+ chunkThreshold = 100;
1940
+ if (value && typeof value === 'object') {
1941
+ encoder.encode(null, THROW_ON_ITERABLE); // start encoding
1942
+ return encodeIterable(value, encoder.iterateProperties || (encoder.iterateProperties = {}), true);
1943
+ }
1944
+ return [encoder.encode(value)];
1945
+ }
1946
+
1947
+ async function* encodeObjectAsAsyncIterable(value, iterateProperties) {
1948
+ for (let encodedValue of encodeObjectAsIterable(value, iterateProperties, true)) {
1949
+ let constructor = encodedValue.constructor;
1950
+ if (constructor === ByteArray || constructor === Uint8Array)
1951
+ yield encodedValue;
1952
+ else if (isBlob(encodedValue)) {
1953
+ let reader = encodedValue.stream().getReader();
1954
+ let next;
1955
+ while (!(next = await reader.read()).done) {
1956
+ yield next.value;
1957
+ }
1958
+ } else if (encodedValue[Symbol.asyncIterator]) {
1959
+ for await (let asyncValue of encodedValue) {
1960
+ restartEncoding();
1961
+ if (asyncValue)
1962
+ yield* encodeObjectAsAsyncIterable(asyncValue, iterateProperties.async || (iterateProperties.async = {}));
1963
+ else yield encoder.encode(asyncValue);
1964
+ }
1965
+ } else {
1966
+ yield encodedValue;
1967
+ }
1968
+ }
1969
+ }
1970
+ }
1971
+ useBuffer(buffer) {
1972
+ // this means we are finished using our own buffer and we can write over it safely
1973
+ target = buffer;
1974
+ targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
1975
+ position = 0;
1976
+ }
1977
+ clearSharedData() {
1978
+ if (this.structures)
1979
+ this.structures = [];
1980
+ if (this.sharedValues)
1981
+ this.sharedValues = undefined;
1982
+ }
1983
+ updateSharedData() {
1984
+ let lastVersion = this.sharedVersion || 0;
1985
+ this.sharedVersion = lastVersion + 1;
1986
+ let structuresCopy = this.structures.slice(0);
1987
+ let sharedData = new SharedData(structuresCopy, this.sharedValues, this.sharedVersion);
1988
+ let saveResults = this.saveShared(sharedData,
1989
+ existingShared => (existingShared && existingShared.version || 0) == lastVersion);
1990
+ if (saveResults === false) {
1991
+ // get updated structures and try again if the update failed
1992
+ sharedData = this.getShared() || {};
1993
+ this.structures = sharedData.structures || [];
1994
+ this.sharedValues = sharedData.packedValues;
1995
+ this.sharedVersion = sharedData.version;
1996
+ this.structures.nextId = this.structures.length;
1997
+ } else {
1998
+ // restore structures
1999
+ structuresCopy.forEach((structure, i) => this.structures[i] = structure);
2000
+ }
2001
+ // saveShared may fail to write and reload, or may have reloaded to check compatibility and overwrite saved data, either way load the correct shared data
2002
+ return saveResults
2003
+ }
2004
+ }
2005
+ function writeEntityLength(length, majorValue) {
2006
+ if (length < 0x18)
2007
+ target[position++] = majorValue | length;
2008
+ else if (length < 0x100) {
2009
+ target[position++] = majorValue | 0x18;
2010
+ target[position++] = length;
2011
+ } else if (length < 0x10000) {
2012
+ target[position++] = majorValue | 0x19;
2013
+ target[position++] = length >> 8;
2014
+ target[position++] = length & 0xff;
2015
+ } else {
2016
+ target[position++] = majorValue | 0x1a;
2017
+ targetView.setUint32(position, length);
2018
+ position += 4;
2019
+ }
2020
+
2021
+ }
2022
+ class SharedData {
2023
+ constructor(structures, values, version) {
2024
+ this.structures = structures;
2025
+ this.packedValues = values;
2026
+ this.version = version;
2027
+ }
2028
+ }
2029
+
2030
+ function writeArrayHeader(length) {
2031
+ if (length < 0x18)
2032
+ target[position++] = 0x80 | length;
2033
+ else if (length < 0x100) {
2034
+ target[position++] = 0x98;
2035
+ target[position++] = length;
2036
+ } else if (length < 0x10000) {
2037
+ target[position++] = 0x99;
2038
+ target[position++] = length >> 8;
2039
+ target[position++] = length & 0xff;
2040
+ } else {
2041
+ target[position++] = 0x9a;
2042
+ targetView.setUint32(position, length);
2043
+ position += 4;
2044
+ }
2045
+ }
2046
+
2047
+ const BlobConstructor = typeof Blob === 'undefined' ? function(){} : Blob;
2048
+ function isBlob(object) {
2049
+ if (object instanceof BlobConstructor)
2050
+ return true;
2051
+ let tag = object[Symbol.toStringTag];
2052
+ return tag === 'Blob' || tag === 'File';
2053
+ }
2054
+ function findRepetitiveStrings(value, packedValues) {
2055
+ switch(typeof value) {
2056
+ case 'string':
2057
+ if (value.length > 3) {
2058
+ if (packedValues.objectMap[value] > -1 || packedValues.values.length >= packedValues.maxValues)
2059
+ return
2060
+ let packedStatus = packedValues.get(value);
2061
+ if (packedStatus) {
2062
+ if (++packedStatus.count == 2) {
2063
+ packedValues.values.push(value);
2064
+ }
2065
+ } else {
2066
+ packedValues.set(value, {
2067
+ count: 1,
2068
+ });
2069
+ if (packedValues.samplingPackedValues) {
2070
+ let status = packedValues.samplingPackedValues.get(value);
2071
+ if (status)
2072
+ status.count++;
2073
+ else
2074
+ packedValues.samplingPackedValues.set(value, {
2075
+ count: 1,
2076
+ });
2077
+ }
2078
+ }
2079
+ }
2080
+ break
2081
+ case 'object':
2082
+ if (value) {
2083
+ if (value instanceof Array) {
2084
+ for (let i = 0, l = value.length; i < l; i++) {
2085
+ findRepetitiveStrings(value[i], packedValues);
2086
+ }
2087
+
2088
+ } else {
2089
+ let includeKeys = !packedValues.encoder.useRecords;
2090
+ for (var key in value) {
2091
+ if (value.hasOwnProperty(key)) {
2092
+ if (includeKeys)
2093
+ findRepetitiveStrings(key, packedValues);
2094
+ findRepetitiveStrings(value[key], packedValues);
2095
+ }
2096
+ }
2097
+ }
2098
+ }
2099
+ break
2100
+ case 'function': console.log(value);
2101
+ }
2102
+ }
2103
+ const isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
2104
+ extensionClasses = [ Date, Set, Error, RegExp, Tag, ArrayBuffer,
2105
+ Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,
2106
+ typeof BigUint64Array == 'undefined' ? function() {} : BigUint64Array, Int8Array, Int16Array, Int32Array,
2107
+ typeof BigInt64Array == 'undefined' ? function() {} : BigInt64Array,
2108
+ Float32Array, Float64Array, SharedData ];
2109
+
2110
+ //Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/
2111
+ extensions = [{ // Date
2112
+ tag: 1,
2113
+ encode(date, encode) {
2114
+ let seconds = date.getTime() / 1000;
2115
+ if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
2116
+ // Timestamp 32
2117
+ target[position++] = 0x1a;
2118
+ targetView.setUint32(position, seconds);
2119
+ position += 4;
2120
+ } else {
2121
+ // Timestamp float64
2122
+ target[position++] = 0xfb;
2123
+ targetView.setFloat64(position, seconds);
2124
+ position += 8;
2125
+ }
2126
+ }
2127
+ }, { // Set
2128
+ tag: 258, // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md
2129
+ encode(set, encode) {
2130
+ let array = Array.from(set);
2131
+ encode(array);
2132
+ }
2133
+ }, { // Error
2134
+ tag: 27, // http://cbor.schmorp.de/generic-object
2135
+ encode(error, encode) {
2136
+ encode([ error.name, error.message ]);
2137
+ }
2138
+ }, { // RegExp
2139
+ tag: 27, // http://cbor.schmorp.de/generic-object
2140
+ encode(regex, encode) {
2141
+ encode([ 'RegExp', regex.source, regex.flags ]);
2142
+ }
2143
+ }, { // Tag
2144
+ getTag(tag) {
2145
+ return tag.tag
2146
+ },
2147
+ encode(tag, encode) {
2148
+ encode(tag.value);
2149
+ }
2150
+ }, { // ArrayBuffer
2151
+ encode(arrayBuffer, encode, makeRoom) {
2152
+ writeBuffer(arrayBuffer, makeRoom);
2153
+ }
2154
+ }, { // Uint8Array
2155
+ getTag(typedArray) {
2156
+ if (typedArray.constructor === Uint8Array) {
2157
+ if (this.tagUint8Array || hasNodeBuffer && this.tagUint8Array !== false)
2158
+ return 64;
2159
+ } // else no tag
2160
+ },
2161
+ encode(typedArray, encode, makeRoom) {
2162
+ writeBuffer(typedArray, makeRoom);
2163
+ }
2164
+ },
2165
+ typedArrayEncoder(68, 1),
2166
+ typedArrayEncoder(69, 2),
2167
+ typedArrayEncoder(70, 4),
2168
+ typedArrayEncoder(71, 8),
2169
+ typedArrayEncoder(72, 1),
2170
+ typedArrayEncoder(77, 2),
2171
+ typedArrayEncoder(78, 4),
2172
+ typedArrayEncoder(79, 8),
2173
+ typedArrayEncoder(85, 4),
2174
+ typedArrayEncoder(86, 8),
2175
+ {
2176
+ encode(sharedData, encode) { // write SharedData
2177
+ let packedValues = sharedData.packedValues || [];
2178
+ let sharedStructures = sharedData.structures || [];
2179
+ if (packedValues.values.length > 0) {
2180
+ target[position++] = 0xd8; // one-byte tag
2181
+ target[position++] = 51; // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
2182
+ writeArrayHeader(4);
2183
+ let valuesArray = packedValues.values;
2184
+ encode(valuesArray);
2185
+ writeArrayHeader(0); // prefixes
2186
+ writeArrayHeader(0); // suffixes
2187
+ packedObjectMap = Object.create(sharedPackedObjectMap || null);
2188
+ for (let i = 0, l = valuesArray.length; i < l; i++) {
2189
+ packedObjectMap[valuesArray[i]] = i;
2190
+ }
2191
+ }
2192
+ if (sharedStructures) {
2193
+ targetView.setUint32(position, 0xd9dffe00);
2194
+ position += 3;
2195
+ let definitions = sharedStructures.slice(0);
2196
+ definitions.unshift(0xe000);
2197
+ definitions.push(new Tag(sharedData.version, 0x53687264));
2198
+ encode(definitions);
2199
+ } else
2200
+ encode(new Tag(sharedData.version, 0x53687264));
2201
+ }
2202
+ }];
2203
+ function typedArrayEncoder(tag, size) {
2204
+ if (!isLittleEndianMachine && size > 1)
2205
+ tag -= 4; // the big endian equivalents are 4 less
2206
+ return {
2207
+ tag: tag,
2208
+ encode: function writeExtBuffer(typedArray, encode) {
2209
+ let length = typedArray.byteLength;
2210
+ let offset = typedArray.byteOffset || 0;
2211
+ let buffer = typedArray.buffer || typedArray;
2212
+ encode(hasNodeBuffer ? Buffer$1.from(buffer, offset, length) :
2213
+ new Uint8Array(buffer, offset, length));
2214
+ }
2215
+ }
2216
+ }
2217
+ function writeBuffer(buffer, makeRoom) {
2218
+ let length = buffer.byteLength;
2219
+ if (length < 0x18) {
2220
+ target[position++] = 0x40 + length;
2221
+ } else if (length < 0x100) {
2222
+ target[position++] = 0x58;
2223
+ target[position++] = length;
2224
+ } else if (length < 0x10000) {
2225
+ target[position++] = 0x59;
2226
+ target[position++] = length >> 8;
2227
+ target[position++] = length & 0xff;
2228
+ } else {
2229
+ target[position++] = 0x5a;
2230
+ targetView.setUint32(position, length);
2231
+ position += 4;
2232
+ }
2233
+ if (position + length >= target.length) {
2234
+ makeRoom(position + length);
2235
+ }
2236
+ // if it is already a typed array (has an ArrayBuffer), use that, but if it is an ArrayBuffer itself,
2237
+ // must wrap it to set it.
2238
+ target.set(buffer.buffer ? buffer : new Uint8Array(buffer), position);
2239
+ position += length;
2240
+ }
2241
+
2242
+ function insertIds(serialized, idsToInsert) {
2243
+ // insert the ids that need to be referenced for structured clones
2244
+ let nextId;
2245
+ let distanceToMove = idsToInsert.length * 2;
2246
+ let lastEnd = serialized.length - distanceToMove;
2247
+ idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
2248
+ for (let id = 0; id < idsToInsert.length; id++) {
2249
+ let referee = idsToInsert[id];
2250
+ referee.id = id;
2251
+ for (let position of referee.references) {
2252
+ serialized[position++] = id >> 8;
2253
+ serialized[position] = id & 0xff;
2254
+ }
2255
+ }
2256
+ while (nextId = idsToInsert.pop()) {
2257
+ let offset = nextId.offset;
2258
+ serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
2259
+ distanceToMove -= 2;
2260
+ let position = offset + distanceToMove;
2261
+ serialized[position++] = 0xd8;
2262
+ serialized[position++] = 28; // http://cbor.schmorp.de/value-sharing
2263
+ lastEnd = offset;
2264
+ }
2265
+ return serialized
2266
+ }
2267
+ function writeBundles(start, encode) {
2268
+ targetView.setUint32(bundledStrings.position + start, position - bundledStrings.position - start + 1); // the offset to bundle
2269
+ let writeStrings = bundledStrings;
2270
+ bundledStrings = null;
2271
+ encode(writeStrings[0]);
2272
+ encode(writeStrings[1]);
2273
+ }
2274
+
2275
+ function addExtension(extension) {
2276
+ if (extension.Class) {
2277
+ if (!extension.encode)
2278
+ throw new Error('Extension has no encode function')
2279
+ extensionClasses.unshift(extension.Class);
2280
+ extensions.unshift(extension);
2281
+ }
2282
+ addExtension$1(extension);
2283
+ }
2284
+ let defaultEncoder = new Encoder({ useRecords: false });
2285
+ const encode = defaultEncoder.encode;
2286
+ const encodeAsIterable = defaultEncoder.encodeAsIterable;
2287
+ const encodeAsAsyncIterable = defaultEncoder.encodeAsAsyncIterable;
2288
+ const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
2289
+ const REUSE_BUFFER_MODE = 512;
2290
+ const RESET_BUFFER_MODE = 1024;
2291
+ const THROW_ON_ITERABLE = 2048;
2292
+
2293
+ /**
2294
+ * Given an Iterable first argument, returns an Iterable where each value is encoded as a Buffer
2295
+ * If the argument is only Async Iterable, the return value will be an Async Iterable.
2296
+ * @param {Iterable|Iterator|AsyncIterable|AsyncIterator} objectIterator - iterable source, like a Readable object stream, an array, Set, or custom object
2297
+ * @param {options} [options] - cbor-x Encoder options
2298
+ * @returns {IterableIterator|Promise.<AsyncIterableIterator>}
2299
+ */
2300
+ function encodeIter (objectIterator, options = {}) {
2301
+ if (!objectIterator || typeof objectIterator !== 'object') {
2302
+ throw new Error('first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable')
2303
+ } else if (typeof objectIterator[Symbol.iterator] === 'function') {
2304
+ return encodeIterSync(objectIterator, options)
2305
+ } else if (typeof objectIterator.then === 'function' || typeof objectIterator[Symbol.asyncIterator] === 'function') {
2306
+ return encodeIterAsync(objectIterator, options)
2307
+ } else {
2308
+ throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise')
2309
+ }
2310
+ }
2311
+
2312
+ function * encodeIterSync (objectIterator, options) {
2313
+ const encoder = new Encoder(options);
2314
+ for (const value of objectIterator) {
2315
+ yield encoder.encode(value);
2316
+ }
2317
+ }
2318
+
2319
+ async function * encodeIterAsync (objectIterator, options) {
2320
+ const encoder = new Encoder(options);
2321
+ for await (const value of objectIterator) {
2322
+ yield encoder.encode(value);
2323
+ }
2324
+ }
2325
+
2326
+ /**
2327
+ * Given an Iterable/Iterator input which yields buffers, returns an IterableIterator which yields sync decoded objects
2328
+ * Or, given an Async Iterable/Iterator which yields promises resolving in buffers, returns an AsyncIterableIterator.
2329
+ * @param {Iterable|Iterator|AsyncIterable|AsyncIterableIterator} bufferIterator
2330
+ * @param {object} [options] - Decoder options
2331
+ * @returns {IterableIterator|Promise.<AsyncIterableIterator}
2332
+ */
2333
+ function decodeIter (bufferIterator, options = {}) {
2334
+ if (!bufferIterator || typeof bufferIterator !== 'object') {
2335
+ throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise')
2336
+ }
2337
+
2338
+ const decoder = new Decoder(options);
2339
+ let incomplete;
2340
+ const parser = (chunk) => {
2341
+ let yields;
2342
+ // if there's incomplete data from previous chunk, concatinate and try again
2343
+ if (incomplete) {
2344
+ chunk = Buffer.concat([incomplete, chunk]);
2345
+ incomplete = undefined;
2346
+ }
2347
+
2348
+ try {
2349
+ yields = decoder.decodeMultiple(chunk);
2350
+ } catch (err) {
2351
+ if (err.incomplete) {
2352
+ incomplete = chunk.slice(err.lastPosition);
2353
+ yields = err.values;
2354
+ } else {
2355
+ throw err
2356
+ }
2357
+ }
2358
+ return yields
2359
+ };
2360
+
2361
+ if (typeof bufferIterator[Symbol.iterator] === 'function') {
2362
+ return (function * iter () {
2363
+ for (const value of bufferIterator) {
2364
+ yield * parser(value);
2365
+ }
2366
+ })()
2367
+ } else if (typeof bufferIterator[Symbol.asyncIterator] === 'function') {
2368
+ return (async function * iter () {
2369
+ for await (const value of bufferIterator) {
2370
+ yield * parser(value);
2371
+ }
2372
+ })()
2373
+ }
2374
+ }
2375
+
2376
+ exports.ALWAYS = ALWAYS;
2377
+ exports.DECIMAL_FIT = DECIMAL_FIT;
2378
+ exports.DECIMAL_ROUND = DECIMAL_ROUND;
2379
+ exports.Decoder = Decoder;
2380
+ exports.Encoder = Encoder;
2381
+ exports.FLOAT32_OPTIONS = FLOAT32_OPTIONS;
2382
+ exports.NEVER = NEVER;
2383
+ exports.REUSE_BUFFER_MODE = REUSE_BUFFER_MODE;
2384
+ exports.Tag = Tag;
2385
+ exports.addExtension = addExtension;
2386
+ exports.clearSource = clearSource;
2387
+ exports.decode = decode;
2388
+ exports.decodeIter = decodeIter;
2389
+ exports.decodeMultiple = decodeMultiple;
2390
+ exports.encode = encode;
2391
+ exports.encodeAsAsyncIterable = encodeAsAsyncIterable;
2392
+ exports.encodeAsIterable = encodeAsIterable;
2393
+ exports.encodeIter = encodeIter;
2394
+ exports.isNativeAccelerationEnabled = isNativeAccelerationEnabled;
2395
+ exports.roundFloat32 = roundFloat32;
2396
+
2397
+ }));
2398
+ //# sourceMappingURL=index-no-eval.cjs.map