cbor-x 1.3.1 → 1.4.0

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