cbor-x 1.5.6 → 1.5.7

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