cbor-x 1.5.6 → 1.5.8

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